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
[PyTorch FE] Support det, svd, rank>2 linalg_norm and defer dynamic-kernel max_pool2d (#36742)
Evgeny Kotove051a8ce64b9
diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cppindex 06e36e3ca12..bd3c2a6a9aa 100644--- a/src/frontends/pytorch/src/frontend.cpp+++ b/src/frontends/pytorch/src/frontend.cpp@@ -30,6 +30,7 @@#include "transforms/einsum_list_construct.hpp"#include "transforms/index_loop_getitem_replacer.hpp"#include "transforms/listconstruct_replacer.hpp"+#include "transforms/max_pool_dynamic_kernel_resolver.hpp"#include "transforms/min_max_prim_list_construct_replacer.hpp"#include "transforms/prim_list_tuple_construct_replacer.hpp"#include "transforms/prim_list_unpack_replacer.hpp"@@ -265,6 +266,10 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {manager.register_pass<ov::frontend::pytorch::pass::AtenIndexToSelect>();manager.register_pass<ov::frontend::pytorch::pass::AtenIndexPutReplacer>();manager.register_pass<ov::frontend::pytorch::pass::IndexLoopGetitemReplacer>();+ // Resolve the deferred max_pool placeholder: after the preceding manager validated shapes, and+ // before SequenceMarkReplacer collapses the kernel_size SequenceMark to a Concat. A kernel that+ // became static (e.g. convert_model(input=...)) lowers to a plain MaxPool, else to ReduceMax.+ manager.register_pass<ov::frontend::pytorch::pass::MaxPoolDynamicKernelResolver>();manager.register_pass<ov::frontend::pytorch::pass::SequenceMarkReplacer>();// Check if model is symmetrically quantizeddiff --git a/src/frontends/pytorch/src/op/linalg_det.cpp b/src/frontends/pytorch/src/op/linalg_det.cppnew file mode 100644index 00000000000..a09ab778fd7--- /dev/null+++ b/src/frontends/pytorch/src/op/linalg_det.cpp@@ -0,0 +1,77 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov::op;++namespace detail {++// Element x[..., i, j] of a batched matrix (trailing singleton axes removed); positional indexing+// works for static and dynamic shapes.+Output<Node> matrix_element(const NodeContext& context, const Output<Node>& x, int64_t i, int64_t j) {+ auto row_idx = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {i}));+ auto col_idx = context.mark_node(v0::Constant::create(element::i32, Shape{1}, {j}));+ auto axis_row = context.mark_node(v0::Constant::create(element::i32, Shape{}, {-2}));+ auto axis_col = context.mark_node(v0::Constant::create(element::i32, Shape{}, {-1}));+ auto row = context.mark_node(std::make_shared<v8::Gather>(x, row_idx, axis_row)); // (..., 1, n)+ auto elem = context.mark_node(std::make_shared<v8::Gather>(row, col_idx, axis_col)); // (..., 1, 1)+ auto squeeze_axes = context.mark_node(v0::Constant::create(element::i32, Shape{2}, {-2, -1}));+ return context.mark_node(std::make_shared<v0::Squeeze>(elem, squeeze_axes)); // (...)+}++// Closed-form determinant of a batched 3x3 matrix via cofactor expansion.+Output<Node> det_3x3(const NodeContext& context, const Output<Node>& x) {+ Output<Node> m[3][3];+ for (int64_t i = 0; i < 3; ++i) {+ for (int64_t j = 0; j < 3; ++j) {+ m[i][j] = matrix_element(context, x, i, j);+ }+ }+ auto mul = [&](const Output<Node>& a, const Output<Node>& b) {+ return context.mark_node(std::make_shared<v1::Multiply>(a, b));+ };+ auto sub = [&](const Output<Node>& a, const Output<Node>& b) {+ return context.mark_node(std::make_shared<v1::Subtract>(a, b));+ };+ auto c0 = sub(mul(m[1][1], m[2][2]), mul(m[1][2], m[2][1]));+ auto c1 = sub(mul(m[1][0], m[2][2]), mul(m[1][2], m[2][0]));+ auto c2 = sub(mul(m[1][0], m[2][1]), mul(m[1][1], m[2][0]));+ auto t0 = mul(m[0][0], c0);+ auto t1 = mul(m[0][1], c1);+ auto t2 = mul(m[0][2], c2);+ return context.mark_node(std::make_shared<v1::Add>(sub(t0, t1), t2));+}++// 3x3 determinant (the rigid-transform / Kabsch use case): guard the trailing axes to 3x3, then+// apply the cofactor expansion.+Output<Node> det_small(const NodeContext& context, const Output<Node>& x) {+ return det_3x3(context, ensure_trailing_square(context, x, 3, "aten::det/linalg_det"));+}++} // namespace detail++OutputVector translate_linalg_det(const NodeContext& context) {+ // aten::linalg_det(Tensor A) -> Tensor+ // aten::det(Tensor self) -> Tensor+ num_inputs_check(context, 1, 1);+ auto x = context.get_input(0);+ return {detail::det_small(context, x)};+};++} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op/max_poolnd.cpp b/src/frontends/pytorch/src/op/max_poolnd.cppindex 7f81956fb9b..0ed7f4a3228 100644--- a/src/frontends/pytorch/src/op/max_poolnd.cpp+++ b/src/frontends/pytorch/src/op/max_poolnd.cpp@@ -2,24 +2,9 @@// SPDX-License-Identifier: Apache-2.0//+#include "openvino/core/validation_util.hpp"#include "openvino/frontend/pytorch/node_context.hpp"-#include "openvino/op/add.hpp"-#include "openvino/op/concat.hpp"-#include "openvino/op/constant.hpp"-#include "openvino/op/gather.hpp"-#include "openvino/op/greater.hpp"-#include "openvino/op/max_pool.hpp"-#include "openvino/op/multiply.hpp"-#include "openvino/op/pad.hpp"-#include "openvino/op/range.hpp"-#include "openvino/op/reshape.hpp"-#include "openvino/op/select.hpp"-#include "openvino/op/shape_of.hpp"-#include "openvino/op/slice.hpp"-#include "openvino/op/squeeze.hpp"-#include "openvino/op/subtract.hpp"-#include "openvino/op/unsqueeze.hpp"-#include "openvino/op/util/framework_node.hpp"+#include "openvino/op/util/attr_types.hpp"#include "utils.hpp"namespace ov {@@ -28,31 +13,23 @@ namespace pytorch {namespace op {using namespace ov::op;+OutputVector translate_max_pool_base(const NodeContext& context, int dims, bool return_indices) {num_inputs_check(context, 2, 6);auto input = context.get_input(0);- auto input_shape = context.mark_node(std::make_shared<v3::ShapeOf>(input));-- auto const_0 = v0::Constant::create(element::i64, Shape{1}, {0});- auto const_1 = v0::Constant::create(element::i64, Shape{1}, {1});- bool is_static = input.get_partial_shape().rank().is_static();- bool no_batch_dim = is_static && input.get_partial_shape().rank().get_length() == dims + 1;- if (is_static) {- if (no_batch_dim) {- input = context.mark_node(std::make_shared<v0::Unsqueeze>(input, const_0));- }- } else {- input = context.mark_node(std::make_shared<v0::Unsqueeze>(input, const_0));- auto unsqueeze_shape = context.mark_node(std::make_shared<v3::ShapeOf>(input));- auto rank = context.mark_node(std::make_shared<v0::ShapeOf>(unsqueeze_shape));- auto end_index = context.mark_node(std::make_shared<v1::Add>(rank, const_1));- auto start_index = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-dims - 2}));- auto reshape_pattern =- context.mark_node(std::make_shared<v8::Slice>(unsqueeze_shape, start_index, end_index, const_1, const_0));- input = context.mark_node(std::make_shared<v1::Reshape>(input, reshape_pattern, true));+ // The MaxPool kernel is a constructor attribute, but PyTorch can build kernel_size from runtime+ // values (e.g. [1, x.size(3)]). If any element is non-constant now, fail conversion so the op is+ // left as a PtFrameworkNode: MaxPoolDynamicKernelResolver picks it up after shapes propagate and+ // either folds it to a plain MaxPool (e.g. convert_model(input=...)) or a ReduceMax fallback.+ for (const auto& e : get_list_as_outputs(context.get_input(1))) {+ PYTORCH_OP_CONVERSION_CHECK(ov::util::get_constant_from_source(e),+ "aten::max_pool",+ dims,+ "d with a non-constant kernel_size is deferred to a normalization pass.");}+ // All kernel elements are constant -> build the static MaxPool directly.auto kernel = context.const_input<Shape>(1);Strides strides;if (!context.input_is_none(2)) {@@ -79,63 +56,10 @@ OutputVector translate_max_pool_base(const NodeContext& context, int dims, boolrounding_type = context.const_input<bool>(5) ? RoundingType::CEIL_TORCH : RoundingType::FLOOR;}- auto res = context.mark_node(std::make_shared<v14::MaxPool>(input,- strides,- dilations,- pads,- pads,- kernel,- rounding_type,- PadType::EXPLICIT,- element::i64,- 2));- if (is_static) {- if (no_batch_dim) {- if (return_indices) {- auto out1 = res->output(0);- auto out2 = res->output(1);- out1 = context.mark_node(std::make_shared<v0::Squeeze>(out1, const_0));- out2 = context.mark_node(std::make_shared<v0::Squeeze>(out2, const_0));- return {std::move(out1), std::move(out2)};- } else {- res = context.mark_node(std::make_shared<v0::Squeeze>(res, const_0));- return {res};- }- } else {- if (return_indices) {- auto out1 = res->output(0);- auto out2 = res->output(1);- return {std::move(out1), std::move(out2)};- } else {- return {res};- }- }-- } else {- auto pooled_output_shape = context.mark_node(std::make_shared<v3::ShapeOf>(res));-- auto start_index_input = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-dims}));- auto slice_input_shape =- context.mark_node(std::make_shared<v8::Slice>(input_shape, const_0, start_index_input, const_1, const_0));-- auto start_index_pooled = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-dims}));- auto end_index_pooled = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {2 + dims}));- auto slice_pooled_output_shape = context.mark_node(- std::make_shared<v8::Slice>(pooled_output_shape, start_index_pooled, end_index_pooled, const_1, const_0));-- auto concat_shape = context.mark_node(- std::make_shared<v0::Concat>(OutputVector{slice_input_shape, slice_pooled_output_shape}, 0));- if (return_indices) {- auto out1 = res->output(0);- auto out2 = res->output(1);- out1 = context.mark_node(std::make_shared<v1::Reshape>(out1, concat_shape, true));- out2 = context.mark_node(std::make_shared<v1::Reshape>(out2, concat_shape, true));- return {std::move(out1), std::move(out2)};- } else {- res = context.mark_node(std::make_shared<v1::Reshape>(res, concat_shape, true));- return {res};- }- }+ ov::pass::NodeRegistry rg;+ auto res = build_static_max_pool(rg, input, dims, return_indices, kernel, strides, pads, dilations, rounding_type);+ context.mark_nodes(rg.get());+ return res;};OutputVector translate_max_pool1d(const NodeContext& context) {diff --git a/src/frontends/pytorch/src/op/norm.cpp b/src/frontends/pytorch/src/op/norm.cppindex a019e53697b..9880ba91791 100644--- a/src/frontends/pytorch/src/op/norm.cpp+++ b/src/frontends/pytorch/src/op/norm.cpp@@ -226,7 +226,7 @@ OutputVector translate_linalg_matrix_norm(const NodeContext& context) {Output<Node> result;// dtype may be used to perform the computation in a more precise dtype. It is semantically equivalent to calling- // linalg.mtrix_norm(x.to(dtype))+ // linalg.matrix_norm(x.to(dtype))if (!context.input_is_none(4)) {x = apply_dtype(context, 4, x);}@@ -269,16 +269,10 @@ OutputVector translate_linalg_norm(const NodeContext& context) {} else {dim = concat_list_construct(context.get_input(2));}- // default norm for matrix is frobenius norm, for vector - L2, for other ranks are not determined+ // ord=None: Frobenius and vector L2 are both sqrt(sum(x^2)) over `dim` for the real inputs here,+ // so a single L2 reduction is correct and rank-agnostic -- no static rank or foldable `dim` needed.if (context.input_is_none(1)) {- auto input_rank = x.get_partial_shape().rank();- if (input_rank.is_static() && input_rank.get_length() == 2) {- result = frobenius_norm(context, x, dim, keep_dim);- } else if (input_rank.is_dynamic() || input_rank.get_length() == 1) {- result = norm_vector(context, x, dim, 2, keep_dim);- } else {- PYTORCH_OP_CONVERSION_CHECK(false, "linalg norm for tensor rank > 2 without ord specification unsupported");- }+ result = norm_vector(context, x, dim, 2, keep_dim);} else {// ord defines the norm that is computed can be string or numberauto ord_type = context.get_input_type(1);diff --git a/src/frontends/pytorch/src/op/svd.cpp b/src/frontends/pytorch/src/op/svd.cppnew file mode 100644index 00000000000..f227403ff0a--- /dev/null+++ b/src/frontends/pytorch/src/op/svd.cpp@@ -0,0 +1,254 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/core/validation_util.hpp"+#include "openvino/op/abs.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.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/divide.hpp"+#include "openvino/op/equal.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/less.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/select.hpp"+#include "openvino/op/sign.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov::op;++namespace {++// One-sided Jacobi for 3x3 converges in ~5 sweeps; 6 adds margin (matches torch.svd to ~1e-5,+// incl. rank-deficient matrices).+constexpr int SVD_SWEEPS = 6;+// Column index pairs swept by one-sided Jacobi.+constexpr int PAIRS[3][2] = {{0, 1}, {0, 2}, {1, 2}};++// SVD of batched 3x3 matrices via ONE-SIDED JACOBI. Operating on A directly (not on A^T A) stays+// fp32-accurate for rank-deficient matrices (the 3-point Kabsch matrices in SAM-6D pose). It+// orthogonalizes A's columns over a fixed number of sweeps (accumulated into V); the singular+// values are then the column norms and U = A_col / sigma, sorted descending like torch.+class JacobiSvd3x3 {+public:+ JacobiSvd3x3(const NodeContext& context, element::Type et) : m_ctx(context), m_et(et), m_tiny(cf(1e-30f)) {}++ // Returns {U, S, V}: U (...,3,3), S (...,3) descending, V (...,3,3) with the right singular+ // vectors as columns (the torch.svd convention).+ std::tuple<Output<Node>, Output<Node>, Output<Node>> build(const Output<Node>& A_in) {+ // Working columns of A and of V (V starts as identity columns).+ Output<Node> a[3] = {mcol(A_in, 0), mcol(A_in, 1), mcol(A_in, 2)};+ Output<Node> v[3] = {ident_col(A_in, 0), ident_col(A_in, 1), ident_col(A_in, 2)};++ for (int sweep = 0; sweep < SVD_SWEEPS; ++sweep) {+ for (auto& pr : PAIRS) {+ jacobi_rotate(a[pr[0]], a[pr[1]], v[pr[0]], v[pr[1]]);+ }+ }++ // Singular values = column norms; left singular vectors = normalized columns.+ Output<Node> sig[3], u[3];+ for (int k = 0; k < 3; ++k) {+ sig[k] = sqrt(dot(a[k], a[k])); // (...,1,1)+ u[k] = div(a[k], add(sig[k], m_tiny));+ }++ // Sort columns by descending singular value (3-element sorting network): (0,1),(1,2),(0,1).+ cmp_exchange(sig[0], sig[1], u[0], u[1], v[0], v[1]);+ cmp_exchange(sig[1], sig[2], u[1], u[2], v[1], v[2]);+ cmp_exchange(sig[0], sig[1], u[0], u[1], v[0], v[1]);++ auto U = colstack(u[0], u[1], u[2]);+ auto V = colstack(v[0], v[1], v[2]);+ // sig[k] are (...,1,1); concat along -1 -> (...,1,3); squeeze -2 -> (...,3).+ auto S_kd = m_ctx.mark_node(std::make_shared<v0::Concat>(OutputVector{sig[0], sig[1], sig[2]}, -1));+ auto S = m_ctx.mark_node(std::make_shared<v0::Squeeze>(S_kd, ci_s(-2)));+ return {U, S, V};+ }++private:+ // --- constant helpers ---+ Output<Node> cf(float v) {+ return m_ctx.mark_node(v0::Constant::create(m_et, Shape{}, {v}));+ }+ static std::shared_ptr<v0::Constant> ci(int64_t v) {+ return v0::Constant::create(element::i32, Shape{1}, {v});+ }+ static std::shared_ptr<v0::Constant> ci_s(int64_t v) {+ return v0::Constant::create(element::i32, Shape{}, {v});+ }++ // --- elementwise wrappers ---+ Output<Node> mul(const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::Multiply>(a, b));+ }+ Output<Node> add(const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::Add>(a, b));+ }+ Output<Node> sub(const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::Subtract>(a, b));+ }+ Output<Node> div(const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::Divide>(a, b));+ }+ Output<Node> sqrt(const Output<Node>& a) {+ return m_ctx.mark_node(std::make_shared<v0::Sqrt>(a));+ }+ Output<Node> sel(const Output<Node>& c, const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::Select>(c, a, b));+ }++ // Column k of a (...,3,3) matrix as a (...,3,1) keepdim vector (trailing axis = component).+ Output<Node> mcol(const Output<Node>& m, int64_t k) {+ return m_ctx.mark_node(std::make_shared<v8::Gather>(m, ci(k), ci_s(-1))); // (...,3,1)+ }+ // Identity column k, broadcast to the batch of `like`, as a (...,3,1) vector.+ Output<Node> ident_col(const Output<Node>& like, int64_t k) {+ std::vector<float> e(3, 0.0f);+ e[static_cast<size_t>(k)] = 1.0f;+ auto col = m_ctx.mark_node(v0::Constant::create(m_et, Shape{3, 1}, e));+ // Broadcast to batch via add with 0*like-column (keeps (...,3,1)).+ auto zero_like = mul(mcol(like, 0), cf(0.0f));+ return add(col, zero_like);+ }+ // Reduce over the vector axis (-2) keeping it: dot of two (...,3,1) vectors -> (...,1,1).+ Output<Node> dot(const Output<Node>& a, const Output<Node>& b) {+ return m_ctx.mark_node(std::make_shared<v1::ReduceSum>(mul(a, b), ci_s(-2), true));+ }++ // One Jacobi rotation orthogonalizing columns (ap, aq); the same rotation is applied to+ // (vp, vq). All operands are (...,3,1) vectors.+ void jacobi_rotate(Output<Node>& ap, Output<Node>& aq, Output<Node>& vp, Output<Node>& vq) {+ auto alpha = dot(ap, ap); // (...,1,1)+ auto beta = dot(aq, aq);+ auto gamma = dot(ap, aq);+ auto denom = mul(cf(2.0f), gamma);+ // zeta = (beta - alpha) / (2 gamma); guard the divide and clamp so zeta*zeta stays fp32-finite.+ auto zeta = div(sub(beta, alpha), add(denom, m_tiny));+ zeta = m_ctx.mark_node(std::make_shared<v0::Clamp>(zeta, -1e18, 1e18));+ auto azeta = absval(zeta);+ // t = sign(zeta) / (|zeta| + sqrt(1 + zeta^2)); |t| <= 1 (overflow-free).+ auto t_mag = div(cf(1.0f), add(azeta, sqrt(add(cf(1.0f), mul(zeta, zeta)))));+ auto t = mul(signum(zeta), t_mag);+ // Columns already orthogonal (gamma ~ 0) -> t = 0 (identity).+ auto orthogonal = m_ctx.mark_node(std::make_shared<v1::Less>(absval(gamma), m_tiny));+ t = sel(orthogonal, cf(0.0f), t);+ auto c = div(cf(1.0f), sqrt(add(cf(1.0f), mul(t, t))));+ auto s = mul(c, t);+ rotate_pair(ap, aq, c, s);+ rotate_pair(vp, vq, c, s);+ }++ void rotate_pair(Output<Node>& p, Output<Node>& q, const Output<Node>& c, const Output<Node>& s) {+ auto np = sub(mul(c, p), mul(s, q));+ auto nq = add(mul(s, p), mul(c, q));+ p = np;+ q = nq;+ }++ // Compare-exchange so sig_p >= sig_q after the call, swapping the U and V columns to match.+ // sig_* are (...,1,1); cols are (...,3,1).+ void cmp_exchange(Output<Node>& sp,+ Output<Node>& sq,+ Output<Node>& up,+ Output<Node>& uq,+ Output<Node>& vp,+ Output<Node>& vq) {+ auto swap = m_ctx.mark_node(std::make_shared<v1::Less>(sp, sq)); // swap if sp < sq+ // The (...,1,1) mask broadcasts over the (...,3,1) vectors.+ auto nsp = sel(swap, sq, sp);+ auto nsq = sel(swap, sp, sq);+ auto nup = sel(swap, uq, up);+ auto nuq = sel(swap, up, uq);+ auto nvp = sel(swap, vq, vp);+ auto nvq = sel(swap, vp, vq);+ sp = nsp;+ sq = nsq;+ up = nup;+ uq = nuq;+ vp = nvp;+ vq = nvq;+ }++ Output<Node> absval(const Output<Node>& x) {+ return m_ctx.mark_node(std::make_shared<v0::Abs>(x));+ }+ Output<Node> signum(const Output<Node>& x) {+ // sign(x) forcing sign(0) = +1: v0::Sign(0) = 0 would zero t and skip the +-45 degree+ // rotation when two equal-norm columns are non-orthogonal (zeta == 0), leaving+ // rank-deficient columns un-orthogonalized.+ auto s = m_ctx.mark_node(std::make_shared<v0::Sign>(x));+ auto is_zero = m_ctx.mark_node(std::make_shared<v1::Equal>(x, cf(0.0f)));+ return sel(is_zero, cf(1.0f), s);+ }++ // Stack three (...,3,1) column vectors into a (...,3,3) matrix (columns).+ Output<Node> colstack(const Output<Node>& a, const Output<Node>& b, const Output<Node>& c) {+ return m_ctx.mark_node(std::make_shared<v0::Concat>(OutputVector{a, b, c}, -1));+ }++ const NodeContext& m_ctx;+ element::Type m_et;+ Output<Node> m_tiny;+};++} // namespace++OutputVector translate_svd(const NodeContext& context) {+ // aten::svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V)+ num_inputs_check(context, 1, 3);++ // PyTorch zero-fills U/V when compute_uv=False, but this translator always produces real U/V,+ // so reject a constant-false (or non-constant, possibly-false) compute_uv. input_is_none checks+ // the input size internally, so no separate get_input_size guard is needed.+ if (!context.input_is_none(2)) {+ const auto c = ov::util::get_constant_from_source(context.get_input(2));+ PYTORCH_OP_CONVERSION_CHECK(c, "aten::svd with a non-constant compute_uv is not supported.");+ const auto vals = c->cast_vector<bool>();+ PYTORCH_OP_CONVERSION_CHECK(vals.empty() || vals[0], "aten::svd with compute_uv=False is not supported.");+ }++ auto x = context.get_input(0);+ // The Jacobi decomposition is 3x3-only; guard the trailing axes (non-3x3 fails at conversion+ // or loudly at runtime).+ x = ensure_trailing_square(context, x, 3, "aten::svd");++ auto in_et = x.get_element_type();+ // Compute in f32 (f16/bf16 are too coarse for the rotations); keep f64 when statically requested.+ auto compute_et = (in_et == element::f64) ? element::f64 : element::f32;+ Output<Node> A = x;+ if (in_et != compute_et) {+ A = context.mark_node(std::make_shared<v0::Convert>(x, compute_et));+ }++ JacobiSvd3x3 builder(context, compute_et);+ Output<Node> U, S, V;+ std::tie(U, S, V) = builder.build(A);++ // Cast outputs back to the input type. ConvertLike resolves it from `x` even when `x`'s type+ // is dynamic at conversion time (a direct Convert would fail).+ if (in_et != compute_et) {+ U = context.mark_node(std::make_shared<v1::ConvertLike>(U, x));+ S = context.mark_node(std::make_shared<v1::ConvertLike>(S, x));+ V = context.mark_node(std::make_shared<v1::ConvertLike>(V, x));+ }+ return {U, S, V};+};++} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 648ac575e5d..36c5c122b2b 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -151,6 +151,7 @@ OP_CONVERTER(translate_layer_norm);OP_CONVERTER(translate_len);OP_CONVERTER(translate_lerp);OP_CONVERTER(translate_linalg_cross);+OP_CONVERTER(translate_linalg_det);OP_CONVERTER(translate_linalg_norm);OP_CONVERTER(translate_linalg_matrix_norm);OP_CONVERTER(translate_linalg_vector_norm);@@ -263,6 +264,7 @@ OP_CONVERTER(translate_stack);OP_CONVERTER(translate_std);OP_CONVERTER(translate_std_mean);OP_CONVERTER(translate_stft);+OP_CONVERTER(translate_svd);OP_CONVERTER(translate_sub);OP_CONVERTER(translate_sub_);OP_CONVERTER(translate_sum);@@ -501,6 +503,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::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{"aten::dim", op::translate_dim},@@ -603,6 +606,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::lift_fresh", op::skip_node},{"aten::lift_fresh_copy", op::skip_node},{"aten::linalg_cross", op::translate_linalg_cross},+ {"aten::linalg_det", op::translate_linalg_det},{"aten::linalg_inv", op::translate_inverse},{"aten::linalg_norm", op::translate_linalg_norm},{"aten::linalg_matrix_norm", op::translate_linalg_matrix_norm},@@ -765,6 +769,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::sub", op::translate_sub},{"aten::sub_", op::translate_sub_},{"aten::sum", op::translate_sum},+ {"aten::svd", op::translate_svd},{"aten::swapaxes", op::quantizable_op<op::translate_transpose>},{"aten::t", op::translate_t},{"aten::take_along_dim", op::translate_take_along_dim},diff --git a/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.cpp b/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.cppnew file mode 100644index 00000000000..132f23dba6f--- /dev/null+++ b/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.cpp@@ -0,0 +1,403 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "max_pool_dynamic_kernel_resolver.hpp"++#include <optional>++#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/validation_util.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/reduce_max.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/util/attr_types.hpp"+#include "openvino/op/util/framework_node.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "pt_framework_node.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace pass {++using namespace ov::op;++namespace {++// Deferred max_pool op-types emitted as PtFrameworkNode by translate_max_pool_base (mirrors the+// TorchScript and FX op_table entries).+const std::initializer_list<std::string> MAX_POOL_TYPES = {"aten::max_pool1d",+ "aten::max_pool1d_with_indices",+ "aten::max_pool2d",+ "aten::max_pool2d_with_indices",+ "aten::max_pool3d",+ "aten::max_pool3d_with_indices",+ "aten.max_pool2d_with_indices.default",+ "aten.max_pool3d_with_indices.default"};++// Recover the spatial rank (1/2/3) from the op-type string.+int dims_from_op_type(const std::string& op_type) {+ if (op_type.find("max_pool1d") != std::string::npos)+ return 1;+ if (op_type.find("max_pool2d") != std::string::npos)+ return 2;+ return 3;+}++// True when input `index` is absent or an explicit `none` node (an omitted optional argument).+bool input_is_none_or_missing(const std::shared_ptr<ov::op::util::FrameworkNode>& fw, size_t index) {+ if (index >= fw->get_input_size())+ return true;+ return is_none_node(fw->input_value(index));+}++// Fold an optional list attribute (stride/padding/dilation) to i64. Returns an (possibly empty)+// vector when foldable -- empty means the input is absent/None/empty ("use the default"). Returns+// nullopt when the input is present but not constant-foldable: a runtime stride/padding/dilation+// fits neither lowering, so the caller rejects the op (leaving the framework node) instead.+std::optional<std::vector<int64_t>> fold_optional_list(const std::shared_ptr<ov::op::util::FrameworkNode>& fw,+ size_t index) {+ if (input_is_none_or_missing(fw, index))+ return std::vector<int64_t>{};+ auto src = fw->input_value(index);+ if (is_empty_list(src))+ return std::vector<int64_t>{};+ auto folded = ov::util::get_constant_from_source(concat_list_construct(src));+ if (!folded)+ return std::nullopt;+ return folded->cast_vector<int64_t>();+}++// Fold the optional ceil_mode flag. False (the default) when absent/None; nullopt when present but+// not constant-foldable (a runtime ceil_mode fits neither lowering).+std::optional<bool> fold_ceil_mode(const std::shared_ptr<ov::op::util::FrameworkNode>& fw, size_t index) {+ if (input_is_none_or_missing(fw, index))+ return false;+ auto ceil_c = ov::util::get_constant_from_source(fw->input_value(index));+ if (!ceil_c)+ return std::nullopt;+ auto vals = ceil_c->cast_vector<bool>();+ if (vals.empty())+ return std::nullopt;+ return vals[0];+}++// Normalize a folded stride/padding/dilation list to exactly `dims` entries: broadcast a size-1+// list (PyTorch's scalar int[N] form) and reject a length that is neither 1 nor `dims`, or any+// value below `min_val` (stride/dilation must be >= 1, padding >= 0). The min_val check also+// rejects a negative that would otherwise wrap to a huge size_t. Returns nullopt on any rejection;+// the caller then annotates the framework node and leaves it (no throw), matching the pass contract.+std::optional<std::vector<size_t>> normalize_pool_attr(const std::vector<int64_t>& vals, int dims, int64_t min_val) {+ if (static_cast<int>(vals.size()) != 1 && static_cast<int>(vals.size()) != dims)+ return std::nullopt;+ std::vector<size_t> out;+ out.reserve(static_cast<size_t>(dims));+ for (int i = 0; i < dims; ++i) {+ const int64_t v = vals.size() == 1 ? vals[0] : vals[i];+ if (v < min_val)+ return std::nullopt;+ out.push_back(static_cast<size_t>(v));+ }+ return out;+}++// Runtime-assert that spatial axis `spatial_idx` (within the trailing `dims` axes) has extent `k`:+// a Reshape copying every axis but pinning this one to `k`. Identity when extent == k; a strided+// pool (k < extent) makes the element counts disagree, so the Reshape fails loudly.+Output<Node> guard_full_extent_axis(ov::pass::NodeRegistry& rg,+ const Output<Node>& tensor,+ int dims,+ int spatial_idx,+ const Output<Node>& k) {+ auto zero = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{0});+ auto one = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{1});+ auto neg_dims = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{-dims});+ auto shape = rg.make<v3::ShapeOf>(tensor, element::i64);+ // Leading (non-pooled) axes, copied verbatim; empty when rank == dims (Concat handles it).+ auto batch = rg.make<v8::Slice>(shape, zero, neg_dims, one, zero);+ Output<Node> k_i64 = k;+ if (k_i64.get_element_type() != element::i64) {+ k_i64 = rg.make<v0::Convert>(k_i64, element::i64);+ }+ // Reshape the scalar kernel element to 1-D [1] so it slots into the shape.+ auto k_1d = rg.make<v1::Reshape>(k_i64, one, false);+ OutputVector parts{batch};+ for (int t = 0; t < dims; ++t) {+ if (t == spatial_idx) {+ parts.push_back(k_1d);+ } else {+ // Copy this axis's current extent (negative index works for dynamic rank).+ auto idx = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{t - dims});+ parts.push_back(rg.make<v8::Gather>(shape, idx, zero));+ }+ }+ auto target = rg.make<v0::Concat>(parts, 0);+ auto guarded = rg.make<v1::Reshape>(tensor, target, false);+ // The CPU plugin embeds this name in the runtime error.+ guarded->set_friendly_name("aten::max_pool" + std::to_string(dims) + "d/require_full_extent");+ return guarded;+}++// Build the full-extent ReduceMax decomposition for a runtime kernel. `reduce_axes` are the negative+// spatial-axis indices to pool (exactly the non-constant kernel elements); each is first guarded to+// equal its runtime kernel value, so a strided pool (kernel < extent) fails loudly at inference.+// The config is validated by the caller before this pure builder runs, so it never rejects.+OutputVector build_dynamic_kernel_max_pool(ov::pass::NodeRegistry& rg,+ int dims,+ const Output<Node>& input,+ const std::vector<bool>& elem_is_const,+ const std::vector<Output<Node>>& elem_runtime_val,+ const std::vector<int64_t>& reduce_axes) {+ Output<Node> guarded = input;+ for (int i = 0; i < dims; ++i) {+ if (!elem_is_const[i]) {+ // Runtime element: guard that it spans the whole axis (global pool).+ guarded = guard_full_extent_axis(rg, guarded, dims, i, elem_runtime_val[i]);+ }+ }+ auto axes = rg.make<v0::Constant>(element::i64, Shape{reduce_axes.size()}, reduce_axes);+ auto res = rg.make<v1::ReduceMax>(guarded, axes, /*keep_dims=*/true);+ return {res};+}++} // namespace++MaxPoolDynamicKernelResolver::MaxPoolDynamicKernelResolver() {+ auto fw_pattern = ov::pass::pattern::wrap_type<ov::op::util::FrameworkNode>(fw_node_predicate(MAX_POOL_TYPES));++ ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {+ auto fw_node = ov::as_type_ptr<ov::op::util::FrameworkNode>(m.get_match_root());+ if (!fw_node) {+ return false;+ }+ const auto& attrs = fw_node->get_attrs();+ const auto op_type_it = attrs.find(PtFrameworkNode::op_type_key);+ if (op_type_it == attrs.end()) {+ return false;+ }+ const std::string op_type = op_type_it->second;+ const int dims = dims_from_op_type(op_type);+ const bool return_indices = fw_node->get_output_size() == 2;+ // Op label used in the annotations below; the unconverted-ops reporter surfaces them.+ const std::string op_label = "aten::max_pool" + std::to_string(dims) + "d";++ // Re-probe the kernel_size now that shapes have propagated. get_list_as_outputs handles both+ // the SequenceMark form and a list already lowered to elementwise outputs.+ std::vector<bool> elem_is_const;+ std::vector<int64_t> elem_const_val;+ std::vector<Output<Node>> elem_runtime_val;+ bool kernel_is_static = true;+ for (const auto& e : get_list_as_outputs(fw_node->input_value(1))) {+ if (const auto c = ov::util::get_constant_from_source(e)) {+ for (auto val : c->cast_vector<int64_t>()) {+ elem_is_const.push_back(true);+ elem_const_val.push_back(val);+ elem_runtime_val.emplace_back();+ }+ } else {+ elem_is_const.push_back(false);+ elem_const_val.push_back(-1);+ elem_runtime_val.push_back(e);+ kernel_is_static = false;+ }+ }+ // A scalar kernel_size applies to every axis. Copy element 0 into locals first:+ // assign(dims, elem_runtime_val[0]) would alias into the vector as it reallocates (UB).+ if (elem_is_const.size() == 1 && dims > 1) {+ const bool c0 = elem_is_const[0];+ const int64_t v0 = elem_const_val[0];+ const Output<Node> r0 = elem_runtime_val[0];+ elem_is_const.assign(dims, c0);+ elem_const_val.assign(dims, v0);+ elem_runtime_val.assign(dims, r0);+ }++ // We don't throw from transformations: on any config neither lowering can honor, annotate the+ // framework node with the reason and return false, leaving it for the unconverted-ops reporter.+ ov::pass::NodeRegistry rg;+ OutputVector new_outputs;++ if (kernel_is_static) {+ // Kernel now fully constant -> build the static MaxPool.+ Shape kernel;+ for (auto v : elem_const_val)+ kernel.push_back(static_cast<size_t>(v));++ auto stride_vals = fold_optional_list(fw_node, 2);+ if (!stride_vals) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant stride is not supported.");+ return false;+ }+ // Normalize each attr to `dims` entries: broadcast a scalar (int[N]) form and reject a+ // bad length or an out-of-range value, so a size-1 or negative list cannot reach the+ // MaxPool op as a mismatched/wrapped size_t.+ Strides strides;+ if (stride_vals->empty()) {+ strides = kernel; // default stride is kernel+ } else {+ auto n = normalize_pool_attr(*stride_vals, dims, /*min_val=*/1);+ if (!n) {+ add_exception_to_fw_node(fw_node, op_label + " with an unsupported stride is not supported.");+ return false;+ }+ strides = Strides(*n);+ }+ auto pad_vals = fold_optional_list(fw_node, 3);+ if (!pad_vals) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant padding is not supported.");+ return false;+ }+ Shape pads;+ if (pad_vals->empty()) {+ pads = Shape(kernel.size(), 0);+ } else {+ auto n = normalize_pool_attr(*pad_vals, dims, /*min_val=*/0);+ if (!n) {+ add_exception_to_fw_node(fw_node, op_label + " with an unsupported padding is not supported.");+ return false;+ }+ pads = Shape(*n);+ }+ auto dil_vals = fold_optional_list(fw_node, 4);+ if (!dil_vals) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant dilation is not supported.");+ return false;+ }+ Strides dilations(dims, 1);+ if (!dil_vals->empty()) {+ auto n = normalize_pool_attr(*dil_vals, dims, /*min_val=*/1);+ if (!n) {+ add_exception_to_fw_node(fw_node, op_label + " with an unsupported dilation is not supported.");+ return false;+ }+ dilations = Strides(*n);+ }+ auto ceil_mode = fold_ceil_mode(fw_node, 5);+ if (!ceil_mode) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant ceil_mode is not supported.");+ return false;+ }+ RoundingType rounding_type = *ceil_mode ? RoundingType::CEIL_TORCH : RoundingType::FLOOR;+ new_outputs = build_static_max_pool(rg,+ fw_node->input_value(0),+ dims,+ return_indices,+ kernel,+ strides,+ pads,+ dilations,+ rounding_type);+ } else {+ // Kernel still dynamic -> the ReduceMax full-extent decomposition. It is exact only for a+ // global pool with default placement: reject everything else, leaving the framework node.+ if (return_indices) {+ add_exception_to_fw_node(+ fw_node,+ op_label + " with a non-constant kernel_size and return_indices=True is not supported.");+ return false;+ }+ bool stride_is_default = input_is_none_or_missing(fw_node, 2) || is_empty_list(fw_node->input_value(2));+ if (!stride_is_default) {+ add_exception_to_fw_node(fw_node,+ op_label + " with a non-constant kernel_size is only supported with the "+ "default stride (stride=kernel_size).");+ return false;+ }+ auto pad_vals = fold_optional_list(fw_node, 3);+ if (!pad_vals) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant padding is not supported.");+ return false;+ }+ for (auto p : *pad_vals) {+ if (p != 0) {+ add_exception_to_fw_node(+ fw_node,+ op_label + " with a non-constant kernel_size is only supported with zero padding.");+ return false;+ }+ }+ auto dil_vals = fold_optional_list(fw_node, 4);+ if (!dil_vals) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant dilation is not supported.");+ return false;+ }+ for (auto d : *dil_vals) {+ if (d != 1) {+ add_exception_to_fw_node(+ fw_node,+ op_label + " with a non-constant kernel_size is only supported with dilation 1.");+ return false;+ }+ }+ auto ceil_mode = fold_ceil_mode(fw_node, 5);+ if (!ceil_mode) {+ add_exception_to_fw_node(fw_node, op_label + " with a non-constant ceil_mode is not supported.");+ return false;+ }+ if (*ceil_mode) {+ add_exception_to_fw_node(+ fw_node,+ op_label + " with a non-constant kernel_size is only supported with ceil_mode=False.");+ return false;+ }+ if (static_cast<int>(elem_is_const.size()) != dims || static_cast<int>(elem_runtime_val.size()) != dims) {+ add_exception_to_fw_node(fw_node,+ op_label + ": could not interpret the non-constant kernel_size (expected " ++ std::to_string(dims) + " spatial entries).");+ return false;+ }+ // Per axis: reduce it (full-extent) or leave it (window 1); a static window > 1 is a+ // sliding-window pool a ReduceMax cannot represent.+ std::vector<int64_t> reduce_axes;+ for (int i = 0; i < dims; ++i) {+ const int64_t axis = static_cast<int64_t>(i) - dims; // negative index of this spatial axis+ if (!elem_is_const[i]) {+ reduce_axes.push_back(axis);+ } else if (elem_const_val[i] == 1) {+ continue; // window of 1 (default stride) is an identity+ } else {+ add_exception_to_fw_node(+ fw_node,+ op_label + " with a non-constant kernel_size is only supported when every pooled axis spans "+ "its full extent (the kernel along statically-sized axes must be 1).");+ return false;+ }+ }+ if (reduce_axes.empty()) {+ add_exception_to_fw_node(fw_node,+ op_label + ": a non-constant kernel_size that pools no axis is unexpected.");+ return false;+ }+ new_outputs = build_dynamic_kernel_max_pool(rg,+ dims,+ fw_node->input_value(0),+ elem_is_const,+ elem_runtime_val,+ reduce_axes);+ }++ // copy_runtime_info (not _and_name) so the guard nodes keep their op-labeled friendly names+ // (e.g. aten::max_poolNd/require_full_extent, asserted by the runtime-guard test).+ ov::copy_runtime_info(fw_node, rg.get());+ replace_node(fw_node, new_outputs);+ return true;+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(fw_pattern,+ "ov::frontend::pytorch::pass::MaxPoolDynamicKernelResolver");+ this->register_matcher(m, callback);+}++} // namespace pass+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.hpp b/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.hppnew file mode 100644index 00000000000..031373cb876--- /dev/null+++ b/src/frontends/pytorch/src/transforms/max_pool_dynamic_kernel_resolver.hpp@@ -0,0 +1,28 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/pass.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace pass {++// Resolves the deferred max_pool placeholder (a PtFrameworkNode emitted by translate_max_pool_base+// when kernel_size was not a compile-time constant). Runs after shape propagation: a kernel that+// became static (e.g. via convert_model(input=...)) lowers to a plain v14::MaxPool; one still+// dynamic falls back to the ReduceMax full-extent decomposition.+class MaxPoolDynamicKernelResolver : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::pytorch::pass::MaxPoolDynamicKernelResolver");+ MaxPoolDynamicKernelResolver();+};++} // namespace pass+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex c11f3912f25..99bf5a92f05 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -19,6 +19,7 @@#include "openvino/op/gather.hpp"#include "openvino/op/gather_nd.hpp"#include "openvino/op/loop.hpp"+#include "openvino/op/max_pool.hpp"#include "openvino/op/mod.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/non_zero.hpp"@@ -160,6 +161,73 @@ Output<Node> reshape_kernel_for_group(const NodeContext& context, const Output<Nreturn res;}+Output<Node> ensure_trailing_square(const NodeContext& context,+ const Output<Node>& x,+ int64_t n,+ const std::string& op_label) {+ const auto& pshape = x.get_partial_shape();+ const auto rank = pshape.rank();+ if (rank.is_static()) {+ // A matrix op needs >= 2 axes; reject a lower static rank rather than letting the runtime+ // guard reinterpret e.g. a 1-D n*n tensor as n x n.+ PYTORCH_OP_CONVERSION_CHECK(rank.get_length() >= 2,+ op_label,+ " requires a batch of ",+ n,+ "x",+ n,+ " matrices (rank >= 2), got rank ",+ rank.get_length(),+ ".");+ const auto& m_dim = pshape[rank.get_length() - 2];+ const auto& n_dim = pshape[rank.get_length() - 1];+ // Fail at conversion on any statically-known trailing dim != n, giving the clean op-labeled+ // message instead of a bare runtime reshape error.+ PYTORCH_OP_CONVERSION_CHECK(+ (!m_dim.is_static() || m_dim.get_length() == n) && (!n_dim.is_static() || n_dim.get_length() == n),+ op_label,+ " is only supported for ",+ n,+ "x",+ n,+ " matrices, got trailing dimensions ",+ m_dim,+ "x",+ n_dim,+ ".");+ if (m_dim.is_static() && n_dim.is_static()) {+ return x; // genuine static n x n: no runtime guard needed+ }+ }+ // Dynamic trailing dims: pin each trailing axis to n with its own Reshape so the element-count+ // check runs per axis (one [..,n,n] reshape checks only n*n total, so [1,9] would pass as 3x3).+ // A genuine n x n is an identity through both; anything else fails loudly at runtime. The+ // op-labeled name surfaces the op and size in the CPU error, matching the static branch.+ const auto guard_name = op_label + "/requires_" + std::to_string(n) + "x" + std::to_string(n);+ auto step = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {1}));+ auto axis = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {0}));+ auto zero = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {0}));+ auto n_1d = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {n}));+ auto nn = context.mark_node(v0::Constant::create(element::i64, Shape{2}, {n, n}));++ // Pin the last axis to n (fails iff the last extent != n).+ auto shape = context.mark_node(std::make_shared<v3::ShapeOf>(x, element::i64));+ auto neg_one = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-1}));+ auto head = context.mark_node(std::make_shared<v8::Slice>(shape, zero, neg_one, step, axis));+ auto shape_last = context.mark_node(std::make_shared<v0::Concat>(OutputVector{head, n_1d}, 0));+ auto g1 = context.mark_node(std::make_shared<v1::Reshape>(x, shape_last, /*special_zero=*/false));+ g1->set_friendly_name(guard_name);++ // Pin the second-to-last axis to n (fails iff the -2 extent != n), keeping the validated last = n.+ auto shape1 = context.mark_node(std::make_shared<v3::ShapeOf>(g1, element::i64));+ auto neg_two = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-2}));+ auto batch_shape = context.mark_node(std::make_shared<v8::Slice>(shape1, zero, neg_two, step, axis));+ auto new_shape = context.mark_node(std::make_shared<v0::Concat>(OutputVector{batch_shape, nn}, 0));+ auto g2 = context.mark_node(std::make_shared<v1::Reshape>(g1, new_shape, /*special_zero=*/false));+ g2->set_friendly_name(guard_name);+ return g2;+}+std::shared_ptr<Node> get_axes_range(const NodeContext& context, int input_id) {auto x = context.get_input(input_id);return get_node_axes_range(context, x);@@ -753,6 +821,83 @@ Output<Node> masked_select(const NodeContext& context, const Output<Node>& data,return context.mark_node(std::make_shared<v8::GatherND>(data, masked_id));}+OutputVector build_static_max_pool(ov::pass::NodeRegistry& rg,+ Output<Node> input,+ int dims,+ bool return_indices,+ const Shape& kernel,+ const Strides& strides,+ const Shape& pads,+ const Strides& dilations,+ RoundingType rounding_type) {+ auto input_shape = rg.make<v3::ShapeOf>(input);++ auto const_0 = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{0});+ auto const_1 = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{1});+ bool is_static = input.get_partial_shape().rank().is_static();+ bool no_batch_dim = is_static && input.get_partial_shape().rank().get_length() == dims + 1;++ if (is_static) {+ if (no_batch_dim) {+ input = rg.make<v0::Unsqueeze>(input, const_0);+ }+ } else {+ input = rg.make<v0::Unsqueeze>(input, const_0);+ auto unsqueeze_shape = rg.make<v3::ShapeOf>(input);+ auto rank = rg.make<v0::ShapeOf>(unsqueeze_shape);+ auto end_index = rg.make<v1::Add>(rank, const_1);+ auto start_index = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{-dims - 2});+ auto reshape_pattern = rg.make<v8::Slice>(unsqueeze_shape, start_index, end_index, const_1, const_0);+ input = rg.make<v1::Reshape>(input, reshape_pattern, true);+ }++ auto res = rg.make<+ v14::MaxPool>(input, strides, dilations, pads, pads, kernel, rounding_type, PadType::EXPLICIT, element::i64, 2);+ if (is_static) {+ if (no_batch_dim) {+ if (return_indices) {+ auto out1 = res->output(0);+ auto out2 = res->output(1);+ out1 = rg.make<v0::Squeeze>(out1, const_0);+ out2 = rg.make<v0::Squeeze>(out2, const_0);+ return {out1, out2};+ } else {+ auto squeezed = rg.make<v0::Squeeze>(res, const_0);+ return {squeezed};+ }+ } else {+ if (return_indices) {+ return {res->output(0), res->output(1)};+ } else {+ return {res};+ }+ }++ } else {+ auto pooled_output_shape = rg.make<v3::ShapeOf>(res);++ auto start_index_input = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{-dims});+ auto slice_input_shape = rg.make<v8::Slice>(input_shape, const_0, start_index_input, const_1, const_0);++ auto start_index_pooled = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{-dims});+ auto end_index_pooled = rg.make<v0::Constant>(element::i64, Shape{1}, std::vector<int64_t>{2 + dims});+ auto slice_pooled_output_shape =+ rg.make<v8::Slice>(pooled_output_shape, start_index_pooled, end_index_pooled, const_1, const_0);++ auto concat_shape = rg.make<v0::Concat>(OutputVector{slice_input_shape, slice_pooled_output_shape}, 0);+ if (return_indices) {+ auto out1 = res->output(0);+ auto out2 = res->output(1);+ out1 = rg.make<v1::Reshape>(out1, concat_shape, true);+ out2 = rg.make<v1::Reshape>(out2, concat_shape, true);+ return {out1, out2};+ } else {+ auto reshaped = rg.make<v1::Reshape>(res, concat_shape, true);+ return {reshaped};+ }+ }+}+Output<Node> flatten(ov::pass::NodeRegistry& rg, const Output<Node>& value, size_t axis) {// First dimension of output tensor is the product of [d_0, ... d_{axis-1}] dimensions of// input tensor. The last dimension is the product of the rest of input tensor dimensions:diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex 733cc2d9f61..b305871a07a 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -55,6 +55,22 @@ std::tuple<Output<Node>, Output<Node>> get_shape_rank(const NodeContext& contextOutput<Node> reshape_kernel_for_group(const NodeContext& context, const Output<Node>& kernel, int64_t groups);+/// \brief Ensures the trailing two axes of `x` form an n x n matrix.+///+/// Static trailing dims that are not n x n are rejected at conversion (`op_label` names the op).+/// When they are dynamic (the common TorchScript case) a runtime guard pins each trailing axis to+/// n with its own Reshape -- the per-axis check catches e.g. [1, 9] that a single [n, n] reshape+/// would accept as 3x3. A genuine n x n is an identity; any other size fails loudly at runtime.+/// \param context Node context for marking nodes.+/// \param x Batched matrix whose trailing two axes are validated/guarded.+/// \param n Expected square matrix size.+/// \param op_label Op name used in the error message.+/// \return `x` unchanged when statically validated, otherwise the runtime reshape-guarded matrix.+Output<Node> ensure_trailing_square(const NodeContext& context,+ const Output<Node>& x,+ int64_t n,+ const std::string& op_label);+std::shared_ptr<Node> get_axes_range(const NodeContext& context, int input_id);std::shared_ptr<Node> get_node_axes_range(const NodeContext& context, const Output<Node>& x);@@ -132,6 +148,20 @@ Output<Node> masked_fill(ov::pass::NodeRegistry& rg,const Output<Node>& mask,const Output<Node>& value);+// Build the static-kernel max pool (v14::MaxPool) for an already-resolved kernel/strides/pads/+// dilations. Shared by the translator (constant kernel) and the deferred resolver (kernel that+// became constant after shape propagation). Nodes go into `rg`; returns the pool result (2 outputs+// when `return_indices`).+OutputVector build_static_max_pool(ov::pass::NodeRegistry& rg,+ Output<Node> input,+ int dims,+ bool return_indices,+ const ov::Shape& kernel,+ const ov::Strides& strides,+ const ov::Shape& pads,+ const ov::Strides& dilations,+ ov::op::RoundingType rounding_type);+Output<Node> masked_select(const NodeContext& context, const Output<Node>& data, const Output<Node>& mask);Output<Node> flatten(ov::pass::NodeRegistry& rg, const Output<Node>& value, size_t axis);diff --git a/tests/layer_tests/pytorch_tests/test_det.py b/tests/layer_tests/pytorch_tests/test_det.pynew file mode 100644index 00000000000..a224a157022--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_det.py@@ -0,0 +1,118 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import numpy as np+import pytest+import torch+import openvino as ov++from pytorch_layer_test_class import PytorchLayerTest+++class TestDet(PytorchLayerTest):+ """aten::det / aten::linalg_det — batched matrix determinant.++ The PyTorch frontend computes the determinant of 3x3 matrices in closed+ form (cofactor expansion) -- the rigid-transform / Kabsch use case.+ Reference values come from PyTorch (torch.det / torch.linalg.det).+ """++ def _prepare_input(self, input_shape):+ return (self.random.randn(*input_shape).astype(np.float32),)++ def create_model(self, variant):+ class aten_det(torch.nn.Module):+ def __init__(self, variant):+ super().__init__()+ self.variant = variant++ def forward(self, x):+ if self.variant == "linalg_det":+ return torch.linalg.det(x)+ return torch.det(x)++ # Both torch.det and torch.linalg.det lower to aten::linalg_det in+ # TorchScript for current PyTorch.+ return aten_det(variant), "aten::linalg_det"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("variant", ["det", "linalg_det"])+ @pytest.mark.parametrize("input_shape", [+ [3, 3], # single matrix, no batch+ [1, 3, 3], # batch of one 3x3+ [5, 3, 3], # batch of 3x3+ [2, 4, 3, 3], # multi-dim batch of 3x3+ ])+ def test_det(self, variant, input_shape, ie_device, precision, ir_version):+ # FP16 is too coarse for the cofactor products; validate the determinant in FP32.+ if precision == "FP16":+ pytest.skip("determinant closed form is validated in FP32")+ self._test(*self.create_model(variant), ie_device, precision, ir_version,+ kwargs_to_prepare_input={"input_shape": input_shape})+++class TestDetNonSquareFailsGracefully(PytorchLayerTest):+ """A non-3x3 determinant must fail loudly, never silently return a wrong value.++ The frontend only implements the 3x3 determinant. ensure_trailing_square+ (utils.cpp) rejects any other size: with statically-known trailing dims the+ op-labeled error is raised at conversion time; when the trailing dims are+ dynamic a runtime reshape guard makes it fail at inference. Either way a 4x4+ matrix must not silently produce a (wrong) 3x3 determinant.+ """++ def _det(self):+ class aten_det(torch.nn.Module):+ def forward(self, x):+ return torch.linalg.det(x)++ return aten_det()++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_static_4x4_fails_at_conversion(self, ie_device, precision, ir_version):+ # Static trailing dims => the conversion-time check in ensure_trailing_square fires.+ example = torch.randn(2, 4, 4, dtype=torch.float32)+ scripted = torch.jit.trace(self._det(), example)+ # Not OpConversionFailure: the 3x3 guard trips core Reshape shape-inference while the model+ # is built, surfaced as a RuntimeError. Assert the op-labeled guard node so an unrelated+ # failure (e.g. a tracing error) cannot green this test.+ with pytest.raises(Exception) as exc_info:+ ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([2, 4, 4])])+ assert "requires_3x3" in str(exc_info.value)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_dynamic_4x4_fails_at_runtime(self, ie_device, precision, ir_version):+ # Dynamic trailing dims => conversion succeeds with the runtime reshape guard,+ # which then fails loudly at inference for a genuine 4x4 input.+ if ie_device != "CPU":+ pytest.skip("runtime reshape-guard failure is asserted on CPU")+ example = torch.randn(2, 4, 4, dtype=torch.float32)+ scripted = torch.jit.trace(self._det(), example)+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([2, -1, -1])])+ compiled = ov.Core().compile_model(ov_model, "CPU")+ # Runtime failure in the CPU plugin (a RuntimeError, not OpConversionFailure). Assert the+ # op-labeled guard node so an unrelated failure cannot green this test.+ with pytest.raises(Exception) as exc_info:+ compiled((example.numpy(),))+ assert "requires_3x3" in str(exc_info.value)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_dynamic_same_numel_nonsquare_fails_at_runtime(self, ie_device, precision, ir_version):+ # [1, 9] has 3x3's element count: a single [n,n] reshape would accept it; the per-axis guard must raise.+ if ie_device != "CPU":+ pytest.skip("runtime reshape-guard failure is asserted on CPU")+ example = torch.randn(3, 3, dtype=torch.float32)+ scripted = torch.jit.trace(self._det(), example)+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([-1, -1])])+ compiled = ov.Core().compile_model(ov_model, "CPU")+ bad = np.arange(9, dtype=np.float32).reshape(1, 9)+ with pytest.raises(Exception) as exc_info:+ compiled((bad,))+ assert "requires_3x3" in str(exc_info.value)diff --git a/tests/layer_tests/pytorch_tests/test_norm.py b/tests/layer_tests/pytorch_tests/test_norm.pyindex e63409ef2f3..6993109155e 100644--- a/tests/layer_tests/pytorch_tests/test_norm.py+++ b/tests/layer_tests/pytorch_tests/test_norm.py@@ -297,6 +297,19 @@ class TestLinalgMatrixNorm(PytorchLayerTest):"dim": dim, "keepdim": keepdim})+# ord=None on rank>2 inputs (previously raised in the FE): torch maps ord=None to the vector+# 2-norm over `dim` (Frobenius for a 2-axis dim), rank-agnostic. Shared by the dynamic-rank+# test_linalg_norm cases and the forced-static-rank cases below.+_ORD_NONE_RANK_GT2_CASES = [+ (None, -1, [2, 4, 3]), # ord=None, scalar dim, rank-3+ (None, 1, [1, 5, 5, 3]), # ord=None, scalar dim, rank-4+ (None, (0, 1), [1, 3, 3]), # ord=None, 2-elem dim -> frobenius+ (None, None, [2, 3, 4]), # ord=None, dim=None, rank-3 -> flat L2+ (None, (-2, -1), [2, 4, 3, 3]), # ord=None, 2-elem dim, rank-4 -> frobenius+ (None, -1, [1, 7, 7, 3, 3]), # SAM-6D geo_embedding shape (rank-5)+]++class TestLinalgNorm(PytorchLayerTest):def _prepare_input(self, out=False, out_dtype=None, input_shape=(3, 3), dim=None, keepdim=False):@@ -367,7 +380,7 @@ class TestLinalgNorm(PytorchLayerTest):(float('inf'), 1, [1, 3, 3]), # numeric ord, scalar dim -> norm_vector(p=inf)("fro", (0, 1), [1, 3, 3]), # string ord -> frobenius_norm(0, 1, [1, 3, 3]), # p==0 branch- ])+ ] + _ORD_NONE_RANK_GT2_CASES)@pytest.mark.parametrize('keepdim', [True, False])@pytest.mark.parametrize("dtype", ["float32", None])@pytest.mark.parametrize("out", [True, False])@@ -383,6 +396,25 @@ class TestLinalgNorm(PytorchLayerTest):"keepdim": keepdim})+ @pytest.mark.nightly+ @pytest.mark.precommit+ # ord=None with static rank > 2 used to raise in the frontend; pin the static-rank path+ # (the harness default uses dynamic rank, a different branch).+ @pytest.mark.parametrize('p,dim,input_shape', _ORD_NONE_RANK_GT2_CASES)+ @pytest.mark.parametrize('keepdim', [True, False])+ def test_linalg_norm_ordNone_rank_gt2_static(self, p, dim, keepdim, input_shape,+ ie_device, precision, ir_version):+ self._test(*self.create_model(p, dim, keepdim, None, False, False),+ ie_device, precision, ir_version,+ dynamic_shapes=False,+ kwargs_to_prepare_input={+ "out": False,+ "out_dtype": None,+ "input_shape": input_shape,+ "dim": dim,+ "keepdim": keepdim+ })+class TestTrickyNorm(PytorchLayerTest):diff --git a/tests/layer_tests/pytorch_tests/test_pooling.py b/tests/layer_tests/pytorch_tests/test_pooling.pyindex e348e5628bd..ebbaf74d55e 100644--- a/tests/layer_tests/pytorch_tests/test_pooling.py+++ b/tests/layer_tests/pytorch_tests/test_pooling.py@@ -5,6 +5,7 @@ import platformimport pytestimport torch+import openvino as ovfrom pytorch_layer_test_class import PytorchLayerTestimport numpy as np@@ -275,3 +276,222 @@ class TestPooling(PytorchLayerTest):self.input_tensor = self.random.randn(*input_shape)self._test(*self.create_model("max_pool3d_with_indices", **params, ceil_mode=ceil_mode, dilation=dilation),ie_device, precision, ir_version, dynamic_shapes=is_dynamic_shapes)+++class TestMaxPoolDynamicKernel(PytorchLayerTest):+ """max_pool with a kernel_size built from x.size(...).++ Such a kernel is a runtime value the OpenVINO MaxPool op cannot represent (its kernel is a+ constructor attribute); for a full-extent (global) pool the frontend decomposes it into a+ ReduceMax over that axis. trace_model=True keeps the kernel a runtime value (a plain literal+ would be const-folded onto the static MaxPool path).+ """++ def _prepare_input(self):+ return (self.input_tensor,)++ def create_model(self, dims, axes):+ # axes: spatial axis indices (within the rank-(dims+2) NCHW... tensor) whose kernel element+ # is the full extent x.size(axis); all other spatial axes get a static window of 1.+ class aten_max_pool_dynamic(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.dims = dims+ self.axes = axes++ def _kernel(self, x):+ # first spatial axis is index 2 (after N, C); for the no-batch case the harness still+ # feeds a rank (dims+1) tensor, handled by using sizes relative to the actual rank.+ first_spatial = x.dim() - self.dims+ ks = []+ for i in range(self.dims):+ axis = first_spatial + i+ # full extent on requested axes (referenced as absolute axis on the rank-(dims+2)+ # tensor), window 1 otherwise+ if (axis - x.dim()) in self.axes or axis in self.axes:+ ks.append(x.size(axis))+ else:+ ks.append(1)+ return ks++ def forward(self, x):+ ks = self._kernel(x)+ if self.dims == 1:+ return torch.nn.functional.max_pool1d(x, kernel_size=ks)+ if self.dims == 2:+ return torch.nn.functional.max_pool2d(x, kernel_size=ks)+ return torch.nn.functional.max_pool3d(x, kernel_size=ks)++ op_name = {1: "aten::max_pool1d", 2: "aten::max_pool2d", 3: "aten::max_pool3d"}[dims]+ return aten_max_pool_dynamic(), op_name++ @pytest.mark.parametrize("input_shape,dims,axes", [+ ([1, 128, 40, 64], 2, [-1]), # pool full last axis (SAM-6D PositionalEncoding)+ ([2, 8, 5, 7], 2, [-1]), # smaller, non-trivial npoint/nsample+ ([1, 128, 40, 64], 2, [-2]), # pool the other spatial axis+ ([1, 128, 40, 64], 2, [-2, -1]), # pool both spatial axes (global)+ ([1, 16, 30], 1, [-1]), # 1d full-extent pool+ ([1, 8, 6, 6, 10], 3, [-1]), # 3d full-extent pool over last axis+ ([3, 40, 64], 2, [-1]), # no batch dim+ ])+ @pytest.mark.parametrize("is_dynamic_shapes", [True, False])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel(self, input_shape, dims, axes, is_dynamic_shapes,+ ie_device, precision, ir_version):+ self.input_tensor = self.random.randn(*input_shape).astype(np.float32)+ self._test(*self.create_model(dims, axes), ie_device, precision, ir_version,+ trace_model=True, dynamic_shapes=is_dynamic_shapes)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel_sliding_window_unsupported(self, ie_device, precision, ir_version):+ # A static window > 1 mixed with a dynamic full-extent axis is a genuine sliding-window pool+ # that a ReduceMax cannot represent: conversion must fail with a clear message. Convert+ # directly (like the det/svd negative tests) so this expected conversion failure skips+ # _test's retry/inference plumbing.+ class aten_max_pool_mixed(torch.nn.Module):+ def forward(self, x):+ return torch.nn.functional.max_pool2d(x, kernel_size=[3, x.size(3)])++ example = torch.randn(1, 8, 15, 20, dtype=torch.float32)+ scripted = torch.jit.trace(aten_max_pool_mixed(), example)+ # The dynamic last axis keeps x.size(3) a runtime value, so the mixed static-window/dynamic+ # kernel reaches the frontend and the conversion guard fires (a static axis would const-fold+ # to [3, 20] and hit the static MaxPool path). The guard raises OpConversionFailure.+ with pytest.raises(ov.frontend.OpConversionFailure):+ ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([1, 8, 15, -1])])++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel_dynamic_stride_unsupported(self, ie_device, precision, ir_version):+ # A stride derived from a runtime size (here x.size(3)) is not a full-extent global pool the+ # ReduceMax decomposition can represent, and it cannot become a MaxPool constructor attribute.+ # The deferred resolver must reject it at conversion (via the stride_is_default guard) rather+ # than silently treating the non-constant stride as the default. Convert directly like the+ # sliding-window negative test above.+ class aten_max_pool_dyn_stride(torch.nn.Module):+ def forward(self, x):+ k = x.size(3)+ return torch.nn.functional.max_pool2d(x, kernel_size=[1, k], stride=[1, k])++ example = torch.randn(1, 8, 15, 20, dtype=torch.float32)+ scripted = torch.jit.trace(aten_max_pool_dyn_stride(), example)+ # Dynamic last axis keeps both the kernel and the stride runtime values, so the non-default+ # dynamic stride reaches the frontend and the conversion guard fires.+ with pytest.raises(ov.frontend.OpConversionFailure):+ ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([1, 8, 15, -1])])++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_partial_kernel_fails_at_runtime(self, ie_device, precision, ir_version):+ # A runtime kernel that does not span the full axis extent is a strided pool the ReduceMax+ # decomposition can't represent; the runtime guard must fail loudly instead of returning a+ # wrong [N, C, H, 1]. Here kernel = x.size(3)//2 = 32 vs. extent 64, so the guard reshape fails.+ if ie_device != "CPU":+ pytest.skip("runtime reshape-guard failure is asserted on CPU")++ class aten_max_pool_partial(torch.nn.Module):+ def forward(self, x):+ return torch.nn.functional.max_pool2d(x, kernel_size=[1, x.size(3) // 2])++ example = torch.randn(1, 128, 40, 64, dtype=torch.float32)+ scripted = torch.jit.trace(aten_max_pool_partial(), example)+ # Dynamic last axis keeps the kernel a runtime value, so the dynamic-kernel guard is emitted.+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([1, 128, 40, -1])])+ op_types = [n.get_type_name() for n in ov_model.get_ordered_ops()]+ assert "ReduceMax" in op_types, f"expected the dynamic-kernel branch; ops: {op_types}"+ compiled = ov.Core().compile_model(ov_model, "CPU")+ # Runtime failure in the CPU plugin (a RuntimeError, not OpConversionFailure). Assert the+ # op-labeled guard node so an unrelated failure cannot green this test.+ with pytest.raises(Exception) as exc_info:+ compiled((example.numpy(),))+ assert "require_full_extent" in str(exc_info.value)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel_uses_reducemax(self, ie_device, precision, ir_version):+ # Structurally prove the dynamic-kernel branch fired: the model must contain a ReduceMax and+ # no MaxPool (the numeric tests above can't distinguish it from a const-folded static MaxPool).+ # A dynamic input shape keeps x.size(3) a runtime value so the kernel cannot const-fold.+ class aten_max_pool_dyn(torch.nn.Module):+ def forward(self, x):+ return torch.nn.functional.max_pool2d(x, kernel_size=[1, x.size(3)])++ example = torch.randn(1, 128, 40, 64, dtype=torch.float32)+ scripted = torch.jit.trace(aten_max_pool_dyn(), example)+ # Dynamic last axis -> the kernel stays a runtime ShapeOf value at conversion time.+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([1, 128, 40, -1])])+ op_types = [n.get_type_name() for n in ov_model.get_ordered_ops()]+ assert "ReduceMax" in op_types, f"expected the dynamic-kernel ReduceMax branch; ops: {op_types}"+ assert "MaxPool" not in op_types, f"static MaxPool must not be present; ops: {op_types}"++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel_static_input_uses_maxpool(self, ie_device, precision, ir_version):+ # The kernel decision is deferred to a post-shape-propagation pass. Converting the module with+ # the input shape specified (convert_model(model, input=...)) traces it against that shape, so+ # x.size(3) folds to a constant after propagation and the deferred resolver lowers to the+ # ordinary static MaxPool -- NOT the ReduceMax fallback. This is the "specify the shape and+ # dynamic max_pool is not needed" path. The complementary dynamic case (no static last axis ->+ # ReduceMax) is covered by the test above.+ if ie_device != "CPU":+ pytest.skip("structural + numeric assertion is checked on CPU")++ class aten_max_pool_dyn(torch.nn.Module):+ def forward(self, x):+ return torch.nn.functional.max_pool2d(x, kernel_size=[1, x.size(3)])++ example = torch.randn(1, 128, 40, 64, dtype=torch.float32)+ model = aten_max_pool_dyn().eval()+ # Pass the module (not a pre-traced ScriptModule) with a fully static input so the shape+ # propagates to x.size(3); the deferred resolver must then produce a plain MaxPool.+ ov_model = ov.convert_model(model, example_input=example,+ input=[ov.PartialShape([1, 128, 40, 64])])+ op_types = [n.get_type_name() for n in ov_model.get_ordered_ops()]+ assert "MaxPool" in op_types, f"expected the folded static MaxPool; ops: {op_types}"+ assert "ReduceMax" not in op_types, f"ReduceMax fallback must not be present; ops: {op_types}"+ assert not any("FrameworkNode" in t for t in op_types), \+ f"deferred placeholder must be resolved; ops: {op_types}"++ # Numeric check against the PyTorch reference (framework golden, per project rule).+ compiled = ov.Core().compile_model(ov_model, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})+ with torch.no_grad():+ ref = model(example).numpy()+ ov_out = compiled((example.numpy(),))[compiled.outputs[0]]+ assert np.max(np.abs(ov_out.astype(np.float64) - ref.astype(np.float64))) < 1e-4++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_max_pool_dynamic_kernel_static_input_explicit_stride_uses_maxpool(self, ie_device, precision, ir_version):+ # As above, but with an explicit non-default stride alongside the deferred kernel. When the+ # shape folds, the resolver's static branch builds a plain MaxPool with that stride; the stride+ # list is normalized to the spatial rank so it becomes a valid MaxPool attribute (not a+ # mismatched/wrapped size). The result must match PyTorch.+ if ie_device != "CPU":+ pytest.skip("structural + numeric assertion is checked on CPU")++ class aten_max_pool_dyn_stride(torch.nn.Module):+ def forward(self, x):+ return torch.nn.functional.max_pool2d(x, kernel_size=[1, x.size(3)], stride=2)++ example = torch.randn(1, 8, 12, 16, dtype=torch.float32)+ model = aten_max_pool_dyn_stride().eval()+ ov_model = ov.convert_model(model, example_input=example,+ input=[ov.PartialShape([1, 8, 12, 16])])+ op_types = [n.get_type_name() for n in ov_model.get_ordered_ops()]+ assert "MaxPool" in op_types, f"expected the folded static MaxPool; ops: {op_types}"+ assert "ReduceMax" not in op_types, f"ReduceMax fallback must not be present; ops: {op_types}"+ assert not any("FrameworkNode" in t for t in op_types), \+ f"deferred placeholder must be resolved; ops: {op_types}"++ # Numeric check against the PyTorch reference (framework golden, per project rule).+ compiled = ov.Core().compile_model(ov_model, "CPU", {"INFERENCE_PRECISION_HINT": "f32"})+ with torch.no_grad():+ ref = model(example).numpy()+ ov_out = compiled((example.numpy(),))[compiled.outputs[0]]+ assert np.max(np.abs(ov_out.astype(np.float64) - ref.astype(np.float64))) < 1e-4diff --git a/tests/layer_tests/pytorch_tests/test_svd.py b/tests/layer_tests/pytorch_tests/test_svd.pynew file mode 100644index 00000000000..e980a9dcdd4--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_svd.py@@ -0,0 +1,202 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import numpy as np+import pytest+import torch+import openvino as ov++from pytorch_layer_test_class import PytorchLayerTest+++class TestSVDReconstruction(PytorchLayerTest):+ """aten::svd — batched 3x3 singular value decomposition.++ The frontend implements a one-sided Jacobi SVD for 3x3 matrices. Singular+ vectors are only defined up to sign, so the model wrapper below returns the+ sign-invariant reconstruction U @ diag(S) @ V^T (which must equal the input)+ and the sorted singular values. Reference values come from PyTorch+ (torch.svd).+ """++ def _prepare_input(self, input_shape, rank_deficient=False):+ x = self.random.randn(*input_shape).astype(np.float32)+ if rank_deficient:+ # Make the last column equal the second => mathematically rank<=2,+ # which is the SAM-6D Weighted-Procrustes (3-point) regime.+ x[..., :, -1] = x[..., :, -2]+ return (x,)++ def create_model(self):+ class aten_svd_recon(torch.nn.Module):+ def forward(self, x):+ u, s, v = torch.svd(x)+ recon = torch.matmul(u * s.unsqueeze(-2), v.transpose(-2, -1))+ # Return reconstruction (sign-invariant) and sorted singular values.+ return recon, s++ return aten_svd_recon(), "aten::svd"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("input_shape", [+ [3, 3], # single 3x3+ [1, 3, 3], # batch of one+ [8, 3, 3], # batch+ [2, 4, 3, 3], # multi-dim batch+ ])+ @pytest.mark.parametrize("rank_deficient", [False, True])+ def test_svd_reconstruction(self, input_shape, rank_deficient,+ ie_device, precision, ir_version):+ # The Jacobi rotations and singular values are computed in FP32; FP16 is+ # too coarse (it forms products of matrix entries). Keep FP32.+ if precision == "FP16":+ pytest.skip("3x3 SVD is validated in FP32")+ # The 3x3 SVD requires statically 3x3 trailing dims; disable the harness's+ # default fully-dynamic-rank tracing.+ self._test(*self.create_model(), ie_device, precision, ir_version,+ dynamic_shapes=False,+ kwargs_to_prepare_input={"input_shape": input_shape,+ "rank_deficient": rank_deficient})+++class TestSVDProcrustes(PytorchLayerTest):+ """End-to-end Weighted-Procrustes (Kabsch) rotation built from svd + det.++ This mirrors the exact SAM-6D usage: R = V @ diag(1,1,sign(det(V U^T))) @ U^T+ on a 3x3 cross-covariance matrix. The recovered rotation is invariant to the+ singular-vector sign ambiguity, so it compares cleanly against PyTorch.+ """++ def _prepare_input(self, batch):+ # Build a 3x3 cross-covariance from 3 random point correspondences (the+ # rank<=2 regime that SAM-6D's coarse matching produces).+ src = self.random.randn(batch, 3, 3).astype(np.float32)+ ref = self.random.randn(batch, 3, 3).astype(np.float32)+ return (src, ref)++ def create_model(self):+ class kabsch(torch.nn.Module):+ def forward(self, src, ref):+ src_c = src - src.mean(dim=1, keepdim=True)+ ref_c = ref - ref.mean(dim=1, keepdim=True)+ h = src_c.transpose(1, 2) @ ref_c+ u, _, v = torch.svd(h)+ ut = u.transpose(1, 2)+ eye = torch.eye(3).unsqueeze(0).repeat(src.shape[0], 1, 1)+ eye[:, -1, -1] = torch.sign(torch.det(v @ ut))+ r = v @ eye @ ut+ return r++ # Exercises both aten::svd and aten::det (torch.det lowers to+ # aten::linalg_det in TorchScript for current PyTorch).+ return kabsch(), ["aten::svd", "aten::linalg_det"]++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("batch", [1, 16])+ def test_procrustes(self, batch, ie_device, precision, ir_version):+ if precision == "FP16":+ pytest.skip("Procrustes (svd+det) is validated in FP32")+ # The recovered rotation is theoretically well-defined despite the sign ambiguity of the+ # near-degenerate (rank<=2) singular vectors, but on GPU the fixed-sweep fp32 Jacobi SVD+ # can produce a non-converged degenerate basis, so R diverges from torch. Validate on CPU.+ if ie_device != "CPU":+ pytest.skip("3x3 Jacobi SVD Procrustes accuracy is validated in FP32 on CPU "+ "(GPU fp32 diverges on the rank-deficient covariance)")+ self._test(*self.create_model(), ie_device, precision, ir_version,+ dynamic_shapes=False,+ kwargs_to_prepare_input={"batch": batch})+++class TestSVDNonSquareFailsGracefully(PytorchLayerTest):+ """A non-3x3 SVD must fail loudly, never silently return a wrong decomposition.++ The frontend only implements the 3x3 SVD. ensure_trailing_square (utils.cpp)+ rejects any other size: with statically-known trailing dims the op-labeled+ error is raised at conversion time; when the trailing dims are dynamic a+ runtime reshape guard makes it fail at inference. Either way a 4x4 matrix must+ not silently produce a (wrong) 3x3 decomposition.+ """++ def _svd(self):+ class aten_svd(torch.nn.Module):+ def forward(self, x):+ u, s, v = torch.svd(x)+ return u, s, v++ return aten_svd()++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_static_4x4_fails_at_conversion(self, ie_device, precision, ir_version):+ # Static trailing dims => the conversion-time check in ensure_trailing_square fires.+ example = torch.randn(2, 4, 4, dtype=torch.float32)+ scripted = torch.jit.trace(self._svd(), example)+ # Not OpConversionFailure: the 3x3 guard trips core Reshape shape-inference while the model+ # is built, surfaced as a RuntimeError. Assert the op-labeled guard node so an unrelated+ # failure (e.g. a tracing error) cannot green this test.+ with pytest.raises(Exception) as exc_info:+ ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([2, 4, 4])])+ assert "requires_3x3" in str(exc_info.value)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_dynamic_4x4_fails_at_runtime(self, ie_device, precision, ir_version):+ # Dynamic trailing dims => conversion succeeds with the runtime reshape guard,+ # which then fails loudly at inference for a genuine 4x4 input.+ if ie_device != "CPU":+ pytest.skip("runtime reshape-guard failure is asserted on CPU")+ example = torch.randn(2, 4, 4, dtype=torch.float32)+ scripted = torch.jit.trace(self._svd(), example)+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([2, -1, -1])])+ compiled = ov.Core().compile_model(ov_model, "CPU")+ # Runtime failure in the CPU plugin (a RuntimeError, not OpConversionFailure). Assert the+ # op-labeled guard node so an unrelated failure cannot green this test.+ with pytest.raises(Exception) as exc_info:+ compiled((example.numpy(),))+ assert "requires_3x3" in str(exc_info.value)++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_dynamic_same_numel_nonsquare_fails_at_runtime(self, ie_device, precision, ir_version):+ # [1, 9] has 3x3's element count: a single [n,n] reshape would accept it; the per-axis guard must raise.+ if ie_device != "CPU":+ pytest.skip("runtime reshape-guard failure is asserted on CPU")+ example = torch.randn(3, 3, dtype=torch.float32)+ scripted = torch.jit.trace(self._svd(), example)+ ov_model = ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([-1, -1])])+ compiled = ov.Core().compile_model(ov_model, "CPU")+ bad = np.arange(9, dtype=np.float32).reshape(1, 9)+ with pytest.raises(Exception) as exc_info:+ compiled((bad,))+ assert "requires_3x3" in str(exc_info.value)+++class TestSVDComputeUvFalseFailsGracefully(PytorchLayerTest):+ """aten::svd with compute_uv=False must fail at conversion, not silently return non-zero U/V.++ PyTorch returns zero-filled U/V when compute_uv=False; this frontend always produces real+ U/V, so it rejects a constant compute_uv=False at conversion time. (A non-constant compute_uv+ is likewise rejected in the translator, but Python bool args const-fold into prim::Constant+ under torch.jit.trace, so that branch is not reachable from a layer test.)+ """++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_compute_uv_false_fails_at_conversion(self, ie_device, precision, ir_version):+ class aten_svd_no_uv(torch.nn.Module):+ def forward(self, x):+ _, s, _ = torch.svd(x, compute_uv=False)+ return s++ example = torch.randn(2, 3, 3, dtype=torch.float32)+ scripted = torch.jit.trace(aten_svd_no_uv(), example)+ # The translator's PYTORCH_OP_CONVERSION_CHECK surfaces as OpConversionFailure; asserting+ # the exact type keeps an unrelated failure from greening this test.+ with pytest.raises(ov.frontend.OpConversionFailure):+ ov.convert_model(scripted, example_input=(example,),+ input=[ov.PartialShape([2, 3, 3])])