From c6e75ed06bc726c7e630a03383210ca9cdb5dece Mon Sep 17 00:00:00 2001 From: jyz Date: Tue, 7 Jul 2026 19:53:18 +0000 Subject: [PATCH] Fix ldexp grad for negative exponents --- test/test_binary_ufuncs.py | 15 +++++++++++++++ tools/autograd/derivatives.yaml | 4 ++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/test/test_binary_ufuncs.py b/test/test_binary_ufuncs.py index 86afbdf6bf83a..5153ea0279a3a 100644 --- a/test/test_binary_ufuncs.py +++ b/test/test_binary_ufuncs.py @@ -227,6 +227,21 @@ def test_lerp_lowp_cpu(self, dtype): expected = torch.lerp(xref, yref, wref).to(dtype) self.assertEqual(actual, expected, atol=0.0, rtol=0.0) + def test_ldexp_backward_negative_exponent(self): + mantissa = torch.tensor([1.0], requires_grad=True) + exponent = torch.tensor([-1], dtype=torch.int32) + + torch.ldexp(mantissa, exponent).sum().backward() + + self.assertEqual(mantissa.grad, torch.tensor([0.5])) + + with fwAD.dual_level(): + mantissa_dual = fwAD.make_dual(torch.tensor([1.0]), torch.tensor([1.0])) + result = torch.ldexp(mantissa_dual, exponent) + _, result_tangent = fwAD.unpack_dual(result) + + self.assertEqual(result_tangent, torch.tensor([0.5])) + class TestBinaryUfuncsDevice(TestCase): # Generic tests for elementwise binary (AKA binary universal (u) functions (funcs)) diff --git a/tools/autograd/derivatives.yaml b/tools/autograd/derivatives.yaml index 9565dd18fe8cc..9d33eb7cd493b 100644 --- a/tools/autograd/derivatives.yaml +++ b/tools/autograd/derivatives.yaml @@ -926,9 +926,9 @@ values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) - name: ldexp.Tensor(Tensor self, Tensor other) -> Tensor - self: grad * at::pow(2, other).conj() + self: grad * at::pow(2.0, other).conj() other: grad * result.conj() * M_LN2 - result: self_t * at::pow(2, other_p) + other_t * result * M_LN2 + result: self_t * at::pow(2.0, other_p) + other_t * result * M_LN2 - name: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) self: zeros_like(self)