Skip to content

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

[PyTorch] Convert exported masking with decoder-side vmap lowering (#39283)

Maxim Vafin8f0a334dfb4b
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 eeb4c73d436..9470aad6b57 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
@@ -25,6 +25,7 @@ from openvino import PartialShape, Type as OVType, OVAny, Shape
from openvino.frontend.pytorch.utils import (
make_constant, fetch_attr, pt_to_ov_type_map, pt_to_scalar_type_map,
torch_tensor_to_ov_const)
+from openvino.frontend.pytorch.vmap_lowering import lower_vmap_regions
logger = logging.getLogger(__name__)
@@ -223,6 +224,10 @@ class TorchFXPythonDecoder (BaseFXDecoder):
input_types=None, dynamic_shapes=False,
op_type_mapping=None, output_names=None):
super().__init__(mark_node_callback)
+ if isinstance(pt_module, torch.fx.GraphModule):
+ lowered = lower_vmap_regions(pt_module)
+ fx_gm = lowered if fx_gm is pt_module else fx_gm
+ pt_module = lowered
self.pt_module = pt_module
self.fx_gm = fx_gm if fx_gm is not None else pt_module
self._module_extension_target_ops = op_type_mapping or {}
@@ -530,8 +535,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):
if arg.op != "get_attr":
return False, None
- # Get the attribute from the root graph module
- subgraph = getattr(self.fx_gm, arg.target, None)
+ subgraph = fetch_attr(self.fx_gm, arg.target)
if subgraph is not None and isinstance(subgraph, torch.fx.GraphModule):
return True, subgraph
# Also handle callables with graph attribute (lambda-wrapped GraphModules)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/vmap_lowering.py b/src/bindings/python/src/openvino/frontend/pytorch/vmap_lowering.py
new file mode 100644
index 00000000000..d6bc465188e
--- /dev/null
+++ b/src/bindings/python/src/openvino/frontend/pytorch/vmap_lowering.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+# mypy: ignore-errors
+
+from contextlib import ExitStack
+
+import torch
+
+
+def _predispatch_name(node):
+ if node.op == "call_function" and getattr(node.target, "__module__", None) == "torch._functorch.predispatch":
+ return node.target.__name__
+ return ""
+
+
+def _region(start):
+ region = []
+ depth = 0
+ node = start
+ while node.op != "output":
+ name = _predispatch_name(node)
+ depth += (name == "_vmap_increment_nesting") - (name == "_vmap_decrement_nesting")
+ region.append(node)
+ if depth == 0:
+ return region
+ node = node.next
+ raise RuntimeError("Unbalanced vmap nesting in exported graph.")
+
+
+def _check(body):
+ for module in body.modules():
+ if not isinstance(module, torch.fx.GraphModule):
+ continue
+ for node in module.graph.nodes:
+ if _predispatch_name(node) == "_vmap_increment_nesting" and node.args[1] != "error":
+ raise RuntimeError("vmap supports only randomness='error'.")
+ if isinstance(node.target, torch._ops.OpOverload):
+ if node.target._schema.is_mutable:
+ raise RuntimeError("Mutation inside vmap is not supported.")
+ if torch.Tag.nondeterministic_seeded in node.target.tags:
+ raise RuntimeError("Random operations inside vmap are not supported.")
+
+
+def _trace(body, examples):
+ """Trace body with vectorized ATen operations, failing instead of specializing symbolic shapes."""
+ from torch.fx.experimental.proxy_tensor import make_fx
+
+ _check(body)
+
+ def run(*args):
+ level = torch._C._functorch.maybe_current_level()
+ try:
+ return torch.fx.Interpreter(body).run(*args)
+ finally:
+ while torch._C._functorch.maybe_current_level() != level:
+ torch._C._functorch._vmap_decrement_nesting()
+
+ shape_envs = {getattr(example.fake_mode if isinstance(example, torch.Tensor) else example.node, "shape_env", None)
+ for example in examples} - {None}
+ with ExitStack() as stack:
+ for shape_env in shape_envs:
+ stack.enter_context(shape_env.error_on_new_guards())
+ return make_fx(run, tracing_mode="fake", _allow_non_fake_inputs=True)(*examples)
+
+
+def _preserve_output_aliases(lowered, outputs):
+ from torch.utils._pytree import tree_map
+
+ traced_outputs = next(node for node in lowered.graph.nodes if node.op == "output").args[0]
+ aliases = [(traced.meta.get("val"), original.meta.get("val"))
+ for traced, original in zip(traced_outputs, outputs)]
+ aliases = [(traced, original) for traced, original in aliases
+ if isinstance(traced, torch.Tensor) and isinstance(original, torch.Tensor)]
+
+ def reconcile(value):
+ if isinstance(value, torch.Tensor):
+ for traced, original in aliases:
+ if torch._C._is_alias_of(value, traced):
+ # Aliases can have different dtypes, so align storage offsets in bytes.
+ offset_bytes = (value.storage_offset() * value.element_size()
+ - traced.storage_offset() * traced.element_size()
+ + original.storage_offset() * original.element_size())
+ return value.new_empty((0,)).set_(
+ original.untyped_storage(), offset_bytes // value.element_size(), value.shape, value.stride())
+ return value
+
+ for node in lowered.graph.nodes:
+ if "val" in node.meta:
+ node.meta["val"] = tree_map(reconcile, node.meta["val"])
+
+
+def lower_vmap_regions(module):
+ """Return a copy of module with each torch.vmap region replaced by its vectorized trace.
+
+ The module itself is returned when it has no vmap regions.
+ """
+ if not any(_predispatch_name(node) == "_vmap_increment_nesting" for node in module.graph.nodes):
+ return module
+
+ graph = torch.fx.Graph()
+ graph.set_codegen(module.graph._codegen)
+ graph.output(graph.graph_copy(module.graph, {}))
+ result = torch.fx.GraphModule(module, graph)
+ ordinal = 0
+ start = next(iter(graph.nodes))
+ while start.op != "output":
+ if _predispatch_name(start) != "_vmap_increment_nesting":
+ start = start.next
+ continue
+ region = _region(start)
+ region_set = set(region)
+ operands = list(dict.fromkeys(value for node in region for value in node.all_input_nodes
+ if value not in region_set and value.op != "get_attr"))
+ outputs = [node for node in region if any(user not in region_set for user in node.users)]
+ if any("val" not in operand.meta for operand in operands):
+ raise RuntimeError("vmap lowering requires FX metadata for the region operands.")
+ body_graph = torch.fx.Graph()
+ values = {operand: body_graph.placeholder(operand.name) for operand in operands}
+ for node in region:
+ for operand in node.all_input_nodes:
+ if operand not in values:
+ values[operand] = body_graph.node_copy(operand, values.__getitem__)
+ values[node] = body_graph.node_copy(node, values.__getitem__)
+ body_graph.output(tuple(values[node] for node in outputs))
+ lowered = _trace(torch.fx.GraphModule(result, body_graph), [operand.meta["val"] for operand in operands])
+ _preserve_output_aliases(lowered, outputs)
+
+ while hasattr(result, f"_ov_vmap_{ordinal}"):
+ ordinal += 1
+ prefix = f"_ov_vmap_{ordinal}"
+ ordinal += 1
+ result.add_submodule(prefix, lowered)
+ replacement = dict(zip((node for node in lowered.graph.nodes if node.op == "placeholder"), operands))
+ with graph.inserting_before(start):
+ for node in lowered.graph.nodes:
+ if node.op == "output":
+ for original, value in zip(outputs, torch.fx.map_arg(node.args[0], replacement.__getitem__)):
+ original.replace_all_uses_with(value)
+ elif node.op == "get_attr":
+ replacement[node] = graph.get_attr(f"{prefix}.{node.target}")
+ replacement[node].meta = node.meta.copy()
+ elif node.op != "placeholder":
+ replacement[node] = graph.node_copy(node, replacement.__getitem__)
+ start = region[-1].next
+ for node in reversed(region):
+ graph.erase_node(node)
+ for node in list(graph.nodes):
+ if _predispatch_name(node) == "lazy_load_decompositions" and not node.users:
+ graph.erase_node(node)
+ graph.lint()
+ result.recompile()
+ return result
diff --git a/src/frontends/pytorch/README.md b/src/frontends/pytorch/README.md
index 615015e1689..325bbca5311 100644
--- a/src/frontends/pytorch/README.md
+++ b/src/frontends/pytorch/README.md
@@ -71,6 +71,15 @@ Outputs of such a region that are its operands or their views keep the alias rel
so later in-place operations on them update the operands. This does not require
`ExportedProgram.run_decompositions()` or an additional trace.
+### Exported `torch.vmap` regions
+
+The FX decoder replaces each exported `torch.vmap` region with its vectorized ATen
+operations, traced from the tensor and symbolic metadata of the region operands.
+Operations inside the region, including `flat_apply` calls, are traced as well.
+This region trace runs after export for both models and supplied exported graphs.
+The original graph stays unchanged, no OpenVINO loops are introduced, and the
+trace must not introduce new shape guards.
+
## 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/cumsum.cpp b/src/frontends/pytorch/src/op/cumsum.cpp
index 9c0afb28158..dbbec8df481 100644
--- a/src/frontends/pytorch/src/op/cumsum.cpp
+++ b/src/frontends/pytorch/src/op/cumsum.cpp
@@ -4,6 +4,7 @@
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
#include "openvino/op/cum_sum.hpp"
#include "utils.hpp"
@@ -18,6 +19,11 @@ OutputVector translate_cumsum(const NodeContext& context) {
auto dim = context.get_input(1);
if (!context.input_is_none(2)) {
x = apply_dtype(context, 2, x);
+ } else if (!context.input_is_none(3)) {
+ x = context.mark_node(std::make_shared<v1::ConvertLike>(x, context.get_input(3)));
+ } else if (get_input_element_type(context, 0) == element::boolean) {
+ // PyTorch cumsum promotes boolean inputs to int64 by default.
+ x = context.mark_node(std::make_shared<v0::Convert>(x, element::i64));
}
auto result = context.mark_node(std::make_shared<v0::CumSum>(x, dim));
if (!context.input_is_none(3)) {
@@ -34,6 +40,8 @@ OutputVector translate_cumsum_fx(const NodeContext& context) {
if (context.has_attribute("dtype")) {
auto dtype = context.get_attribute<element::Type>("dtype");
x = context.mark_node(std::make_shared<v0::Convert>(x, dtype));
+ } else if (get_input_element_type(context, 0) == element::boolean) {
+ x = context.mark_node(std::make_shared<v0::Convert>(x, element::i64));
}
auto result = context.mark_node(std::make_shared<v0::CumSum>(x, dim));
return {result};
diff --git a/src/frontends/pytorch/src/op/diff.cpp b/src/frontends/pytorch/src/op/diff.cpp
new file mode 100644
index 00000000000..c772ae0f273
--- /dev/null
+++ b/src/frontends/pytorch/src/op/diff.cpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <limits>
+
+#include "openvino/frontend/complex_type_mark.hpp"
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "openvino/op/convert_promote_types.hpp"
+#include "openvino/op/floor_mod.hpp"
+#include "openvino/op/logical_xor.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/subtract.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::pytorch::op {
+using namespace ov::op;
+
+OutputVector translate_diff(const NodeContext& context) {
+ num_inputs_check(context, 1, 6, true);
+ auto value = context.get_input(0);
+ const auto order = context.input_is_none(1) ? 1 : context.const_input<int64_t>(1);
+ PYTORCH_OP_CONVERSION_CHECK(order >= 0, "diff order must be nonnegative.");
+ const auto finish = [&](Output<Node> result) -> OutputVector {
+ if (!context.input_is_none(5)) {
+ result = ComplexTypeMark::convert_like(context, result, context.get_input(5));
+ context.mutate_input(5, result);
+ }
+ return {result};
+ };
+ if (order == 0) {
+ return finish(value);
+ }
+ const auto get_value = [&](int index) -> Output<Node> {
+ auto input = context.get_input(index);
+ const auto dtype = get_input_element_type(context, index);
+ if (input.get_element_type().is_dynamic() && dtype.is_static() &&
+ !ov::is_type<ComplexTypeMark>(input.get_node())) {
+ input = context.mark_node(std::make_shared<v0::Convert>(input, dtype));
+ }
+ return input;
+ };
+ value = get_value(0);
+ auto axis = context.input_is_none(2) ? -1 : context.const_input<int64_t>(2);
+ OutputVector values;
+ if (!context.input_is_none(3)) {
+ values.push_back(get_value(3));
+ }
+ values.push_back(value);
+ if (!context.input_is_none(4)) {
+ values.push_back(get_value(4));
+ }
+ const auto complex = std::any_of(values.begin(), values.end(), [](const auto& input) {
+ return ov::is_type<ComplexTypeMark>(input.get_node());
+ });
+ if (complex) {
+ for (auto& input : values) {
+ const auto marker = ov::as_type_ptr<ComplexTypeMark>(input.get_node_shared_ptr());
+ PYTORCH_OP_CONVERSION_CHECK(marker, "diff does not support mixing complex and real inputs.");
+ input = marker->get_data();
+ }
+ if (axis < 0) {
+ --axis;
+ }
+ }
+ value = values.front();
+ for (size_t i = 1; i < values.size(); ++i) {
+ value = context.mark_node(std::make_shared<v14::ConvertPromoteTypes>(value, values[i], true))->output(0);
+ }
+ if (values.size() > 1) {
+ // Convert each value directly to the promoted type to avoid intermediate rounding.
+ for (auto& input : values) {
+ input = context.mark_node(std::make_shared<v1::ConvertLike>(input, value));
+ }
+ value = context.mark_node(std::make_shared<v0::Concat>(values, axis));
+ }
+ const auto unsigned_byte = value.get_element_type() == element::u8;
+ std::shared_ptr<Node> modulus;
+ if (unsigned_byte) {
+ value = context.mark_node(std::make_shared<v0::Convert>(value, element::i32));
+ modulus = context.mark_node(v0::Constant::create(element::i32, Shape{}, {256}));
+ }
+ const auto axes = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {axis}));
+ const auto zero = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {0}));
+ const auto one = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {1}));
+ const auto minus_one = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-1}));
+ const auto end =
+ context.mark_node(v0::Constant::create(element::i64, Shape{1}, {std::numeric_limits<int64_t>::max()}));
+ for (int64_t i = 0; i < order; ++i) {
+ auto left = context.mark_node(std::make_shared<v8::Slice>(value, zero, minus_one, one, axes));
+ auto right = context.mark_node(std::make_shared<v8::Slice>(value, one, end, one, axes));
+ if (value.get_element_type() == element::boolean) {
+ value = context.mark_node(std::make_shared<v1::LogicalXor>(right, left));
+ } else {
+ value = context.mark_node(std::make_shared<v1::Subtract>(right, left));
+ if (unsigned_byte) {
+ value = context.mark_node(std::make_shared<v1::FloorMod>(value, modulus));
+ }
+ }
+ }
+ if (unsigned_byte) {
+ value = context.mark_node(std::make_shared<v0::Convert>(value, element::u8));
+ }
+ if (complex) {
+ value = context.mark_node(std::make_shared<ComplexTypeMark>(value, value.get_element_type()));
+ }
+ return finish(value);
+}
+} // namespace ov::frontend::pytorch::op
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index df7d779d14b..9147e554157 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -75,6 +75,7 @@ OP_CONVERTER(translate_constant_pad_nd);
OP_CONVERTER(translate_copy_);
OP_CONVERTER(translate_cross);
OP_CONVERTER(translate_cumsum);
+OP_CONVERTER(translate_diff);
OP_CONVERTER(translate_deform_conv);
OP_CONVERTER(translate_derive_index);
OP_CONVERTER(translate_dim);
@@ -501,6 +502,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::cosh_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Cosh>>},
{"aten::cross", op::translate_cross},
{"aten::cumsum", op::translate_cumsum},
+ {"aten::diff", op::translate_diff},
{"aten::det", op::translate_linalg_det},
{"aten::detach", op::skip_node},
{"aten::dequantize", op::skip_node}, // we convert model to fp32 using FQ, so dequantization is not needed
diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cpp
index 96a025f99cb..94319880a7b 100644
--- a/src/frontends/pytorch/src/utils.cpp
+++ b/src/frontends/pytorch/src/utils.cpp
@@ -684,6 +684,20 @@ Output<Node> get_input_with_floating_type(const NodeContext& context, size_t idx
return x;
}
+element::Type get_input_element_type(const NodeContext& context, size_t idx) {
+ auto type = context.get_input(static_cast<int>(idx)).get_element_type();
+ if (type.is_dynamic()) {
+ type = context.get_input_from_visible_context(idx).get_element_type();
+ }
+ if (type.is_dynamic()) {
+ const auto decoded = simplified_type_interpret(context.get_input_type(idx));
+ if (decoded.is<element::Type>()) {
+ type = decoded.as<element::Type>();
+ }
+ }
+ return type;
+}
+
Output<Node> trunc_toward_zero(const NodeContext& context, const Output<Node>& x) {
if (x.get_element_type().is_static() && x.get_element_type().is_integral_number()) {
return x;
@@ -1220,6 +1234,11 @@ bool index_tensor_on_list(ov::pass::NodeRegistry& rg,
cum_adv_index = rg.make<v1::Add>(cum_adv_index, adv_index);
multiplier = rg.make<v1::Multiply>(multiplier, input_dims->output(input_id));
}
+ if (adv_idx_count > 1 && std::all_of(advanced_ids.begin(), advanced_ids.end(), [&](size_t id) {
+ return masked_indices[id].get_partial_shape().rank() == 0;
+ })) {
+ cum_adv_index = rg.make<v0::Squeeze>(cum_adv_index, zero);
+ }
std::shared_ptr<Node> gather = rg.make<v8::Gather>(flatten_input, cum_adv_index, zero);
OutputVector concat_dims;
// check if all advanced indices are consecutive.
diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hpp
index 9a64ca27e74..e4672b9354f 100644
--- a/src/frontends/pytorch/src/utils.hpp
+++ b/src/frontends/pytorch/src/utils.hpp
@@ -154,6 +154,9 @@ Output<Node> try_constfold(const Output<Node>& x);
Output<Node> get_input_with_floating_type(const NodeContext& context, size_t idx);
+/// \brief Returns the input element type, falling back to the visible context and the decoder type when it is dynamic.
+element::Type get_input_element_type(const NodeContext& context, size_t idx);
+
/// \brief Rounds toward zero, keeping infinities and NaN. Integer inputs are returned unchanged.
Output<Node> trunc_toward_zero(const NodeContext& context, const Output<Node>& x);
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_cumsum.py b/tests/layer_tests/py_frontend_tests/test_torch_cumsum.py
new file mode 100644
index 00000000000..300ac4ef03e
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_cumsum.py
@@ -0,0 +1,73 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+
+
+pytestmark = [pytest.mark.precommit, pytest.mark.nightly]
+
+
[email protected]("capture", ["export", "script"])
[email protected]("dtype", [torch.bool, torch.int64])
[email protected]("explicit_dtype", [False, True])
+def test_cumsum_dtype(capture, dtype, explicit_dtype, monkeypatch):
+ class Model(torch.nn.Module):
+ __constants__ = ["explicit_dtype"]
+
+ def __init__(self):
+ super().__init__()
+ self.explicit_dtype = explicit_dtype
+
+ def forward(self, x):
+ if self.explicit_dtype:
+ return torch.cumsum(x, -1, dtype=torch.float32)
+ return torch.cumsum(x, -1)
+
+ model = Model().eval()
+ x = torch.tensor([[0, 1, 1, 0, 1], [1, 0, 1, 1, 1]], dtype=dtype)
+ program = torch.export.export(model, (x,)) if capture == "export" else torch.jit.script(model)
+ monkeypatch.setattr(torch.export.ExportedProgram, "run_decompositions",
+ lambda *args, **kwargs: pytest.fail("Conversion must not run decompositions"))
+ converted = ov.convert_model(program, example_input=(x,) if capture == "script" else None)
+ expected = model(x).numpy()
+ assert converted.output(0).get_element_type().to_dtype() == expected.dtype
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ np.testing.assert_array_equal(compiled(x.numpy())[0], expected)
+
+
[email protected]("dtype", [torch.bool, torch.int32])
+def test_cumsum_out_dtype(dtype):
+ class Model(torch.nn.Module):
+ def forward(self, x, out):
+ return torch.cumsum(x, -1, out=out)
+
+ x = torch.tensor([0, 1, 1, 0, 1], dtype=dtype)
+ out = torch.zeros(5, dtype=torch.int32)
+ model = Model()
+ converted = ov.convert_model(torch.jit.script(model), example_input=(x, out))
+ assert converted.output(0).get_element_type() == ov.Type.i32
+ compiled = ov.Core().compile_model(converted, "CPU")
+ inputs = {port: tensor.numpy() for port, tensor in zip(compiled.inputs, (x, out))}
+ np.testing.assert_array_equal(compiled(inputs)[0], model(x, out).numpy())
+
+
[email protected]("dtype", [torch.float32, torch.bool])
+def test_cumsum_scripted_branch_dtype(dtype):
+ class Model(torch.nn.Module):
+ def forward(self, x, condition):
+ if condition:
+ return torch.cumsum(x, -1)
+ return torch.cumsum(x, 0)
+
+ x = torch.tensor([[0.25, 0.5, 0.75], [1.25, 1.5, 1.75]], dtype=dtype)
+ model = Model()
+ converted = ov.convert_model(torch.jit.script(model), example_input=(x, torch.tensor(True)))
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for condition in (False, True):
+ expected = model(x, torch.tensor(condition)).numpy()
+ actual = compiled([x.numpy(), np.array(condition)])[0]
+ assert actual.dtype == expected.dtype
+ np.testing.assert_array_equal(actual, expected)
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_diff.py b/tests/layer_tests/py_frontend_tests/test_torch_diff.py
new file mode 100644
index 00000000000..bfe7d45564e
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_diff.py
@@ -0,0 +1,207 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+
+
+class Diff(torch.nn.Module):
+ __constants__ = ["order", "axis", "prepend", "append"]
+
+ def __init__(self, order, axis, prepend, append):
+ super().__init__()
+ self.order = order
+ self.axis = axis
+ self.prepend = prepend
+ self.append = append
+
+ def forward(self, x, before, after):
+ return torch.diff(x, n=self.order, dim=self.axis,
+ prepend=before if self.prepend else None,
+ append=after if self.append else None)
+
+
[email protected]("capture", ["export", "script"])
[email protected]("dtype", [torch.float32, torch.int64, torch.uint8, torch.bool])
[email protected]("order,axis,prepend,append", [
+ (0, -1, True, True),
+ (1, -1, False, False),
+ (2, 0, False, False),
+ (1, 1, True, False),
+ (2, -1, True, True),
+ (5, -1, False, False),
+])
+def test_torch_diff(capture, dtype, order, axis, prepend, append, monkeypatch):
+ model = Diff(order, axis, prepend, append).eval()
+ x = torch.arange(12).reshape(3, 4).to(dtype)
+ if dtype == torch.uint8:
+ x = torch.tensor([[255, 0, 1, 128], [2, 250, 3, 0], [240, 4, 128, 1]], dtype=dtype)
+ shape = list(x.shape)
+ shape[axis] = 2
+ before = torch.ones(shape, dtype=dtype)
+ after = torch.zeros(shape, dtype=dtype)
+ inputs = (x, before, after)
+ if capture == "export":
+ program = torch.export.export(model, inputs)
+ monkeypatch.setattr(torch.export.ExportedProgram, "run_decompositions",
+ lambda *args, **kwargs: pytest.fail("Conversion must not run decompositions"))
+ else:
+ program = torch.jit.script(model)
+ converted = ov.convert_model(program, example_input=inputs if capture == "script" else None)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ runtime = {port: inputs[i].numpy() for i, port in enumerate(compiled.inputs)}
+ actual = compiled(runtime)[0]
+ expected = model(*inputs).numpy()
+ assert actual.dtype == expected.dtype
+ np.testing.assert_array_equal(actual, expected)
+
+
+def test_torch_diff_dynamic_length(monkeypatch):
+ class Model(torch.nn.Module):
+ def forward(self, x):
+ return torch.diff(x, n=2, dim=-1)
+
+ program = torch.export.export(Model(), (torch.randn(2, 4),),
+ dynamic_shapes=({1: torch.export.Dim("length", min=4, max=16)},))
+ monkeypatch.setattr(torch.export.ExportedProgram, "run_decompositions",
+ lambda *args, **kwargs: pytest.fail("Conversion must not run decompositions"))
+ converted = ov.convert_model(program)
+ converted.reshape([2, -1])
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for length in [0, 1, 2, 3, 7]:
+ x = torch.arange(2 * length, dtype=torch.float32).reshape(2, length)
+ np.testing.assert_array_equal(compiled(x.numpy())[0], Model()(x).numpy())
+
+
[email protected]("capture", ["export", "script"])
[email protected]("prepend_dtype,input_dtype,prepend_value,input_value", [
+ (torch.int32, torch.float16, 2049, 2048),
+ (torch.float16, torch.int32, 2048, 2049),
+])
+def test_torch_diff_promotes_all_boundaries(capture, prepend_dtype, input_dtype, prepend_value, input_value):
+ model = Diff(1, -1, True, True).eval()
+ inputs = (torch.tensor([input_value], dtype=input_dtype),
+ torch.tensor([prepend_value], dtype=prepend_dtype),
+ torch.tensor([2048], dtype=torch.float32))
+ program = torch.export.export(model, inputs) if capture == "export" else torch.jit.script(model)
+ converted = ov.convert_model(program, example_input=inputs if capture == "script" else None)
+ expected = model(*inputs).numpy()
+ reference = ov.Tensor(np.empty_like(expected))
+ assert converted.evaluate([reference], [ov.Tensor(value.numpy()) for value in inputs])
+ np.testing.assert_array_equal(reference.data, expected)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = compiled([x.numpy() for x in inputs])[0]
+ assert actual.dtype == expected.dtype
+ np.testing.assert_array_equal(actual, expected)
+
+
[email protected]("capture", ["export", "script"])
[email protected]("order,input_dtype,out_dtype", [
+ (0, torch.float32, torch.float32),
+ (1, torch.float32, torch.float32),
+ (1, torch.int64, torch.int8),
+ (1, torch.int64, torch.float32),
+])
+def test_torch_diff_out(capture, order, input_dtype, out_dtype):
+ class Model(torch.nn.Module):
+ __constants__ = ["order"]
+
+ def __init__(self):
+ super().__init__()
+ self.order = order
+
+ def forward(self, x, out):
+ value = torch.diff(x, n=self.order, out=out)
+ return value, out * 2
+
+ values = [0, 200, 500] if out_dtype == torch.int8 else [0, 16777217, 33554434]
+ inputs = (torch.tensor(values, dtype=input_dtype), torch.zeros(3 - order, dtype=out_dtype))
+ model = Model()
+ program = torch.export.export(model, inputs) if capture == "export" else torch.jit.script(model)
+ converted = ov.convert_model(program, example_input=inputs if capture == "script" else None)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ actual = list(compiled([inputs[i].numpy() for i in range(len(compiled.inputs))]).values())
+ expected = model(*(value.clone() for value in inputs))
+ assert len(actual) == len(expected)
+ for result, reference in zip(actual, expected):
+ assert result.dtype == reference.numpy().dtype
+ np.testing.assert_array_equal(result, reference.numpy())
+
+
[email protected]("capture", ["export", "script"])
[email protected]("order,axis", [(1, -1), (2, 0)])
+def test_torch_diff_polar(capture, order, axis):
+ class Model(torch.nn.Module):
+ __constants__ = ["order", "axis"]
+
+ def __init__(self):
+ super().__init__()
+ self.order = order
+ self.axis = axis
+
+ def forward(self, magnitude, angle):
+ value = torch.polar(magnitude, angle)
+ boundary = torch.polar(magnitude.narrow(self.axis, 0, 1), angle.narrow(self.axis, 0, 1))
+ return torch.view_as_real(torch.diff(value, n=self.order, dim=self.axis,
+ prepend=boundary))
+
+ inputs = (torch.arange(1, 9, dtype=torch.float32).reshape(2, 4),
+ torch.arange(-4, 4, dtype=torch.float32).reshape(2, 4) / 3)
+ model = Model()
+ program = torch.export.export(model, inputs) if capture == "export" else torch.jit.script(model)
+ converted = ov.convert_model(program, example_input=inputs if capture == "script" else None)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ np.testing.assert_allclose(compiled([x.numpy() for x in inputs])[0], model(*inputs).numpy(),
+ rtol=1e-5, atol=1e-5)
+
+
[email protected]("prepend", [True, False])
[email protected]("input_dtype,boundary_dtype", [
+ (torch.bool, torch.bool),
+ (torch.bool, torch.int32),
+ (torch.bool, torch.uint8),
+ (torch.uint8, torch.uint8),
+ (torch.uint8, torch.int32),
+ (torch.uint8, torch.bool),
+])
+def test_torch_diff_script_branch_promotion(prepend, input_dtype, boundary_dtype):
+ class Model(torch.nn.Module):
+ __constants__ = ["prepend"]
+
+ def __init__(self):
+ super().__init__()
+ self.prepend = prepend
+
+ def forward(self, x, boundary, take_branch):
+ if take_branch:
+ return torch.diff(x, n=2, prepend=boundary if self.prepend else None,
+ append=boundary if not self.prepend else None)
+ return torch.diff(x, prepend=boundary if self.prepend else None,
+ append=boundary if not self.prepend else None)
+
+ x = torch.tensor([255, 0, 128, 1], dtype=torch.uint8).to(input_dtype)
+ boundary = torch.tensor([3, 250], dtype=torch.uint8).to(boundary_dtype)
+ model = Model()
+ inputs = (x, boundary, torch.tensor(True))
+ converted = ov.convert_model(torch.jit.script(model), example_input=inputs)
+ compiled = ov.Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for take_branch in [True, False]:
+ inputs = (x, boundary, torch.tensor(take_branch))
+ actual = compiled([value.numpy() for value in inputs])[0]
+ expected = model(*inputs).numpy()
+ assert actual.dtype == expected.dtype
+ np.testing.assert_array_equal(actual, expected)
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_scalar_index.py b/tests/layer_tests/py_frontend_tests/test_torch_scalar_index.py
new file mode 100644
index 00000000000..be9306df851
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_scalar_index.py
@@ -0,0 +1,70 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import openvino as ov
+import pytest
+import torch
+
+
+pytestmark = [pytest.mark.precommit, pytest.mark.nightly]
+
+
+class IndexModel(torch.nn.Module):
+ __constants__ = ["pattern"]
+
+ def __init__(self, pattern):
+ super().__init__()
+ self.pattern = pattern
+
+ def forward(self, x, i, j):
+ if self.pattern == "consecutive":
+ return torch.ops.aten.index(x, [i, j])
+ if self.pattern == "separated":
+ return torch.ops.aten.index(x, [i, None, j])
+ return torch.ops.aten.index(x, [None, i])
+
+
+def _compare(compiled, model, inputs):
+ expected = model(*inputs).numpy()
+ runtime = {port: inputs[index].numpy() for index, port in enumerate(compiled.inputs)}
+ np.testing.assert_array_equal(compiled(runtime)[0], expected)
+
+
[email protected]("capture", ["export", "script"])
[email protected]("pattern,vector_index", [
+ ("consecutive", False),
+ ("consecutive", True),
+ ("separated", False),
+ ("separated", True),
+ ("single", False),
+])
+def test_scalar_advanced_index(capture, pattern, vector_index):
+ model = IndexModel(pattern)
+ x = torch.arange(60, dtype=torch.float32).reshape(3, 4, 5)
+ i = torch.tensor(1)
+ j = torch.tensor([0, 2]) if vector_index else torch.tensor(2)
+ inputs = (x, i, j)
+ program = torch.export.export(model, inputs) if capture == "export" else torch.jit.script(model)
+ converted = ov.convert_model(program, example_input=inputs if capture == "script" else None)
+ expected = model(*inputs).numpy()
+ assert converted.output(0).get_partial_shape().rank.get_length() == expected.ndim
+ compiled = ov.Core().compile_model(converted, "CPU")
+ _compare(compiled, model, inputs)
+
+
[email protected]("pattern,indices", [
+ pytest.param("consecutive", (1, 2), id="scalar"),
+ pytest.param("consecutive", ([[0], [2]], [[0, 2]]), id="broadcast"),
+ pytest.param("separated", ([[0], [2]], 2), id="mixed-separated"),
+])
+def test_scalar_advanced_index_dynamic(pattern, indices):
+ model = IndexModel(pattern)
+ x = torch.arange(60, dtype=torch.float32).reshape(3, 4, 5)
+ i, j = (torch.tensor(index) for index in indices)
+ dims = {axis: torch.export.Dim("dim" + str(axis), min=3, max=9) for axis in range(3)}
+ program = torch.export.export(model, (x, i, j), dynamic_shapes=(dims, None, None))
+ compiled = ov.Core().compile_model(ov.convert_model(program), "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for delta, shape in enumerate(((3, 4, 5), (5, 6, 7))):
+ x = torch.arange(int(np.prod(shape)), dtype=torch.float32).reshape(shape)
+ _compare(compiled, model, (x, i + delta, j + delta))
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_vmap.py b/tests/layer_tests/py_frontend_tests/test_torch_vmap.py
new file mode 100644
index 00000000000..3767a58b4fd
--- /dev/null
+++ b/tests/layer_tests/py_frontend_tests/test_torch_vmap.py
@@ -0,0 +1,276 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from unittest.mock import patch
+
+import numpy as np
+import pytest
+import torch
+from packaging import version
+
+from openvino import Core, convert_model
+from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
+
+
+pytestmark = [
+ pytest.mark.precommit,
+ pytest.mark.skipif(version.parse(torch.__version__) < version.parse("2.14"),
+ reason="Requires torch 2.14 or newer"),
+]
+
+
+def _convert_export(model, inputs, dynamic_shapes=None):
+ exported = torch.export.export(model, tuple(value.clone() for value in inputs), dynamic_shapes=dynamic_shapes)
+ 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)
+ assert not any(node.get_type_name() == "Loop" for node in converted.get_ordered_ops())
+ for name, graph in graphs.items():
+ assert str(exported.graph_module.get_submodule(name).graph) == graph
+ return Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+
+
+def _compare(compiled, model, inputs):
+ expected = model(*inputs)
+ expected = expected if isinstance(expected, tuple) else (expected,)
+ actual = compiled([value.numpy() for value in inputs])
+ for i, value in enumerate(expected):
+ reference = value.numpy()
+ assert actual[i].dtype == reference.dtype
+ np.testing.assert_allclose(actual[i], reference, atol=1e-6, rtol=1e-5)
+
+
[email protected]("out_dim", [0, 1, -1])
+def test_export_vmap_dimensions(out_dim):
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("weight", torch.tensor([1., 2., 3.]))
+
+ def forward(self, data, bias, captured):
+ # Torch 2.14 export supports only these out_dims for the batched outputs.
+ return torch.vmap(lambda row, offset: ((row + offset * self.weight).sum(-1), row.cos(), captured.sin()),
+ in_dims=(1, 0), out_dims=(0, 1, out_dim))(data, bias)
+
+ model = Model()
+ batch = torch.export.Dim("batch", min=2, max=16)
+ compiled = _convert_export(model, (torch.randn(2, 4, 3), torch.randn(4, 3), torch.randn(5)),
+ ({1: batch}, {0: batch}, {}))
+ for size in (0, 4, 6):
+ _compare(compiled, model, (torch.randn(2, size, 3), torch.randn(size, 3), torch.randn(5)))
+
+
[email protected]("mod_index", [False, True])
+def test_export_vmap_nested_mask(mod_index):
+ # Transformers masking indexes inside vmap through TransformGetItemToIndex, which exports flat_apply.
+ from contextlib import nullcontext
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
+
+ class Model(torch.nn.Module):
+ def forward(self, groups):
+ indices = torch.arange(groups.shape[1])
+
+ def mask(batch, head, query, key):
+ return (key <= query) & (groups[batch, query] == groups[batch, key])
+
+ mapped = torch.vmap(mask, in_dims=(None, None, None, 0))
+ mapped = torch.vmap(mapped, in_dims=(None, None, 0, None))
+ mapped = torch.vmap(mapped, in_dims=(None, 0, None, None))
+ mapped = torch.vmap(mapped, in_dims=(0, None, None, None))
+ with TransformGetItemToIndex() if mod_index else nullcontext():
+ return mapped(torch.arange(groups.shape[0]), torch.arange(1), indices, indices)
+
+ model = Model()
+ sequence = torch.export.Dim("sequence", min=2, max=16)
+ compiled = _convert_export(model, (torch.tensor([[0, 0, 1, 1, 1]]),), ({1: sequence},))
+ for values in ([[0, 0, 1, 1, 1]], [[0, 1, 1]]):
+ _compare(compiled, model, (torch.tensor(values),))
+
+
[email protected]("nested", [False, True])
[email protected]("dynamic", [False, True])
+def test_model_vmap_preserves_export_capture(nested, dynamic):
+ import torch.export._trace as export_trace
+ import torch.fx.experimental.proxy_tensor as proxy_tensor
+
+ class Model(torch.nn.Module):
+ @torch.no_grad()
+ def forward(self, data):
+ difference = torch.diff(data, dim=-1)
+ mapped = torch.vmap(lambda row: row.sin().sum(-1))
+ if nested:
+ mapped = torch.vmap(mapped)
+ return mapped(difference), difference
+
+ model = Model()
+ inputs = (torch.randn(2, 4, 3),)
+ shapes = ({1: torch.export.Dim("batch", min=2, max=16)},) if dynamic else None
+ with patch.object(export_trace, "make_fx", wraps=export_trace.make_fx) as export_tracer, \
+ patch.object(proxy_tensor, "make_fx", wraps=proxy_tensor.make_fx) as region_tracer, \
+ patch.object(torch.export.ExportedProgram, "run_decompositions",
+ side_effect=AssertionError("Conversion must not run decompositions")):
+ decoder = TorchFXPythonDecoder.from_model(model, inputs, dynamic_shapes=shapes)
+ converted = convert_model(decoder)
+ assert export_tracer.call_count == 1
+ assert region_tracer.call_count > 0
+ targets = [str(node.target) for module in decoder.pt_module.modules()
+ if isinstance(module, torch.fx.GraphModule) for node in module.graph.nodes]
+ assert any("aten.diff" in target for target in targets)
+ assert any("wrap_with_set_grad_enabled" in target for target in targets)
+ # The vmap region is lowered on a copy of the no_grad body, leaving the exported body unchanged.
+ assert any("_add_batch_dim" in target for target in targets)
+ assert not any(node.get_type_name() == "Loop" for node in converted.get_ordered_ops())
+ compiled = Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for size in ((4, 6) if dynamic else (4,)):
+ _compare(compiled, model, (torch.randn(2, size, 3),))
+
+
+def test_model_vmap_module_extension():
+ from openvino.frontend.pytorch import ModuleExtension
+
+ class Cosine(torch.nn.Module):
+ def forward(self, data):
+ return data.cos()
+
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.cosine = Cosine()
+
+ def forward(self, data):
+ return torch.vmap(lambda row: row.sin())(self.cosine(data))
+
+ data = torch.randn(3, 4)
+ model = Model()
+ converted = convert_model(model, example_input=(data,), dynamo=True,
+ extension=[ModuleExtension(Cosine, "aten.sin.default")])
+ assert not any(node.get_type_name() == "Loop" for node in converted.get_ordered_ops())
+ assert not hasattr(model.cosine, "_openvino_module_extension_patch_orig_forward")
+ compiled = Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ np.testing.assert_allclose(compiled(data.numpy())[0], data.sin().sin().numpy(), atol=1e-6, rtol=1e-5)
+
+
[email protected]("view_inside", [False, True])
+def test_export_vmap_output_alias_mutation(view_inside):
+ class Model(torch.nn.Module):
+ def forward(self, data):
+ if view_inside:
+ def mapped(row):
+ value = row.sin()
+ return value.view(2, 4), value.view(-1)
+
+ value, view = torch.vmap(mapped)(data)
+ else:
+ value = torch.vmap(torch.sin)(data)
+ view = value.view(-1)
+ view.add_(1)
+ return value, view
+
+ model = Model()
+ data = torch.randn(3, 2, 4)
+ batch = torch.export.Dim("batch", min=2, max=8)
+ compiled = _convert_export(model, (data,), ({0: batch},))
+ for size in (3, 5):
+ _compare(compiled, model, (torch.randn(size, 2, 4),))
+
+
+def test_export_vmap_cond_unmapped_predicate():
+ class Model(torch.nn.Module):
+ def forward(self, data, predicate):
+ return torch.vmap(lambda row: torch.ops.higher_order.cond(
+ predicate, lambda x: (x.sin(),), lambda x: (x.cos(),), (row,)))(data)[0]
+
+ model = Model()
+ data = torch.randn(3, 4)
+ compiled = _convert_export(model, (data, torch.tensor(True)))
+ for predicate in (True, False):
+ _compare(compiled, model, (data, torch.tensor(predicate)))
+
+
[email protected]("complex_first", [False, True])
+def test_export_vmap_mixed_dtype_aliases(complex_first):
+ from openvino.frontend.pytorch import vmap_lowering
+
+ class Model(torch.nn.Module):
+ def forward(self, data):
+ def mapped(row):
+ value = torch.view_as_complex(row.sin()[1:])
+ real = torch.view_as_real(value)
+ return (value, real) if complex_first else (real, value)
+
+ outputs = torch.vmap(mapped)(data)
+ value, real = outputs if complex_first else outputs[::-1]
+ return value.real, value.imag, real
+
+ model = Model()
+ batch = torch.export.Dim("batch", min=2, max=8)
+ exported = torch.export.export(model, (torch.randn(3, 6, 2),), dynamic_shapes=({0: batch},))
+ metadata = {}
+ trace = vmap_lowering._trace
+
+ def capture(*args):
+ traced = trace(*args)
+ for node in traced.graph.nodes:
+ value = node.meta.get("val")
+ if isinstance(value, torch.Tensor):
+ metadata[node] = (value.dtype, value.shape, value.stride(), value.storage_offset())
+ return traced
+
+ with patch.object(vmap_lowering, "_trace", side_effect=capture):
+ lowered = vmap_lowering.lower_vmap_regions(exported.graph_module)
+ assert metadata
+ for node, expected in metadata.items():
+ value = node.meta["val"]
+ assert (value.dtype, value.shape, value.stride(), value.storage_offset()) == expected
+ converted = convert_model(TorchFXPythonDecoder(lowered))
+ compiled = Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ for size in (3, 5):
+ _compare(compiled, model, (torch.randn(size, 6, 2),))
+
+
+def test_export_vmap_existing_attribute():
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self._ov_vmap_0 = torch.nn.Module()
+ self._ov_vmap_0.register_buffer("weight", torch.tensor(2.))
+
+ def forward(self, data):
+ return torch.vmap(torch.sin)(data) * self._ov_vmap_0.weight
+
+ model = Model().eval()
+ data = torch.randn(3, 4)
+ module = torch.export.export(model, (data,)).module()
+ decoder = TorchFXPythonDecoder(module)
+ assert decoder.pt_module._ov_vmap_0.weight is module._ov_vmap_0.weight
+ converted = convert_model(decoder)
+ compiled = Core().compile_model(converted, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})
+ with torch.no_grad():
+ _compare(compiled, model, (data,))
+
+
[email protected]("case", ["same", "different", "mutation", "captured_mutation", "wrapped_mutation"])
+def test_export_vmap_rejects(case):
+ @torch.no_grad()
+ def wrapped_mutation(row):
+ return row.clone().add_(1)
+
+ class Model(torch.nn.Module):
+ def forward(self, data):
+ captured = torch.zeros_like(data[0])
+
+ def captured_mutation(row):
+ captured.add_(1)
+ return row + captured
+
+ if case in ("same", "different"):
+ return torch.vmap(torch.sin, randomness=case)(data)
+ functions = {"mutation": lambda row: row.clone().add_(1), "captured_mutation": captured_mutation,
+ "wrapped_mutation": wrapped_mutation}
+ return torch.vmap(functions[case])(data)
+
+ match = "randomness='error'" if case in ("same", "different") else "Mutation inside vmap is not supported"
+ with pytest.raises(RuntimeError, match=match):
+ _convert_export(Model(), (torch.randn(2, 4),))