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] Extend keypoint detector conversion coverage (#38789)
Maxim Vafin2f12b92f0d6a
diff --git a/.github/workflows/job_pytorch_models_tests.yml b/.github/workflows/job_pytorch_models_tests.ymlindex 5a945aef363..a7d9a9ce99a 100644--- a/.github/workflows/job_pytorch_models_tests.yml+++ b/.github/workflows/job_pytorch_models_tests.yml@@ -127,7 +127,8 @@ jobs:-r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/easyocr.txt \-r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/gfpgan.txt \-r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/tpsmm.txt \- -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/lightglue.txt+ -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/lightglue.txt \+ -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/keypoints.txt- name: PyTorch Models Tests Not Timm or Torchvisionif: ${{ inputs.model_scope == 'precommit' || inputs.model_scope == 'nightly_scope2' }}diff --git a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csvindex df761a5993e..cc098eec435 100644--- a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv+++ b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv@@ -220,6 +220,7 @@ aten::logical_or,aten::logical_xor,aten::lstm,aten::lt,+aten::mT,Real-valued tensorsaten::masked_fill,aten::masked_fill_,aten::masked_scatter,diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex 80dde866c64..6c041ecf626 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -644,6 +644,8 @@ class TorchFXPythonDecoder (BaseFXDecoder):return PartialShape.dynamic()def get_attribute(self, name):+ if name == "__openvino_legacy_op_type":+ return OVAny(self.get_legacy_op_type())if name in self.pt_module.kwargs:attr = self.pt_module.kwargs[name]if isinstance(attr, torch.dtype):@@ -729,10 +731,13 @@ class TorchFXPythonDecoder (BaseFXDecoder):if isinstance(self.pt_module, torch.fx.GraphModule):return "GraphModule"if self.pt_module.op == "call_function":- if type(self.pt_module.target).__name__ == "EdgeOpOverload":- name = self.pt_module.target.__name__+ target = self.pt_module.target+ if type(target).__name__ == "EdgeOpOverload":+ name = target.__name__+ elif inspect.isfunction(target):+ name = f"{target.__module__}.{target.__qualname__}"else:- name = str(self._functional_out_target(self.pt_module.target))+ name = str(self._functional_out_target(target))if self._module_extension_target_ops:if name in self._module_extension_target_ops:return self._module_extension_target_ops[name]@@ -742,6 +747,12 @@ class TorchFXPythonDecoder (BaseFXDecoder):else:return "UNKNOWN_TYPE_" + str(self.pt_module.op)+ def get_legacy_op_type(self):+ if (isinstance(self.pt_module, torch.fx.Node) and self.pt_module.op == "call_function"+ and inspect.isfunction(self.pt_module.target)):+ return str(self.pt_module.target)+ return ""+def get_schema(self):schema = getattr(getattr(self.pt_module, "target", None), "_schema", None)return str(schema) if schema is not None else "NONE"diff --git a/src/frontends/pytorch/README.md b/src/frontends/pytorch/README.mdindex 6da5b2a812b..5717428b633 100644--- a/src/frontends/pytorch/README.md+++ b/src/frontends/pytorch/README.md@@ -51,6 +51,8 @@ flowchart TDOpenVINO PyTorch Frontend supports extensions. To add an extension, use`ov::frontend::pytorch::Frontend::add_extension()` API.+In FX graphs, `ConversionExtension` matches plain Python function targets by their+defining `module.qualified_name`, which can differ from an import alias.The following extension types are supported:* `ov::frontend::tensorflow::ConversionExtension` or `ov::frontend::ConversionExtension` - add a new Loader into the conversion pipeline.diff --git a/src/frontends/pytorch/src/node_context.cpp b/src/frontends/pytorch/src/node_context.cppindex 315cd39cc3f..40cdcc12602 100644--- a/src/frontends/pytorch/src/node_context.cpp+++ b/src/frontends/pytorch/src/node_context.cpp@@ -266,8 +266,11 @@ Output<Node> NodeContext::get_input_from_visible_context(size_t index) const {Output<Node> NodeContext::get_input_from_visible_context(size_t index, bool resolve_sequence_constants) const {FRONT_END_GENERAL_CHECK(index < get_input_size(), "Index ", index, " is lower than number of inputs.");auto input_tensor = get_input(static_cast<int>(index));+ // FX subgraphs receive outer values as explicit operands and their tensor ids index the subgraph itself, so+ // they must not be resolved in the outer context.+ const bool use_external = !m_ext_tensor_map.empty() && m_decoder->decoder_type_name() != "fx";auto input_node = input_tensor.get_node_shared_ptr();- if (ov::as_type_ptr<v0::Parameter>(input_node)) {+ if (use_external && ov::as_type_ptr<v0::Parameter>(input_node)) {// We need to look into external context for inputs that would be fed into this parametersize_t tensor_idx = m_translate_session->decode_tensor_name(input_node->output(0));if (m_ext_tensor_map.count(tensor_idx)) {@@ -277,7 +280,7 @@ Output<Node> NodeContext::get_input_from_visible_context(size_t index, bool resoif (resolve_sequence_constants) {std::function<Output<Node>(const Output<Node>&)> resolve_constants =[&](const Output<Node>& value) -> Output<Node> {- if (ov::is_type<v0::Parameter>(value.get_node())) {+ if (use_external && ov::is_type<v0::Parameter>(value.get_node())) {const auto tensor_id = m_translate_session->decode_tensor_name(value);const auto external = m_ext_tensor_map.find(tensor_id);if (external != m_ext_tensor_map.end()) {diff --git a/src/frontends/pytorch/src/op/convnd.cpp b/src/frontends/pytorch/src/op/convnd.cppindex 06544b48bf4..27573b6db9f 100644--- a/src/frontends/pytorch/src/op/convnd.cpp+++ b/src/frontends/pytorch/src/op/convnd.cpp@@ -15,34 +15,45 @@ using namespace ov::op;OutputVector translate_convnd(const NodeContext& context) {num_inputs_check(context, 7, 7);auto strides = context.const_input<Strides>(3);+ auto dilations = context.const_input<Strides>(5);// In torch pads at beginning are same as at end- auto pads = CoordinateDiff(strides.size(), 0);+ auto pads_begin = CoordinateDiff(strides.size(), 0);+ auto pads_end = pads_begin;auto pad_type = ov::op::PadType::EXPLICIT;+ bool dynamic_same_padding = false;auto dtype = context.get_input_type(4);if (dtype.is<type::Str>()) {- auto pad_mode = context.const_input<std::string>(4);- pad_type = convert_pad(pad_mode);+ const auto config =+ convert_conv_pad(context.const_input<std::string>(4), context.get_input(1), strides, dilations);+ pad_type = config.pad_type;+ pads_begin = config.pads_begin;+ pads_end = config.pads_end;+ dynamic_same_padding = config.dynamic_same_padding;} else {- pads = context.const_input<CoordinateDiff>(4);+ pads_begin = context.const_input<CoordinateDiff>(4);+ pads_end = pads_begin;}- auto dilations = context.const_input<Strides>(5);auto groups = context.const_input<int64_t>(6);+ auto data = context.get_input(0);+ if (dynamic_same_padding) {+ data = apply_dynamic_same_padding(context, data, context.get_input(1), dilations);+ }std::shared_ptr<ov::Node> conv;if (groups == 1) {- conv = std::make_shared<v1::Convolution>(context.get_input(0),+ conv = std::make_shared<v1::Convolution>(data,context.get_input(1),strides,- pads,- pads,+ pads_begin,+ pads_end,dilations,pad_type);} else {- conv = std::make_shared<v1::GroupConvolution>(context.get_input(0),+ conv = std::make_shared<v1::GroupConvolution>(data,reshape_kernel_for_group(context, context.get_input(1), groups),strides,- pads,- pads,+ pads_begin,+ pads_end,dilations,pad_type);}diff --git a/src/frontends/pytorch/src/op/convolution_mode.cpp b/src/frontends/pytorch/src/op/convolution_mode.cppindex 8d15335d530..0102a713dad 100644--- a/src/frontends/pytorch/src/op/convolution_mode.cpp+++ b/src/frontends/pytorch/src/op/convolution_mode.cpp@@ -20,28 +20,30 @@ OutputVector translate_convolution_mode(const NodeContext& context) {auto pad_mode = context.const_input<std::string>(4);auto dilations = context.const_input<Strides>(5);auto groups = context.const_input<int64_t>(6);- auto pad_const = CoordinateDiff(strides.size(), 0);-- auto auto_pad_mode = convert_pad(pad_mode);+ const auto config = convert_conv_pad(pad_mode, context.get_input(1), strides, dilations);+ auto data = context.get_input(0);+ if (config.dynamic_same_padding) {+ data = apply_dynamic_same_padding(context, data, context.get_input(1), dilations);+ }std::shared_ptr<ov::Node> conv;if (groups == 1) {- conv = context.mark_node(std::make_shared<v1::Convolution>(context.get_input(0),+ conv = context.mark_node(std::make_shared<v1::Convolution>(data,context.get_input(1),strides,- pad_const,- pad_const,+ config.pads_begin,+ config.pads_end,dilations,- auto_pad_mode));+ config.pad_type));} else {conv = context.mark_node(- std::make_shared<v1::GroupConvolution>(context.get_input(0),+ std::make_shared<v1::GroupConvolution>(data,reshape_kernel_for_group(context, context.get_input(1), groups),strides,- pad_const,- pad_const,+ config.pads_begin,+ config.pads_end,dilations,- auto_pad_mode));+ config.pad_type));}if (!context.input_is_none(2)) {diff --git a/src/frontends/pytorch/src/op/transpose.cpp b/src/frontends/pytorch/src/op/transpose.cppindex 2ea0ebe5573..7e9c0bc2e6d 100644--- a/src/frontends/pytorch/src/op/transpose.cpp+++ b/src/frontends/pytorch/src/op/transpose.cpp@@ -17,6 +17,7 @@#include "openvino/op/reshape.hpp"#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/shape_of.hpp"+#include "openvino/op/subtract.hpp"#include "openvino/op/unsqueeze.hpp"#include "utils.hpp"@@ -53,6 +54,31 @@ OutputVector translate_transpose(const NodeContext& context) {return {context.mark_node(std::make_shared<v1::Transpose>(data, scatter))};};+OutputVector translate_mT(const NodeContext& context) {+ num_inputs_check(context, 1, 1);+ const auto input = context.get_input(0);+ const auto input_rank = input.get_partial_shape().rank();+ if (input_rank.is_static()) {+ if (input_rank.get_length() == 0) {+ return {input};+ }+ PYTORCH_OP_CONVERSION_CHECK(input_rank.get_length() >= 2, "mT requires a tensor with at least 2 dimensions.");+ }+ Output<Node> rank;+ std::tie(std::ignore, rank) = get_shape_rank(context, input, true);+ const auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));+ const auto one = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));+ const auto two = context.mark_node(v0::Constant::create(element::i32, Shape{}, {2}));+ const auto last = context.mark_node(std::make_shared<v1::Subtract>(rank, one));+ const auto penultimate = context.mark_node(std::make_shared<v1::Subtract>(rank, two));+ const auto prefix = context.mark_node(std::make_shared<v4::Range>(zero, penultimate, one, element::i32));+ const auto last_axis = context.mark_node(std::make_shared<v0::Unsqueeze>(last, zero));+ const auto penultimate_axis = context.mark_node(std::make_shared<v0::Unsqueeze>(penultimate, zero));+ const auto order =+ context.mark_node(std::make_shared<v0::Concat>(OutputVector{prefix, last_axis, penultimate_axis}, 0));+ return {context.mark_node(std::make_shared<v1::Transpose>(input, order))};+}+OutputVector translate_t(const NodeContext& context) {num_inputs_check(context, 1, 1);auto input = context.get_input(0);diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex beeac0d5ad5..65c6e3cc9dc 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -278,6 +278,7 @@ OP_CONVERTER(translate_sub);OP_CONVERTER(translate_sub_);OP_CONVERTER(translate_sum);OP_CONVERTER(translate_t);+OP_CONVERTER(translate_mT);OP_CONVERTER(translate_take_along_dim);OP_CONVERTER(translate_to);OP_CONVERTER(translate_topk);@@ -781,6 +782,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::svd", op::translate_svd},{"aten::swapaxes", op::quantizable_op<op::translate_transpose>},{"aten::t", op::translate_t},+ {"aten::mT", op::translate_mT},{"aten::take_along_dim", op::translate_take_along_dim},{"aten::tan", op::optional_out<op::translate_1to1_match_1_inputs_with_fp32_type_alignment<opset10::Tan>, 1>},{"aten::tan_", op::inplace_op<op::translate_1to1_match_1_inputs<opset10::Tan>>},@@ -987,6 +989,8 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten.zeros_like.default", op::translate_zeros_like_fx},{"get_attr", op::translate_constant},{"scalar_tensor.default", op::translate_scalar_tensor_fx},+ {"torch.sym_min", op::translate_minimum},+ {"torch.sym_max", op::translate_maximum},{"torchvision.deform_conv2d.default", op::translate_deform_conv},{"torchvision.nms.default", op::translate_nms},{"torchvision.roi_align.default", op::translate_roi_align},diff --git a/src/frontends/pytorch/src/translate_session.cpp b/src/frontends/pytorch/src/translate_session.cppindex 6e69c0b7392..38ca6bf714b 100644--- a/src/frontends/pytorch/src/translate_session.cpp+++ b/src/frontends/pytorch/src/translate_session.cpp@@ -30,6 +30,11 @@ namespace ov::frontend::pytorch {using namespace ov::op;namespace {+std::string get_legacy_op_type(const TorchDecoder& decoder) {+ const auto value = decoder.get_attribute("__openvino_legacy_op_type");+ return value.is<std::string>() ? value.as<std::string>() : std::string{};+}+// Alias views and their base values belong to the graph where they were converted.class AliasScope {public:@@ -528,6 +533,12 @@ OutputVector TranslateSession::convert_node(const NodeContext& context) {canonical_op_type = normalize_op_type(raw_op_type);it = m_translator_map.find(canonical_op_type);}+ if (it == m_translator_map.end()) {+ const auto legacy_op_type = get_legacy_op_type(*context.get_decoder());+ if (!legacy_op_type.empty()) {+ it = m_translator_map.find(legacy_op_type);+ }+ }const std::string& op_type = canonical_op_type.empty() ? raw_op_type : canonical_op_type;if (it != m_translator_map.end()) {auto outputs = it->second(context);diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex 94319880a7b..c298a74bbeb 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -4,6 +4,8 @@#include "utils.hpp"+#include <numeric>+#include "op_table.hpp"#include "openvino/core/rt_info.hpp"#include "openvino/core/validation_util.hpp"@@ -20,7 +22,9 @@#include "openvino/op/floor.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gather_nd.hpp"+#include "openvino/op/greater_eq.hpp"#include "openvino/op/less.hpp"+#include "openvino/op/logical_and.hpp"#include "openvino/op/logical_not.hpp"#include "openvino/op/loop.hpp"#include "openvino/op/matmul.hpp"@@ -28,6 +32,7 @@#include "openvino/op/mod.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/non_zero.hpp"+#include "openvino/op/pad.hpp"#include "openvino/op/range.hpp"#include "openvino/op/reduce_mean.hpp"#include "openvino/op/reduce_prod.hpp"@@ -348,6 +353,69 @@ PadType convert_pad(const std::string& pt_pad) {return TORCH_AUTO_PAD_TO_OV.at(pt_pad);};+ConvPadConfig convert_conv_pad(const std::string& pt_pad,+ const Output<Node>& weight,+ const Strides& strides,+ const Strides& dilations) {+ const auto pad_type = convert_pad(pt_pad);+ const auto num_spatial = strides.size();+ CoordinateDiff pads_begin(num_spatial, 0), pads_end(num_spatial, 0);+ if (pad_type != PadType::SAME_UPPER) {+ return {pad_type, pads_begin, pads_end};+ }+ const auto& kernel = weight.get_partial_shape();+ if (kernel.rank().is_dynamic() || kernel.size() != num_spatial + 2 || dilations.size() != num_spatial ||+ std::any_of(strides.begin(), strides.end(), [](size_t s) {+ return s != 1;+ })) {+ return {pad_type, pads_begin, pads_end};+ }+ for (size_t i = 0; i < num_spatial; ++i) {+ const auto& dim = kernel[i + 2];+ if (dim.is_dynamic()) {+ return {PadType::VALID, pads_begin, pads_end, true};+ }+ // Torch places the extra padding at the end, same as SAME_UPPER.+ const auto total = static_cast<std::ptrdiff_t>(dilations[i] * (dim.get_length() - 1));+ pads_begin[i] = total / 2;+ pads_end[i] = total - pads_begin[i];+ }+ return {PadType::EXPLICIT, pads_begin, pads_end};+}++Output<Node> apply_dynamic_same_padding(const NodeContext& context,+ const Output<Node>& input,+ const Output<Node>& weight,+ const Strides& dilations) {+ const auto spatial_dims = dilations.size();+ const auto weight_shape = context.mark_node(std::make_shared<v3::ShapeOf>(weight, element::i64));+ const auto starts = v0::Constant::create(element::i64, Shape{1}, {2});+ const auto stops = v0::Constant::create(element::i64, Shape{1}, {static_cast<int64_t>(2 + spatial_dims)});+ const auto steps = v0::Constant::create(element::i64, Shape{1}, {1});+ const auto kernel = context.mark_node(std::make_shared<v8::Slice>(weight_shape, starts, stops, steps));++ std::vector<int64_t> ones(spatial_dims, 1);+ std::vector<int64_t> divisors(spatial_dims, 2);+ std::vector<int64_t> dilation_values(dilations.begin(), dilations.end());+ const auto one = context.mark_node(v0::Constant::create(element::i64, Shape{spatial_dims}, ones));+ const auto dilation = context.mark_node(v0::Constant::create(element::i64, Shape{spatial_dims}, dilation_values));+ const auto kernel_minus_one = context.mark_node(std::make_shared<v1::Subtract>(kernel, one));+ const auto effective_padding = context.mark_node(std::make_shared<v1::Multiply>(kernel_minus_one, dilation));+ const auto divisor = context.mark_node(v0::Constant::create(element::i64, Shape{spatial_dims}, divisors));+ const auto pads_begin_spatial = context.mark_node(std::make_shared<v1::Divide>(effective_padding, divisor, false));+ const auto pads_end_spatial =+ context.mark_node(std::make_shared<v1::Subtract>(effective_padding, pads_begin_spatial));++ const auto no_padding = context.mark_node(v0::Constant::create(element::i64, Shape{2}, {0, 0}));+ const auto pads_begin =+ context.mark_node(std::make_shared<v0::Concat>(OutputVector{no_padding, pads_begin_spatial}, 0));+ const auto pads_end =+ context.mark_node(std::make_shared<v0::Concat>(OutputVector{no_padding, pads_end_spatial}, 0));+ const auto pad_value =+ context.mark_node(std::make_shared<v1::ConvertLike>(v0::Constant::create(element::f32, Shape{}, {0}), input));+ return context.mark_node(std::make_shared<v12::Pad>(input, pads_begin, pads_end, pad_value, PadMode::CONSTANT));+}+Output<Node> concat_list_construct(const Output<Node>& input) {if (auto seq_mark = ov::as_type_ptr<SequenceMark>(input.get_node_shared_ptr())) {auto list_inputs = seq_mark->input_values();@@ -1212,6 +1280,47 @@ bool index_tensor_on_list(ov::pass::NodeRegistry& rg,auto input_shape = rg.make<v3::ShapeOf>(data, element::i32);auto zero = rg.make<v0::Constant>(element::i32, Shape{}, 0);auto input_dims = rg.make<v1::Split>(input_shape, zero, rank.get_length());+ const auto first_advanced_axis = advanced_ids.front();+ const bool trailing_integer_indices = advanced_ids.back() == static_cast<size_t>(rank.get_length() - 1) &&+ advanced_ids.size() == rank.get_length() - first_advanced_axis &&+ std::none_of(is_masked_bool.begin(), is_masked_bool.end(), [](bool masked) {+ return masked;+ });+ if (trailing_integer_indices) {+ // Gather selected spatial positions before materializing a dense transpose.+ Output<Node> linear_index = zero;+ Output<Node> valid_indices = rg.make<v0::Constant>(element::boolean, Shape{}, true);+ for (auto axis : advanced_ids) {+ auto index = rg.make<v0::Convert>(masked_indices[axis], element::i32);+ const auto dimension = rg.make<v0::Squeeze>(input_dims->output(axis), zero);+ const auto negative = rg.make<v1::Less>(index, zero);+ const auto normalized = rg.make<v1::Select>(negative, rg.make<v1::Add>(index, dimension), index);+ const auto valid_axis = rg.make<v1::LogicalAnd>(rg.make<v1::GreaterEqual>(normalized, zero),+ rg.make<v1::Less>(normalized, dimension));+ valid_indices = rg.make<v1::LogicalAnd>(valid_indices, valid_axis);+ linear_index = rg.make<v1::Add>(rg.make<v1::Multiply>(linear_index, dimension), normalized);+ }+ linear_index = rg.make<v1::Select>(valid_indices, linear_index, zero);+ auto first_axis = rg.make<v0::Constant>(element::i32, Shape{1}, first_advanced_axis);+ auto start = rg.make<v0::Constant>(element::i32, Shape{1}, 0);+ auto step = rg.make<v0::Constant>(element::i32, Shape{1}, 1);+ auto prefix_shape = rg.make<v8::Slice>(input_shape, start, first_axis, step);+ auto minus_one = rg.make<v0::Constant>(element::i32, Shape{1}, -1);+ auto flat_shape = rg.make<v0::Concat>(OutputVector{prefix_shape, minus_one}, 0);+ auto flattened = rg.make<v1::Reshape>(data, flat_shape, false);+ auto gather_axis = rg.make<v0::Constant>(element::i32, Shape{}, first_advanced_axis);+ const auto gathered = rg.make<v8::Gather>(flattened, linear_index, gather_axis);+ if (first_advanced_axis > 0) {+ std::vector<int32_t> axes(first_advanced_axis);+ std::iota(axes.begin(), axes.end(), 0);+ const auto prefix_axes = rg.make<v0::Constant>(element::i32, Shape{axes.size()}, axes);+ valid_indices = rg.make<v0::Unsqueeze>(valid_indices, prefix_axes);+ }+ const auto output_zero = rg.make<v1::ConvertLike>(zero, data);+ new_output = rg.make<v1::Select>(valid_indices, gathered, output_zero);+ use_input_as_output = false;+ return true;+ }std::vector<size_t> non_used_dims;for (auto i = 0; i < rank.get_length(); i++) {if (std::find(advanced_ids.begin(), advanced_ids.end(), i) == advanced_ids.end()) {diff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex e4672b9354f..fb5c9b3857c 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -4,6 +4,8 @@#pragma once+#include <tuple>+#include "openvino/frontend/complex_type_mark.hpp"#include "openvino/frontend/pytorch/node_context.hpp"#include "openvino/frontend/sequence_mark.hpp"@@ -89,6 +91,23 @@ Output<Node> apply_optional_dtype(const NodeContext& context, size_t dtype_port,op::PadType convert_pad(const std::string& pt_pad);+struct ConvPadConfig {+ op::PadType pad_type;+ CoordinateDiff pads_begin;+ CoordinateDiff pads_end;+ bool dynamic_same_padding = false;+};++// Resolves convolution padding where possible; dynamic SAME kernels are padded at runtime before the convolution.+ConvPadConfig convert_conv_pad(const std::string& pt_pad,+ const Output<Node>& weight,+ const Strides& strides,+ const Strides& dilations);+Output<Node> apply_dynamic_same_padding(const NodeContext& context,+ const Output<Node>& input,+ const Output<Node>& weight,+ const Strides& dilations);+Output<Node> concat_list_construct(const Output<Node>& input);/// \brief Checks if input represents empty list.diff --git a/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py b/tests/layer_tests/py_frontend_tests/test_export_grad_mode.pyindex a2abf3d86cd..ea5def83dc5 100644--- a/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py+++ b/tests/layer_tests/py_frontend_tests/test_export_grad_mode.py@@ -133,6 +133,28 @@ def test_export_autocast_returns_view(mutate_base):np.testing.assert_allclose(actual[index], value.numpy(), atol=1e-5, rtol=1e-5)+def test_export_autocast_convolution_bias():+ # Body tensor ids must not resolve to parent graph values with the same index.+ class Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.conv1 = torch.nn.Conv2d(3, 8, 3, padding=1)+ self.conv2 = torch.nn.Conv2d(8, 4, 3, padding=1)++ def forward(self, x):+ with torch.autocast("cpu", enabled=False):+ return self.conv2(self.conv1(x).relu())++ model = Model().eval()+ data = torch.randn(1, 3, 16, 16)+ exported = torch.export.export(model, (data,))+ assert any(str(node.target) == "wrap_with_autocast" for node in exported.graph.nodes)+ compiled = convert_without_decompositions(exported)+ with torch.no_grad():+ expected = model(data)+ np.testing.assert_allclose(compiled([data.numpy()])[0], expected.numpy(), atol=1e-4, rtol=1e-4)++def test_export_enabled_autocast_output_types():class Model(torch.nn.Module):def forward(self, x, w):diff --git a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py b/tests/layer_tests/py_frontend_tests/test_torch_decoder.pyindex 914e86b0aaa..b1e84ff41c3 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_decoder.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_decoder.py@@ -7,6 +7,57 @@ import pytestfrom packaging import versionfrom openvino.frontend.pytorch.torchdynamo.backend_utils import _is_testing++def test_pytorch_fx_decoder_without_sym_min(monkeypatch):+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder++ graph = torch.fx.Graph()+ value = graph.placeholder("value")+ result = graph.call_function(torch.ops.aten.relu.default, (value,))+ graph.output(result)+ decoder = TorchFXPythonDecoder(result, nodes=list(graph.nodes))+ monkeypatch.delattr(torch, "sym_min", raising=False)+ assert decoder.get_op_type() == "aten.relu.default"++[email protected]("name", ["sym_min", "sym_max"])+def test_pytorch_fx_decoder_symbolic_functions(name):+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder++ target = getattr(torch, name, None)+ if target is None:+ pytest.skip(f"torch.{name} is unavailable")++ from openvino import Core, convert_model++ class Model(torch.nn.Module):+ def forward(self, x):+ if name == "sym_min":+ end = torch.sym_min(2, x.shape[0])+ else:+ end = torch.sym_max(2, x.shape[0])+ return x.new_zeros((end,))++ model = Model().eval()+ example = torch.arange(4, dtype=torch.float32)+ exported = torch.export.export(+ model,+ (example,),+ dynamic_shapes={"x": {0: torch.export.Dim("n", min=1, max=8)}},+ )+ symbolic_node = next(node for node in exported.graph.nodes if node.target is target)+ decoder = TorchFXPythonDecoder(symbolic_node, nodes=list(exported.graph.nodes))+ assert decoder.get_op_type() == f"torch.{name}"++ compiled = Core().compile_model(convert_model(exported), "CPU")+ for size in (1, 4, 7):+ data = torch.arange(size, dtype=torch.float32)+ actual = compiled([data.numpy()])[0]+ assert actual.tolist() == model(data).tolist()++class AtenDiv(torch.nn.Module):# aten::div can have str or NoneType constantdef __init__(self, rounding_mode):@@ -1110,3 +1161,59 @@ def test_pytorch_decoder_conversion_without_sequence_override(metadata, wrapped,assert len(actual) == len(expected)for result, expected in zip(actual, expected):np.testing.assert_array_equal(result, expected)+++def test_pytorch_fx_decoder_python_function_names(monkeypatch):+ import operator+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder++ def nested_function(x):+ return x++ graph = torch.fx.Graph()+ value = graph.placeholder("value")+ targets = [+ (nested_function, f"{__name__}.{nested_function.__qualname__}"),+ (operator.neg, str(operator.neg)),+ (torch.ops.aten.relu.default, "aten.relu.default"),+ ]+ for name in ("sym_min", "sym_max", "sym_float"):+ target = getattr(torch, name, None)+ if target is not None:+ targets.append((target, f"torch.{name}"))+ nodes = [(graph.call_function(target, (value,)), expected) for target, expected in targets]+ for node, expected in nodes:+ assert TorchFXPythonDecoder(node, nodes=list(graph.nodes)).get_op_type() == expected+ monkeypatch.delattr(torch, "sym_min", raising=False)+ node = graph.call_function(torch.ops.aten.relu.default, (value,))+ assert TorchFXPythonDecoder(node, nodes=list(graph.nodes)).get_op_type() == "aten.relu.default"++[email protected]("legacy_name", [False, True])+def test_pytorch_fx_python_function_conversion_extension(legacy_name):+ import numpy as np+ import openvino as ov+ from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder+ import openvino.opset10 as ops++ def custom_function(x):+ return -x++ graph = torch.fx.Graph()+ value = graph.placeholder("value")+ graph.output(graph.call_function(custom_function, (value,)))+ graph_module = torch.fx.GraphModule(torch.nn.Module(), graph)+ decoder = TorchFXPythonDecoder(graph_module)+ frontend = ov.frontend.FrontEndManager().load_by_framework("pytorch")+ frontend.add_extension(ov.frontend.ConversionExtension(+ str(custom_function) if legacy_name else f"{__name__}.{custom_function.__qualname__}",+ lambda context: ops.negative(context.get_input(0)).outputs()))+ input_model = frontend.load(decoder)+ input_model.set_element_type(input_model.get_inputs()[0], ov.Type.f32)+ input_model.set_partial_shape(input_model.get_inputs()[0], ov.PartialShape([2]))+ converted = frontend.convert(input_model)+ compiled = ov.Core().compile_model(converted, "CPU")+ data = np.array([1.0, -2.0], dtype=np.float32)+ np.testing.assert_array_equal(compiled([data])[0], -data)diff --git a/tests/layer_tests/pytorch_tests/test_convnd.py b/tests/layer_tests/pytorch_tests/test_convnd.pyindex 0008ce43e16..039e2211c64 100644--- a/tests/layer_tests/pytorch_tests/test_convnd.py+++ b/tests/layer_tests/pytorch_tests/test_convnd.py@@ -161,6 +161,96 @@ class TestConv3D(PytorchLayerTest):self._test(*self.create_model(**params, bias=bias),ie_device, precision, ir_version)+class TestPadConv2DSame(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(1, 3, 24, 30),)++ def create_model(self, kernel, dilation):+ import torch+ import torch.nn.functional as F++ class pad_conv2d_same(torch.nn.Module):+ def __init__(self, rng):+ super().__init__()+ self.weight = rng.torch_randn(4, 3, kernel, kernel)+ self.dilation = dilation++ def forward(self, x):+ return F.conv2d(F.pad(x, [0, 1, 0, 1]), self.weight, padding="same", dilation=self.dilation)++ return pad_conv2d_same(self.random), "aten::conv2d"++ @pytest.mark.parametrize("kernel,dilation", [(3, 1), (4, 1), (3, 2)])+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_pad_conv2d_same(self, kernel, dilation, ie_device, precision, ir_version):+ self._test(*self.create_model(kernel, dilation), ie_device, precision, ir_version)++[email protected]("capture", ["trace", "export"])[email protected]("groups", [1, 2])[email protected]("kernel_parity", ["odd", "even"])[email protected]("dilation", [1, 2])+def test_conv2d_same_dynamic_kernel_after_pad(capture, groups, kernel_parity, dilation, ie_device, precision):+ import numpy as np+ import torch+ import torch.nn.functional as F+ import openvino as ov++ class Model(torch.nn.Module):+ def forward(self, x, weight):+ return F.conv2d(+ F.pad(x, [0, 1, 0, 1]),+ weight,+ padding="same",+ dilation=dilation,+ groups=groups,+ )++ model = Model().eval()+ x = torch.randn(1, 4, 12, 14)+ sample_kernel = 3 if kernel_parity == "odd" else 4+ weight = torch.randn(4, 4 // groups, sample_kernel, sample_kernel)+ if capture == "trace":+ traced = torch.jit.trace(model, (x, weight))+ converted = ov.convert_model(+ traced,+ input=[ov.PartialShape(x.shape), ov.PartialShape([4, 4 // groups, -1, -1])],+ )+ else:+ if kernel_parity == "odd":+ kernel_h = 2 * torch.export.Dim("kernel_h_half", min=2, max=3) - 1+ kernel_w = 2 * torch.export.Dim("kernel_w_half", min=2, max=3) - 1+ kernel_shapes = ((3, 3), (3, 5), (5, 5))+ else:+ kernel_h = 2 * torch.export.Dim("kernel_h_half", min=1, max=3)+ kernel_w = 2 * torch.export.Dim("kernel_w_half", min=1, max=3)+ kernel_shapes = ((2, 2), (2, 4), (4, 4))+ exported = torch.export.export(+ model,+ (x, weight),+ dynamic_shapes=({}, {2: kernel_h, 3: kernel_w}),+ )+ converted = ov.convert_model(exported)+ if capture == "trace":+ kernel_shapes = ((2, 2), (2, 4), (4, 4)) if kernel_parity == "even" else ((3, 3), (3, 5), (5, 5))++ for kernel_shape in kernel_shapes:+ shape_model = converted.clone()+ weight_shape = [4, 4 // groups, *kernel_shape]+ shape_model.reshape(dict(zip(shape_model.inputs, [x.shape, weight_shape])))+ config = {"INFERENCE_PRECISION_HINT": "f32"} if precision == "FP32" else {}+ compiled = ov.Core().compile_model(shape_model, ie_device, config)+ test_x = torch.randn_like(x)+ test_weight = torch.randn(weight_shape)+ actual = compiled([test_x.numpy(), test_weight.numpy()])[0]+ expected = model(test_x, test_weight).numpy()+ assert actual.shape == expected.shape+ np.testing.assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)++class TestConv2DInSubgraph(PytorchLayerTest):def _prepare_input(self):import numpy as npdiff --git a/tests/layer_tests/pytorch_tests/test_index.py b/tests/layer_tests/pytorch_tests/test_index.pyindex 8adf1c82187..f72f6df46ed 100644--- a/tests/layer_tests/pytorch_tests/test_index.py+++ b/tests/layer_tests/pytorch_tests/test_index.py@@ -4,6 +4,7 @@import pytestimport numpy as npimport torch+import openvino as ovfrom pytorch_layer_test_class import PytorchLayerTest@@ -181,3 +182,57 @@ class TestIndexNone(PytorchLayerTest):self._test(self.aten_index_list(idxs), "aten::index", ie_device, precision,ir_version, use_convert_model=True, trace_model=True)+++class TestIndexTrailingDimensions(PytorchLayerTest):+ def _prepare_input(self, prefix, indices):+ return (self.random.randn(*prefix, 4, 5),+ np.asarray(indices[0], dtype=np.int64),+ np.asarray(indices[1], dtype=np.int64))++ @pytest.mark.parametrize("prefix", [(), (3,), (2, 3)])+ @pytest.mark.parametrize("indices", [+ ([0, 3, 1], [4, 0, 2]),+ ([-1, 0, -2], [-1, -3, 2]),+ ([-4, 3], [-5, 4]),+ ([[0], [3]], [[0, 2, 4]]),+ (2, [0, -1]),+ (2, -1),+ ])+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_index_trailing(self, prefix, indices, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x, rows, columns):+ return torch.ops.aten.index.Tensor(x, [None] * len(prefix) + [rows, columns])++ self._test(Model(), "aten::index", ie_device, precision, ir_version,+ kwargs_to_prepare_input={"prefix": prefix, "indices": indices}, trace_model=True)++ @pytest.mark.parametrize("prefix", [(), (3,), (2, 3)])+ @pytest.mark.parametrize("invalid_index", [(-5, 0), (4, -5), (0, 5), (3, -6)])+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_index_trailing_out_of_bounds(self, prefix, invalid_index, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x, rows, columns):+ return torch.ops.aten.index.Tensor(x, [None] * len(prefix) + [rows, columns])++ model = Model().eval()+ data = torch.arange(1, np.prod((*prefix, 4, 5)) + 1, dtype=torch.float32).reshape(*prefix, 4, 5)+ example = (data, torch.tensor([0, -1]), torch.tensor([-1, 0]))+ captured = torch.export.export(model, example) if self.use_torch_export() else torch.jit.trace(model, example)+ converted = ov.convert_model(captured)+ converted.reshape({converted.input(0): [-1] * data.ndim})+ compiled = ov.Core().compile_model(converted, ie_device)+ rows = torch.tensor([0, invalid_index[0], -1])+ columns = torch.tensor([-1, invalid_index[1], 0])+ with pytest.raises(IndexError):+ model(data, rows, columns)+ # Invalid coordinates produce zero and must never spill into another axis.+ expected = model(data, rows[[0, 2]], columns[[0, 2]]).numpy()+ expected = np.insert(expected, 1, 0, axis=-1)+ actual = compiled((data.numpy(), rows.numpy(), columns.numpy()))[0]+ np.testing.assert_array_equal(actual, expected)diff --git a/tests/layer_tests/pytorch_tests/test_kthvalue.py b/tests/layer_tests/pytorch_tests/test_kthvalue.pyindex ac7a883d275..1ce51806bfa 100644--- a/tests/layer_tests/pytorch_tests/test_kthvalue.py+++ b/tests/layer_tests/pytorch_tests/test_kthvalue.py@@ -52,3 +52,24 @@ class TestKthValue(PytorchLayerTest):kwargs_to_prepare_input={"shape": shape, "dtype": dtype},trace_model=True,)+++class TestSymbolicMinKthValue(PytorchLayerTest):+ def _prepare_input(self, count):+ return (np.arange(count, dtype=np.float32) - 0.5,)++ @pytest.mark.parametrize("count", [2, 4, 7])+ @pytest.mark.nightly+ @pytest.mark.precommit_torch_export+ def test_symbolic_min(self, count, ie_device, precision, ir_version):+ if not self.use_torch_export():+ pytest.skip("Tests symbolic min in an exported graph")++ class Model(torch.nn.Module):+ def forward(self, x):+ selected = x[x > 0]+ k = torch.sym_min(3, selected.shape[0])+ return torch.kthvalue(selected, k)++ self._test(Model(), "aten::kthvalue", ie_device, precision, ir_version,+ kwargs_to_prepare_input={"count": count})diff --git a/tests/layer_tests/pytorch_tests/test_transpose.py b/tests/layer_tests/pytorch_tests/test_transpose.pyindex 3f193fcb5a0..50b2eac824b 100644--- a/tests/layer_tests/pytorch_tests/test_transpose.py+++ b/tests/layer_tests/pytorch_tests/test_transpose.py@@ -122,3 +122,20 @@ class TestTSmall(PytorchLayerTest):kwargs_to_prepare_input={"num_dims": num_dims, "input_dtype": input_dtype},use_convert_model=True,)+++class TestMatrixTranspose(PytorchLayerTest):+ def _prepare_input(self, shape):+ return (np.asarray(self.random.randn(*shape), dtype=np.float32),)++ @pytest.mark.parametrize("shape", [(), (3, 5), (2, 3, 5), (2, 4, 3, 5)])+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_mT(self, shape, ie_device, precision, ir_version):+ class Model(torch.nn.Module):+ def forward(self, x):+ return x.mT++ self._test(Model(), "aten::mT", ie_device, precision, ir_version,+ kwargs_to_prepare_input={"shape": shape}, trace_model=True)diff --git a/tests/model_hub_tests/pytorch/envs/hf_transformers.txt b/tests/model_hub_tests/pytorch/envs/hf_transformers.txtindex 359fada5c4d..c8e43936877 100644--- a/tests/model_hub_tests/pytorch/envs/hf_transformers.txt+++ b/tests/model_hub_tests/pytorch/envs/hf_transformers.txt@@ -19,7 +19,7 @@ rjieba==0.1.11# - katuni4ka/tiny-random-qwen# - katuni4ka/tiny-random-internlm2transformers_stream_generator==0.0.5-einops==0.8.0+einops==0.8.1# librosa/pyctcdecode needed internally by some HF audio modelslibrosa==0.10.2; python_version < "3.12"diff --git a/tests/model_hub_tests/pytorch/envs/keypoints.txt b/tests/model_hub_tests/pytorch/envs/keypoints.txtnew file mode 100644index 00000000000..725fe074908--- /dev/null+++ b/tests/model_hub_tests/pytorch/envs/keypoints.txt@@ -0,0 +1,3 @@+# Dependencies for test_keypoint_detectors.py.+kornia==0.8.2+dad-detector @ git+https://github.com/Parskatt/DaD.git@41b9e86a1a3ae52128485cc1094aa4952ef489badiff --git a/tests/model_hub_tests/pytorch/scripts/benchmark_keypoints.py b/tests/model_hub_tests/pytorch/scripts/benchmark_keypoints.pynew file mode 100644index 00000000000..6dc7f5ef219--- /dev/null+++ b/tests/model_hub_tests/pytorch/scripts/benchmark_keypoints.py@@ -0,0 +1,246 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import argparse+import contextlib+import hashlib+import json+import os+import platform+import statistics+import sys+import time+import traceback+from pathlib import Path++import numpy as np+import openvino as ov+import torch+from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from test_keypoint_detectors import MODEL_INPUTS, TestKeypointDetectorsConvertModel+from torch_utils import flattenize_structure+++def measure(call, seconds):+ samples = []+ deadline = time.perf_counter() + seconds+ while len(samples) < 5 or time.perf_counter() < deadline:+ start = time.perf_counter_ns()+ call()+ samples.append((time.perf_counter_ns() - start) / 1e6)+ return samples+++def file_fingerprint(path):+ path = Path(path).resolve()+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for chunk in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(chunk)+ return {"path": str(path), "sha256": digest.hexdigest()}+++def loaded_libraries():+ maps = Path("/proc/self/maps")+ if not maps.exists():+ return []+ paths = {line.split()[-1] for line in maps.read_text().splitlines()+ if ".so" in line and any(name in line for name in ("openvino", "libtorch", "libigdrcl", "libze_"))}+ return [file_fingerprint(path) for path in sorted(paths) if Path(path).is_file()]+++def image_tensor(path, shape):+ _, channels, height, width = shape+ image = Image.open(path).convert("RGB").resize((width, height), Image.Resampling.BILINEAR)+ tensor = torch.from_numpy(np.asarray(image).copy()).permute(2, 0, 1).float().div_(255).unsqueeze(0)+ if channels == 1:+ tensor = tensor.mean(1, keepdim=True)+ return tensor.contiguous()+++def benchmark(name, shape, args):+ case = TestKeypointDetectorsConvertModel()+ case.mode = args.mode+ model_args = (shape, case.get_aliked_repo()) if name.startswith("aliked-") else shape+ model = case.load_model(name, model_args)+ examples = [image_tensor(path, shape) for path in args.images]+ case.example = (examples[0],)+ start = time.perf_counter()+ ov_model = case.convert_model(model)+ conversion_seconds = time.perf_counter() - start+ config = {+ "INFERENCE_PRECISION_HINT": args.ov_precision.lower().replace("fp", "f"),+ "PERFORMANCE_HINT": "LATENCY",+ "NUM_STREAMS": ov.properties.streams.Num(1),+ }+ if args.device == "CPU":+ config.update(INFERENCE_NUM_THREADS=args.threads, ENABLE_CPU_PINNING=False)+ core = ov.Core()+ start = time.perf_counter()+ compiled = core.compile_model(ov_model, args.device, config)+ compilation_seconds = time.perf_counter() - start+ request = compiled.create_infer_request()+ numpy_inputs = [image.numpy() for image in examples]+ output_shapes = []+ accuracy_errors = []+ for image, data in zip(examples, numpy_inputs):+ reference = flattenize_structure(model(image))+ values = list(reference.values()) if isinstance(reference, dict) else reference+ result = request.infer([data], share_inputs=True, share_outputs=True)+ assert len(values) == len(compiled.outputs)+ keys = reference if isinstance(reference, dict) else range(len(reference))+ actual = {key: result[port] for key, port in zip(keys, compiled.outputs)}+ if name == "XFeat":+ # Nearly equal scores can swap ranks while preserving the same feature set.+ for outputs in (reference, actual):+ points = outputs["keypoints"]+ order = np.lexsort((points[:, 1], points[:, 0]))+ for key in outputs:+ outputs[key] = outputs[key][order]+ entries = reference.items() if isinstance(reference, dict) else enumerate(reference)+ try:+ for key, expected in entries:+ assert actual[key].shape == expected.shape, f"Output {key} shapes differ"+ assert np.isfinite(expected).all() and np.isfinite(actual[key]).all()+ np.testing.assert_allclose(actual[key], expected, atol=5e-2, rtol=5e-2)+ assert values[0].size > 0, "Benchmark image produced no keypoints"+ except AssertionError as error:+ if not args.allow_accuracy_failures:+ raise+ accuracy_errors.append({"image": str(args.images[len(output_shapes)]), "error": str(error)})+ output_shapes.append([list(value.shape) for value in values])++ index = 0++ def infer_torch():+ nonlocal index+ result = model(examples[index % len(examples)])+ index += 1+ return result++ def infer_openvino():+ nonlocal index+ result = request.infer([numpy_inputs[index % len(examples)]], share_inputs=True, share_outputs=True)+ index += 1+ return result++ for _ in range(args.warmup):+ infer_torch()+ infer_openvino()+ timings = {"torch": [], "openvino": []}+ rounds = []+ for round_index in range(args.rounds):+ order = [("torch", infer_torch), ("openvino", infer_openvino)]+ if round_index % 2:+ order.reverse()+ summary = {}+ for engine, call in order:+ index = 0+ samples = measure(call, args.seconds)+ timings[engine].extend(samples)+ summary[engine] = statistics.median(samples)+ rounds.append(summary)+ result = {+ "model": name,+ "shape": list(shape),+ "mode": args.mode,+ "device": args.device,+ "device_name": core.get_property(args.device, "FULL_DEVICE_NAME"),+ "openvino_precision": args.ov_precision,+ "execution_devices": compiled.get_property("EXECUTION_DEVICES"),+ "inference_precision_hint": str(compiled.get_property("INFERENCE_PRECISION_HINT")),+ "compilation_config": {key: 1 if key == "NUM_STREAMS" else value for key, value in config.items()},+ "conversion_seconds": conversion_seconds,+ "compilation_seconds": compilation_seconds,+ "output_shapes": output_shapes,+ "accuracy_passed": not accuracy_errors,+ "accuracy_errors": accuracy_errors,+ "accuracy_order": "coordinates" if name == "XFeat" else "model outputs",+ "round_medians_ms": rounds,+ }+ for engine, samples in timings.items():+ result[engine] = {+ "median_ms": statistics.median(round_[engine] for round_ in rounds),+ "p90_ms": float(np.percentile(samples, 90)),+ "iterations": len(samples),+ "samples_ms": samples,+ }+ result["speedup"] = result["torch"]["median_ms"] / result["openvino"]["median_ms"]+ return result+++def main():+ parser = argparse.ArgumentParser(description="Compare full keypoint inference with PyTorch CPU FP32.")+ parser.add_argument("--images", nargs="+", type=Path, required=True)+ parser.add_argument("--models", nargs="+", default=sorted({name for name, _ in MODEL_INPUTS}))+ parser.add_argument("--shapes", nargs="+", help="Override tested shapes, for example 256x320 480x640")+ parser.add_argument("--mode", choices=["trace", "export"], default="export")+ parser.add_argument("--device", choices=["CPU", "GPU"], default="CPU")+ parser.add_argument("--ov-precision", choices=["FP32", "FP16"], default="FP32")+ parser.add_argument("--allow-accuracy-failures", action="store_true",+ help="Retain failed accuracy checks and measure latency for investigation")+ parser.add_argument("--threads", type=int, default=4)+ parser.add_argument("--rounds", type=int, default=7)+ parser.add_argument("--warmup", type=int, default=10)+ parser.add_argument("--seconds", type=float, default=0.2, help="Minimum measurement time per engine per round")+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ if min(args.threads, args.rounds, args.seconds) <= 0 or args.warmup < 0:+ parser.error("Threads, rounds and seconds must be positive; warmup must be nonnegative")+ unknown_models = set(args.models) - {name for name, _ in MODEL_INPUTS}+ if unknown_models:+ parser.error(f"Unknown models: {sorted(unknown_models)}")+ torch.set_num_threads(args.threads)+ torch.set_num_interop_threads(1)+ torch.set_grad_enabled(False)+ source = Path(__file__).resolve().parents[1] / "test_keypoint_detectors.py"+ report = {+ "metadata": {+ "platform": platform.platform(),+ "cpu_affinity": sorted(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else None,+ "torch": torch.__version__, "openvino": ov.__version__,+ "torch_module": torch.__file__, "openvino_module": ov.__file__,+ "torch_threads": torch.get_num_threads(), "torch_interop_threads": torch.get_num_interop_threads(),+ "baseline": "PyTorch eager, inference_mode, contiguous NCHW",+ "torch_precision": "FP32", "precision": args.ov_precision, "device": args.device, "streams": 1,+ "warmup": args.warmup, "rounds": args.rounds, "seconds_per_round": args.seconds,+ "sources": [file_fingerprint(source), file_fingerprint(__file__)],+ "images": [file_fingerprint(path) for path in args.images],+ "accuracy_atol": 5e-2, "accuracy_rtol": 5e-2,+ "allow_accuracy_failures": args.allow_accuracy_failures,+ },+ "results": [],+ }+ args.output.parent.mkdir(parents=True, exist_ok=True)+ cases = [(name, shape) for name, shape in MODEL_INPUTS if name in args.models]+ if args.shapes:+ shapes = [(1, 3, *map(int, shape.split("x"))) for shape in args.shapes]+ cases = [(name, shape) for name in args.models for shape in shapes]+ failures = 0+ with torch.inference_mode(), contextlib.ExitStack() as cleanup:+ cleanup.callback(TestKeypointDetectorsConvertModel.teardown_class, TestKeypointDetectorsConvertModel)+ for name, shape in cases:+ try:+ result = benchmark(name, shape, args)+ print(f"{name} {shape}: torch={result['torch']['median_ms']:.3f} ms "+ f"openvino={result['openvino']['median_ms']:.3f} ms speedup={result['speedup']:.2f}x "+ f"accuracy={result['accuracy_passed']}", flush=True)+ failures += not result["accuracy_passed"]+ except Exception as error:+ traceback.print_exc()+ failures += 1+ result = {"model": name, "shape": list(shape), "mode": args.mode, "error": str(error)}+ report["results"].append(result)+ if "loaded_libraries" not in report["metadata"]:+ report["metadata"]["loaded_libraries"] = loaded_libraries()+ args.output.write_text(json.dumps(report, indent=2))+ if failures:+ raise SystemExit(1)+++if __name__ == "__main__":+ main()diff --git a/tests/model_hub_tests/pytorch/test_aliked.py b/tests/model_hub_tests/pytorch/test_aliked.pydeleted file mode 100644index c738a2a726d..00000000000--- a/tests/model_hub_tests/pytorch/test_aliked.py+++ /dev/null@@ -1,139 +0,0 @@-# Copyright (C) 2018-2026 Intel Corporation-# SPDX-License-Identifier: Apache-2.0--import math-import os-import platform-import subprocess-import sys-import tempfile--import numpy as np-import openvino.opset12 as ops-import pytest-import torch-from openvino import convert_model, Model, PartialShape, Type-from openvino.frontend import ConversionExtension--from torch_utils import TestTorchConvertModel--# To make tests reproducible we seed the random generator-torch.manual_seed(0)---def custom_op_loop(context):- map = context.get_input(0)- points = context.get_input(1)- kernel_size = context.get_values_from_const_input(2, None, int)- # kernel_size=2, radius=0.5, pad_left_top=0, pad_right_bottom=1- # kernel_size=3, radius=1.0, pad_left_top=1, pad_right_bottom=1- # kernel_size=4, radius=1.5, pad_left_top=1, pad_right_bottom=2- # kernel_size=5, radius=2.0, pad_left_top=2, pad_right_bottom=2- radius = (kernel_size - 1.0) / 2.0- pad_left_top = math.floor(radius)- pad_right_bottom = math.ceil(radius)-- # pad map: Cx(H+2*radius)x(W+2*radius)- map_pad = ops.pad(map,- np.int32([0, pad_left_top, pad_left_top]),- np.int32([0, pad_right_bottom, pad_right_bottom]),- "constant",- 0.)-- # get patches- points_shape = ops.shape_of(points)- batch = ops.gather(points_shape, np.int32([0]), 0)- loop = ops.loop(batch.output(0), ops.constant([True]).output(0))- points_i = ops.parameter(PartialShape([1, 2]), Type.i64)- points_i_1d = ops.squeeze(points_i, 0)- points_i_rev = ops.gather(points_i_1d, np.int32([1, 0]), 0)- map_body = ops.parameter(PartialShape([-1, -1, -1]), Type.i32)- points_plus_kenel = ops.add(points_i_rev, np.int64(kernel_size))- patch_i = ops.slice(- map_body, points_i_rev, points_plus_kenel, np.int64([1, 1]), np.int64([1, 2]))- patch_i = ops.unsqueeze(patch_i, 0)- body = Model([ops.constant([True]), patch_i], [points_i, map_body])- loop.set_function(body)- loop.set_special_body_ports([-1, 0])- loop.set_sliced_input(points_i, points, 0, 1, 1, -1, 0)- loop.set_invariant_input(map_body, map_pad.output(0))- res = loop.get_concatenated_slices(patch_i.output(0), 0, 1, 1, -1, 0)- return [res]---def read_image(path, idx):- import cv2- from torchvision.transforms import ToTensor-- img_path = os.path.join(path, f"{idx}.jpg")- img_ref = cv2.imread(img_path)- img_ref = cv2.resize(img_ref, (640, 640))- img_rgb = cv2.cvtColor(img_ref, cv2.COLOR_BGR2RGB)- img_tensor = ToTensor()(img_rgb)- return img_tensor.unsqueeze_(0)---class TestAlikedConvertModel(TestTorchConvertModel):- def setup_class(self):- self.repo_dir = tempfile.TemporaryDirectory()- os.system(- f"git clone https://github.com/mvafin/ALIKED.git {self.repo_dir.name}")- subprocess.check_call(- ["git", "checkout", "6008af43942925eec7e32006814ef41fbd0858d8"], cwd=self.repo_dir.name)- subprocess.check_call([sys.executable, "-m", "pip", "install",- "-r", os.path.join(self.repo_dir.name, "requirements.txt")])- subprocess.check_call(["sh", "build.sh"], cwd=os.path.join(- self.repo_dir.name, "custom_ops"))-- def load_model(self, model_name, model_link):- sys.path.append(self.repo_dir.name)- from nets.aliked import ALIKED-- m = ALIKED(model_name=model_name, device="cpu")- img_tensor = read_image(os.path.join(- self.repo_dir.name, "assets", "st_pauls_cathedral"), 1)- self.example = (img_tensor,)- img_tensor2 = read_image(os.path.join(- self.repo_dir.name, "assets", "st_pauls_cathedral"), 2)- self.inputs = (img_tensor2,)- return m-- def convert_model(self, model_obj):- m = convert_model(model_obj,- example_input=self.example,- extension=ConversionExtension(- "custom_ops::get_patches_forward", custom_op_loop)- )- return m-- def infer_fw_model(self, model_obj, inputs):- fw_outputs = model_obj(*[torch.from_numpy(i) for i in inputs])- if isinstance(fw_outputs, dict):- for k in fw_outputs.keys():- fw_outputs[k] = fw_outputs[k].numpy(force=True)- elif isinstance(fw_outputs, (list, tuple)):- fw_outputs = [o.numpy(force=True) for o in fw_outputs]- else:- fw_outputs = [fw_outputs.numpy(force=True)]- return fw_outputs-- def teardown_class(self):- # remove all downloaded files from cache- self.repo_dir.cleanup()-- def get_supported_precommit_models():- models = []- if platform.machine() not in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:- models.extend(['aliked-n16rot'])- return models-- @pytest.mark.nightly- @pytest.mark.precommit- @pytest.mark.parametrize("name", get_supported_precommit_models())- def test_convert_model_all_models_default(self, name, ie_device):- self.run(name, None, ie_device)-- @pytest.mark.nightly- @pytest.mark.parametrize("name", ['aliked-t16', 'aliked-n16', 'aliked-n32'])- def test_convert_model_all_models(self, name, ie_device):- self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_keypoint_detectors.py b/tests/model_hub_tests/pytorch/test_keypoint_detectors.pynew file mode 100644index 00000000000..0fb08380fb0--- /dev/null+++ b/tests/model_hub_tests/pytorch/test_keypoint_detectors.py@@ -0,0 +1,212 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import subprocess+import sys+import tempfile+from contextlib import contextmanager+from types import MethodType++import pytest+import torch+import torch.nn.functional as F++from torch_utils import TestTorchConvertModel+++MODEL_INPUTS = [+ ("aliked-t16", (1, 3, 256, 320)),+ ("aliked-n16", (1, 3, 256, 320)),+ ("aliked-n16rot", (1, 3, 256, 320)),+ ("aliked-n32", (1, 3, 256, 320)),+ ("DaD", (1, 3, 256, 320)),+ ("DaD", (1, 3, 255, 319)),+ ("RaCo", (1, 3, 256, 320)),+ ("RaCo", (1, 3, 255, 319)),+ ("RaCo", (1, 1, 256, 320)),+ ("DISK", (1, 3, 256, 320)),+ ("DISK", (1, 3, 255, 319)),+ ("XFeat", (1, 3, 256, 320)),+ ("XFeat", (1, 1, 255, 319)),+ ("DeDoDe", (1, 3, 256, 320)),+ ("DeDoDe", (1, 3, 255, 319)),+]+++def xfeat_nms(self, image, threshold=0.05, kernel_size=5):+ # Batch-one inference avoids padding to a Python length derived from detected points.+ assert image.shape[0] == 1+ maxima = F.max_pool2d(image, kernel_size, stride=1, padding=kernel_size // 2)+ positions = (image == maxima) & (image > threshold)+ return positions[0].nonzero()[..., 1:].flip(-1).unsqueeze(0)+++@contextmanager+def isolated_package(package):+ # Model repositories use generic package names that conflict with other model-hub repositories.+ def is_package_module(name):+ return name == package or name.startswith(f"{package}.")++ saved_modules = {name: module for name, module in list(sys.modules.items()) if is_package_module(name)}+ for name in saved_modules:+ sys.modules.pop(name)+ try:+ yield+ finally:+ for name in list(sys.modules):+ if is_package_module(name):+ sys.modules.pop(name)+ sys.modules.update(saved_modules)+++def load_xfeat():+ with isolated_package("modules"):+ return torch.hub.load(+ "verlab/accelerated_features:e92685f57f8318b18725c5c8c0bd28c7fe188d9a",+ "XFeat",+ trust_repo=True,+ skip_validation=True,+ top_k=128,+ )+++def load_aliked(repo_dir, model_name):+ sys.path.insert(0, repo_dir)+ try:+ with isolated_package("nets"), isolated_package("custom_ops"):+ # Use the PyTorch get_patches fallback instead of the uncompiled extension.+ sys.modules["custom_ops"] = None+ from nets.aliked import ALIKED++ return ALIKED(model_name=model_name, device="cpu", top_k=128)+ finally:+ sys.path.remove(repo_dir)+++class KeypointDetector(torch.nn.Module):+ def __init__(self, model, model_name):+ super().__init__()+ self.model = model+ self.model_name = model_name++ def forward(self, image):+ if self.model_name.startswith("aliked-"):+ # Original forward synchronizes CUDA for timing, so run its stages directly.+ feature_map, score_map = self.model.extract_dense_map(image)+ keypoints, scores, _ = self.model.dkd(score_map)+ descriptors, _ = self.model.desc_head(feature_map, keypoints)+ return {+ "keypoints": torch.stack(keypoints),+ "keypoint_scores": torch.stack(scores),+ "descriptors": torch.stack(descriptors),+ }+ if self.model_name == "DISK":+ features = self.model(image, n=128, window_size=5, score_threshold=0.0, pad_if_not_divisible=True)+ return {+ "keypoints": torch.stack([f.keypoints for f in features]),+ "keypoint_scores": torch.stack([f.detection_scores for f in features]),+ "descriptors": torch.stack([f.descriptors for f in features]),+ }+ if self.model_name == "DaD":+ return self.model.detect(+ {"image": self.model.normalizer(image)},+ num_keypoints=128,+ return_dense_probs=True,+ )+ if self.model_name == "XFeat":+ return self.model.detectAndCompute(image)[0]+ if self.model_name == "DeDoDe":+ keypoints, scores, descriptors = self.model(image, n=128)+ return {"keypoints": keypoints, "keypoint_scores": scores, "descriptors": descriptors}+ return self.model({"image": image})+++class TestKeypointDetectorsConvertModel(TestTorchConvertModel):+ ov_config = {"INFERENCE_PRECISION_HINT": "f32"}+ aliked_repo = None++ def teardown_class(self):+ if self.aliked_repo is not None:+ self.aliked_repo.cleanup()+ self.aliked_repo = None++ def get_aliked_repo(self):+ cls = type(self)+ if cls.aliked_repo is None:+ repo = tempfile.TemporaryDirectory()+ subprocess.check_call(["git", "clone", "-q", "https://github.com/Shiaoming/ALIKED.git", repo.name])+ subprocess.check_call(+ ["git", "checkout", "-q", "683d7c65197395c0b3f01ebe76e1084a27e73a65"], cwd=repo.name)+ cls.aliked_repo = repo+ return cls.aliked_repo.name++ def load_model(self, model_name, model_args):+ aliked_repo_dir = None+ if model_name.startswith("aliked-"):+ input_shape, aliked_repo_dir = model_args+ else:+ input_shape = model_args++ if model_name.startswith("aliked-"):+ model = load_aliked(aliked_repo_dir, model_name)+ elif model_name == "DaD":+ import dad++ model = dad.load_DaD()+ # Compare FP32 inference without the detector's automatic mixed precision.+ for module in model.modules():+ if hasattr(module, "amp"):+ module.amp = False+ elif model_name == "RaCo":+ model = torch.hub.load(+ "cvg/RaCo:35790eb48074ed14839d0fb496b8806caa4e766b",+ "raco",+ trust_repo=True,+ skip_validation=True,+ max_num_keypoints=128,+ )+ elif model_name == "DISK":+ from kornia.feature import DISK++ model = DISK.from_pretrained("depth", device=torch.device("cpu"))+ elif model_name == "XFeat":+ model = load_xfeat()+ model.dev = torch.device("cpu")+ model.NMS = MethodType(xfeat_nms, model)+ elif model_name == "DeDoDe":+ from kornia.feature import DeDoDe++ model = DeDoDe.from_pretrained(+ detector_weights="L-C4-v2", descriptor_weights="B-upright", amp_dtype=torch.float32)+ for module in model.modules():+ if hasattr(module, "amp"):+ module.amp = False+ else:+ raise ValueError(f"Unknown keypoint detector: {model_name}")++ if model_name in ("DaD", "RaCo"):+ from torchvision.transforms.v2 import Normalize++ normalizer = model.normalizer+ # v2 checks the fixed standard deviations without tensor-dependent branching.+ model.normalizer = Normalize(normalizer.mean, normalizer.std)++ generator = torch.Generator().manual_seed(0)+ self.example = (torch.rand(input_shape, generator=generator),)+ self.inputs = (torch.rand(input_shape, generator=generator),)+ return KeypointDetector(model, model_name).cpu().eval()++ @pytest.mark.nightly+ @pytest.mark.parametrize("name,input_shape,mode", [+ pytest.param(+ name, input_shape, mode,+ id=f"{name}-{input_shape[1]}ch-{input_shape[2]}x{input_shape[3]}-{mode}",+ marks=pytest.mark.precommit if name == "aliked-n16rot" and mode == "trace" else (),+ )+ for name, input_shape in MODEL_INPUTS+ for mode in ("trace", "export")+ ])+ def test_convert_model(self, name, input_shape, mode, ie_device):+ self.mode = mode+ model_args = (input_shape, self.get_aliked_repo()) if name.startswith("aliked-") else input_shape+ self.run(name, model_args, ie_device)