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
[PT FE] Upgrade tests to torch 2.12 (#36098)
Maxim Vafin514fc283fd6e
diff --git a/.claude/skills/ov-update-pytorch-version/SKILL.md b/.claude/skills/ov-update-pytorch-version/SKILL.mdnew file mode 100644index 00000000000..6ff283c89b2--- /dev/null+++ b/.claude/skills/ov-update-pytorch-version/SKILL.md@@ -0,0 +1,208 @@+---+name: ov-update-pytorch-version+description: Upgrade the PyTorch version used by OpenVINO tests (torch / torchvision / torchaudio) and resolve fallout — missing operator translators, new functionalized `*_copy` aten ops, decomposition changes, FX-only tests failing in TorchScript mode, and accuracy regressions caused by stricter typing. Use when the user asks to "bump torch", "update pytorch to X.Y", "upgrade torch tests", or when pytorch_tests / model_hub pytorch tests fail after a torch version change. Do not use for: enabling a single new PyTorch operator unrelated to a version bump, GenAI / Optimum upgrades, or plugin-level numerical bugs unrelated to the frontend.+---++# Update PyTorch Version in OpenVINO++End-to-end procedure for bumping the PyTorch version used by OpenVINO layer tests and the PyTorch frontend, and fixing the regressions that typically follow.++## Step 0: Confirm Scope++Before editing anything, confirm with the user:++- Target versions for `torch`, `torchvision`:+ - `torchvision` minor = torch minor **+ 15** — e.g. torch `2.9.0` ↔ torchvision `0.24.0`, torch `2.12.0` ↔ torchvision `0.27.0`. Always confirm against the official release matrix.+ - `torchaudio` is **not** pinned by [tests/requirements_pytorch](../../../tests/requirements_pytorch): it is unused by these tests and PyTorch removed it from the official installation instructions starting with the 2.8 release. **Do not re-add it.** If a future task genuinely needs torchaudio, note that it is in a maintenance phase and its latest release can lag torch by one or more minors (e.g. torch `2.12.0` ↔ torchaudio `2.11.0`), so `torchaudio==<torch version>` may not exist — look up the latest available wheel at `https://download.pytorch.org/whl/cpu/torchaudio/`. Recent torchaudio wheels carry **no** `Requires-Dist: torch` pin, so a slightly older torchaudio installs cleanly alongside a newer torch.+- Whether `tests/model_hub_tests/pytorch/envs/compile_gptq.txt` (pinned at `torch==2.3.1`, `torchaudio==2.3.1` for auto-gptq) should be touched. **Default: leave it alone.**+- Both the default TorchScript path **and** `PYTORCH_TRACING_MODE=EXPORT` (FX) path must be validated. Skip the FX run only if the user explicitly opts out.++## Step 1: Update Version Pins++Edit the following files. Keep `~=` style in `constraints.txt`, exact `==` in `requirements_*`. `A.B` is the torchvision version (torch minor + 15):++- [tests/constraints.txt](../../../tests/constraints.txt) — `torch~=X.Y.0`, `torchvision~=A.B.0` (constraints.txt does not pin torchaudio)+- [tests/requirements_pytorch](../../../tests/requirements_pytorch) — `torch==X.Y.0`, `torchvision==A.B.0` (no torchaudio — see Step 0)+- `tests/model_hub_tests/pytorch/envs/*.txt` — bump in lockstep **except** `compile_gptq.txt` unless the user confirms.++Install into the active environment:++```bash+pip3 install --index-url https://download.pytorch.org/whl/cpu --upgrade \+ torch==X.Y.0 torchvision==A.B.0+```++## Step 2: Run the Layer Tests in Parallel++Always test against a freshly built `openvino_pytorch_frontend`. A site-wide install (e.g. under `~/.local`) can shadow the dev build — explicitly point at the build output. Set `OV_REPO` to the OpenVINO checkout root and `OV_BUILD_BIN` to its build artifact dir (typically `$OV_REPO/bin/intel64/Release`):++```bash+cd "$OV_REPO/tests/layer_tests"+export PYTHONPATH="$OV_BUILD_BIN/python"+export LD_LIBRARY_PATH="$OV_BUILD_BIN"+export TEST_DEVICE=CPU TEST_PRECISION=FP32+```++The pytorch layer tests use two pytest markers to gate which path a test runs on:++- `-m precommit` — TorchScript path (default tracing mode). Use this to validate the TS frontend.+- `-m precommit_torch_export` — `torch.export` / FX path. Requires `PYTORCH_TRACING_MODE=EXPORT`; the test runner reads that env var to switch the test class behaviour.++Both runs are required after a version bump:++```bash+# TorchScript path+python3 -m pytest pytorch_tests/ -m precommit -n auto --tb=line -q \+ 2>&1 | tee /tmp/pt_run_ts.log | tail -5++# torch.export (FX) path+PYTORCH_TRACING_MODE=EXPORT \+python3 -m pytest pytorch_tests/ -m precommit_torch_export -n auto --tb=line -q \+ 2>&1 | tee /tmp/pt_run_fx.log | tail -5+```++Collect unique failing test files from either log:++```bash+grep -E "^FAILED" /tmp/pt_run_ts.log /tmp/pt_run_fx.log | sed 's/\[.*//' | sort -u+```++Run one failing test verbosely to see the real traceback before grouping fixes (add `PYTORCH_TRACING_MODE=EXPORT` for FX-side reproduction):++```bash+python3 -m pytest pytorch_tests/test_<name>.py -k <case> -x --tb=long+```++## Step 3: Triage Failures++Sort failures into these buckets. The first three are the common ones for any minor torch bump.++> **Rebuild after any C++ change.** Buckets A and B both modify the PyTorch frontend; re-run before re-testing:+>+> ```bash+> cmake --build "$OV_REPO/build" --target openvino_pytorch_frontend -j$(nproc)+> ```++### Bucket A — Newly-emitted aten ops with no translator++Each torch release tends to lower more ops to new aten variants. The `*_copy` family from functionalization (e.g. `aten::select_copy`, `aten::view_copy`, `aten::squeeze_copy`, `aten::expand_copy`, `aten::permute_copy`, `aten::as_strided_copy`, `aten::split_with_sizes_copy`, `aten::unsqueeze_copy`) is one common pattern, but the bucket also covers any other freshly-introduced op (renames, new overloads, ops promoted out of decomposition, etc.). Symptom: log line like `No translator found for aten::<name>`.++Decision tree:++1. **Semantically equivalent to an existing op** (typical for `_copy` variants — OV graphs are functional, so the copy is a no-op) → alias to the existing translator in the **TorchScript** table (`aten::*` keys) of [src/frontends/pytorch/src/op_table.cpp](../../../src/frontends/pytorch/src/op_table.cpp):++ ```cpp+ {"aten::select_copy", op::quantizable_op<op::translate_select>},+ {"aten::view_copy", op::quantizable_op<op::translate_reshape>},+ {"aten::split_with_sizes_copy", op::translate_split_with_sizes},+ ```++2. **Different signature but same underlying op** → write a thin wrapper that adapts inputs/attrs and dispatches to the existing translator.++3. **Genuinely new behavior** → implement a new translator under `src/frontends/pytorch/src/op/` and register it in both tables if the FX path also emits it.++Add an FX-table entry (`aten.<name>.default` / specific overload) only if the FX path also reports the op missing.++**Ensure the alias is actually covered by a TorchScript test.** Many existing `*_copy` layer tests are marked only `@pytest.mark.precommit_fx_backend` (and sometimes `precommit_torch_export`), so the TS table entry you just added is never exercised by the TorchScript precommit job. After adding a TS alias, find the matching test class (e.g. `TestSelectCopy`, `TestViewCopy`) and add `@pytest.mark.nightly` + `@pytest.mark.precommit` so the new registration is validated. If no test exists for the op, add one. Reviewers (including Copilot) flag missing TS coverage for new TS registrations.++### Bucket B — Translator only registered for FX++Symptom: TS test fails with "No translator found for `aten::<op>`" while an `*_fx` translator already exists.++Fix: register the existing `translate_<op>_fx` (or write a thin TS wrapper) in the TS section of `op_table.cpp`, and extend the translator body to accept the TS calling convention. Use `num_inputs_check(context, min, max)` and branch on input count for the TS dtype/layout/device tail. Example: see `translate_scalar_tensor_fx` in [src/frontends/pytorch/src/op/scalar_tensor.cpp](../../../src/frontends/pytorch/src/op/scalar_tensor.cpp).++As in Bucket A, add `@pytest.mark.nightly` + `@pytest.mark.precommit` to the corresponding test so the TS path is exercised. If you added a new TS-only code branch (e.g. a TS dtype tail), add a parametrized case that hits it — extending the existing test, not duplicating it.++### Bucket C — FX-only test code reached in TorchScript mode++This bucket only applies when a test ends up executed in the TS path while its body relies on FX-only constructs (`torch.cond`, `torch.while_loop`, `torch.ops.aten.*`, `torch.ops.quantized_decomposed.*`, etc.). It happens when:++1. The test class carries both `@pytest.mark.precommit` and `@pytest.mark.precommit_torch_export` but the body works only on one path, **or**+2. The suite is run without `-m` (e.g. ad-hoc full-suite reproduction).++If the test is genuinely FX-only, drop the `precommit` marker so `-m precommit` skips it cleanly. If both backends are intended, add a body-level guard:++```python+if not (self.use_torch_export() or self.use_torch_compile_backend()):+ pytest.skip("FX-only test")+```++For parametrize-time skipping, the helpers in [tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py](../../../tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py) are `skip_if_export(*params, reason=...)` (skips on the `torch.export` path), `skip_if_fx(*params, reason=...)` (skips on the `torch.compile`/FX path), and `skip_check(*params, reason=...)` (skips on whichever non-TS path is active). There is **no** `skip_if_ts` helper — to skip the TorchScript path, gate inside the test body with `if not (self.use_torch_export() or self.use_torch_compile_backend()): pytest.skip(...)`.++### Bucket D — Stricter typing / changed default kwargs++Examples observed in past bumps:++- `aten::hardtanh_` is now emitted instead of `aten::hardtanh` when `inplace=True` — make the expected op-kind dynamic in the test.+- Literal `[0, 1.0]` rejected as mixed int/float — change to `[0.0, 1.0]`.+- New kwargs default-on (e.g. `scaled_dot_product_attention(enable_gqa=...)`) — pass the value explicitly so traced graphs match across versions.++### Bucket E — Accuracy regressions++Before assuming a translator bug, check whether the same input pattern triggers a known plugin issue (e.g. CPU `Multiply(x, Constant(inf))` followed by `IsInf` with dynamic shape returns all-False due to a Mul+IsInf fusion). If reproducible without the PT FE, work around in the test input and note the underlying ticket in the commit message — do not paper over real frontend regressions.++## Step 4: Re-validate++Re-run both marker scopes from Step 2 until each ends with `0 failed`:++```bash+python3 -m pytest pytorch_tests/ -m precommit -n auto --tb=line -q 2>&1 | tail -5+PYTORCH_TRACING_MODE=EXPORT \+python3 -m pytest pytorch_tests/ -m precommit_torch_export -n auto --tb=line -q 2>&1 | tail -5+```++Expect a handful of new skipped/xfailed tests after Bucket C fixes — that is normal. FX-path failures usually point to missing FX-table entries or decomposition changes, not TS aliasing.++## Step 5: Check Model Hub Tests++Model hub tests load real (downloaded) models and prepare inputs using torchvision/torch helpers directly in the test file. These helpers can break when the new torchvision version removes or renames an API.++**Where to look**: `tests/model_hub_tests/pytorch/test_torchvision_models.py` and similar files in that directory. Focus on `load_model()` — it typically contains model-specific input preparation branches.++**Common failure pattern**:++```+ImportError: cannot import name '<name>' from 'torchvision.<module>'+```++A helper function inside the test file imports an API (e.g. `torchvision.io.read_video`, `torchvision.transforms.*`) that was removed in the new version. The function is called from inside a `load_model()` branch for a specific model (e.g. optical-flow models like RAFT).++**Fix**:++1. Identify what input shape the removed pipeline produced. Check the original code for resize/transform dimensions applied to the input.+2. Replace the helper call with a `torch.randn(...)` tensor of the same shape.+3. Remove the now-unused imports and the helper function itself.++Example (optical-flow model input after a 520×960 resize+transform pipeline):++```python+# before+frames = get_video()+self.example = prepare_frames_for_raft(model_name, [frames[100], frames[150]], ...)++# after+self.example = (torch.randn(2, 3, 520, 960), torch.randn(2, 3, 520, 960))+self.inputs = (torch.randn(2, 3, 520, 960), torch.randn(2, 3, 520, 960))+```++Also check that any imports only needed by the removed helper are cleaned up (e.g. `import tempfile`, `import torchvision.transforms.functional as F`, `get_model_weights`).++**Verify** by checking the torchvision changelog for removed APIs whenever tests in this directory fail after a version bump.++## Step 6: Commit++One commit on a feature branch (project convention: `<user>/pt_fe/<short-topic>`, e.g. `mvafin/pt_fe/torch_2_12_upgrade`) covering: requirements, `op_table.cpp` additions, any translator extensions, and test fixes. List the new translators and the broken-test categories in the commit body — reviewers use it to map CI changes to user-visible behavior.++The pre-commit hook runs `clang-format` and may amend `src/frontends/pytorch/src/op/*.cpp`; re-stage and recommit if it does.++## Pitfalls++- **Model hub test helpers** (in `tests/model_hub_tests/pytorch/`) sometimes import torchvision/torch APIs that are removed in a new release. The failure surfaces as an `ImportError` inside a subprocess (via `multiprocessing_run`), so the traceback points into the helper, not the test parametrize line. Always check the torchvision changelog for removed APIs when these tests fail after a bump. Replace removed API calls with equivalent `torch.randn(...)` inputs of the same shape.+- **Do not** alias a new aten op to an existing translator without confirming semantic equivalence (signature, dtype/broadcast rules, attribute defaults). Aliasing is only safe when the new op is a behavioral no-op or true synonym of the existing one.+- **Do not** rely on `id(node)` when walking ov.Node graphs in Python; wrappers are recreated. Use `get_friendly_name()`.+- Test markers are filterable but not enforced — a class marked only `precommit_torch_export` still runs under TS if pytest is invoked without `-m`. Use marker-filtered invocations from Step 2; reserve inline `pytest.skip` for genuinely dual-marked tests.+- New TS op_table aliases/registrations are easy to leave untested: their tests are frequently marked `precommit_fx_backend` only. Always add `precommit` + `nightly` so the TorchScript job covers them (see Buckets A/B).+- `pytest -n auto` requires `pytest-xdist` (in `tests/requirements_pytorch`); confirm it is installed in the active env.+- `torchvision` minor = torch minor **+ 15** (`torch 2.9` ↔ `torchvision 0.24`, `torch 2.12` ↔ `torchvision 0.27`). Double-check the official release matrix before pinning.+- In `tests/requirements_pytorch`, place `--extra-index-url https://download.pytorch.org/whl/cpu` **before** the `torch==` and `torchvision==` lines so the PyTorch CPU index is available when pip resolves those packages. The line order matters for some pip-based tooling even though pip applies the option globally once parsed.+- `torchaudio` is intentionally **not** in `requirements_pytorch` (unused; dropped from PyTorch's official install since 2.8). Do not re-add it. If you ever must, note it is in a maintenance phase and lags torch (`torch 2.12.0` ↔ `torchaudio 2.11.0`), so pinning `torchaudio==<torch version>` blindly causes a CI install failure (`No matching distribution found for torchaudio==X.Y.0`) — look up the latest available wheel.diff --git a/src/frontends/pytorch/src/op/full.cpp b/src/frontends/pytorch/src/op/full.cppindex baba649a084..2884d556911 100644--- a/src/frontends/pytorch/src/op/full.cpp+++ b/src/frontends/pytorch/src/op/full.cpp@@ -424,6 +424,21 @@ OutputVector translate_fill_diagonal(const NodeContext& context) {filled_tensor = context.mark_node(std::make_shared<v1::Reshape>(filled_tensor, input_shape, false));return {filled_tensor};}++OutputVector translate_empty_fx(const NodeContext& context) {+ // aten.empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, ...)+ // In the FX graph dtype is passed as a node attribute, not as a positional input.+ // In OV uninitialized data is not supported, so we fill with zeros.+ num_inputs_check(context, 1, 1);+ auto sizes = context.get_input(0);+ auto value = context.mark_node(v0::Constant::create(element::f32, Shape{}, {0}));+ auto filled_tensor = base_translate_full(context, sizes, value);+ if (context.has_attribute("dtype")) {+ auto dtype = context.get_attribute<element::Type>("dtype");+ filled_tensor = context.mark_node(std::make_shared<v0::Convert>(filled_tensor, dtype));+ }+ return {filled_tensor};+};} // namespace op} // namespace pytorch} // namespace frontenddiff --git a/src/frontends/pytorch/src/op/scalar_tensor.cpp b/src/frontends/pytorch/src/op/scalar_tensor.cppindex a958ab013a5..02ed5385bf6 100644--- a/src/frontends/pytorch/src/op/scalar_tensor.cpp+++ b/src/frontends/pytorch/src/op/scalar_tensor.cpp@@ -18,11 +18,15 @@ using namespace ov::op;OutputVector translate_scalar_tensor_fx(const NodeContext& context) {// aten.scalar_tensor.default(-100.0, dtype = torch.float32, layout = torch.strided, device = device(type='cpu'))- num_inputs_check(context, 1, 1);+ // TorchScript: aten::scalar_tensor(Scalar s, *, ScalarType? dtype, Layout? layout, Device? device, bool?+ // pin_memory)+ num_inputs_check(context, 1, 5);auto data = context.get_input(0);if (context.has_attribute("dtype")) {auto dtype = context.get_attribute<element::Type>("dtype");data = context.mark_node(std::make_shared<v0::Convert>(context.get_input(0), dtype));+ } else if (context.get_input_size() > 1 && !context.input_is_none(1)) {+ data = apply_dtype(context, 1, data);}// layout and device can be ignoredreturn {data};diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 40c033b5d7d..d98261aa2c2 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -87,6 +87,7 @@ OP_CONVERTER(translate_elu);OP_CONVERTER(translate_embedding);OP_CONVERTER(translate_embedding_bag);OP_CONVERTER(translate_empty);+OP_CONVERTER(translate_empty_fx);OP_CONVERTER(translate_empty_like);OP_CONVERTER(translate_erf);OP_CONVERTER(translate_erfc);@@ -432,6 +433,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::argmin", op::translate_argmin},{"aten::argsort", op::translate_argsort},{"aten::as_strided", op::translate_as_strided},+ {"aten::as_strided_copy", op::translate_as_strided},{"aten::as_tensor", op::translate_as_tensor},{"aten::asin", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Asin>, 1>},{"aten::asin_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Asin>>},@@ -518,6 +520,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::exp", op::optional_out<op::translate_exp, 1>},{"aten::exp_", op::inplace_op<op::translate_exp>},{"aten::expand", op::translate_expand},+ {"aten::expand_copy", op::translate_expand},{"aten::expand_as", op::translate_expand_as},{"aten::expm1", op::translate_expm1},{"aten::eye", op::translate_eye},@@ -666,6 +669,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::pad", op::translate_pad},{"aten::pairwise_distance", op::translate_pairwise_distance},{"aten::permute", op::translate_permute},+ {"aten::permute_copy", op::translate_permute},{"aten::pixel_shuffle", op::translate_pixel_shuffle},{"aten::pixel_unshuffle", op::translate_pixel_unshuffle},{"aten::prelu", op::translate_1to1_match_2_inputs<opset10::PRelu>},@@ -715,11 +719,13 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::rsub", op::translate_rsub},{"aten::searchsorted", op::translate_search_sorted},{"aten::ScalarImplicit", op::skip_node},+ {"aten::scalar_tensor", op::translate_scalar_tensor_fx},{"aten::scaled_dot_product_attention", op::translate_scaled_dot_product_attention},{"aten::scatter", op::translate_scatter},{"aten::scatter_add", op::translate_scatter_add},{"aten::scatter_reduce", op::translate_scatter_reduce},{"aten::select", op::quantizable_op<op::translate_select>},+ {"aten::select_copy", op::quantizable_op<op::translate_select>},{"aten::selu", op::translate_selu},{"aten::sigmoid",op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sigmoid>, 1>},@@ -739,10 +745,12 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sigmoid>, 1>},// aten::split - Supported in limited set of patterns{"aten::split_with_sizes", op::translate_split_with_sizes},+ {"aten::split_with_sizes_copy", op::translate_split_with_sizes},{"aten::sqrt", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sqrt>, 1>},{"aten::sqrt_", op::inplace_op<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Sqrt>>},{"aten::square", op::translate_square},{"aten::squeeze", op::quantizable_op<op::translate_squeeze>},+ {"aten::squeeze_copy", op::quantizable_op<op::translate_squeeze>},{"aten::stack", op::translate_stack},{"aten::std", op::translate_std},{"aten::std_mean", op::translate_std_mean},@@ -771,6 +779,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::unfold", op::translate_unfold},// aten::unsafe_chunk - Supported in limited set of patterns{"aten::unsqueeze", common_translators::translate_unsqueeze},+ {"aten::unsqueeze_copy", common_translators::translate_unsqueeze},{"aten::upsample_bicubic2d", op::translate_upsample_bicubic2d},{"aten::upsample_bilinear2d", op::translate_upsample_bilinear2d},{"aten::upsample_linear1d", op::translate_upsample_linear1d},@@ -781,6 +790,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::var", op::translate_var},{"aten::var_mean", op::translate_var_mean},{"aten::view", op::quantizable_op<op::translate_reshape>},+ {"aten::view_copy", op::quantizable_op<op::translate_reshape>},{"aten::view_as", op::translate_reshape_as},{"aten::view_as_complex", op::translate_view_as_complex},{"aten::view_as_real", op::translate_view_as_real},@@ -938,7 +948,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten.elu.default", op::translate_elu},{"aten.elu_.default", op::inplace_op<op::translate_elu>},{"aten.embedding.default", op::translate_embedding},- {"aten.empty.memory_format", op::translate_empty},+ {"aten.empty.memory_format", op::translate_empty_fx},{"aten.eq.Scalar", op::translate_1to1_match_2_inputs_align_types<opset10::Equal>},{"aten.eq.Tensor", op::translate_1to1_match_2_inputs_align_types<opset10::Equal>},{"aten.erf.default", op::translate_erf},diff --git a/tests/constraints.txt b/tests/constraints.txtindex c309407cba7..ebfd7ab767a 100644--- a/tests/constraints.txt+++ b/tests/constraints.txt@@ -23,5 +23,5 @@ pytest-timeout==2.4.0kornia==0.8.2--extra-index-url https://download.pytorch.org/whl/cpu-torch~=2.8.0-torchvision~=0.23.0+torch~=2.12.0+torchvision~=0.27.0diff --git a/tests/layer_tests/pytorch_tests/test_as_strided.py b/tests/layer_tests/pytorch_tests/test_as_strided.pyindex 685eb883929..32968e1f6f5 100644--- a/tests/layer_tests/pytorch_tests/test_as_strided.py+++ b/tests/layer_tests/pytorch_tests/test_as_strided.py@@ -73,6 +73,8 @@ class TestAsStridedCopy(PytorchLayerTest):],)@pytest.mark.parametrize("offset", [None, 1, 3, 7])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_as_strided_copy(self, size, stride, offset, ie_device, precision, ir_version):self._test(*self.create_model(size, stride, offset), ie_device, precision, ir_version, trace_model=True)diff --git a/tests/layer_tests/pytorch_tests/test_expand.py b/tests/layer_tests/pytorch_tests/test_expand.pyindex 307cedbeb37..e50c773cc26 100644--- a/tests/layer_tests/pytorch_tests/test_expand.py+++ b/tests/layer_tests/pytorch_tests/test_expand.py@@ -59,6 +59,8 @@ class TestExpandCopy(PytorchLayerTest):return aten_expand_copy(dim), f"aten::expand_copy"@pytest.mark.parametrize("dims", [(4, 3), (-1, -1), (1, 2, 3), (1, 2, 2, 3)])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_expand_copy(self, dims, ie_device, precision, ir_version):self._test(*self.create_model(dims), ie_device, precision, ir_version)diff --git a/tests/layer_tests/pytorch_tests/test_hardtanh.py b/tests/layer_tests/pytorch_tests/test_hardtanh.pyindex 1ad2e992a18..3a2cd746076 100644--- a/tests/layer_tests/pytorch_tests/test_hardtanh.py+++ b/tests/layer_tests/pytorch_tests/test_hardtanh.py@@ -26,9 +26,9 @@ class TestHardtanh(PytorchLayerTest):return F.hardtanh(x, min_val=self.min_val, max_val=self.max_val, inplace=self.inplace)- return aten_hardtanh(min_val, max_val, inplace), "aten::hardtanh"+ return aten_hardtanh(min_val, max_val, inplace), "aten::hardtanh_" if inplace else "aten::hardtanh"- @pytest.mark.parametrize(("min_val", "max_val"), [[-1.0,1.0], [0, 1.0], [-2.0, 2.0]])+ @pytest.mark.parametrize(("min_val", "max_val"), [[-1.0,1.0], [0.0, 1.0], [-2.0, 2.0]])@pytest.mark.parametrize("inplace", [True, False])@pytest.mark.parametrize("input_dtype", ['float32', 'int32', 'int64', 'float64'])@pytest.mark.parametrize("input_shape", [(1, 3, 10, 10), (100,), (24, 24)])diff --git a/tests/layer_tests/pytorch_tests/test_isinf.py b/tests/layer_tests/pytorch_tests/test_isinf.pyindex b6dc2f9e6ec..cbcd242f8a8 100644--- a/tests/layer_tests/pytorch_tests/test_isinf.py+++ b/tests/layer_tests/pytorch_tests/test_isinf.py@@ -8,7 +8,9 @@ import torchfrom pytorch_layer_test_class import PytorchLayerTest[email protected]('input_tensor', (np.array([1, 0, -1]),))[email protected]('input_tensor',+ (np.array([float("inf"), float("nan"), -float("inf"), 0.0, 1.0, -1.0],+ dtype=np.float32),))class TestIsInf(PytorchLayerTest):def _prepare_input(self):@@ -19,7 +21,7 @@ class TestIsInf(PytorchLayerTest):class aten_isinf(torch.nn.Module):def forward(self, input_tensor):- return torch.isinf(input_tensor * float("inf"))+ return torch.isinf(input_tensor)return aten_isinf(), "aten::isinf"diff --git a/tests/layer_tests/pytorch_tests/test_permute.py b/tests/layer_tests/pytorch_tests/test_permute.pyindex a3dbd54f5fd..dcc292cd240 100644--- a/tests/layer_tests/pytorch_tests/test_permute.py+++ b/tests/layer_tests/pytorch_tests/test_permute.py@@ -60,6 +60,8 @@ class TestPermuteCopy(PytorchLayerTest):return aten_permute_copy(order), "aten::permute_copy"@pytest.mark.parametrize("order", [[0, 2, 3, 1], [0, 3, 1, 2], [0, -1, 1, -2]])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_permute_copy(self, order, ie_device, precision, ir_version):self._test(*self.create_model(order), ie_device, precision, ir_version)diff --git a/tests/layer_tests/pytorch_tests/test_scalar_tensor.py b/tests/layer_tests/pytorch_tests/test_scalar_tensor.pyindex cce20ac011f..5681568941a 100644--- a/tests/layer_tests/pytorch_tests/test_scalar_tensor.py+++ b/tests/layer_tests/pytorch_tests/test_scalar_tensor.py@@ -13,21 +13,27 @@ class TestScalarTensor(PytorchLayerTest):def _prepare_input(self):return (np.array(self.random.randn(), dtype=np.float32),)- def create_model(self):+ def create_model(self, dtype):class aten_scalar_tensor(torch.nn.Module):- def __init__(self) -> None:+ def __init__(self, dtype) -> None:super().__init__()+ self.dtype = dtypedef forward(self, lhs):- return torch.scalar_tensor(lhs.item())+ if self.dtype is None:+ return torch.scalar_tensor(lhs.item())+ return torch.scalar_tensor(lhs.item(), dtype=self.dtype)- return aten_scalar_tensor(), f"aten::scalar_tensor"+ return aten_scalar_tensor(dtype), f"aten::scalar_tensor"+ @pytest.mark.parametrize("dtype", [None, torch.float32, torch.float64, torch.int32, torch.int64])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backend- def test_scalar_tensor(self, ie_device, precision, ir_version):- self._test(*self.create_model(), ie_device, precision, ir_version, use_convert_model=True)+ def test_scalar_tensor(self, dtype, ie_device, precision, ir_version):+ self._test(*self.create_model(dtype), ie_device, precision, ir_version, use_convert_model=True)diff --git a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.pyindex c1b9fc965e8..9d48f83d916 100644--- a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py+++ b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py@@ -83,7 +83,7 @@ class TestScaledDotProductAttention(PytorchLayerTest):if PytorchLayerTest.use_torch_export() and not mask and is_causal:pytest.xfail(reason="Unsupported case for torch.export")dtype = np.float64- self._test(*self.create_model(mask, is_causal, dtype, mask_shape),+ self._test(*self.create_model(mask, is_causal, dtype, mask_shape, enable_gqa=False),ie_device, precision, ir_version, dynamic_shapes=dyn_shapes,kwargs_to_prepare_input={"dtype": dtype})diff --git a/tests/layer_tests/pytorch_tests/test_select.py b/tests/layer_tests/pytorch_tests/test_select.pyindex 3fc862e72a1..d08f309696b 100644--- a/tests/layer_tests/pytorch_tests/test_select.py+++ b/tests/layer_tests/pytorch_tests/test_select.py@@ -57,6 +57,8 @@ class TestSelectCopy(PytorchLayerTest):return aten_select_copy(input_dim, input_index), "aten::select_copy"+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_select_copy(self, ie_device, precision, ir_version, input_dim, input_index):self._test(*self.create_model(input_dim, input_index),diff --git a/tests/layer_tests/pytorch_tests/test_split.py b/tests/layer_tests/pytorch_tests/test_split.pyindex e242d7d4687..c9f3406ebcd 100644--- a/tests/layer_tests/pytorch_tests/test_split.py+++ b/tests/layer_tests/pytorch_tests/test_split.py@@ -109,8 +109,10 @@ class TestSplitWithSizesCopy(PytorchLayerTest):return torch.split_with_sizes_copy(x, [y.shape[0]], dim=0)- return aten_split_with_sizes_copy(), ["aten::split_with_sizes", "prim::ListConstruct"]+ return aten_split_with_sizes_copy(), ["aten::split_with_sizes_copy", "prim::ListConstruct"]+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_torch_export@pytest.mark.precommit_fx_backenddef test_split_with_sizes_copy(self, ie_device, precision, ir_version):diff --git a/tests/layer_tests/pytorch_tests/test_squeeze.py b/tests/layer_tests/pytorch_tests/test_squeeze.pyindex 0e2415b59e2..38459b174df 100644--- a/tests/layer_tests/pytorch_tests/test_squeeze.py+++ b/tests/layer_tests/pytorch_tests/test_squeeze.py@@ -63,6 +63,8 @@ class TestSqueezeCopy(PytorchLayerTest):return aten_squeeze_copy(dim), "aten::squeeze_copy"@pytest.mark.parametrize("dim,dynamic_shapes", [(-2, True), (0, True), (None, False)])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_squeeze_copy(self, dim, dynamic_shapes, ie_device, precision, ir_version):if PytorchLayerTest.use_torch_export() and dim is None:diff --git a/tests/layer_tests/pytorch_tests/test_unsqueeze.py b/tests/layer_tests/pytorch_tests/test_unsqueeze.pyindex f9fd4df5205..7322a5ed93e 100644--- a/tests/layer_tests/pytorch_tests/test_unsqueeze.py+++ b/tests/layer_tests/pytorch_tests/test_unsqueeze.py@@ -64,6 +64,8 @@ class TestUnsqueezeCopy(PytorchLayerTest):return model_class(dim), op@pytest.mark.parametrize("dim", [0, 1, -1])+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_unsqueeze_copy(self, dim, ie_device, precision, ir_version):self._test(*self.create_model(dim), ie_device, precision, ir_version)diff --git a/tests/layer_tests/pytorch_tests/test_view.py b/tests/layer_tests/pytorch_tests/test_view.pyindex 8934e253095..98316e63ae9 100644--- a/tests/layer_tests/pytorch_tests/test_view.py+++ b/tests/layer_tests/pytorch_tests/test_view.py@@ -179,6 +179,8 @@ class TestViewCopy(PytorchLayerTest):return aten_view_copy(self.input_data), "aten::view_copy"+ @pytest.mark.nightly+ @pytest.mark.precommit@pytest.mark.precommit_fx_backenddef test_view_copy(self, ie_device, precision, ir_version, input_shapes):self.input_data = []diff --git a/tests/layer_tests/pytorch_tests/test_where.py b/tests/layer_tests/pytorch_tests/test_where.pyindex d377824f4b2..f8409e7f232 100644--- a/tests/layer_tests/pytorch_tests/test_where.py+++ b/tests/layer_tests/pytorch_tests/test_where.py@@ -142,7 +142,8 @@ class Testwhere(PytorchLayerTest):'mask_dtype': mask_dtype,'return_x_y': False,"x_dtype": x_dtype,- })+ },+ trace_model=True)@pytest.mark.parametrize("cond_val", ['zeros', 'ones'])@pytest.mark.parametrize("x_dtype", ["float32", "int32"])diff --git a/tests/model_hub_tests/pytorch/test_torchvision_models.py b/tests/model_hub_tests/pytorch/test_torchvision_models.pyindex 66a425d7308..75dcfae8b96 100644--- a/tests/model_hub_tests/pytorch/test_torchvision_models.py+++ b/tests/model_hub_tests/pytorch/test_torchvision_models.py@@ -3,12 +3,10 @@import osimport platform-import tempfileimport pytestimport torch-import torchvision.transforms.functional as F-from torchvision.models import list_models, get_model, get_model_weights+from torchvision.models import list_models, get_modelfrom models_hub_common.utils import get_models_list, retryfrom torch_utils import TestTorchConvertModel@@ -19,35 +17,6 @@ def get_all_models() -> list:return m_list-def get_video():- """- Download video and return frames.- Using free video from pexels.com, credits go to Pavel Danilyuk.- Initially used in https://pytorch.org/vision/stable/auto_examples/plot_optical_flow.html- """- from pathlib import Path- from urllib.request import urlretrieve- from torchvision.io import read_video-- video_url = "https://download.pytorch.org/tutorial/pexelscom_pavel_danilyuk_basketball_hd.mp4"- with tempfile.TemporaryDirectory() as tmp:- video_path = Path(tmp) / "basketball.mp4"- _ = urlretrieve(video_url, video_path)-- frames, _, _ = read_video(str(video_path), output_format="TCHW")- return frames---def prepare_frames_for_raft(name, frames1, frames2):- w = get_model_weights(name).DEFAULT- img1_batch = torch.stack(frames1)- img2_batch = torch.stack(frames2)- img1_batch = F.resize(img1_batch, size=[520, 960], antialias=False)- img2_batch = F.resize(img2_batch, size=[520, 960], antialias=False)- img1_batch, img2_batch = w.transforms()(img1_batch, img2_batch)- return (img1_batch, img2_batch)--# To make tests reproducible we seed the random generatortorch.manual_seed(0)@@ -65,13 +34,28 @@ class TestTorchHubConvertModel(TestTorchConvertModel):self.example = (torch.randn(2, 3, 16, 224, 224),)self.inputs = (torch.randn(3, 3, 16, 224, 224),)elif "raft" in model_name:- frames = get_video()- self.example = prepare_frames_for_raft(model_name,- [frames[100], frames[150]],- [frames[101], frames[151]])- self.inputs = prepare_frames_for_raft(model_name,- [frames[75], frames[125]],- [frames[76], frames[126]])+ # torchvision.io.read_video was removed in torchvision 0.27.0 and the+ # CPU wheel has no video-reading backend. Use smooth synthetic frames+ # (sine/cosine patterns with a small periodic shift) instead: structured+ # inputs give RAFT a well-conditioned optical-flow problem so the FP32+ # differences between OV and PyTorch stay within the 0.05 tolerance.+ # The shape (2, 3, 520, 960) matches what the old resize+normalise+ # pipeline produced from the basketball clip.+ import math+ h, w = 520, 960+ y = torch.linspace(-math.pi, math.pi, h).view(h, 1)+ x = torch.linspace(-math.pi, math.pi, w).view(1, w)+ freq = 4.0+ frame = torch.stack([+ torch.sin(freq * x) * torch.cos(freq * y),+ torch.cos(freq * x) * torch.sin(freq * y),+ torch.sin(freq * (x + y) * 0.5),+ ], dim=0) # [3, 520, 960], values in [-1, 1]+ # 2-pixel cyclic roll along width = stable constant horizontal flow+ frame1 = frame.unsqueeze(0).expand(2, -1, -1, -1).contiguous()+ frame2 = torch.roll(frame, shifts=2, dims=2).unsqueeze(0).expand(2, -1, -1, -1).contiguous()+ self.example = (frame1, frame2)+ self.inputs = (frame1.clone(), frame2.clone())elif "vit_h_14" in model_name:self.example = (torch.randn(1, 3, 518, 518),)self.inputs = (torch.randn(1, 3, 518, 518),)diff --git a/tests/requirements_pytorch b/tests/requirements_pytorchindex debf84e24ff..ac1b2bbe324 100644--- a/tests/requirements_pytorch+++ b/tests/requirements_pytorch@@ -6,11 +6,11 @@# test against NumPy 1.x with older Python versionsnumpy==1.26.4; python_version < "3.12"numpy==2.1.1; python_version >= "3.12"-torch==2.9.0+--extra-index-url https://download.pytorch.org/whl/cpu+torch==2.12.0+torchvision==0.27.0-torchvision==0.24.0-torchaudio==2.9.0pytest==7.0.1; python_version < '3.10'pytest==7.2.0; python_version >= '3.10'pytest-html==4.2.0