Fix indexedarray adjoint
Description
wp.indexedarray inputs were not differentiable: wp.Tape raised AttributeError
(no .grad), a manual adjoint launch segfaulted on CPU, and on CUDA it silently
produced zero gradients. This adds gradient support for indexed-array inputs so the
adjoint follows the gather indirection and accumulates into the base array's gradient.
right now this is only handling 1-D arrays, multi-dim is still needing to be implemented
closes #1479
Checklist
- [x] I am familiar with the Contributing Guidelines.
- [x] New or existing tests cover these changes.
- [ ] The documentation is up to date with these changes.
Test plan
uv run warp/tests/test_indexedarray.py
uv run warp/tests/test_indexedarray.py -k grad_1d
Verified gradients are correct on CPU and CUDA via both wp.Tape and a manual
adjoint launch (expected [0, 0.25, 0, 0.5, 0, 1.0]).
Bug fix
import warp as wp
import numpy as np
@wp.kernel
def weighted_sample_sum(samples: wp.indexedarray[float], weights: wp.array[float], total: wp.array[float]):
i = wp.tid()
wp.atomic_add(total, 0, samples[i] * weights[i])
base = wp.array(np.linspace(1, 6, 6, dtype=np.float32), dtype=float, requires_grad=True)
weights = wp.array([0.25, 0.5, 1.0], dtype=float)
samples = wp.indexedarray1d(base, [wp.array([1, 3, 5], dtype=wp.int32)])
total = wp.zeros(1, dtype=float, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(weighted_sample_sum, dim=samples.size, inputs=[samples, weights], outputs=[total])
tape.backward(loss=total)
print(base.grad.numpy()) # without this PR: AttributeError / zeros / segfault
Summary by CodeRabbit
-
New Features
- Improved gradient support for indexed arrays in automatic differentiation; gradients now properly propagate through indexed array operations.
-
Tests
- Added tests validating gradient computation through indexed array inputs.
This pull request requires additional validation before any workflows can run on NVIDIA's runners.
Pull request vetters can view their responsibilities here.
Contributors can view more details about this message here.
📝 Walkthrough
Walkthrough
This PR fixes adjoint gradient computation through indexedarray inputs by adding gradient view support to indexed arrays, implementing index-remapping adjoint address resolution in the native layer, updating kernel argument validation in adjoint mode, and adding comprehensive gradient propagation tests.
Changes
Indexedarray Adjoint Gradients
| Layer / File(s) | Summary |
|---|---|
Indexedarray gradient view support warp/_src/types.py |
indexedarray class gains a grad property that returns an indexed view into self.data.grad using the same indices (up to self.ndim), or None if the base data or its gradient is missing. |
Adjoint address resolution for indexed arrays warp/native/array.h |
Two adj_address template overloads added for indexedarray_t<T> that resolve first-dimension index indirection via buf.indices[0] (handling negative indices), then route gradient accumulation to either an indexed adjoint buffer or the base array's embedded gradient. |
Adjoint mode array validation warp/_src/context.py |
pack_arg() adjoint-mode validation relaxed to accept both isinstance(value, warp.array) and values whose concrete type exactly matches concrete_array_type(arg_type), enabling indexed gradient views to pass kernel argument checks. |
Gradient propagation test warp/tests/test_indexedarray.py |
New kernel kernel_indexedarray_grad_1d and test test_indexedarray_grad_1d verify that gradients correctly propagate through gather-weighted reduction via indexedarray1d, with validation that backward pass accumulates gradients into the base array at gathered indices. |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title clearly summarizes the main change: implementing gradient/adjoint support for indexedarray, which is the primary objective of the PR. |
| Linked Issues check | ✅ Passed | The PR fully implements the coding requirements from issue #1479: relaxed adjoint mode validation, added grad property to indexedarray, implemented adjoint address resolution for indexedarray, and provided tests validating correct gradient propagation. |
| Out of Scope Changes check | ✅ Passed | All changes are directly scoped to fixing indexedarray adjoint behavior: validation relaxation, grad property implementation, adjoint address overloads, and corresponding tests. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
Comment @coderabbitai help to get the list of available commands and usage tips.
Greptile Summary
This PR fixes a long-standing bug (GH-1479) where wp.indexedarray inputs were not differentiable: wp.Tape raised AttributeError (no .grad), manual adjoint launches segfaulted on CPU, and CUDA silently produced zero gradients. The fix adds a grad property to indexedarray that returns an indexed view over the base array's gradient, updates pack_arg to accept either a plain warp.array or an indexedarray as an adjoint argument, and adds two new C++ adj_address overloads that resolve the gather indirection before accumulating into the base gradient.
Confidence Score: 4/5
Safe to merge for 1-D indexed array differentiation; multi-dim will fail at C++ compile time rather than produce wrong gradients.
The 1-D implementation is logically consistent across Python and C++: the grad property, the pack_arg relaxation, and both adj_address overloads correctly follow gather indirection before accumulating into base.grad. The main gap is that indexedarray.grad is accessible for ndim > 1 but C++ templates are absent, so multi-dim differentiation fails at kernel compilation with an unhelpful error. Test coverage is good for the happy path but misses tape.zero() and negative-index scenarios.
warp/_src/types.py — the grad property should guard against ndim > 1 to prevent opaque C++ template failures.
Important Files Changed
| Filename | Overview |
|---|---|
| warp/_src/types.py | Adds grad property to indexedarray; correct for 1D, but no guard prevents multi-dim usage that lacks C++ support. |
| warp/native/array.h | Two new adj_address overloads for indexedarray_t correctly resolve 1D gather indirection; only 1D is supported (multi-dim overloads absent by design). |
| warp/_src/context.py | Minimal, correct relaxation of adjoint type-matching to accept indexedarray alongside plain warp.array. |
| warp/tests/test_indexedarray.py | New test_indexedarray_grad_1d validates forward values and gradient at indexed positions; lacks tape.zero() verification and negative-index coverage. |
Reviews (1): Last reviewed commit: "1-D unit test as example" | Re-trigger Greptile