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] Add support for LieTorch decomposed ops (#36482)
Piotr Krzemińskia9955dc014bb
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex 6ad4ff35879..f03547cc920 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -399,6 +399,14 @@ class TorchScriptPythonDecoder(TorchDecoderBase):# temporary name to custom graph. But providing conversion code# as a callable `target` is more convenient.return target+ # lietorch group ops surface as opaque prim::PythonOp autograd functions+ # report a dedicated op type so the frontend can route them to native ops+ if self.graph_element.kind() == "prim::PythonOp":+ fn_cls = getattr(self.graph_element.pyobj(), "__self__", None)+ module = getattr(fn_cls, "__module__", "")+ op_name = getattr(fn_cls, "__name__", "")+ if (module == "lietorch" or module.startswith("lietorch.")) and op_name:+ return "lietorch::" + op_namereturn self.graph_element.kind()def get_schema(self) -> str:diff --git a/src/frontends/pytorch/src/op/lietorch.cpp b/src/frontends/pytorch/src/op/lietorch.cppnew file mode 100644index 00000000000..bfacb260dbb--- /dev/null+++ b/src/frontends/pytorch/src/op/lietorch.cpp@@ -0,0 +1,141 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#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/convert_like.hpp"+#include "openvino/op/cos.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/sin.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/subtract.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov::op;++namespace {++Output<Node> mul(const NodeContext& ctx, const Output<Node>& a, const Output<Node>& b) {+ return ctx.mark_node(std::make_shared<v1::Multiply>(a, b));+}++Output<Node> sub(const NodeContext& ctx, const Output<Node>& a, const Output<Node>& b) {+ return ctx.mark_node(std::make_shared<v1::Subtract>(a, b));+}++Output<Node> add(const NodeContext& ctx, const Output<Node>& a, const Output<Node>& b) {+ return ctx.mark_node(std::make_shared<v1::Add>(a, b));+}++Output<Node> div(const NodeContext& ctx, const Output<Node>& a, const Output<Node>& b) {+ return ctx.mark_node(std::make_shared<v1::Divide>(a, b));+}++Output<Node> concat_last(const NodeContext& ctx, const OutputVector& items) {+ return ctx.mark_node(std::make_shared<v0::Concat>(items, -1));+}++Output<Node> i64c(const NodeContext& ctx, const Shape& shape, const std::vector<int64_t>& vals) {+ return ctx.mark_node(v0::Constant::create(element::i64, shape, vals));+}++// float constant matching the data tensor element type+Output<Node> fconst(const NodeContext& ctx, float value, const Output<Node>& like) {+ auto c = ctx.mark_node(v0::Constant::create(element::f32, Shape{}, {value}));+ return ctx.mark_node(std::make_shared<v1::ConvertLike>(c, like));+}++// gather one component along the last axis, shape (..., 1)+Output<Node> comp(const NodeContext& ctx, const Output<Node>& x, int64_t i) {+ return ctx.mark_node(std::make_shared<v8::Gather>(x, i64c(ctx, Shape{1}, {i}), i64c(ctx, Shape{}, {-1})));+}++// slice [lo:hi) along the last axis+Output<Node> range_last(const NodeContext& ctx, const Output<Node>& x, int64_t lo, int64_t hi) {+ auto start = i64c(ctx, Shape{1}, {lo});+ auto stop = i64c(ctx, Shape{1}, {hi});+ auto step = i64c(ctx, Shape{1}, {1});+ auto axes = i64c(ctx, Shape{1}, {-1});+ return ctx.mark_node(std::make_shared<v8::Slice>(x, start, stop, step, axes));+}++// cross product of two (..., 3) tensors along the last axis+Output<Node> cross_last(const NodeContext& ctx, const Output<Node>& a, const Output<Node>& b) {+ auto ax = comp(ctx, a, 0), ay = comp(ctx, a, 1), az = comp(ctx, a, 2);+ auto bx = comp(ctx, b, 0), by = comp(ctx, b, 1), bz = comp(ctx, b, 2);+ auto cx = sub(ctx, mul(ctx, ay, bz), mul(ctx, az, by));+ auto cy = sub(ctx, mul(ctx, az, bx), mul(ctx, ax, bz));+ auto cz = sub(ctx, mul(ctx, ax, by), mul(ctx, ay, bx));+ return concat_last(ctx, {cx, cy, cz});+}++// SE3 exp: tangent (..., 6) to SE3 data (..., 7)+// tau_phi = [tau(3) translation, phi(3) rotation], data layout [tx, ty, tz, qx, qy, qz, qw]+Output<Node> decompose_exp(const NodeContext& ctx, const Output<Node>& tau_phi) {+ auto tau = range_last(ctx, tau_phi, 0, 3);+ auto phi = range_last(ctx, tau_phi, 3, 6);++ // theta^2 as an explicit component sum, phi always has 3 elements+ auto px = comp(ctx, phi, 0), py = comp(ctx, phi, 1), pz = comp(ctx, phi, 2);+ auto theta2 = add(ctx, add(ctx, mul(ctx, px, px), mul(ctx, py, py)), mul(ctx, pz, pz));+ auto theta2_eps = add(ctx, theta2, fconst(ctx, 1e-12f, tau_phi));+ auto theta = ctx.mark_node(std::make_shared<v0::Sqrt>(theta2_eps));+ auto half_theta = mul(ctx, theta, fconst(ctx, 0.5f, tau_phi));++ // quaternion: q_xyz = sin(theta/2)/theta * phi, q_w = cos(theta/2)+ auto real = ctx.mark_node(std::make_shared<v0::Cos>(half_theta));+ auto imag = div(ctx, ctx.mark_node(std::make_shared<v0::Sin>(half_theta)), theta);+ auto q = concat_last(ctx, {mul(ctx, imag, phi), real});++ // translation: t = tau + c1*(phi x tau) + c2*(phi x (phi x tau))+ // c1 = (1 - cos theta) / theta^2, c2 = (theta - sin theta) / theta^3+ auto c1 =+ div(ctx, sub(ctx, fconst(ctx, 1.0f, tau_phi), ctx.mark_node(std::make_shared<v0::Cos>(theta))), theta2_eps);+ auto c2 = div(ctx, sub(ctx, theta, ctx.mark_node(std::make_shared<v0::Sin>(theta))), mul(ctx, theta2_eps, theta));+ auto phi_x_tau = cross_last(ctx, phi, tau);+ auto phi_x_phi_x_tau = cross_last(ctx, phi, phi_x_tau);+ auto t = add(ctx, tau, add(ctx, mul(ctx, c1, phi_x_tau), mul(ctx, c2, phi_x_phi_x_tau)));+ return concat_last(ctx, {t, q});+}++// SE3 act: SE3 data (..., 7) and points (..., 3) to (..., 3)+Output<Node> decompose_act(const NodeContext& ctx, const Output<Node>& data, const Output<Node>& p) {+ auto t = range_last(ctx, data, 0, 3);+ auto qv = range_last(ctx, data, 3, 6);+ auto qw = comp(ctx, data, 6);++ // rotate: u = 2*(qv x p); p_rot = p + qw*u + qv x u+ auto u = mul(ctx, fconst(ctx, 2.0f, data), cross_last(ctx, qv, p));+ auto p_rot = add(ctx, add(ctx, p, mul(ctx, qw, u)), cross_last(ctx, qv, u));+ return add(ctx, p_rot, t);+}++} // namespace++// lietorch traces group ops as prim::PythonOp, leading inputs are tensor operands,+// any trailing inputs are closure captures and are ignored+OutputVector translate_lietorch_exp(const NodeContext& context) {+ num_inputs_check(context, 1, context.get_input_size());+ return {decompose_exp(context, context.get_input(0))};+};++OutputVector translate_lietorch_act3(const NodeContext& context) {+ num_inputs_check(context, 2, context.get_input_size());+ return {decompose_act(context, context.get_input(0), context.get_input(1))};+};++} // 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 b7125eeeb56..13d7a6a1a90 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -158,6 +158,8 @@ OP_CONVERTER(translate_linalg_matrix_norm);OP_CONVERTER(translate_linalg_vector_norm);OP_CONVERTER(translate_linear);OP_CONVERTER(translate_linspace);+OP_CONVERTER(translate_lietorch_exp);+OP_CONVERTER(translate_lietorch_act3);OP_CONVERTER(translate_list_construct);OP_CONVERTER(translate_list_unpack);OP_CONVERTER(translate_logaddexp);@@ -814,6 +816,8 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"ov_ext::embedding", op::translate_embedding_ext},{"ov_ext::conv1d", op::translate_conv1d_ext},{"ov_ext::linear", op::translate_linear_ext},+ {"lietorch::Exp", op::translate_lietorch_exp},+ {"lietorch::Act3", op::translate_lietorch_act3},{"prim::abs", op::translate_1to1_match_1_inputs<opset10::Abs>},{"prim::Constant", op::translate_constant},{"prim::device", op::translate_constant},diff --git a/tests/layer_tests/pytorch_tests/test_lietorch_se3.py b/tests/layer_tests/pytorch_tests/test_lietorch_se3.pynew file mode 100644index 00000000000..44d791254e6--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_lietorch_se3.py@@ -0,0 +1,104 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import pytest+import torch+from torch.autograd.function import Function++from pytorch_layer_test_class import PytorchLayerTest+++def _cross_last(a, b):+ # cross product along the last axis+ ax, ay, az = a[..., 0:1], a[..., 1:2], a[..., 2:3]+ bx, by, bz = b[..., 0:1], b[..., 1:2], b[..., 2:3]+ cx = ay * bz - az * by+ cy = az * bx - ax * bz+ cz = ax * by - ay * bx+ return torch.cat([cx, cy, cz], dim=-1)+++def _se3_exp(tangent):+ # tangent (..., 6) -> SE3 data (..., 7) = [tx, ty, tz, qx, qy, qz, qw]+ tau = tangent[..., 0:3]+ phi = tangent[..., 3:6]+ theta2 = (phi * phi).sum(-1, keepdim=True) + 1e-12+ theta = torch.sqrt(theta2)+ half_theta = theta * 0.5+ qw = torch.cos(half_theta)+ imag = torch.sin(half_theta) / theta+ q = torch.cat([imag * phi, qw], dim=-1)+ c1 = (1.0 - torch.cos(theta)) / theta2+ c2 = (theta - torch.sin(theta)) / (theta2 * theta)+ phi_x_tau = _cross_last(phi, tau)+ phi_x_phi_x_tau = _cross_last(phi, phi_x_tau)+ t = tau + c1 * phi_x_tau + c2 * phi_x_phi_x_tau+ return torch.cat([t, q], dim=-1)+++def _se3_act(data, points):+ # data (..., 7), points (..., 3) -> (..., 3)+ t = data[..., 0:3]+ qv = data[..., 3:6]+ qw = data[..., 6:7]+ u = 2.0 * _cross_last(qv, points)+ p_rot = (points + qw * u) + _cross_last(qv, u)+ return p_rot + t+++class Exp(Function):+ @staticmethod+ def forward(ctx, tangent):+ ctx.save_for_backward(tangent)+ return _se3_exp(tangent)+++class Act3(Function):+ @staticmethod+ def forward(ctx, data, points):+ ctx.save_for_backward(data, points)+ return _se3_act(data, points)+++Exp.__module__ = "lietorch.group_ops"+Act3.__module__ = "lietorch.group_ops"+++class TestLieTorchSE3Exp(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(2, 6, dtype="float32"),)++ def create_model(self):+ class lietorch_exp(torch.nn.Module):+ def forward(self, tangent):+ # the reshape gives the op a static rank input, like lietorch does+ return Exp.apply(tangent.reshape(-1, 6))++ return lietorch_exp(), "prim::PythonOp"++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_lietorch_se3_exp(self, ie_device, precision, ir_version):+ self._test(*self.create_model(), ie_device, precision, ir_version,+ trace_model=True)+++class TestLieTorchSE3Act(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(2, 8, 7, dtype="float32"),+ self.random.randn(2, 8, 3, dtype="float32"))++ def create_model(self):+ class lietorch_act(torch.nn.Module):+ def forward(self, data, points):+ d = data.reshape(data.shape[0], -1, 7)+ p = points.reshape(points.shape[0], -1, 3)+ return Act3.apply(d, p)++ return lietorch_act(), "prim::PythonOp"++ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_lietorch_se3_act(self, ie_device, precision, ir_version):+ self._test(*self.create_model(), ie_device, precision, ir_version,+ trace_model=True)