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.while_loop support for FX frontend (#33173)
Evgeny Kotov42a1ef1f8752
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex 0c604a7bd68..e7f5f08c8b7 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -8,6 +8,15 @@ import loggingimport inspectimport torch+# Import HigherOrderOperator for detecting higher-order operations (while_loop, cond, etc.)+# This is the official PyTorch API used in torch.export, torch.compile backends, etc.+try:+ from torch._ops import HigherOrderOperator+ _HAS_HIGHER_ORDER_OPERATOR = True+except ImportError:+ _HAS_HIGHER_ORDER_OPERATOR = False+ HigherOrderOperator = None+from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoderfrom openvino.frontend.pytorch.py_pytorch_frontend import _Type as DecoderTypefrom openvino import PartialShape, Type as OVType, OVAny, Shape@@ -218,14 +227,39 @@ class TorchFXPythonDecoder (BaseFXDecoder):self._outputs = [("", self._nodes.index(pt_module))]self.input_types = []- for arg in pt_module.args:- if isinstance(arg, torch.fx.Node):+ self._subgraph_inputs = [] # Separate storage for subgraph arguments++ # Check if this is a higher-order operation that needs special tuple handling+ is_higher_order_op = self._is_higher_order_op(pt_module)++ for arg_idx, arg in enumerate(pt_module.args):+ is_subgraph, graph_module = self._is_subgraph_arg(arg)++ if is_subgraph:+ # Subgraph argument (e.g., cond_fn, body_fn in while_loop)+ # Store separately - subgraphs are accessed via get_subgraphs(), not inputs()+ self._subgraph_inputs.append(SubgraphInput(arg, graph_module, arg_idx))+ elif is_higher_order_op and isinstance(arg, (tuple, list)):+ # Special handling for higher-order operations (while_loop, cond, etc.)+ if len(arg) == 0:+ # Empty tuple/list (e.g., additional_inputs=() in while_loop) - skip entirely+ pass+ elif all(isinstance(item, torch.fx.Node) for item in arg):+ # Tuple of nodes (e.g., carried_inputs in while_loop) - unpack into separate inputs+ for item in arg:+ self._inputs.append(self._nodes.index(item))+ self.input_types.append(BaseFXDecoder.get_type_for_value(item))+ else:+ # Mixed tuple - keep as single InlinedInput+ self._inputs.append(InlinedInput(arg))+ self.input_types.append(BaseFXDecoder.get_type_for_value(arg))+ elif isinstance(arg, torch.fx.Node):self._inputs.append(self._nodes.index(arg))+ self.input_types.append(BaseFXDecoder.get_type_for_value(arg))else:- # Not a node, consider it inlined+ # Not a node, consider it inlined (constant)self._inputs.append(InlinedInput(arg))- self.input_types.append(- BaseFXDecoder.get_type_for_value(arg))+ self.input_types.append(BaseFXDecoder.get_type_for_value(arg))@classmethoddef from_exported_program(cls, exported_program: torch.export.ExportedProgram) -> "TorchFXPythonDecoder":@@ -268,6 +302,49 @@ class TorchFXPythonDecoder (BaseFXDecoder):return OVAny(pt_to_ov_type_map[str(value.meta["tensor_meta"].dtype)])return None+ def _is_higher_order_op(self, node):+ """Check if the node is a higher-order operation.++ Uses the official PyTorch API (isinstance check with HigherOrderOperator).+ This is the same approach used in torch.export, torch.compile backends,+ and other PyTorch components (torch/_export/serde/serialize.py,+ torch/_export/pass_base.py, torch/utils/flop_counter.py).++ Higher-order operations (while_loop, cond, map, scan, etc.) pass tuple+ of tensors as carried inputs that need to be unpacked into separate inputs.+ Regular operations should keep tuples as-is (InlinedInput).+ """+ if node.op != "call_function":+ return False++ if not _HAS_HIGHER_ORDER_OPERATOR:+ return False++ return isinstance(node.target, HigherOrderOperator)++ def _is_subgraph_arg(self, arg):+ """Check if argument is a subgraph reference (get_attr node pointing to GraphModule).++ This provides universal detection of subgraph arguments for any higher-order+ operation (while_loop, cond, map, scan, etc.).++ Returns:+ tuple: (is_subgraph: bool, graph_module: GraphModule or None)+ """+ if not isinstance(arg, torch.fx.Node):+ return False, None+ if arg.op != "get_attr":+ return False, None++ # Get the attribute from the root graph module+ subgraph = getattr(self.fx_gm, arg.target, None)+ if subgraph is not None and isinstance(subgraph, torch.fx.GraphModule):+ return True, subgraph+ # Also handle callables with graph attribute (lambda-wrapped GraphModules)+ if callable(subgraph) and hasattr(subgraph, "graph"):+ return True, subgraph+ return False, None+def get_input_signature_name(self, index: int) -> str:if self._input_signature is not None and index < len(self._input_signature):return self._input_signature[index]@@ -352,15 +429,40 @@ class TorchFXPythonDecoder (BaseFXDecoder):continue # skipping non-operational nodesif node.op == "call_function" and str(node.target) in ["aten._assert_async.msg"]:continue+ # Skip get_attr nodes that reference subgraph GraphModules+ # These are handled by higher-order op translators (while_loop, cond, etc.)+ if node.op == "get_attr":+ is_subgraph, _ = self._is_subgraph_arg(node)+ if is_subgraph:+ continuedecoder = TorchFXPythonDecoder(node, self.fx_gm, self._nodes, mark_node_callback=self.mark_node_callback)self.m_decoders.append(decoder)node_visitor(decoder)+ def get_subgraphs(self):+ """Return list of subgraphs for higher-order operations.++ Works universally for any operation with subgraph arguments+ (while_loop, cond, map, scan, etc.). Subgraphs are returned+ in their original argument order.+ """+ if not hasattr(self, "_subgraph_inputs") or not self._subgraph_inputs:+ return []+ return [sg.graph_module for sg in self._subgraph_inputs]+def get_subgraph_decoder(self, index):- decoder = TorchFXPythonDecoder(self.get_subgraphs()[index],- self.fx_gm,- mark_node_callback=self.mark_node_callback)+ """Return decoder for subgraph at given index."""+ subgraphs = self.get_subgraphs()+ if index >= len(subgraphs):+ raise IndexError(f"Subgraph index {index} out of range (have {len(subgraphs)} subgraphs)")++ subgraph = subgraphs[index]+ decoder = TorchFXPythonDecoder(+ subgraph,+ subgraph, # Use subgraph as fx_gm for proper constant resolution+ mark_node_callback=self.mark_node_callback+ )self.m_decoders.append(decoder)return decoder@@ -440,6 +542,19 @@ class InlinedInput:self.data = data+class SubgraphInput:+ """Represents a subgraph input (GraphModule reference via get_attr).++ This is used for higher-order operations like while_loop, cond, map, etc.+ where arguments can be callable subgraphs instead of tensor data.+ """++ def __init__(self, node, graph_module, original_arg_index) -> None:+ self.node = node # The get_attr node referencing the subgraph+ self.graph_module = graph_module # The actual GraphModule+ self.original_arg_index = original_arg_index # Position in original args++class InlinedInputDecoder (BaseFXDecoder):"""Decoder for inlined inputs in PyTorch FX graphs."""diff --git a/src/frontends/pytorch/src/op/loop.cpp b/src/frontends/pytorch/src/op/loop.cppindex 49a8a55230d..21d4ca716e1 100644--- a/src/frontends/pytorch/src/op/loop.cpp+++ b/src/frontends/pytorch/src/op/loop.cpp@@ -4,7 +4,14 @@#include "openvino/op/loop.hpp"+#include <limits>+#include "openvino/frontend/pytorch/node_context.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/opsets/opset10.hpp"#include "translate_session.hpp"#include "utils.hpp"@@ -75,6 +82,221 @@ OutputVector translate_loop(const NodeContext& context) {return {context.mark_node(loop)->outputs()};};+OutputVector translate_while_loop_fx(const NodeContext& context) {+ // FX while_loop has structure:+ // - 2 subgraphs: cond_fn (index 0) and body_fn (index 1)+ // - inputs = carried_inputs (values that are updated each iteration)+ // - cond_fn takes carried_inputs, returns boolean scalar+ // - body_fn takes carried_inputs, returns new carried_inputs+ //+ // OpenVINO Loop requires:+ // - trip_count (max iterations)+ // - execution_condition (initial condition)+ // - body model with Parameters and Results where:+ // - Parameter[0] is iteration counter+ // - Result[0] is next condition+ // - Other parameters/results are carried values++ auto decoder = context.get_decoder();+ PYTORCH_OP_CONVERSION_CHECK(+ decoder->get_subgraph_size() == 2,+ "while_loop must have 2 subgraphs (cond and body), got " + std::to_string(decoder->get_subgraph_size()));++ const auto& inputs = context.inputs();+ const size_t num_carried = inputs.size();+ PYTORCH_OP_CONVERSION_CHECK(num_carried > 0, "while_loop must have at least one carried input.");++ // Convert cond and body subgraphs+ auto cond_model = context.convert_subgraph(0);+ auto body_model = context.convert_subgraph(1);++ auto cond_params = cond_model->get_parameters();+ auto cond_results = cond_model->get_results();+ auto body_params = body_model->get_parameters();+ auto body_results = body_model->get_results();++ PYTORCH_OP_CONVERSION_CHECK(cond_results.size() == 1, "cond_fn must have exactly one output (boolean condition).");+ PYTORCH_OP_CONVERSION_CHECK(body_results.size() == num_carried,+ "body_fn must return same number of outputs as carried inputs. Expected " ++ std::to_string(num_carried) + ", got " + std::to_string(body_results.size()));++ // Build combined body model for OpenVINO Loop:+ // Parameters: [counter, ...carried_inputs]+ // Results: [condition, ...new_carried_values]+ //+ // Implementation approach:+ // 1. Create parameters for [counter, carried_inputs]+ // 2. Clone body operations connected to new parameters+ // 3. Clone cond operations connected to body outputs+ // 4. Return [cond_output, body_outputs]++ // Create trip_count (large number for while loop)+ auto trip_count =+ ov::opset10::Constant::create(ov::element::i64, ov::Shape{}, {std::numeric_limits<int32_t>::max()});++ // Create initial condition (true)+ auto init_cond = ov::opset10::Constant::create(ov::element::boolean, ov::Shape{}, {true});++ // For FX while_loop, we need to construct a proper body+ // The body should be: [counter, x0, x1, ...] -> [cond(body(x0,x1,...)), body(x0,x1,...)]++ // Create new parameters for the loop body+ ov::ParameterVector loop_body_params;+ // counter+ auto loop_counter = std::make_shared<ov::opset10::Parameter>(ov::element::i64, ov::PartialShape{});+ loop_counter->set_friendly_name("loop_iteration");+ loop_body_params.push_back(loop_counter);++ // carried inputs+ for (size_t i = 0; i < num_carried; i++) {+ auto param =+ std::make_shared<ov::opset10::Parameter>(inputs[i].get_element_type(), inputs[i].get_partial_shape());+ param->set_friendly_name("loop_carried_" + std::to_string(i));+ loop_body_params.push_back(param);+ }++ // Map body model parameters to loop body parameters+ std::map<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>> body_param_map;+ for (size_t i = 0; i < body_params.size() && i < num_carried; i++) {+ body_param_map[body_params[i]] = loop_body_params[i + 1];+ }++ // Clone body model operations+ ov::NodeVector body_ops;+ std::map<ov::Node*, ov::Node*> node_map;+ for (const auto& orig_param : body_params) {+ if (body_param_map.count(orig_param)) {+ node_map[orig_param.get()] = body_param_map[orig_param].get();+ }+ }++ // Clone all body operations (except parameters and results)+ for (const auto& op : body_model->get_ordered_ops()) {+ if (ov::is_type<ov::opset10::Parameter>(op) || ov::is_type<ov::opset10::Result>(op)) {+ continue;+ }+ ov::OutputVector new_inputs;+ for (const auto& input : op->inputs()) {+ auto source = input.get_source_output();+ auto source_node = source.get_node();+ if (node_map.count(source_node)) {+ new_inputs.push_back(node_map[source_node]->output(source.get_index()));+ } else {+ new_inputs.push_back(source);+ }+ }+ auto cloned = op->clone_with_new_inputs(new_inputs);+ cloned->set_friendly_name(op->get_friendly_name());+ node_map[op.get()] = cloned.get();+ body_ops.push_back(cloned);+ }++ // Get cloned body outputs+ std::vector<ov::Output<ov::Node>> cloned_body_outputs;+ for (const auto& result : body_results) {+ auto source = result->input(0).get_source_output();+ auto source_node = source.get_node();+ if (node_map.count(source_node)) {+ cloned_body_outputs.push_back(node_map[source_node]->output(source.get_index()));+ } else {+ cloned_body_outputs.push_back(source);+ }+ }++ // Now clone cond model and connect to cloned body outputs+ // Create separate maps for cond params -> body outputs and cloned operations+ std::map<ov::Node*, size_t> cond_param_to_idx; // Maps cond param to index+ for (size_t i = 0; i < cond_params.size(); i++) {+ cond_param_to_idx[cond_params[i].get()] = i;+ }+ std::map<ov::Node*, ov::Node*> cond_cloned_map; // Maps original cond ops to cloned ops++ // Clone cond operations+ for (const auto& op : cond_model->get_ordered_ops()) {+ if (ov::is_type<ov::opset10::Parameter>(op) || ov::is_type<ov::opset10::Result>(op)) {+ continue;+ }+ ov::OutputVector new_inputs;+ for (const auto& input : op->inputs()) {+ auto source = input.get_source_output();+ auto source_node = source.get_node();+ if (cond_param_to_idx.count(source_node)) {+ // This input is from a cond parameter - connect to corresponding body output+ size_t param_idx = cond_param_to_idx.at(source_node);+ new_inputs.push_back(cloned_body_outputs[param_idx]);+ } else if (cond_cloned_map.count(source_node)) {+ // This input is from a previously cloned cond operation+ new_inputs.push_back(cond_cloned_map[source_node]->output(source.get_index()));+ } else if (node_map.count(source_node)) {+ // This input is from a body operation+ new_inputs.push_back(node_map[source_node]->output(source.get_index()));+ } else {+ // Keep original (e.g., constants from outside)+ new_inputs.push_back(source);+ }+ }+ auto cloned = op->clone_with_new_inputs(new_inputs);+ cloned->set_friendly_name(op->get_friendly_name() + "_cond");+ cond_cloned_map[op.get()] = cloned.get();+ body_ops.push_back(cloned);+ }++ // Get condition output+ ov::Output<ov::Node> cond_output;+ for (const auto& result : cond_results) {+ auto source = result->input(0).get_source_output();+ if (cond_cloned_map.count(source.get_node())) {+ cond_output = cond_cloned_map[source.get_node()]->output(source.get_index());+ } else {+ cond_output = source;+ }+ }++ // Ensure condition is scalar boolean+ if (cond_output.get_partial_shape().rank().is_static() && cond_output.get_partial_shape().rank().get_length() > 0) {+ cond_output = std::make_shared<ov::opset10::Squeeze>(cond_output);+ }++ // Create results: [condition, body_output_0, body_output_1, ...]+ ov::ResultVector loop_body_results;+ loop_body_results.push_back(std::make_shared<ov::opset10::Result>(cond_output));+ for (const auto& out : cloned_body_outputs) {+ loop_body_results.push_back(std::make_shared<ov::opset10::Result>(out));+ }++ // Create body model+ auto loop_body = std::make_shared<ov::Model>(loop_body_results, loop_body_params, "while_loop_body");++ // Create Loop operation+ auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, init_cond);+ loop->set_function(loop_body);++ // Set special body ports: counter at index 0, condition output at index 0+ ov::op::v5::Loop::SpecialBodyPorts spec_ports{0, 0};+ loop->set_special_body_ports(spec_ports);++ // Set merged inputs (carried values)+ for (size_t i = 0; i < num_carried; i++) {+ loop->set_merged_input(loop_body_params[i + 1], inputs[i], loop_body_results[i + 1]);+ }++ // Validate and get outputs+ loop->validate_and_infer_types();++ // Get outputs (skip condition result which is index 0)+ OutputVector outputs;+ for (size_t i = 0; i < num_carried; i++) {+ auto out = loop->get_iter_value(loop_body_results[i + 1], -1);+ outputs.push_back(out);+ }++ context.mark_node(loop);++ // In FX, while_loop returns a tuple that is accessed via getitem.+ // We wrap outputs in make_list_construct so getitem can extract individual elements.+ return {context.mark_node(make_list_construct(outputs))};+}+} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex bba8dd6fa81..7e2392f84d7 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -161,6 +161,7 @@ OP_CONVERTER(translate_log2);OP_CONVERTER(translate_log10);OP_CONVERTER(translate_logsumexp);OP_CONVERTER(translate_loop);+OP_CONVERTER(translate_while_loop_fx);OP_CONVERTER(translate_lstm);OP_CONVERTER(translate_masked_fill);OP_CONVERTER(translate_masked_scatter);@@ -1115,6 +1116,8 @@ 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};};diff --git a/tests/layer_tests/pytorch_tests/test_loop.py b/tests/layer_tests/pytorch_tests/test_loop.pyindex 3a1682f73a7..88421e97279 100644--- a/tests/layer_tests/pytorch_tests/test_loop.py+++ b/tests/layer_tests/pytorch_tests/test_loop.py@@ -6,6 +6,91 @@ import pytestimport numpy as npfrom pytorch_layer_test_class import PytorchLayerTest+import torch+++class TestWhileLoopFX(PytorchLayerTest):+ """Tests for torch.while_loop support in FX export (torch.export)."""++ def _prepare_input(self):+ return (np.random.randn(*self.input_shape).astype(np.float32),)++ def create_model_simple_counter(self, num_iterations):+ """Simple while_loop that counts up to num_iterations."""+ class WhileLoopCounter(torch.nn.Module):+ def __init__(self, limit):+ super().__init__()+ self.limit = limit++ def forward(self, x):+ def cond(i, x):+ return i < self.limit++ def body(i, x):+ return i + 1, x + 1++ i = torch.tensor(0)+ _, out = torch.while_loop(cond, body, (i, x))+ return out++ return WhileLoopCounter(num_iterations), None, "while_loop"++ def create_model_accumulator(self):+ """While loop that accumulates a value - with clone to avoid aliasing."""+ class WhileLoopAccumulator(torch.nn.Module):+ def forward(self, x):+ def cond(i, acc, x):+ return i < 5++ def body(i, acc, x):+ # Clone x to avoid aliasing (PyTorch higher order op limitation)+ return i + 1, acc + x, x.clone()++ i = torch.tensor(0)+ acc = torch.zeros_like(x)+ _, result, _ = torch.while_loop(cond, body, (i, acc, x))+ return result++ return WhileLoopAccumulator(), None, "while_loop"++ def create_model_scalar_only(self):+ """While loop with only scalar values (no tensor input needed)."""+ class WhileLoopScalar(torch.nn.Module):+ def forward(self, x):+ def cond(i):+ return i < 10++ def body(i):+ return (i + 1,)++ i = torch.tensor(0)+ (result,) = torch.while_loop(cond, body, (i,))+ # Use x to keep it as an input, but return scalar result+ return result + x.sum() * 0++ return WhileLoopScalar(), None, "while_loop"++ @pytest.mark.parametrize("num_iterations", [1, 3, 5, 10])+ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_while_loop_counter(self, num_iterations, ie_device, precision, ir_version):+ self.input_shape = (2, 4)+ self._test(*self.create_model_simple_counter(num_iterations), ie_device, precision,+ ir_version, trace_model=False, use_torch_export=True)++ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_while_loop_accumulator(self, ie_device, precision, ir_version):+ self.input_shape = (3, 5)+ self._test(*self.create_model_accumulator(), ie_device, precision,+ ir_version, trace_model=False, use_torch_export=True)++ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_while_loop_scalar_only(self, ie_device, precision, ir_version):+ self.input_shape = (2, 3)+ self._test(*self.create_model_scalar_only(), ie_device, precision,+ ir_version, trace_model=False, use_torch_export=True)class TestLoopWithAlias(PytorchLayerTest):