PAYATHON 2026

LibTorch C++ JIT 中 prim::Loop 的构造与 Python printer 大小不匹配错误

数据小陈

结论

报错 Python printer expected 2 lists of same size 的根源是手动构造 prim::Loop 时,循环体 block 的输入/输出与循环节点携带依赖(carried dependencies)在数量或结构上不一致。你的代码中额外携带了一个手工 counter,并且整数加法节点 aten::add 传入了 3 个输入,同时 block 第一个输入未设置 IntType,这些都会让 JIT 在序列化时无法正确对齐 loop 的 carried deps,最终在 python_print.cpp 的 zipWith 中抛出长度不匹配。

更简单的做法是:不要手工携带 counter,直接用 prim::Loop 的 max_trip_count=20 控制迭代次数,并把 block 的第一个输入(迭代索引)当作 i。这样 loop 只携带 status 和 value 两个依赖,结构为:

  • loop 节点输入:max_trip_count, initial_condition, status, value
  • loop 节点输出:status, value
  • block 输入:iter, status, value
  • block 输出:next_condition, status, value

原因分析

prim::Loop 的 IR 约定如下:

loop 节点输入 = [max_trip_count, initial_condition, carried_deps...]
loop 节点输出 = carried_deps
block 输入   = [iter_index, carried_deps...]
block 输出   = [next_condition, carried_deps...]

因此必须满足:

  • loop_node->outputs().size() == loop_block->outputs().size() - 1
  • loop_node->inputs().size() == 2 + loop_block->inputs().size() - 1

你的代码里 loop 节点有 3 个输出,block 有 4 个输出,数量关系看似正确,但手工 counter 的 next_counter 使用了:

auto next_counter = graph->create(torch::jit::aten::add, {counter_curr, const_1, const_1});

整数加法应为两个输入,这里传了三个,导致节点 schema 与类型推断异常。另外:

auto block_iter = loop_block->addInput();

没有设置 IntType。这些结构/类型问题会在 module_.save() 触发 Python printer 时暴露为 zipWith 长度不匹配。

修正步骤

  1. 用 const_20 作为 max_trip_count,不再手工携带 counter。
  2. loop 节点只携带 status_init 和 value_init,输出只保留 final_status 和 final_value。
  3. block 输入设置为 iter(Int), status_curr(Int), value_curr(Tensor);block 输出设置为 next_cond(Bool), if_status(Int), if_value(Tensor)。
  4. 把 iter 直接当作 i 使用,计算 value_scaled = value_curr * iter * 0.05。
  5. 整数加法使用两个输入,所有中间 Value* 显式 setType。
  6. 保存前检查 loop 节点与 block 的输入/输出数量关系。

修正后的 C++ 代码

auto cu = std::make_shared<torch::jit::CompilationUnit>();
auto class_name = c10::QualifiedName("_torch_.ConditionalLoopModule");
auto class_type = c10::ClassType::create(class_name, cu, /*is_module=*/true);
torch::jit::Module module_(cu, class_type);
auto graph = std::make_shared<torch::jit::Graph>();

torch::jit::Value* self_val = graph->addInput("self")->setType(class_type);
torch::jit::Value* input_val = graph->addInput("input_val")->setType(c10::TensorType::get());

// 常量
torch::jit::Value* const_true = graph->insertConstant(true)->setType(c10::BoolType::get());
torch::jit::Value* const_false = graph->insertConstant(false)->setType(c10::BoolType::get());
torch::jit::Value* status_init = graph->insertConstant((int64_t)0)->setType(c10::IntType::get());
torch::jit::Value* const_2 = graph->insertConstant((int64_t)2)->setType(c10::IntType::get());
torch::jit::Value* const_20 = graph->insertConstant((int64_t)20)->setType(c10::IntType::get());
torch::jit::Value* const_1 = graph->insertConstant((int64_t)1)->setType(c10::IntType::get());
torch::jit::Value* const_0_05 = graph->insertConstant(0.05)->setType(c10::FloatType::get());
torch::jit::Value* const_0_01 = graph->insertConstant(0.01)->setType(c10::FloatType::get());
torch::jit::Value* const_10 = graph->insertConstant(10.0)->setType(c10::FloatType::get());

// value_init = input_val * 2
torch::jit::Node* mul_node = graph->create(torch::jit::aten::mul, {input_val, const_2});
graph->insertNode(mul_node);
torch::jit::Value* value_init = mul_node->output()->setType(c10::TensorType::get());

// prim::Loop:max_trip_count=20, condition=true, carried: status, value
torch::jit::Node* loop_node = graph->create(torch::jit::prim::Loop, {const_20, const_true, status_init, value_init});
graph->insertNode(loop_node);
torch::jit::Block* loop_block = loop_node->addBlock();

// block 输入:iter(Int), status(Int), value(Tensor)
torch::jit::Value* iter = loop_block->addInput()->setType(c10::IntType::get());
torch::jit::Value* status_curr = loop_block->addInput()->setType(c10::IntType::get());
torch::jit::Value* value_curr = loop_block->addInput()->setType(c10::TensorType::get());

// value_scaled = value_curr * iter * 0.05
torch::jit::Node* mul_iter = graph->create(torch::jit::aten::mul, {value_curr, iter});
loop_block->appendNode(mul_iter);
torch::jit::Node* mul_0_05 = graph->create(torch::jit::aten::mul, {mul_iter->output(), const_0_05});
loop_block->appendNode(mul_0_05);
torch::jit::Value* value_scaled = mul_0_05->output()->setType(c10::TensorType::get());

// if_condition = torch.all(value_scaled > 0.01)
torch::jit::Node* gt_node = graph->create(torch::jit::aten::gt, {value_scaled, const_0_01});
loop_block->appendNode(gt_node);
torch::jit::Node* all_node = graph->create(torch::jit::aten::all, {gt_node->output()});
loop_block->appendNode(all_node);
torch::jit::Node* bool_cast = graph->create(torch::jit::aten::Bool, {all_node->output()});
loop_block->appendNode(bool_cast);
torch::jit::Value* if_condition = bool_cast->output()->setType(c10::BoolType::get());

// prim::If
torch::jit::Node* if_node = graph->create(torch::jit::prim::If, {if_condition});
loop_block->appendNode(if_node);
torch::jit::Block* then_block = if_node->addBlock();
torch::jit::Block* else_block = if_node->addBlock();

// then: status=1, value=value_scaled+10.0, continue=true
torch::jit::Node* then_add = graph->create(torch::jit::aten::add, {value_scaled, const_10, const_1});
then_block->appendNode(then_add);
then_block->registerOutput(const_true);
then_block->registerOutput(const_1);
then_block->registerOutput(then_add->output()->setType(c10::TensorType::get()));

// else: break,保持 status,value=value_scaled,continue=false
else_block->registerOutput(const_false);
else_block->registerOutput(status_curr);
else_block->registerOutput(value_scaled);

// if_node 输出:continue, status, value
torch::jit::Value* if_continue = if_node->addOutput()->setType(c10::BoolType::get());
torch::jit::Value* if_status = if_node->addOutput()->setType(c10::IntType::get());
torch::jit::Value* if_value = if_node->addOutput()->setType(c10::TensorType::get());

// loop block 输出:next_condition, status, value
loop_block->registerOutput(if_continue);
loop_block->registerOutput(if_status);
loop_block->registerOutput(if_value);

// loop_node 输出:final_status, final_value
torch::jit::Value* final_status = loop_node->addOutput()->setType(c10::IntType::get());
torch::jit::Value* final_value = loop_node->addOutput()->setType(c10::TensorType::get());

// 返回 tuple
torch::jit::Node* tuple_node = graph->create(torch::jit::prim::TupleConstruct, {final_status, final_value});
graph->insertNode(tuple_node);
graph->registerOutput(tuple_node->output());

// 类型注册与 schema
auto tensor_type = c10::TensorType::get();
auto int_type = c10::IntType::get();
auto tuple_return_type = c10::TupleType::create({int_type, tensor_type});
cu->register_type(tuple_return_type);
tuple_node->output()->setType(tuple_return_type);

std::vector<c10::Argument> arguments = {
  c10::Argument("self", class_type),
  c10::Argument("input_val", tensor_type)
};
std::vector<c10::Argument> returns = {
  c10::Argument("", tuple_return_type)
};

c10::QualifiedName method_name(class_name, "forward");
c10::FunctionSchema schema(method_name.name(), "", arguments, returns);
auto method = module_._ivalue()->compilation_unit()->create_function(method_name, graph);
method->setSchema(std::move(schema));
class_type->addMethod(method);

module_.save("conditional_subgraph.pt");

注意事项

  • 手动构造 prim::Loop 时,务必保证 block 的第一个输入为 IntType,第一个输出为 BoolType。
  • 不要随意给 aten::add 传入三个输入:Tensor + Scalar + alpha 是三输入,Int + Int 是两输入。
  • module_.save() 会调用 Python printer,所以 IR 结构必须严格符合 JIT 约定,否则容易在 zipWith 处报长度不匹配。
  • 如果一定要完全复现 TorchScript 打印出的 graph(带手工 counter),则需把 next_counter 改成 {counter_curr, const_1},并显式设置 next_counter->output()->setType(c10::IntType::get()),同时给 block_iter 设置 IntType。

备注:内容仅供参考。