Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion keras/src/backend/tensorflow/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2403,7 +2403,9 @@ def take(x, indices, axis=None):

def fix_negative_indices(i):
# Correct the indices using "fill" mode which is the same as in jax
return tf.where(i < 0, i + tf.cast(tf.shape(x)[axis], i.dtype), i)
return tf.where(
i < 0, tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype), i
)
Comment on lines +2406 to +2408
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While this fix is correct, the implementation is a bit dense. Refactoring it to use an intermediate variable for the corrected indices would make the code more readable and easier to maintain. This also provides a good place to add a comment explaining why this explicit cast is necessary, which is helpful for future contributors.

Suggested change
return tf.where(
i < 0, tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype), i
)
positive_i = tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype)
# Explicitly cast back to original dtype to fix TF casting issue for int64.
return tf.where(i < 0, positive_i, i)


if isinstance(indices, tf.SparseTensor):
if x.dtype not in (tf.float16, tf.float32, tf.float64, tf.bfloat16):
Expand Down
13 changes: 13 additions & 0 deletions keras/src/ops/numpy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3265,6 +3265,19 @@ def test_take(self):
knp.take(x, indices, axis=2), np.take(x, indices, axis=2)
)

# Test with a Keras int64 Variable which causes weird casting behavior
# in TF.
x = rng.standard_normal((2, 3, 4, 5))
indices = keras.Variable(
initializer="ones",
shape=(3,),
dtype="int64",
trainable=False,
)
self.assertAllClose(
knp.take(x, indices, axis=2), np.take(x, indices, axis=2)
)

@parameterized.named_parameters(
named_product(
[
Expand Down
Loading