Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Atan2(0,0) fix following IEEE standard. (#34720)

Pramit Biswas23e17aa8627d
diff --git a/src/frontends/common_translators/src/op/atan2.cpp b/src/frontends/common_translators/src/op/atan2.cpp
index 2c9279baa92..39b0754af93 100644
--- a/src/frontends/common_translators/src/op/atan2.cpp
+++ b/src/frontends/common_translators/src/op/atan2.cpp
@@ -12,7 +12,9 @@
#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/logical_or.hpp"
+#include "openvino/op/negative.hpp"
#include "openvino/op/select.hpp"
#include "openvino/op/subtract.hpp"
#include "utils.hpp"
@@ -51,7 +53,6 @@ OutputVector translate_atan2_util(const NodeContext& context, const Output<Node>
// x < 0 and y < 0, need to minus pi
auto y_less_than_zero = make_shared<v1::Less>(lhs, zero);
- auto subtract_pi_condition = context.mark_node(make_shared<v1::LogicalAnd>(x_less_than_zero, y_less_than_zero));
// x = 0 and y > 0, pi/2
auto x_equal_zero = make_shared<v1::Equal>(rhs, zero);
@@ -64,15 +65,56 @@ OutputVector translate_atan2_util(const NodeContext& context, const Output<Node>
auto special_case_condition =
context.mark_node(make_shared<v1::LogicalOr>(half_pi_condition, neg_half_pi_condition));
+ // x = 0 and y = 0: with IEEE 754 signed-zero handling.
+ // IEEE 754 definitions:
+ // atan2(+0,+0)=+0,
+ // atan2(-0,+0)=-0,
+ // atan2(+0,-0)=+π,
+ // atan2(-0,-0)=-π
+ // Standard comparison ops cannot distinguish ±0 (-0 == +0 is true, and -0 < 0 is false).
+ // Detect sign via reciprocal: 1/(+0)=+inf, 1/(-0)=-inf, then Less(recip, 0) detects negative sign.
+ auto y_equal_zero = context.mark_node(make_shared<v1::Equal>(lhs, zero));
+ auto both_zero_condition = context.mark_node(make_shared<v1::LogicalAnd>(x_equal_zero, y_equal_zero));
+
+ auto one = context.mark_node(v0::Constant::create(ov::element::f64, Shape{}, {1.0}));
+ one = context.mark_node(make_shared<v1::ConvertLike>(one, rhs));
+
+ // for safe division when non-zero, +inf for +0, -inf for -0 when zero
+ auto rhs_for_sign = context.mark_node(make_shared<v1::Select>(both_zero_condition, rhs, one));
+ auto lhs_for_sign = context.mark_node(make_shared<v1::Select>(both_zero_condition, lhs, one));
+ auto recip_x = context.mark_node(make_shared<v1::Divide>(one, rhs_for_sign));
+ auto recip_y = context.mark_node(make_shared<v1::Divide>(one, lhs_for_sign));
+
+ auto x_sign_negative = context.mark_node(make_shared<v1::Less>(recip_x, zero));
+ auto y_sign_negative = context.mark_node(make_shared<v1::Less>(recip_y, zero));
+ auto x_sign_positive = context.mark_node(make_shared<v1::LogicalNot>(x_sign_negative));
+ auto y_sign_positive = context.mark_node(make_shared<v1::LogicalNot>(y_sign_negative));
+
+ auto neg_pi = context.mark_node(make_shared<v0::Negative>(pi));
+ auto neg_zero = context.mark_node(make_shared<v0::Negative>(zero));
+
+ // atan2(-0, -0) = -π
+ auto case_y_neg_x_neg = context.mark_node(make_shared<v1::LogicalAnd>(x_sign_negative, y_sign_negative));
+ // atan2(+0, -0) = +π
+ auto case_y_pos_x_neg = context.mark_node(make_shared<v1::LogicalAnd>(x_sign_negative, y_sign_positive));
+ // atan2(-0, +0) = -0
+ auto case_y_neg_x_pos = context.mark_node(make_shared<v1::LogicalAnd>(x_sign_positive, y_sign_negative));
+ // atan2(+0, +0) = +0 (default fallback)
+
+ auto signed_zero_result = context.mark_node(make_shared<v1::Select>(case_y_neg_x_neg, neg_pi, zero));
+ signed_zero_result = context.mark_node(make_shared<v1::Select>(case_y_pos_x_neg, pi, signed_zero_result));
+ signed_zero_result = context.mark_node(make_shared<v1::Select>(case_y_neg_x_pos, neg_zero, signed_zero_result));
+
// do adjustment
auto atan_plus_pi = context.mark_node(make_shared<v1::Add>(atan, pi));
auto atan_minus_pi = context.mark_node(make_shared<v1::Subtract>(atan, pi));
// select result
- auto ajusted_case = context.mark_node(make_shared<v1::Select>(add_pi_condition, atan_plus_pi, atan_minus_pi));
+ auto adjusted_case = context.mark_node(make_shared<v1::Select>(add_pi_condition, atan_plus_pi, atan_minus_pi));
auto special_case = context.mark_node(make_shared<v1::Select>(half_pi_condition, half_pi, neg_half_pi));
- auto adjusted_atan = context.mark_node(make_shared<v1::Select>(x_greater_than_zero, atan, ajusted_case));
+ auto adjusted_atan = context.mark_node(make_shared<v1::Select>(x_greater_than_zero, atan, adjusted_case));
auto result = context.mark_node(make_shared<v1::Select>(special_case_condition, special_case, adjusted_atan));
+ result = context.mark_node(make_shared<v1::Select>(both_zero_condition, signed_zero_result, result));
return {result};
}
diff --git a/tests/layer_tests/pytorch_tests/test_atan2.py b/tests/layer_tests/pytorch_tests/test_atan2.py
index 4863c1daa6a..c0bd936ec31 100644
--- a/tests/layer_tests/pytorch_tests/test_atan2.py
+++ b/tests/layer_tests/pytorch_tests/test_atan2.py
@@ -74,4 +74,71 @@ class TestAtan2Types(PytorchLayerTest):
self.rhs_type = rhs_type
self.rhs_shape = rhs_shape
self._test(*self.create_model(lhs_type, rhs_type),
- ie_device, precision, ir_version, freeze_model=False, trace_model=True, fx_kind="aten.arctan2")
\ No newline at end of file
+ ie_device, precision, ir_version, freeze_model=False, trace_model=True, fx_kind="aten.arctan2")
+
+
+class TestAtan2ZeroEdgeCases(PytorchLayerTest):
+ """Test atan2 with zero in the inputs - regression test for atan2(0, 0)
+ returning NaN.
+
+ The common_translators atan2 decomposition computes atan(y/x), which for
+ x=0, y=0 produces atan(NaN) = NaN. Test handling for all IEEE 754
+ signed-zero cases:
+ atan2(+0, +0) = +0
+ atan2(-0, +0) = -0
+ atan2(+0, -0) = +π
+ atan2(-0, -0) = -π
+ """
+
+ def _prepare_input(self):
+ if self.zero_case == "both_positive_zero":
+ y = torch.zeros(1, dtype=torch.float32).numpy()
+ x = torch.zeros(1, dtype=torch.float32).numpy()
+ elif self.zero_case == "mixed_zeros_and_axes":
+ y = torch.tensor([0.0, 1.0, 0.0, -1.0, 0.0], dtype=torch.float32).numpy()
+ x = torch.tensor([0.0, 0.0, 1.0, 0.0, -1.0], dtype=torch.float32).numpy()
+ elif self.zero_case == "all_zeros":
+ y = torch.zeros(3, dtype=torch.float32).numpy()
+ x = torch.zeros(3, dtype=torch.float32).numpy()
+ elif self.zero_case == "x_zero_various_y":
+ y = torch.tensor([0.0, 1.0, -1.0], dtype=torch.float32).numpy()
+ x = torch.zeros(3, dtype=torch.float32).numpy()
+ elif self.zero_case == "signed_neg_zero_x":
+ y = torch.tensor([0.0, -0.0], dtype=torch.float32).numpy()
+ x = torch.tensor([-0.0, -0.0], dtype=torch.float32).numpy()
+ elif self.zero_case == "signed_neg_zero_y":
+ y = torch.tensor([-0.0, -0.0], dtype=torch.float32).numpy()
+ x = torch.tensor([0.0, -0.0], dtype=torch.float32).numpy()
+ elif self.zero_case == "all_four_signed_zero_combos":
+ y = torch.tensor([0.0, -0.0, 0.0, -0.0], dtype=torch.float32).numpy()
+ x = torch.tensor([0.0, 0.0, -0.0, -0.0], dtype=torch.float32).numpy()
+ return (y, x)
+
+ def create_model(self):
+ class aten_atan2(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, lhs, rhs):
+ out = torch.arctan2(lhs, rhs)
+ # Use reciprocal so that signed-zero differences become
+ # observable: +0 -> +inf, -0 -> -inf.
+ return 1.0 / out
+
+ return aten_atan2(), "aten::atan2"
+
+ @pytest.mark.parametrize("zero_case", [
+ "both_positive_zero",
+ "mixed_zeros_and_axes",
+ "all_zeros",
+ "x_zero_various_y",
+ "signed_neg_zero_x",
+ "signed_neg_zero_y",
+ "all_four_signed_zero_combos",
+ ])
+ @pytest.mark.precommit
+ @pytest.mark.nightly
+ def test_atan2_zero_edge_cases(self, ie_device, precision, ir_version, zero_case):
+ self.zero_case = zero_case
+ self._test(*self.create_model(), ie_device, precision, ir_version,
+ use_convert_model=True, fx_kind="aten.arctan2")
diff --git a/tests/layer_tests/tensorflow_tests/test_tf_Atan2.py b/tests/layer_tests/tensorflow_tests/test_tf_Atan2.py
index dc951194a5a..74b45b15ad8 100644
--- a/tests/layer_tests/tensorflow_tests/test_tf_Atan2.py
+++ b/tests/layer_tests/tensorflow_tests/test_tf_Atan2.py
@@ -42,3 +42,93 @@ class TestAtan2(CommonTFLayerTest):
def test_atan2_basic(self, params, ie_device, precision, ir_version, temp_dir):
self._test(*self.create_atan2_net(**params),
ie_device, precision, ir_version, temp_dir=temp_dir)
+
+
+class TestAtan2ZeroEdgeCases(CommonTFLayerTest):
+ """Test atan2 with zero in the inputs - regression test for atan2(0, 0)
+ returning NaN.
+
+ The common_translators atan2 decomposition computes atan(y/x), which for
+ x=0, y=0 produces atan(NaN) = NaN. Test handling for all IEEE 754
+ signed-zero cases:
+ atan2(+0, +0) = +0
+ atan2(-0, +0) = -0
+ atan2(+0, -0) = +π
+ atan2(-0, -0) = -π
+ """
+
+ def _prepare_input(self, inputs_info):
+ assert 'y:0' in inputs_info
+ assert 'x:0' in inputs_info
+ if self.zero_case == "both_positive_zero":
+ y = np.zeros(inputs_info['y:0'], dtype=np.float32)
+ x = np.zeros(inputs_info['x:0'], dtype=np.float32)
+ elif self.zero_case == "mixed_zeros_and_axes":
+ y = np.array([0.0, 1.0, 0.0, -1.0, 0.0], dtype=np.float32)
+ x = np.array([0.0, 0.0, 1.0, 0.0, -1.0], dtype=np.float32)
+ elif self.zero_case == "all_zeros":
+ y = np.zeros(inputs_info['y:0'], dtype=np.float32)
+ x = np.zeros(inputs_info['x:0'], dtype=np.float32)
+ elif self.zero_case == "x_zero_various_y":
+ y = np.array([0.0, 1.0, -1.0], dtype=np.float32)
+ x = np.zeros(inputs_info['x:0'], dtype=np.float32)
+ elif self.zero_case == "signed_neg_zero_x":
+ y = np.array([0.0, -0.0], dtype=np.float32)
+ x = np.array([-0.0, -0.0], dtype=np.float32)
+ elif self.zero_case == "signed_neg_zero_y":
+ y = np.array([-0.0, -0.0], dtype=np.float32)
+ x = np.array([0.0, -0.0], dtype=np.float32)
+ elif self.zero_case == "all_four_signed_zero_combos":
+ y = np.array([0.0, -0.0, 0.0, -0.0], dtype=np.float32)
+ x = np.array([0.0, 0.0, -0.0, -0.0], dtype=np.float32)
+ return {'y:0': y, 'x:0': x}
+
+ def create_atan2_net(self, input_shape, input_type):
+ self.input_type = input_type
+ tf.compat.v1.reset_default_graph()
+ with tf.compat.v1.Session() as sess:
+ y = tf.compat.v1.placeholder(input_type, input_shape, 'y')
+ x = tf.compat.v1.placeholder(input_type, input_shape, 'x')
+ atan2_res = tf.raw_ops.Atan2(y=y, x=x)
+ # Make signed-zero outputs observable: +0 -> +1, -0 -> -1.
+ # Wrap in where + sign to keep only finite values in the output:
+ # sign(1/+0) = sign(+inf) = +1
+ # sign(1/-0) = sign(-inf) = -1
+ # non-zero outputs are kept as-is.
+ zero_const = tf.constant(0.0, dtype=input_type)
+ is_zero = tf.equal(atan2_res, zero_const)
+ sign_of_recip = tf.sign(tf.math.reciprocal(atan2_res))
+ tf.where(is_zero, sign_of_recip, atan2_res,
+ name="atan2_sign_aware")
+ tf.compat.v1.global_variables_initializer()
+ tf_net = sess.graph_def
+
+ return tf_net, None
+
+ _case_shapes = {
+ "both_positive_zero": [1],
+ "mixed_zeros_and_axes": [5],
+ "all_zeros": [3],
+ "x_zero_various_y": [3],
+ "signed_neg_zero_x": [2],
+ "signed_neg_zero_y": [2],
+ "all_four_signed_zero_combos": [4],
+ }
+
+ @pytest.mark.parametrize("zero_case", [
+ "both_positive_zero",
+ "mixed_zeros_and_axes",
+ "all_zeros",
+ "x_zero_various_y",
+ "signed_neg_zero_x",
+ "signed_neg_zero_y",
+ "all_four_signed_zero_combos",
+ ])
+ @pytest.mark.precommit
+ @pytest.mark.nightly
+ def test_atan2_zero_edge_cases(self, ie_device, precision, ir_version,
+ temp_dir, zero_case):
+ self.zero_case = zero_case
+ input_shape = self._case_shapes[zero_case]
+ self._test(*self.create_atan2_net(input_shape, np.float32),
+ ie_device, precision, ir_version, temp_dir=temp_dir)