BUGFix: Wrap roll as OpFromGraph with custom JAX dispatch to jnp.roll
Description
pt.roll is currently implemented as a pure macro that decomposes into
two Subtensor slice operations and a Join. When shift is a symbolic
scalar, the slice boundaries become dynamic JAX tracers at compile time,
causing JIT compilation to fail:
IndexError: Slice entries must be static integers. Got slice(None, JitTracer(int32[]), None) at position 0 Apply node: Join(0, Subtensor{start:}.0, Subtensor{:stop}.0)
This is a fundamental incompatibility between PyTensor's macro-based roll
expansion and JAX's strict static indexing requirements under jax.jit.
Fix:
Introduced Roll(OpFromGraph) — a thin wrapper that encapsulates the
existing roll graph while exposing a registration point for backend-specific
dispatch. All existing backends (C, Python) continue to execute the original
graph transparently via OpFromGraph inlining, preserving full correctness
and gradient flow through the existing graph structure.
For the JAX backend, a dedicated jax_funcify dispatch is registered that
maps Roll directly to jnp.roll, which internally uses lax.dynamic_slice
and handles symbolic shift values correctly under JIT.
This approach follows the established pattern used by Pad, AllocDiag,
and KroneckerProduct in the codebase — minimizing Op count while still
enabling backend-specific lowering where necessary.
Changes:
pytensor/tensor/basic.py: IntroducedRoll(OpFromGraph)and updatedroll()to wrap its output graph in the new Oppytensor/link/jax/dispatch/subtensor.py: Registered JAX dispatch forRollmapping tojnp.rolltests/link/jax/test_tensor_basic.py: Addedtest_jax_rollcovering dynamic shift, negative shift, axis=None, and shift > axis size
Related Issue
- [x] Closes #1899
- [ ] Related to #
Checklist
- [x] Checked that the pre-commit linting/style checks pass
- [x] Included tests that prove the fix is effective or that the new feature works
- [ ] Added necessary documentation (docstrings and/or example notebooks)
- [x] If you are a pro: each commit corresponds to a relevant logical change
Type of change
- [ ] New feature / enhancement
- [x] Bug fix
- [ ] Documentation
- [ ] Maintenance
- [ ] Other (please specify):
@ricardoV94 take a look at it when u have a moment thx for your guidance yesterday
I thought we settled on just improving Subtensor dispatch for jax, since jnp.roll is basically doing the same we are?
@ricardoV94 I thoroughly investigated the Subtensor dispatch path — lax.dynamic_slice_in_dim needs static size, both roll's slice sizes are dynamic, and the size isn't recoverable from idx_list or shape inference at dispatch time. The OpFromGraph approach is the only working fix I can find. Happy to keep exploring if you have a specific direction in mind.