warp icon indicating copy to clipboard operation
warp copied to clipboard

Incorrect `if`/`else` result when a branch modifies its condition

Open shi-eric opened this issue 1 month ago • 1 comments

When an if condition uses an array element, changing that element inside the branch gives the wrong result.

import warp as wp


@wp.kernel
def repro(flags: wp.array[wp.bool], out: wp.array[int]):
    i = wp.tid()
    if flags[i]:
        flags[i] = False
        value = 11
    else:
        value = 22
    out[i] = value


flags = wp.array([True, False], dtype=wp.bool)
out = wp.empty(2, dtype=int)
wp.launch(repro, dim=2, inputs=[flags], outputs=[out])
print(out.numpy().tolist())

Expected: [11, 22]

Actual: [22, 22]

The first flag starts as True, so the first result should be 11. Setting the flag to False inside that branch should not change which result is selected.

Reproduced with Warp 1.17.0 and 1.18.0 on CPU and CUDA, using Linux and Python 3.12.

shi-eric avatar Oct 24 '26 20:10 shi-eric

@shi-eric I have a fix for this and tested it on CPU and a T4. Would a pull request be welcome, or would you rather keep it?

The cause is that a reference guard such as flags[i] is loaded again after the if body runs: for the else guard (begin_else emits if (!flags[i])), for the merges, and for the reverse guards. When the if body writes that element, those reloads see the new value and the kernel takes the other branch's results.

The fix loads a reference guard once, before either branch, in emit_If (and in emit_IfExp), so the forward branches, the merges and the reverse pass all use that one value; begin_else then always emits a plain else. It adds test_reference_condition_mutated_in_branch to test_conditional.py (your example, the mirror case where the else branch sets the flag, and an if-expression) and a changelog entry.

Results on Warp main (ea7b748), built from source, CPU and Tesla T4:

main with the fix
your example [22, 22] on CPU and CUDA [11, 22] on CPU and CUDA
else branch sets the flag [11, 11] on CPU and CUDA [11, 22] on CPU and CUDA
test_conditional.py 93 passed 96 passed
test_codegen*.py 424 passed
test_grad*.py 167 passed

Run log: https://www.kaggle.com/code/obsidian93/notebooke5518a3e7b

Shakhtar-Sankur avatar Nov 05 '26 00:11 Shakhtar-Sankur