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] Keep aten::log1p and aten::expm1 accurate for small inputs (#39608)
Cekaruc64f0fe07bbe
diff --git a/src/frontends/pytorch/src/op/expm1.cpp b/src/frontends/pytorch/src/op/expm1.cppindex 856c035ad79..0a5de42bf5a 100644--- a/src/frontends/pytorch/src/op/expm1.cpp+++ b/src/frontends/pytorch/src/op/expm1.cpp@@ -5,7 +5,14 @@#include "openvino/frontend/pytorch/node_context.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert_like.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/equal.hpp"#include "openvino/op/exp.hpp"+#include "openvino/op/is_inf.hpp"+#include "openvino/op/log.hpp"+#include "openvino/op/logical_or.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/select.hpp"#include "openvino/op/subtract.hpp"#include "utils.hpp"@@ -18,14 +25,27 @@ OutputVector translate_expm1(const NodeContext& context) {// aten::expm1(Tensor self) -> Tensor// aten::expm1(Tensor self, Tensor out) -> out Tensor- auto exp_vector = translate_1to1_match_1_inputs_with_fp32_type_alignment<v0::Exp>(context);- PYTORCH_OP_CONVERSION_CHECK(exp_vector.size() == 1,- "Expected exactly one element in the vector. Got: ",- exp_vector.size());- auto exp = exp_vector[0];+ auto x = get_input_with_floating_type(context, 0);+ auto exp = context.mark_node(std::make_shared<v0::Exp>(x));auto const_1 = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));const_1 = context.mark_node(std::make_shared<v1::ConvertLike>(const_1, exp));- auto expm1 = context.mark_node(std::make_shared<v1::Subtract>(exp, const_1));+ auto exp_minus_one = context.mark_node(std::make_shared<v1::Subtract>(exp, const_1));+ // exp(x) - 1 loses all precision for small x, because exp(x) rounds to 1. Compensate the rounding error of+ // u = exp(x) as (u - 1) * (x / log(u)), and return x itself where u rounds to exactly 1.+ auto log = context.mark_node(std::make_shared<v0::Log>(exp));+ auto scale = context.mark_node(std::make_shared<v1::Divide>(x, log));+ Output<Node> expm1 = context.mark_node(std::make_shared<v1::Multiply>(exp_minus_one, scale));+ auto u_is_one = context.mark_node(std::make_shared<v1::Equal>(exp, const_1));+ expm1 = context.mark_node(std::make_shared<v1::Select>(u_is_one, x, expm1));+ // For large negative x, exp(x) - 1 rounds to exactly -1, which is already the correct result. There u may be+ // subnormal or 0, where log(u) is imprecise or -inf and the formula above is wrong. Where exp(x) overflows to+ // +inf, the formula gives nan while exp(x) - 1 is +inf.+ auto const_minus_1 = context.mark_node(v0::Constant::create(element::i32, Shape{}, {-1}));+ const_minus_1 = context.mark_node(std::make_shared<v1::ConvertLike>(const_minus_1, exp));+ auto is_minus_one = context.mark_node(std::make_shared<v1::Equal>(exp_minus_one, const_minus_1));+ auto exp_is_inf = context.mark_node(std::make_shared<v10::IsInf>(exp));+ auto keep_exp_minus_one = context.mark_node(std::make_shared<v1::LogicalOr>(is_minus_one, exp_is_inf));+ expm1 = context.mark_node(std::make_shared<v1::Select>(keep_exp_minus_one, exp_minus_one, expm1));if (!context.input_is_none(1)) {context.mutate_input(1, expm1);diff --git a/src/frontends/pytorch/src/op/log.cpp b/src/frontends/pytorch/src/op/log.cppindex a7f2d96b868..33ff059b0b2 100644--- a/src/frontends/pytorch/src/op/log.cpp+++ b/src/frontends/pytorch/src/op/log.cpp@@ -10,9 +10,13 @@#include "openvino/op/convert.hpp"#include "openvino/op/convert_like.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/equal.hpp"#include "openvino/op/exp.hpp"+#include "openvino/op/is_inf.hpp"+#include "openvino/op/multiply.hpp"#include "openvino/op/reduce_max.hpp"#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/select.hpp"#include "openvino/op/sigmoid.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"@@ -114,7 +118,17 @@ OutputVector translate_log1p(const NodeContext& context) {one = context.mark_node(std::make_shared<v1::ConvertLike>(one, x));auto x_plus_one = context.mark_node(std::make_shared<v1::Add>(x, one));auto log = context.mark_node(std::make_shared<v0::Log>(x_plus_one));- return {log};+ // log(1 + x) loses all precision for small x, because 1 + x rounds to 1. Compensate the rounding error of+ // u = 1 + x as log(u) * (x / (u - 1)), and return x itself where u rounds to exactly 1.+ auto u_minus_one = context.mark_node(std::make_shared<v1::Subtract>(x_plus_one, one));+ auto scale = context.mark_node(std::make_shared<v1::Divide>(x, u_minus_one));+ Output<Node> log1p = context.mark_node(std::make_shared<v1::Multiply>(log, scale));+ auto u_is_one = context.mark_node(std::make_shared<v1::Equal>(x_plus_one, one));+ log1p = context.mark_node(std::make_shared<v1::Select>(u_is_one, x, log1p));+ // log1p(+inf) = +inf, while the formula above gives inf / inf = nan.+ auto x_is_pos_inf = context.mark_node(std::make_shared<v10::IsInf>(x, v10::IsInf::Attributes(false, true)));+ log1p = context.mark_node(std::make_shared<v1::Select>(x_is_pos_inf, x, log1p));+ return {log1p};};} // namespace ov::frontend::pytorch::opdiff --git a/tests/layer_tests/pytorch_tests/test_unary_ops.py b/tests/layer_tests/pytorch_tests/test_unary_ops.pyindex 33997a1e2f2..37142adfdfc 100644--- a/tests/layer_tests/pytorch_tests/test_unary_ops.py+++ b/tests/layer_tests/pytorch_tests/test_unary_ops.py@@ -1,6 +1,7 @@# Copyright (C) 2018-2026 Intel Corporation# SPDX-License-Identifier: Apache-2.0+import numpy as npimport pytestimport torchimport torch.nn.functional as F@@ -334,3 +335,68 @@ class TestUnaryOp(PytorchLayerTest):self.dtype = dtypeself._test(unary_op_complex_net(OPS[op_type], dtype), op_type,ie_device, precision, ir_version)+++class TestLog1pExpm1Accuracy(PytorchLayerTest):+ # log1p and expm1 exist to stay accurate for small inputs, where 1 + x and exp(x) round to 1.+ # The result is divided by x so that it is ~1 for small x and the absolute tolerance of the+ # comparison cannot hide a result that collapsed to 0 or lost most of its digits.+ def _prepare_input(self):+ return (np.array([1e-30, -1e-30, 1e-10, -1e-10, 1e-7, -1e-7, 1e-4, -1e-4, 0.5, -0.5], dtype=np.float32),)++ def create_model(self, op_name, dtype):++ class aten_op_relative(torch.nn.Module):+ def __init__(self, op, dtype):+ super().__init__()+ self.op = op+ self.dtype = dtype++ def forward(self, x):+ x = x.to(self.dtype)+ return self.op(x) / x++ return aten_op_relative(getattr(torch, op_name), dtype), "aten::" + op_name++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.precommit_fx_backend+ @pytest.mark.parametrize("op_name", ["log1p", "expm1"])+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64])+ def test_small_values(self, op_name, dtype, ie_device, precision, ir_version):+ if precision == "FP16":+ pytest.skip("Values exceed the f16 range")+ self._test(*self.create_model(op_name, dtype), ie_device, precision, ir_version)+++class TestLog1pExpm1SpecialValues(PytorchLayerTest):+ def _prepare_input(self):+ return (np.array(self.values, dtype=np.float32),)++ def create_model(self, op_name):++ class aten_op(torch.nn.Module):+ def __init__(self, op):+ super().__init__()+ self.op = op++ def forward(self, x):+ return self.op(x)++ return aten_op(getattr(torch, op_name)), "aten::" + op_name++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.precommit_fx_backend+ @pytest.mark.parametrize(("op_name", "values"), [+ ("log1p", [np.inf, -1.0, -1.5, np.nan, 3e38]),+ # -87.5, -100 and -103 make exp(x) subnormal, where expm1 must still be exactly -1+ ("expm1", [np.inf, -np.inf, -87.5, -100.0, -103.0, 80.0]),+ ])+ def test_special_values(self, op_name, values, ie_device, precision, ir_version):+ if precision == "FP16":+ pytest.skip("Values exceed the f16 range")+ self.values = values+ self._test(*self.create_model(op_name), ie_device, precision, ir_version)