Repository navigation
Description
Issue type
Bug
Have you reproduced the bug with TensorFlow Nightly?
Yes
Source
binary
TensorFlow version
tf-nightly 2.23.0.dev20261028
Custom code
Yes
OS platform and distribution
macOS 15.7.2 (arm64)
Python version
3.11.7
Current behavior?
tf.roll with a negative axis gives wrong results under tf.vectorized_map, and under tf.GradientTape.jacobian and batch_jacobian, which use the same vectorization by default. No error is raised.
The cause is in the Roll converter in tensorflow/python/ops/parallel_for/pfor.py:
axis = pfor_input.unstacked_input(2)
if not shift_stacked:
return wrap(manip_ops.roll(t, shift, axis + 1), True)pfor adds a loop dimension at the front, so non-negative axes must move up by one. Negative axes count from the end and must stay as they are, but axis + 1 turns -1 into 0, which is the loop dimension. So tf.roll(x, 1, axis=-1) rotates whole elements of the batch instead of rolling inside each one: values from one batch element end up in another. Other negative axes are shifted one dimension too.
The gradient of Roll is a Roll along the same axis, so any jacobian or batch_jacobian of a computation that uses tf.roll(..., axis=-1) is wrong as well, even though the forward pass is correct.
When the shift is loop variant, the converter takes a separate path that computes axis_segment_ids from axis. A negative axis gives the wrong ids there too.
The other converters guard against this (for example if axis >= 0: axis += 1), and tf.roll is the only one of about 350 ops I compared where vectorized_map returned different values from a per-element loop, apart from tf.strings.format output.
Expected: vectorized_map(f, X) equals tf.stack([f(x) for x in X]), and jacobian with experimental_use_pfor=True equals experimental_use_pfor=False.
Standalone code to reproduce the issue
import tensorflow as tf
X = tf.constant([[1., 2., 3.], [4., 5., 6.]])
print("loop:", tf.stack([tf.roll(x, 1, -1) for x in X]).numpy().tolist())
print("vmap:", tf.vectorized_map(lambda x: tf.roll(x, 1, -1), X).numpy().tolist())
x = tf.constant([1., 2., 3.])
w = tf.constant([1., 10., 100.])
for use_pfor in (False, True):
with tf.GradientTape(persistent=not use_pfor) as tape:
tape.watch(x)
y = tf.roll(x, 1, -1) * w
print(f"jacobian use_pfor={use_pfor}:",
tape.jacobian(y, x, experimental_use_pfor=use_pfor).numpy().tolist())Relevant log output
loop: [[3.0, 1.0, 2.0], [6.0, 4.0, 5.0]]
vmap: [[4.0, 5.0, 6.0], [1.0, 2.0, 3.0]]
jacobian use_pfor=False: [[0.0, 0.0, 1.0], [10.0, 0.0, 0.0], [0.0, 100.0, 0.0]]
jacobian use_pfor=True: [[0.0, 10.0, 0.0], [0.0, 0.0, 100.0], [1.0, 0.0, 0.0]]I have a fix ready and will open a PR that links here.
Activity
google-ml-butler commentedon Nov 3, 2026
Are you satisfied with the resolution of your issue?
Yes
No