warp icon indicating copy to clipboard operation
warp copied to clipboard

`wp.rand*` only partially have Pass-by-reference semantics for its `state` parameter.

Open YouJiacheng opened this issue 1 month ago • 3 comments

Bug Description

All calls to Warp random functions accept a uint32 RNG state, which is internally updated when the function is called. Hence, consecutive calls to the same random function will generate different numbers

BUT: wp.randu(state) will advance state inplace, but wp.randu(state_array[tid]) won't advance state_array[tid] inplace.

import sys
import warp as wp


@wp.kernel
def draw(state: wp.array(dtype=wp.uint32), out: wp.array(dtype=wp.uint32)):
    out[0] = wp.randu(state[0])
    out[1] = wp.randu(state[0])


device = sys.argv[1] if len(sys.argv) > 1 else "cpu"
initial = wp.rand_init(42)
state = wp.array([initial], dtype=wp.uint32, device=device)
out = wp.empty(2, dtype=wp.uint32, device=device)
wp.launch(draw, dim=1, inputs=[state, out], device=device)
print(f"Warp {wp.__version__}, device={device}")
print("initial:", initial)
print("draws:", out.numpy().tolist())
print("state:", state.numpy().tolist())

will print

initial: 1223963391
draws: [2785308739, 2785308739]
state: [1223963391]

While wp.rand* are not user functions, their semantics should be aligned with user functions.

With wp.ref[T], increment(values[i]) works as expected.

Image

System Information

Warp 1.18

YouJiacheng avatar Oct 07 '26 03:10 YouJiacheng

I can reproduce this with Warp 1.18.0 on CPU and on an RTX 5060 Ti (cuda:0), with the script above: both draws are 2785308739 and state stays 1223963391.

The cause seems to be in Adjoint.add_call (warp/_src/codegen.py): reference parameters are only handled for user functions,

parameter_types = func.input_types if not func.is_builtin() else {}

so for a builtin, state[0] is loaded into a temporary and the native randu(uint32& state) advances that temporary. A local state variable works because it is passed directly.

This affects every builtin in warp/native/rand.h that takes uint32& state: randi, randu, randf, randn, poisson, sample_cdf, sample_triangle and the sample_unit_* functions.

One way to fix it would be to let these builtins declare state as a reference parameter and reuse the wp.ref[T] path (emit_addressable_reference) for builtins in add_call, so state[i] is passed by address, while Python-scope calls keep passing by value as documented.

I didn't hit this in my own Warp code; I came across the report and looked into the cause. Would an outside PR along these lines be welcome? I can test it on CPU and on the RTX card.

usmanmateen avatar Oct 09 '26 08:10 usmanmateen

Reproduced on 1.19.0.dev1 (CPU). The generated C++ makes the cause fairly clear, and it's two things compounding.

1. Nothing connects the C++ reference signature to codegen. warp/_src/builtins.py declares

input_types={"state": uint32}

but warp/native/rand.h declares

inline CUDA_CALLABLE uint32 randu(uint32& state)

2. The reference-aware path is gated off for builtins. codegen.py:

parameter_types = func.input_types if not func.is_builtin() else {}
...
parameter_is_ref = is_reference(parameter_type)

For every builtin that is unconditionally false, so the argument falls through to adj.load(func_arg).

Net effect. state as a plain kernel scalar emits:

var_0 = wp::randu(var_state);   // reuses the local, so the mutation persists

whereas state_array[tid] emits:

var_1 = wp::address(var_state, var_0);
var_3 = wp::load(var_1);        // temporary
var_2 = wp::randu(var_3);       // mutates the temporary

A second call allocates var_8 rather than reusing var_3, so both draws return the same value and the array element is never written back — matching the [2785308739, 2785308739] you reported.


I'm asking rather than sending a patch because the fix isn't self-contained. emit_addressable_reference already handles array elements (it has a branch for a traced lvalue origin from a direct ast.Subscript), so the reference machinery itself exists. But routing builtins through it collides with a deliberate guard:

Cannot call 'array_store' with wp.ref[T] parameters from a backward-enabled kernel

References and reverse-mode autodiff don't compose in Warp by design — ModuleBuilder rejects ref-param calls from backward-enabled kernels unless the callee declares a manual ref adjoint. So this needs one of:

  • the random builtins exempted from that guard on the grounds that a non-differentiable builtin (is_differentiable=False) needs no ref adjoint, or
  • an explicit manual ref adjoint declaration on the random family, or
  • wp.ref / a local copy being the intended answer, with the docs corrected instead.

Questions for maintainers:

  1. Should non-differentiable builtins be exempt from the ref-adjoint guard?
  2. If a reference_inputs opt-in on add_builtin is acceptable, is that the shape you'd want? It can't ride in input_types as-is: Reference(T) is an instance rather than a type, and Function.mangle() reads t.__name__, so it raises AttributeError.

Happy to implement whichever direction you prefer.

deepspace28 avatar Oct 12 '26 05:10 deepspace28

Thanks @deepspace28, that's a good point about the ref-adjoint guard. I looked at where it's enforced. In add_call, a call is only recorded in unvalidated_ref_calls inside the if func.is_differentiable and ... block, and the random builtins are registered with is_differentiable=False. So they never reach that check, and a backward-enabled kernel compiles fine with them.

I prototyped this on top of main: https://github.com/usmanmateen/warp/tree/usmanmateen/rand-state-array-reference

  • add_builtin gets a reference_inputs option. The rand.h builtins that take uint32& state (randi, randu, randf, randn, poisson, sample_cdf, sample_triangle, sample_unit_*, 18 overloads) declare reference_inputs=("state",).
  • In add_call, when such an input is an array element or struct field, the forward pass passes it by address via emit_addressable_reference. Local variables, kernel parameters and expressions keep the current path, so nothing that works today changes.
  • The replay in the backward pass passes a copy, so tape.backward() doesn't advance the stored state a second time.

Results on CPU and an RTX 5060 Ti (cuda:0):

  • The script from the issue now prints draws [2785308739, 4004461565] and state [4004461565].
  • For states[i], all 18 overloads give the same draws and final state as copying into a local, drawing and writing back. states[i, j] and states[i].state advance as well (checked with randf).
  • With wp.Tape, the state array is unchanged by tape.backward(). The forward values, the gradients and the final state are identical to the copy-and-write-back pattern.
  • The new test_rand_state_in_array and test_rand_state_in_array_backward fail on main and pass with the change. test_rand, test_noise, test_ref, test_lvalue, test_codegen, test_func, test_func_parameter_targets, test_grad, test_grad_customs and test_struct pass (528 tests).

One behavior to be aware of, which already applies to the copy-and-write-back pattern: the replay in the backward pass draws from the advanced state, so a gradient through a random draw uses a different sample than the forward pass did. Deriving the state per launch, e.g. with wp.rand_init(seed, tid), avoids that, and it might be worth a note in the docs.

I'm happy to open this as a PR if the direction works for you, or to adjust it. For example, reference_inputs could become a different opt-in, or the fix could stay docs-only instead.

usmanmateen avatar Oct 12 '26 11:10 usmanmateen