warp icon indicating copy to clipboard operation
warp copied to clipboard

`v.y += x` on a local vector double-counts the gradient

Open 0z5a opened this issue 3 weeks ago • 1 comments

Bug Description

+= and -= through an attribute of a local vector, quaternion, or transform give wrong gradients in the backward pass. The subscript form v[1] += x is correct.

import warp as wp


@wp.kernel
def attribute(a: wp.array[wp.vec3], b: wp.array[float], out: wp.array[float]):
    w = a[0]
    w.y += b[0]
    w.y += b[0]
    w.y += b[0]
    out[0] = w.y


@wp.kernel
def subscript(a: wp.array[wp.vec3], b: wp.array[float], out: wp.array[float]):
    w = a[0]
    w[1] += b[0]
    w[1] += b[0]
    w[1] += b[0]
    out[0] = w[1]


for kernel in (attribute, subscript):
    a = wp.array([[1.0, 2.0, 3.0]], dtype=wp.vec3, requires_grad=True)
    b = wp.array([0.5], dtype=float, requires_grad=True)
    out = wp.zeros(1, dtype=float, requires_grad=True)
    tape = wp.Tape()
    with tape:
        wp.launch(kernel, dim=1, inputs=[a, b, out])
    tape.backward(grads={out: wp.ones(1, dtype=float)})
    print(kernel.key, out.numpy()[0], a.grad.numpy()[0], b.grad.numpy()[0])

Observed:

attribute 3.5 [0. 8. 0.] 7.0
subscript 3.5 [0. 1. 0.] 3.0

Expected: both kernels print [0. 1. 0.] 3.0, which is also what central differences give. The forward value is correct either way.

The attribute form loads the component, applies the operator, and writes it back with assign_inplace (transform_set_translation or transform_set_rotation for t.p and t.q). That write does not clear the component's adjoint, so the error doubles with each update; one update already gives 2 instead of 1. The same happens for -=, q.y += x, t.p += u and t.q += d. With enable_vector_component_overwrites, vectors and quaternions are correct, but t.p and t.q are still wrong.

The user guide says in-place addition and subtraction can be used in kernels participating in the backward pass. The existing tests miss this because they do one update per component on a zero wp.vec3(), so no prior value carries a gradient.

Reproduced on CPU with warp-lang 1.20.0.dev20261107 (a8a52c2) on GH200 (aarch64).

I have a fix ready that uses the in-place builtins of the subscript form, and can open a PR. It does not address w.y *= b, w[1] *= b or plain w.y = w.y + b, which give wrong gradients without enable_vector_component_overwrites.

0z5a avatar Nov 07 '26 16:11 0z5a

Hi @0z5a, I'd like to work on this issue and try to fix it. Could you please assign it to me? Thanks!

Marouane-elfadli avatar Nov 08 '26 22:11 Marouane-elfadli