#1552·warp

在动态 for 循环中使用连续的附加函数会为 argmax 风格的减少产生错误的梯度

作者: daedalus5创建于 2026年6月12日更新于 2026年9月29日
标签bugautodiff
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}")