#1552·warp

Adjoint of continue in dynamic for-loops produces wrong gradients for argmax-style reductions

Author: daedalus5Created Jun 12, 2026Updated Sep 29, 2026
Labelsbugautodiff

The adjoint of a continue statement inside a dynamic Warp for-loop produces incorrect gradients for argmax-style reductions: the gradient is computed as if every output's argmax landed on the same iteration (the last one that ran the body in the forward pass), independent of the per-thread input that actually selected the winner. Forward outputs are correct; gradients are not.

Discovered while working on GH-1497. The "predicate" form (which fully unrolls) returns correct gradients; the "continue" form (which keeps the inner loop dynamic because contains_break refuses to unroll loops containing continue/break) does not.

Reproducer

python
import numpy as np
import warp as wp


@wp.kernel
def k_predicate(
    c_arr: wp.array2d(dtype=wp.float32),
    x_arr: wp.array(dtype=wp.float32),
    out: wp.array(dtype=wp.float32),
):
    tid = wp.tid()
    max_val = wp.float(-1e20)
    for p in range(5):
        for q in range(5):
            c = c_arr[p, q]
            if c != 0.0:
                d = c * (wp.float(p + 1) + wp.float(q + 1))
                v = x_arr[tid] * d
                if v > max_val:
                    max_val = v
    out[tid] = max_val


@wp.kernel
def k_continue(
    c_arr: wp.array2d(dtype=wp.float32),
    x_arr: wp.array(dtype=wp.float32),
    out: wp.array(dtype=wp.float32),
):
    tid = wp.tid()
    max_val = wp.float(-1e20)
    for p in range(5):
        for q in range(5):
            c = c_arr[p, q]
            if c == 0.0:
                continue
            d = c * (wp.float(p + 1) + wp.float(q + 1))
            v = x_arr[tid] * d
            if v > max_val:
                max_val = v
    out[tid] = max_val


def run(kernel, c_np, x_np, device):
    n = x_np.shape[0]
    x = wp.array(x_np, device=device, requires_grad=True)
    c = wp.array(c_np, device=device, requires_grad=False)
    out = wp.zeros(n, dtype=wp.float32, device=device, requires_grad=True)
    tape = wp.Tape()
    with tape:
        wp.launch(kernel, n, inputs=[c, x, out], device=device)
    out.grad = wp.array(np.ones(n, dtype=np.float32), device=device)
    tape.backward()
    return out.numpy(), tape.gradients[x].numpy()


c_np = np.zeros((5, 5), dtype=np.float32)
c_np[0, 0] = 1.0   # d = 1 * (1 + 1) = 2
c_np[1, 1] = -1.0  # d = -1 * (2 + 2) = -4
x_np = np.array([1.0, -1.0, 2.0, -2.0], dtype=np.float32)

# Analytical reference (argmax flips with sign of x):
#   tid 0 (x=+1):  max(1*2, 1*-4)  = 2  -> d/dx = d* = 2
#   tid 1 (x=-1):  max(-1*2, -1*-4)= 4  -> d/dx = d* = -4
#   tid 2 (x=+2):  max(2*2, 2*-4)  = 4  -> d/dx = d* = 2
#   tid 3 (x=-2):  max(-2*2, -2*-4)= 8  -> d/dx = d* = -4
# Expected fwd: [2, 4, 4, 8]; expected grad: [2, -4, 2, -4]

for device in ("cpu", "cuda:0"):
    out_p, grad_p = run(k_predicate, c_np, x_np, device)
    out_c, grad_c = run(k_continue, c_np, x_np, device)
    print(f"--- {device} ---")
    print(f"predicate fwd: {out_p}  grad: {grad_p}")
    print(f"continue  fwd: {out_c}  grad: {grad_c}")

Observed behavior

Warp 1.15.0.dev0, CUDA Toolkit 12.8, NVIDIA L40 (sm_89). Same failure on CPU and CUDA:

--- cpu ---
predicate fwd: [2. 4. 4. 8.]  grad: [ 2. -4.  2. -4.]   # correct
continue  fwd: [2. 4. 4. 8.]  grad: [-4. -4. -4. -4.]   # WRONG

--- cuda:0 ---
predicate fwd: [2. 4. 4. 8.]  grad: [ 2. -4.  2. -4.]   # correct
continue  fwd: [2. 4. 4. 8.]  grad: [-4. -4. -4. -4.]   # WRONG

Forward outputs are bit-identical between the two kernels and match the analytical reference. The predicate form's gradient is correct on both devices. The continue form's gradient is the constant value d* = -4 for every thread — exactly the d at the last nonzero cell visited in the forward pass (c[1,1] * ((1+1)+(1+1)) = -4).

Hypothesis

In the predicate form both loops fully unroll, so the body is straight-line SSA: every iteration has its own if (v > max_val) { max_val = v; } ... wp::where(cond, ..., max_val) chain, and the adjoint walks straight back through it.

In the continue form contains_break (warp/_src/codegen.py:2898) refuses to unroll the inner loop. The body is emitted once and runs via goto start_for_/end_for_, with materialize_redefinitions emitting wp::assign(var1, var2) writebacks at the loop boundary and at the continue site (warp/_src/codegen.py:2964). The reverse pass replays via wp::iter_reverse(iter) plus body_replay/body_reverse (warp/_src/codegen.py:2233-2267).

The constant-across-tids gradient value equals the last nonzero iteration's d*, which suggests the reverse pass attributes adj_max_val to whatever was last written to the loop's iteration-local state at end of the forward pass — i.e. the in-place wp::assign(max_val, v) from the final accepted iteration — rather than to the per-tid argmax winner. Combined with the non-SSA writebacks, the per-tid winner is no longer recoverable on the reverse replay.

This is a starting hypothesis, not a confirmed fix point. The simpler statement is: any dynamic Warp for-loop containing both continue and an in-place max-style reduction likely produces wrong gradients today.

Workaround

Replace continue with a predicate-guarded block (e.g. if c != 0.0: wrapping the body) so the loop is fully unrolled. The output and the gradient both become correct. The code-size blowup that previously made the predicate form unattractive is addressed by GH-1497.