Hello there, I was able to successfully represent the following Python code
def test_if_else(condition: bool, input_val: Tensor) -> Tuple[int, Tensor]:
status = 0
value = input_val * 2
if condition:
status = 1
value = value + 10.0
else:
status = -1
value = value - 5.0
return status, value
as follows:
// 1. Initialization
auto cu = std::make_shared<torch::jit::CompilationUnit>();
auto class_name = c10::QualifiedName("__torch__.ConditionalModule");
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>();
// 1. Inputs
torch::jit::Value* self_val = graph->addInput("self")->setType(class_type);
torch::jit::Value* condition = graph->addInput("condition")->setType(c10::BoolType::get());
torch::jit::Value* input_val = graph->addInput("input_val")->setType(c10::TensorType::get());
torch::jit::Value* const_2 = graph->insertConstant(2)->setType( c10::IntType::get());
// Alpha formale (scalar = 1)
torch::jit::Value* alpha_1 = graph->insertConstant(1)->setType( c10::IntType::get());
// 2. value = 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* initial_value = mul_node->output()->setType(c10::TensorType::get());
// 3. If switch statemet
torch::jit::Node* if_node = graph->create(torch::jit::prim::If, {condition});
graph->insertNode(if_node);
torch::jit::Block* then_block = if_node->addBlock();
torch::jit::Block* else_block = if_node->addBlock();
// --- THEN (True) ---
auto then_status_node = graph->create(torch::jit::prim::Constant);
then_status_node->output()->setType(c10::IntType::get());
then_status_node->i_(c10::attr::value, 1);
then_block->appendNode(then_status_node);
torch::jit::Value* then_status = then_status_node->output();
auto const_10_node = graph->create(torch::jit::prim::Constant);
const_10_node->output()->setType(c10::FloatType::get());
const_10_node->f_(c10::attr::value, 10.0);
then_block->appendNode(const_10_node);
// JIT: aten::add(Tensor self, Scalar other, Scalar alpha) -> Tensor
torch::jit::Node* then_add = graph->create(torch::jit::aten::add, {initial_value, const_10_node->output(), alpha_1});
then_block->appendNode(then_add);
torch::jit::Value* then_value = then_add->output()->setType(c10::TensorType::get()); // Forza tipo Tensor singolo
then_block->registerOutput(then_status);
then_block->registerOutput(then_value);
// --- ELSE (False) ---
auto else_status_node = graph->create(torch::jit::prim::Constant);
else_status_node->output()->setType(c10::IntType::get());
else_status_node->i_(c10::attr::value, -1);
else_block->appendNode(else_status_node);
torch::jit::Value* else_status = else_status_node->output();
auto const_5_node = graph->create(torch::jit::prim::Constant);
const_5_node->output()->setType(c10::FloatType::get());
const_5_node->f_(c10::attr::value, 5.0);
else_block->appendNode(const_5_node);
// Want to match: aten::sub(Tensor self, Scalar other, Scalar alpha) -> Tensor
torch::jit::Node* else_sub = graph->create(torch::jit::aten::sub, {initial_value, const_5_node->output(), alpha_1});
else_block->appendNode(else_sub);
torch::jit::Value* else_value = else_sub->output()->setType(c10::TensorType::get()); // Forza tipo Tensor singolo
else_block->registerOutput(else_status);
else_block->registerOutput(else_value);
// 4. Mappatura degli output FISICI sul nodo IF (SOLO 2 OUTPUT)
// Svuotiamo prima eventuali output spuri ereditati se presenti
while(if_node->outputs().size() > 0) {
if_node->eraseOutput(0);
}
torch::jit::Value* final_status = if_node->addOutput()->setType(c10::IntType::get());
torch::jit::Value* final_value = if_node->addOutput()->setType(c10::TensorType::get());
// 5. creating the tuple returned by the graph
torch::jit::Node* tuple_node = graph->create(torch::jit::prim::TupleConstruct, {final_status, final_value});
graph->insertNode(tuple_node);
graph->registerOutput(tuple_node->output());
// Registering the tuple formally
auto tensor_type = c10::TensorType::get();
auto int_type = c10::IntType::get();
auto bool_type = c10::BoolType::get();
auto tuple_name = c10::QualifiedName("__torch__.MyReturnTypeTuple");
auto tuple_return_type = c10::TupleType::create({int_type, tensor_type});
cu->register_type(tuple_return_type);
tuple_node->output()->setType(tuple_return_type);
// 6. Schema and final generation
std::vector<c10::Argument> arguments = {
c10::Argument("self", class_type),
c10::Argument("condition", bool_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);
// 10. Dumping and jit compiling the model
module_.save("conditional_subgraph.pt");
std::cout << "Modello salvato con successo senza eccezioni JIT!" << std::endl;
Still, I cannot get my head around a simple tiny variation of it, where I am using a for loop as such:
def test_if_else(input_val: Tensor) -> Tuple[int, Tensor]:
# 1. Some initialization
status = 0
value = input_val * 2
for i in range(20):
# 2. Moving the if switch and computation within the for loop
value = value * i * 0.05
if torch.all(value > 0.01):
status = 1
value = value + 10.0
else:
break
return status, value
I tried something like the following:
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>();
// Definizione formale degli input del grafo (Index 0: self, Index 1: input_val)
torch::jit::Value* self_val = graph->addInput("self")->setType(class_type);
torch::jit::Value* input_val = graph->addInput("input_val")->setType(c10::TensorType::get());
// =========================================================================
// 2. Costanti del Grafo Principale (Utilizzando la sintassi nativa inline)
// =========================================================================
torch::jit::Value* const_max_int = graph->insertConstant((int64_t)9223372036854775807LL)->setType(c10::IntType::get()); // %80
torch::jit::Value* const_true = graph->insertConstant(true)->setType(c10::BoolType::get()); // %8
torch::jit::Value* status_init = graph->insertConstant((int64_t)0)->setType(c10::IntType::get()); // %status.1
torch::jit::Value* const_2 = graph->insertConstant((int64_t)2)->setType(c10::IntType::get()); // %3
torch::jit::Value* const_20 = graph->insertConstant((int64_t)20)->setType(c10::IntType::get()); // %5
torch::jit::Value* const_1 = graph->insertConstant((int64_t)1)->setType(c10::IntType::get()); // %22
torch::jit::Value* loop_counter_init = graph->insertConstant((int64_t)0)->setType(c10::IntType::get()); // Contatore iniziale range(20)
torch::jit::Value* const_false = graph->insertConstant(false)->setType(c10::BoolType::get()); // %55
// Costanti in virgola mobile (FloatType)
torch::jit::Value* const_0_05 = graph->insertConstant(0.05)->setType(c10::FloatType::get()); // %13
torch::jit::Value* const_0_01 = graph->insertConstant(0.01)->setType(c10::FloatType::get()); // %17
torch::jit::Value* const_10 = graph->insertConstant(10.0)->setType(c10::FloatType::get()); // %25
// 3. Calcolo iniziale esterno al ciclo: value = 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());
// =========================================================================
// 4. CREAZIONE DEL NODO PRIM::LOOP
// Passiamo le 3 dipendenze portate dal ciclo: status_init, value_init, loop_counter_init
// =========================================================================
torch::jit::Node* loop_node = graph->create(torch::jit::prim::Loop, {const_max_int, const_true, status_init, value_init, loop_counter_init});
graph->insertNode(loop_node);
torch::jit::Block* loop_block = loop_node->addBlock();
// Configurazione degli input del blocco (Index 0: iterazione JIT implicita, Index 1+: dipendenze)
torch::jit::Value* block_iter = loop_block->addInput(); // Obbligatorio a livello strutturale JIT
torch::jit::Value* status_curr = loop_block->addInput()->setType(c10::IntType::get());
torch::jit::Value* value_curr = loop_block->addInput()->setType(c10::TensorType::get());
torch::jit::Value* counter_curr = loop_block->addInput()->setType(c10::IntType::get());
// --- LOGICA INTERNA AL LOOP ---
// value = value * i * 0.05
torch::jit::Node* mul_i = graph->create(torch::jit::aten::mul, {value_curr, counter_curr});
loop_block->appendNode(mul_i);
torch::jit::Node* mul_0_05 = graph->create(torch::jit::aten::mul, {mul_i->output(), const_0_05});
loop_block->appendNode(mul_0_05);
torch::jit::Value* value_scaled = mul_0_05->output()->setType(c10::TensorType::get());
// Condizione: torch::all(value > 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());
// =========================================================================
// 5. CREAZIONE DEL NODO PRIM::IF DENTRO IL LOOP
// =========================================================================
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();
// Ramo THEN (True): continua=True, status=1, value=value+10.0
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()));
// Ramo ELSE (False / BREAK): continua=False, status=status_attuale, value=value_attuale
else_block->registerOutput(const_false);
else_block->registerOutput(status_curr);
else_block->registerOutput(value_scaled);
// Catturiamo i 3 output generati dal blocco condizionale condotto all'esterno
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());
// Incremento del contatore di ciclo: counter = counter + 1
torch::jit::Node* next_counter = graph->create(torch::jit::aten::add, {counter_curr, const_1, const_1});
loop_block->appendNode(next_counter);
// Condizione di arresto basata sulle iterazioni massime: counter < 20
torch::jit::Node* lt_node = graph->create(torch::jit::aten::lt, {next_counter->output(), const_20});
loop_block->appendNode(lt_node);
// Condizione di ciclo complessiva combinata in AND logico: (counter < 20) AND (if_continue)
torch::jit::Node* and_node = graph->create(torch::jit::aten::__and__, {lt_node->output(), if_continue});
loop_block->appendNode(and_node);
torch::jit::Value* loop_keep_going = and_node->output()->setType(c10::BoolType::get());
// =========================================================================
// 6. REGISTRAZIONE DEGLI OUTPUT DEL BLOCCO DEL LOOP
// Index 0: Segnale di continuazione (loop_keep_going)
// Index 1+: Le 3 dipendenze speculari in uscita (status, value, counter)
// =========================================================================
loop_block->registerOutput(loop_keep_going);
loop_block->registerOutput(if_status);
loop_block->registerOutput(if_value);
loop_block->registerOutput(next_counter->output());
// =========================================================================
// 7. ASSEGNAZIONE DEGLI OUTPUT ESTERNI DEL NODO LOOP
// Forniamo 3 punti di ancoraggio esterni per raccogliere i risultati finali del ciclo
// =========================================================================
torch::jit::Value* final_status = loop_node->addOutput()->setType(c10::IntType::get());
torch::jit::Value* final_value = loop_node->addOutput()->setType(c10::TensorType::get());
torch::jit::Value* final_counter = loop_node->addOutput()->setType(c10::IntType::get()); // Variabile di appoggio interna
// =========================================================================
// 8. COSTRUZIONE DELLA TUPLA DI RITORNO DEL GRAFO PRINCIPALE
// =========================================================================
torch::jit::Node* tuple_node = graph->create(torch::jit::prim::TupleConstruct, {final_status, final_value});
graph->insertNode(tuple_node);
graph->registerOutput(tuple_node->output());
// Registrazione formale del tipo della Tupla Nominata all'interno del gestore tipi della CompilationUnit
auto tensor_type = c10::TensorType::get();
auto int_type = c10::IntType::get();
auto bool_type = c10::BoolType::get();
auto tuple_name = c10::QualifiedName("__torch__.MyReturnTypeTuple");
auto tuple_return_type = c10::TupleType::create({int_type, tensor_type});
cu->register_type(tuple_return_type);
tuple_node->output()->setType(tuple_return_type);
// =========================================================================
// 9. DEFINIZIONE DELLO SCHEMA REALE E COMPILAZIONE FINALE DEL METODO
// =========================================================================
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);
// Generazione del metodo di runtime nell'unità di compilazione
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");
But I still get the following issue
“terminate called after throwing an instance of ‘c10::Error’
what(): Python printer expected 2 lists of same size
Exception raised from zipWith at /__w/pytorch/pytorch/torch/csrc/jit/serialization/python_print.cpp:460 (most recent call first):”
Which, by looking at the associated file, should exactly correspond to the mismatch between the input and output arguments of the for loop. The confusing part is that the output printed graph of the associated jit graph directly derived from the code actually shows such a mismatch in terms of dimensions, which I tried to replicate in C++
graph(%input_val.1 : Tensor):
%80 : int = prim::Constant[value=9223372036854775807]()
%8 : bool = prim::Constant[value=1]() # <string>:7:12
%status.1 : int = prim::Constant[value=0]() # <string>:4:21
%3 : int = prim::Constant[value=2]() # <string>:5:32
%5 : int = prim::Constant[value=20]() # <string>:7:27
%13 : float = prim::Constant[value=0.050000000000000003]() # <string>:9:36
%17 : float = prim::Constant[value=0.01]() # <string>:10:37
%22 : int = prim::Constant[value=1]() # <string>:11:29
%25 : float = prim::Constant[value=10.]() # <string>:12:36
%55 : bool = prim::Constant[value=0]()
%value.1 : Tensor = aten::mul(%input_val.1, %3) # <string>:5:20
%status : int, %value : Tensor, %81 : int = prim::Loop(%80, %8, %status.1, %value.1, %status.1) # <string>:7:12
block0(%9 : int, %status.17 : int, %value.29 : Tensor, %82 : int):
%12 : Tensor = aten::mul(%value.29, %82) # <string>:9:24
%value.5 : Tensor = aten::mul(%12, %13) # <string>:9:24
%18 : Tensor = aten::gt(%value.5, %17) # <string>:10:29
%19 : Tensor = aten::all(%18) # <string>:10:19
%21 : bool = aten::Bool(%19) # <string>:10:19
%74 : bool, %75 : int, %76 : Tensor = prim::If(%21) # <string>:10:16
block0():
%value.13 : Tensor = aten::add(%value.5, %25, %22) # <string>:12:28
-> (%8, %22, %value.13)
block1():
-> (%55, %status.17, %value.5)
%83 : int = aten::add(%82, %22)
%84 : bool = aten::lt(%83, %5)
%85 : bool = aten::__and__(%84, %74)
-> (%85, %75, %76, %83)
%39 : (int, Tensor) = prim::TupleConstruct(%status, %value)
return (%39)
Any suggestions on how to fix the last C++ code so to fix this issue? Thanks a lot in advance.