OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
Add torch.cond support for FX export mode (#33219)
Evgeny Kotovd919dcf6ccfc
diff --git a/src/frontends/pytorch/src/op/if.cpp b/src/frontends/pytorch/src/op/if.cppindex 9a214013c95..f6c453011b1 100644--- a/src/frontends/pytorch/src/op/if.cpp+++ b/src/frontends/pytorch/src/op/if.cpp@@ -198,6 +198,119 @@ OutputVector translate_if(const NodeContext& context) {return res;};+OutputVector translate_cond_fx(const NodeContext& context) {+ // torch.cond(pred, true_fn, false_fn, operands)+ // FX representation after decoder processing:+ // - Input 0: pred (boolean tensor)+ // - Subgraph 0: true_fn (GraphModule)+ // - Subgraph 1: false_fn (GraphModule)+ // - Inputs 1+: operands (unpacked from tuple by decoder)++ auto decoder = context.get_decoder();+ PYTORCH_OP_CONVERSION_CHECK(decoder->get_subgraph_size() == 2,+ "torch.cond must have exactly 2 subgraphs (true_fn and false_fn), got: ",+ decoder->get_subgraph_size());++ // Get predicate (first input)+ auto pred = context.get_input(0);++ // Create If node with predicate+ auto if_node = std::make_shared<v8::If>(pred);+ context.mark_node(if_node);++ // Convert subgraphs to OpenVINO Models+ auto then_body = context.convert_subgraph(0);+ auto else_body = context.convert_subgraph(1);++ if_node->set_then_body(then_body);+ if_node->set_else_body(else_body);++ // Get body parameters - both branches receive the same operands in torch.cond+ auto then_params = then_body->get_parameters();+ auto else_params = else_body->get_parameters();++ // Map operands to body parameters+ // In FX, operands are explicitly passed and should match parameter count+ const auto num_operands = context.get_input_size() - 1; // exclude pred++ // Connect each operand to corresponding parameter in both bodies+ // Note: In torch.cond, both branches receive the same operands+ for (size_t i = 0; i < num_operands && i < then_params.size() && i < else_params.size(); i++) {+ auto operand = context.get_input(static_cast<int>(i) + 1);+ if_node->set_input(operand, then_params[i], else_params[i]);+ }++ // Handle case where one body has more parameters (they might capture external tensors)+ // This shouldn't happen in well-formed torch.cond, but handle defensively+ auto session = context.get_session();+ for (size_t i = num_operands; i < then_params.size(); i++) {+ auto param = then_params[i];+ auto input_idx = session->decode_tensor_name(param->output(0));+ auto external_output = context.get_tensor_from_model_or_create_input(input_idx);++ // Find or create matching parameter in else body+ std::shared_ptr<v0::Parameter> else_param = nullptr;+ for (const auto& ep : else_params) {+ if (session->decode_tensor_name(ep->output(0)) == input_idx) {+ else_param = ep;+ break;+ }+ }+ if (!else_param) {+ else_param = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic());+ session->encode_tensor_name(else_param->output(0), input_idx);+ auto else_result = std::make_shared<v0::Result>(else_param);+ else_body->add_parameters({else_param});+ else_body->add_results({else_result});+ }+ if_node->set_input(external_output, param, else_param);+ }++ for (size_t i = num_operands; i < else_params.size(); i++) {+ auto param = else_params[i];+ auto input_idx = session->decode_tensor_name(param->output(0));+ auto external_output = context.get_tensor_from_model_or_create_input(input_idx);++ // Find or create matching parameter in then body+ std::shared_ptr<v0::Parameter> then_param = nullptr;+ for (const auto& tp : then_params) {+ if (session->decode_tensor_name(tp->output(0)) == input_idx) {+ then_param = tp;+ break;+ }+ }+ if (!then_param) {+ then_param = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic());+ session->encode_tensor_name(then_param->output(0), input_idx);+ auto then_result = std::make_shared<v0::Result>(then_param);+ then_body->add_parameters({then_param});+ then_body->add_results({then_result});+ }+ if_node->set_input(external_output, then_param, param);+ }++ // Map outputs - both branches must have same number of results+ auto then_results = then_body->get_results();+ auto else_results = else_body->get_results();+ PYTORCH_OP_CONVERSION_CHECK(then_results.size() == else_results.size(),+ "torch.cond branches must return same number of outputs. "+ "then_body has ",+ then_results.size(),+ " outputs, else_body has ",+ else_results.size());++ OutputVector res;+ for (size_t i = 0; i < then_results.size(); i++) {+ align_result_types(context, then_results[i], else_results[i]);+ res.push_back(if_node->set_output(then_results[i], else_results[i]));+ }++ if_node->validate_and_infer_types();++ // Return outputs - torch.cond returns a tuple, so wrap in list construct+ return {make_list_construct(res)};+}+} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 68c5adfefa6..f5d173221cf 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -129,6 +129,7 @@ OP_CONVERTER(translate_hann_window);OP_CONVERTER(translate_hardtanh);OP_CONVERTER(translate_hstack);OP_CONVERTER(translate_if);+OP_CONVERTER(translate_cond_fx);OP_CONVERTER(translate_im2col);OP_CONVERTER(translate_index);OP_CONVERTER(translate_index_add);@@ -1116,8 +1117,9 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"quantized_decomposed.dequantize_per_tensor.default", op::skip_node},{"quantized_decomposed.dequantize_per_channel.default", op::skip_node},{"inlined.constant.default", op::translate_constant}, // this is a custom ov type- // Higher-order operations- {"while_loop", op::translate_while_loop_fx}, // torch.ops.higher_order.while_loop+ // Higher-order operations from torch.export (torch.cond, torch.while_loop, etc.)+ {"cond", op::translate_cond_fx},+ {"while_loop", op::translate_while_loop_fx},};};diff --git a/tests/layer_tests/pytorch_tests/test_cond.py b/tests/layer_tests/pytorch_tests/test_cond.pynew file mode 100644index 00000000000..c67b0dc1bca--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_cond.py@@ -0,0 +1,95 @@+# Copyright (C) 2018-2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+import pytest+import numpy as np++from pytorch_layer_test_class import PytorchLayerTest+++class TestCondFX(PytorchLayerTest):+ """Test torch.cond operation for FX export mode."""++ def _prepare_input(self):+ rng = np.random.default_rng(43)+ return (rng.normal(size=self.input_shape).astype(np.float32), self.pred_value)++ def create_simple_cond_model(self):+ import torch++ class SimpleCond(torch.nn.Module):+ def forward(self, x, pred):+ def true_fn(x):+ return x * 2++ def false_fn(x):+ return x + 1++ return torch.cond(pred, true_fn, false_fn, (x,))++ return SimpleCond(), None, "cond"++ def create_multi_output_cond_model(self):+ import torch++ class MultiOutputCond(torch.nn.Module):+ def forward(self, x, pred):+ def true_fn(x):+ return x * 2, x + 1++ def false_fn(x):+ return x + 1, x * 2++ return torch.cond(pred, true_fn, false_fn, (x,))++ return MultiOutputCond(), None, "cond"++ def create_linear_cond_model(self, hidden_size):+ import torch++ class LinearCond(torch.nn.Module):+ def __init__(self, hidden_size):+ super().__init__()+ self.proj = torch.nn.Linear(hidden_size, hidden_size)++ def forward(self, x, is_prefill):+ def prefill_fn(x):+ return self.proj(x) * x.sum(dim=-1, keepdim=True)++ def decode_fn(x):+ return self.proj(x)++ return torch.cond(is_prefill, prefill_fn, decode_fn, (x,))++ return LinearCond(hidden_size), None, "cond"++ @pytest.mark.parametrize("pred_value", [np.array(True), np.array(False)])+ @pytest.mark.parametrize("input_shape", [(1, 4), (2, 3, 4)])+ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_simple_cond(self, pred_value, input_shape, ie_device, precision, ir_version):+ self.pred_value = pred_value+ self.input_shape = input_shape+ self._test(*self.create_simple_cond_model(), ie_device, precision, ir_version,+ use_convert_model=True)++ @pytest.mark.parametrize("pred_value", [np.array(True), np.array(False)])+ @pytest.mark.parametrize("input_shape", [(1, 4)])+ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_multi_output_cond(self, pred_value, input_shape, ie_device, precision, ir_version):+ if ie_device == "GPU":+ pytest.skip("Multi-output If not supported on GPU - CVS-178157")+ self.pred_value = pred_value+ self.input_shape = input_shape+ self._test(*self.create_multi_output_cond_model(), ie_device, precision, ir_version,+ use_convert_model=True)++ @pytest.mark.parametrize("pred_value", [np.array(True), np.array(False)])+ @pytest.mark.parametrize("input_shape,hidden_size", [((1, 10, 64), 64)])+ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_linear_cond(self, pred_value, input_shape, hidden_size, ie_device, precision, ir_version):+ self.pred_value = pred_value+ self.input_shape = input_shape+ self._test(*self.create_linear_cond_model(hidden_size), ie_device, precision, ir_version,+ use_convert_model=True)