Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PyTorch] Support exported grad-mode and autocast regions without decompositions (#38396)

Maxim Vafin846954b7edb6
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
index 2b224f7fe70..04a9f25db5b 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
@@ -546,6 +546,11 @@ class TorchFXPythonDecoder (BaseFXDecoder):
def get_output_type(self, index):
output = self._raw_output(index)
+ if isinstance(self.pt_module, torch.fx.GraphModule) and isinstance(output, torch.fx.Node):
+ # Graph outputs report the dtype recorded by export, e.g. for bodies of autocast regions.
+ value = output.meta.get("val")
+ if isinstance(value, torch.Tensor) and not value.is_complex() and str(value.dtype) in pt_to_ov_type_map:
+ return OVAny(pt_to_ov_type_map[str(value.dtype)])
return self.get_type_for_value(output)
def get_shape_for_value(self, value):
diff --git a/src/frontends/pytorch/README.md b/src/frontends/pytorch/README.md
index f2f54b2e0df..82c2b148850 100644
--- a/src/frontends/pytorch/README.md
+++ b/src/frontends/pytorch/README.md
@@ -58,6 +58,19 @@ The following extension types are supported:
* `ov::BaseOpExtension` - enable support for a custom operation.
* `ov::detail::SOExtension` - allow support for `ov::BaseOpExtension` extensions loaded from an external library.
+### Context-manager scopes in exported models
+
+OpenVINO performs inference only. `torch.export` represents `torch.no_grad()`,
+`torch.set_grad_enabled()` and `torch.autocast()` regions as
+`wrap_with_set_grad_enabled` and `wrap_with_autocast` operations. Their bodies
+are inlined into the converted graph: gradient mode is ignored, and region
+outputs are converted to the element types recorded by `torch.export`, so an
+enabled autocast region returns the same types as in PyTorch. Precision of
+operations inside the region is selected by the OpenVINO device.
+Outputs of such a region that are its operands or their views keep the alias relation,
+so later in-place operations on them update the operands. This does not require
+`ExportedProgram.run_decompositions()` or an additional trace.
+
## How to Implement Support for a New PyTorch Operation
PyTorch conversion into the OpenVINO opset operations consists of two stages:
diff --git a/src/frontends/pytorch/src/op/wrap_with_context.cpp b/src/frontends/pytorch/src/op/wrap_with_context.cpp
new file mode 100644
index 00000000000..de7c86f2fb6
--- /dev/null
+++ b/src/frontends/pytorch/src/op/wrap_with_context.cpp
@@ -0,0 +1,105 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "translate_session.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::pytorch::op {
+
+using namespace ov::op;
+
+OutputVector translate_wrap_with_context_fx(const NodeContext& context) {
+ // wrap_with_set_grad_enabled(enabled, body, *operands) and
+ // wrap_with_autocast(device_type, dtype, enabled, cache_enabled, body, *operands) run the body under a
+ // context manager. Gradient mode does not change inference semantics, so the body is inlined. Autocast changes
+ // only the precision of operations; outputs are converted to the element types recorded by export.
+ // Decoder inputs are the inlined context arguments followed by the operands.
+ const auto decoder = context.get_decoder();
+ PYTORCH_OP_CONVERSION_CHECK(decoder->get_subgraph_size() == 1,
+ context.get_op_type(),
+ " must have exactly 1 subgraph, got: ",
+ decoder->get_subgraph_size());
+ const auto body_decoder = decoder->get_subgraph_decoder(0);
+ const auto body_inputs = body_decoder->inputs();
+ PYTORCH_OP_CONVERSION_CHECK(context.get_input_size() >= body_inputs.size(),
+ context.get_op_type(),
+ " body expects ",
+ body_inputs.size(),
+ " operands, got: ",
+ context.get_input_size());
+ const auto first_operand = context.get_input_size() - body_inputs.size();
+
+ const auto body = context.convert_subgraph(0);
+ const auto session = context.get_session();
+ const auto aliases = session->m_body_output_aliases;
+ const auto get_operand = [&](size_t body_tensor) {
+ const auto operand = std::find(body_inputs.begin(), body_inputs.end(), body_tensor);
+ PYTORCH_OP_CONVERSION_CHECK(operand != body_inputs.end(),
+ context.get_op_type(),
+ " body references a value which is not its operand.");
+ return first_operand + static_cast<size_t>(operand - body_inputs.begin());
+ };
+
+ const auto num_outputs = body_decoder->num_of_outputs();
+ const auto& results = body->get_results();
+ PYTORCH_OP_CONVERSION_CHECK(results.size() >= num_outputs,
+ context.get_op_type(),
+ " body has fewer outputs than expected.");
+ // Results after the declared outputs hold operands mutated by the body.
+ // Values are read after parameter replacement, so a mutated value which is an operand refers to the parent input.
+ std::vector<std::pair<size_t, std::shared_ptr<v0::Result>>> mutations;
+ for (size_t i = num_outputs; i < results.size(); ++i) {
+ mutations.emplace_back(get_operand(session->decode_tensor_name(results[i]->input_value(0))), results[i]);
+ }
+ std::vector<std::pair<std::shared_ptr<v0::Parameter>, size_t>> parameters;
+ for (const auto& parameter : body->get_parameters()) {
+ parameters.emplace_back(parameter, get_operand(session->decode_tensor_name(parameter->output(0))));
+ }
+
+ const auto body_nodes = body->get_ordered_ops();
+ // Body tensor names index the body graph and must not be decoded as parent tensors.
+ for (const auto& node : body_nodes) {
+ for (auto& output : node->outputs()) {
+ output.set_names({});
+ }
+ }
+ for (const auto& [parameter, operand] : parameters) {
+ parameter->output(0).replace(context.get_input(static_cast<int>(operand)));
+ }
+
+ OutputVector outputs;
+ for (size_t i = 0; i < num_outputs; ++i) {
+ auto output = results[i]->input_value(0);
+ const auto type = simplified_type_interpret(body_decoder->get_output_type(i));
+ if (type.is<element::Type>() && type.as<element::Type>().is_static() &&
+ output.get_element_type() != type.as<element::Type>()) {
+ output = context.mark_node(std::make_shared<v0::Convert>(output, type.as<element::Type>()));
+ }
+ outputs.push_back(output);
+ }
+ for (const auto& [operand, result] : mutations) {
+ context.mutate_input(operand, result->input_value(0));
+ }
+ // Outputs which are views of operands are registered as aliases. The inlined view operations connect them to
+ // the operand, so in-place updates are propagated like for any other view. The current operand value already
+ // includes mutations made by the body.
+ const auto& operand_ids = decoder->inputs();
+ for (const auto& [output_index, root_id] : aliases) {
+ const auto operand = get_operand(root_id);
+ const auto& output = outputs.at(output_index);
+ session->m_tuple_element_aliases[{decoder->output(0), static_cast<int64_t>(output_index)}] = {
+ operand_ids.at(operand),
+ decoder,
+ output,
+ context.get_input(static_cast<int>(operand))};
+ }
+ // The wrapper returns a tuple even for a single value; parent getitem nodes select its elements.
+ return {context.mark_node(make_list_construct(outputs))};
+}
+
+} // namespace ov::frontend::pytorch::op
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index 5d87763f4c0..28db6b42c73 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -169,6 +169,7 @@ OP_CONVERTER(translate_log10);
OP_CONVERTER(translate_logsumexp);
OP_CONVERTER(translate_loop);
OP_CONVERTER(translate_while_loop_fx);
+OP_CONVERTER(translate_wrap_with_context_fx);
OP_CONVERTER(translate_lstm);
OP_CONVERTER(translate_masked_fill);
OP_CONVERTER(translate_masked_scatter);
@@ -983,6 +984,8 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {
// Higher-order operations from torch.export (torch.cond, torch.while_loop, etc.)
{"cond", op::translate_cond_fx},
{"while_loop", op::translate_while_loop_fx},
+ {"wrap_with_autocast", op::translate_wrap_with_context_fx},
+ {"wrap_with_set_grad_enabled", op::translate_wrap_with_context_fx},
};
};
diff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cpp
index 777e32f9aae..5b47ef06f70 100644
--- a/src/frontends/pytorch/src/translate_session.cpp
+++ b/src/frontends/pytorch/src/translate_session.cpp
@@ -35,15 +35,19 @@ class AliasScope {
public:
explicit AliasScope(TranslateSession& session) : m_session(session) {
m_aliases.swap(m_session.m_may_be_alias);
+ m_tuple_element_aliases.swap(m_session.m_tuple_element_aliases);
}
~AliasScope() {
m_aliases.swap(m_session.m_may_be_alias);
+ m_tuple_element_aliases.swap(m_session.m_tuple_element_aliases);
}
private:
TranslateSession& m_session;
decltype(TranslateSession::m_may_be_alias) m_aliases;
+ // Tensor ids are local to a graph, so tuple element aliases are scoped like other aliases.
+ decltype(TranslateSession::m_tuple_element_aliases) m_tuple_element_aliases;
};
// Helper to extract complex part element type from raw type
@@ -329,6 +333,19 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
}
}
#endif
+ if (op_type == "<built-in function getitem>" && has_inputs && !m_may_be_alias.count(fw_tensor_id)) {
+ // Elements of a tuple returned by an inlined subgraph may be views of its operands.
+ if (const auto index_node = ov::util::get_constant_from_source(context.get_input(1))) {
+ auto index = index_node->cast_vector<int64_t>().at(0);
+ if (index < 0) {
+ index += static_cast<int64_t>(get_list_as_outputs(context.get_input(0)).size());
+ }
+ const auto element_alias = m_tuple_element_aliases.find({first_input_id, index});
+ if (element_alias != m_tuple_element_aliases.end()) {
+ m_may_be_alias[fw_tensor_id] = element_alias->second;
+ }
+ }
+ }
(*tensor_map)[fw_tensor_id] = converted_outputs[i];
encode_tensor_name(converted_outputs[i], fw_tensor_id, {node->get_output_debug_name(i)});
}
@@ -395,6 +412,23 @@ std::shared_ptr<Model> TranslateSession::convert_pytorch_model(
OPENVINO_DEBUG("Mutated tensor with id ", tensor_id, " doesn't exist in inputs, skipping.");
}
}
+ if (!external_tensor_map.empty() && !input_model) {
+ // Record declared outputs which are body inputs or their views, so a parent inlining the body keeps the
+ // alias.
+ m_body_output_aliases.clear();
+ for (size_t i = 0; i < pytorch_model->num_of_outputs(); ++i) {
+ auto root = pytorch_model->output(i);
+ for (auto alias = m_may_be_alias.find(root);
+ alias != m_may_be_alias.end() && alias->second.element_ids.empty() &&
+ alias->second.base_id != root;
+ alias = m_may_be_alias.find(root)) {
+ root = alias->second.base_id;
+ }
+ if (param_names.count(root)) {
+ m_body_output_aliases[i] = root;
+ }
+ }
+ }
if (!external_tensor_map.empty()) {
// for internal bodies we want to remove all extra inputs that were created, but not used
parameters->erase(std::remove_if(parameters->begin(),
@@ -659,7 +693,7 @@ Output<Node> TranslateSession::get_reverseprop_op(const std::shared_ptr<TorchDec
}
#endif
// Create PtFrameworkNode representing unconverted backprop operation
- return std::make_shared<PtFrameworkNode>(node, OutputVector{value}, 1, true);
+ return std::make_shared<PtFrameworkNode>(node, OutputVector{value}, 1, true, true);
}
} // namespace ov::frontend::pytorch
diff --git a/src/frontends/pytorch/src/translate_session.hpp b/src/frontends/pytorch/src/translate_session.hpp
index 006087adfb5..2564f7bcf75 100644
--- a/src/frontends/pytorch/src/translate_session.hpp
+++ b/src/frontends/pytorch/src/translate_session.hpp
@@ -56,6 +56,11 @@ public:
std::vector<size_t> element_ids;
};
std::map<size_t, AliasInfo> m_may_be_alias;
+ // Aliases of tuple elements returned by inlined subgraphs, keyed by tuple tensor id and element index and
+ // registered when an element is selected.
+ std::map<std::pair<size_t, int64_t>, AliasInfo> m_tuple_element_aliases;
+ // Declared outputs of the last converted internal body which are views of its inputs: output index to input id.
+ std::map<size_t, size_t> m_body_output_aliases;
OutputVector convert_node(const NodeContext& context);
diff --git a/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py b/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py
new file mode 100644
index 00000000000..a2abf3d86cd
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py
@@ -0,0 +1,299 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import operator
+from unittest.mock import patch
+
+import numpy as np
+import pytest
+import torch
+from packaging import version
+
+from openvino import Core, Type, convert_model
+from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+
+pytestmark = [
+ pytest.mark.precommit,
+ pytest.mark.skipif(version.parse(torch.__version__) < version.parse("2.9"),
+ reason="Requires grad-mode wrappers in torch.export"),
+]
+
+
+def convert_without_decompositions(exported):
+ original_graphs = {
+ name: str(module.graph)
+ for name, module in exported.graph_module.named_modules()
+ if isinstance(module, torch.fx.GraphModule)
+ }
+ with patch.object(torch.export.ExportedProgram, "run_decompositions",
+ side_effect=AssertionError("Conversion must not run decompositions")):
+ converted = convert_model(exported)
+ for name, graph in original_graphs.items():
+ assert str(exported.graph_module.get_submodule(name).graph) == graph
+ return Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+
+
[email protected]("grad_enabled", [False, True])
[email protected]("multiple_outputs", [False, True])
+def test_export_grad_mode(grad_enabled, multiple_outputs):
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("inv_freq", torch.arange(1, 5, dtype=torch.float32))
+
+ @torch.set_grad_enabled(grad_enabled)
+ def rotary(self, x, positions):
+ frequencies = self.inv_freq[None, :, None] @ positions[:, None, :].float()
+ frequencies = frequencies.transpose(1, 2)
+ return frequencies.cos() + x, frequencies.sin() + x
+
+ def forward(self, data):
+ cosine, sine = self.rotary(data["x"], data["positions"])
+ return (cosine, sine) if multiple_outputs else sine
+
+ model = Model().eval()
+ data = {"x": torch.ones(2, 8, 4), "positions": torch.arange(8).expand(2, -1)}
+ batch, sequence = torch.export.Dim("batch"), torch.export.Dim("sequence")
+ dynamic = {"data": {key: {0: batch, 1: sequence} for key in data}}
+ with torch.set_grad_enabled(not grad_enabled):
+ exported = torch.export.export(model, (data,), dynamic_shapes=dynamic)
+ assert any(str(node.target) == "wrap_with_set_grad_enabled" for node in exported.graph.nodes)
+ compiled = convert_without_decompositions(exported)
+ for batch_size, sequence_length in [(2, 8), (3, 5)]:
+ inputs = {
+ "x": torch.ones(batch_size, sequence_length, 4),
+ "positions": torch.arange(sequence_length).expand(batch_size, -1),
+ }
+ with torch.no_grad():
+ expected = model(inputs)
+ if not multiple_outputs:
+ expected = (expected,)
+ actual = compiled([value.numpy() for value in inputs.values()])
+ assert len(actual) == len(expected)
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value.numpy(), atol=1e-5, rtol=1e-5)
+
+
+def test_export_grad_mode_mutations():
+ class Model(torch.nn.Module):
+ @torch.no_grad()
+ def update(self, x):
+ view = x[:, 1:]
+ view.add_(2)
+ with torch.enable_grad():
+ before = view.sin()
+ return view, before
+
+ def forward(self, x):
+ x = x.clone()
+ view, before = self.update(x)
+ view.add_(1)
+ return x, view, before
+
+ model = Model().eval()
+ data = torch.arange(12, dtype=torch.float32).reshape(3, 4)
+ with torch.enable_grad():
+ exported = torch.export.export(model, (data,))
+ wrappers = [node for node in exported.graph.nodes
+ if str(node.target) == "wrap_with_set_grad_enabled"]
+ assert wrappers
+ compiled = convert_without_decompositions(exported)
+ expected = model(data)
+ actual = compiled([data.numpy()])
+ assert len(actual) == len(expected)
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value.numpy(), atol=1e-5, rtol=1e-5)
+
+
[email protected]("mutate_base", [False, True])
+def test_export_autocast_returns_view(mutate_base):
+ class Model(torch.nn.Module):
+ def forward(self, x):
+ x = x.clone()
+ with torch.autocast("cpu", enabled=False):
+ view = x.transpose(0, 1)[1:]
+ view.add_(2)
+ before = view * 2
+ if mutate_base:
+ x.mul_(3)
+ else:
+ view.add_(1)
+ return x, view, before
+
+ model = Model().eval()
+ data = torch.arange(12, dtype=torch.float32).reshape(3, 4)
+ exported = torch.export.export(model, (data,))
+ assert any(str(node.target) == "wrap_with_autocast" for node in exported.graph.nodes)
+ compiled = convert_without_decompositions(exported)
+ expected = model(data)
+ actual = compiled([data.numpy()])
+ assert len(actual) == len(expected)
+ for index, value in enumerate(expected):
+ np.testing.assert_allclose(actual[index], value.numpy(), atol=1e-5, rtol=1e-5)
+
+
+def test_export_enabled_autocast_output_types():
+ class Model(torch.nn.Module):
+ def forward(self, x, w):
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ y = x @ w
+ z = y + x
+ return y, z
+
+ model = Model().eval()
+ data = (torch.randn(4, 4), torch.randn(4, 4))
+ exported = torch.export.export(model, data)
+ assert any(str(node.target) == "wrap_with_autocast" for node in exported.graph.nodes)
+ ov_model = convert_model(exported)
+ expected = model(*data)
+ assert [output.get_element_type() for output in ov_model.outputs] == [Type.bf16, Type.f32]
+ actual = Core().compile_model(ov_model, "CPU")([value.numpy() for value in data])
+ # bf16 results are returned as raw 16-bit data.
+ y = (actual[0].view(np.uint16).astype(np.uint32) << 16).view(np.float32)
+ np.testing.assert_allclose(y, expected[0].float().numpy(), atol=0.05, rtol=0.02)
+ np.testing.assert_allclose(actual[1], expected[1].numpy(), atol=0.05, rtol=0.02)
+
+
+def test_export_grad_mode_returns_view_and_clone():
+ class Model(torch.nn.Module):
+ def forward(self, x):
+ x = x.clone()
+ with torch.no_grad():
+ view = x[1:]
+ copy = view.clone()
+ # The clone is converted to the same value as the view, but must not alias the operand.
+ copy.add_(1)
+ return x, view, copy
+
+ model = Model().eval()
+ data = torch.arange(4, dtype=torch.float32)
+ exported = torch.export.export(model, (data,))
+ assert any(str(node.target) == "wrap_with_set_grad_enabled" for node in exported.graph.nodes)
+ compiled = convert_without_decompositions(exported)
+ expected = model(data)
+ actual = compiled([data.numpy()])
+ for index, value in enumerate(expected):
+ np.testing.assert_array_equal(actual[index], value.numpy())
+
+
+def test_export_grad_mode_unsupported_view_mutation():
+ class Model(torch.nn.Module):
+ def forward(self, x):
+ x = x.clone()
+ with torch.no_grad():
+ view = x.diagonal()
+ view.add_(1)
+ return x
+
+ data = torch.arange(9, dtype=torch.float32).reshape(3, 3)
+ exported = torch.export.export(Model().eval(), (data,))
+ # The mutation cannot be propagated to the operand, so conversion must fail instead of dropping it.
+ with pytest.raises(Exception, match="wrap_with_set_grad_enabled_reverseprop"):
+ convert_model(exported)
+
+
+def test_fx_nested_grad_mode():
+ from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled
+
+ body_graph = torch.fx.Graph()
+ data = body_graph.placeholder("x")
+ offset = body_graph.get_attr("offset")
+ result = body_graph.call_function(torch.ops.aten.add.Tensor, (data, offset))
+ body_graph.output((result,))
+ body = torch.fx.GraphModule({"offset": torch.tensor([2.0, 3.0])}, body_graph)
+
+ def wrap(module, enabled):
+ graph = torch.fx.Graph()
+ data = graph.placeholder("x")
+ body_node = graph.get_attr("body")
+ result = graph.call_function(wrap_with_set_grad_enabled, (enabled, body_node, data))
+ graph.output(result)
+ return torch.fx.GraphModule({"body": module}, graph)
+
+ model = wrap(wrap(body, False), True)
+ original = str(model.graph)
+ data = torch.ones(2)
+ with patch.object(torch.export.ExportedProgram, "run_decompositions",
+ side_effect=AssertionError("Conversion must not run decompositions")):
+ decoder = TorchFXPythonDecoder(model, input_shapes=[data.shape], input_types=[data.dtype])
+ converted = convert_model(decoder)
+ compiled = Core().compile_model(converted, "CPU")
+ actual = compiled([data.numpy()])
+ np.testing.assert_array_equal(actual[0], model(data)[0].numpy())
+ assert str(model.graph) == original
+
+
+def test_fx_grad_mode_returns_operand():
+ from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled
+
+ body_graph = torch.fx.Graph()
+ body_graph.output((body_graph.placeholder("x"),))
+ body = torch.fx.GraphModule({}, body_graph)
+
+ # torch.export does not return operands from the body, but FX graphs may.
+ graph = torch.fx.Graph()
+ data = graph.placeholder("x")
+ data = graph.call_function(torch.ops.aten.clone.default, (data,))
+ wrapped = graph.call_function(wrap_with_set_grad_enabled, (False, graph.get_attr("body"), data))
+ returned = graph.call_function(operator.getitem, (wrapped, 0))
+ graph.call_function(torch.ops.aten.add_.Tensor, (returned, 1))
+ graph.output((data,))
+ model = torch.fx.GraphModule({"body": body}, graph)
+
+ data = torch.zeros(2)
+ decoder = TorchFXPythonDecoder(model, input_shapes=[data.shape], input_types=[data.dtype])
+ compiled = Core().compile_model(convert_model(decoder), "CPU")
+ np.testing.assert_array_equal(compiled([data.numpy()])[0], model(data)[0].numpy())
+
+
+def _fx_wrap(graph, body_name, data):
+ from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled
+
+ return graph.call_function(wrap_with_set_grad_enabled, (False, graph.get_attr(body_name), data))
+
+
+def _convert_fx(model, data):
+ decoder = TorchFXPythonDecoder(model, input_shapes=[data.shape], input_types=[data.dtype])
+ return Core().compile_model(convert_model(decoder), "CPU")
+
+
+def test_fx_grad_mode_negative_index():
+ body_graph = torch.fx.Graph()
+ body_data = body_graph.placeholder("x")
+ body_graph.output((body_graph.call_function(torch.ops.aten.slice.Tensor, (body_data, 0, 1)),))
+ body = torch.fx.GraphModule({}, body_graph)
+
+ graph = torch.fx.Graph()
+ data = graph.call_function(torch.ops.aten.clone.default, (graph.placeholder("x"),))
+ view = graph.call_function(operator.getitem, (_fx_wrap(graph, "body", data), -1))
+ graph.call_function(torch.ops.aten.add_.Tensor, (view, 1))
+ graph.output((data,))
+ model = torch.fx.GraphModule({"body": body}, graph)
+
+ data = torch.zeros(3)
+ np.testing.assert_array_equal(_convert_fx(model, data)([data.numpy()])[0], model(data)[0].numpy())
+
+
+def test_fx_grad_mode_nested_alias_scope():
+ view_graph = torch.fx.Graph()
+ view_data = view_graph.placeholder("x")
+ view_graph.output((view_graph.call_function(torch.ops.aten.slice.Tensor, (view_data, 0, 1)),))
+ view_body = torch.fx.GraphModule({}, view_graph)
+
+ # The nested wrapper has the same graph-local position as the outer one, but the outer element is a copy.
+ body_graph = torch.fx.Graph()
+ body_data = body_graph.placeholder("x")
+ body_graph.call_function(operator.getitem, (_fx_wrap(body_graph, "view_body", body_data), 0))
+ body_graph.output((body_graph.call_function(torch.ops.aten.clone.default, (body_data,)),))
+ body = torch.fx.GraphModule({"view_body": view_body}, body_graph)
+
+ graph = torch.fx.Graph()
+ data = graph.placeholder("x")
+ copy = graph.call_function(operator.getitem, (_fx_wrap(graph, "body", data), 0))
+ graph.call_function(torch.ops.aten.add_.Tensor, (copy, 1))
+ graph.output((data,))
+ model = torch.fx.GraphModule({"body": body}, graph)
+
+ data = torch.zeros(3)
+ np.testing.assert_array_equal(_convert_fx(model, data)([data.numpy()])[0], model(data.clone())[0].numpy())