Skip to content

tf.gather returns a value for an out-of-bounds index under tf.function(jit_compile=True) while eager rejects it #115254

@rookieLiu2018

Description

@rookieLiu2018

Issue type

Bug

Have you reproduced the bug with TensorFlow Nightly?

Yes

Source

source

TensorFlow version

tf 2.21

Custom code

Yes

OS platform and distribution

No response

Mobile device

No response

Python version

No response

Bazel version

No response

GCC/compiler version

No response

CUDA/cuDNN version

No response

GPU model and memory

No response

Current behavior?

tf.gather rejects an out-of-bounds index in eager mode, but under tf.function(jit_compile=True) it returns a value instead.

According to the TensorFlow docs, out-of-bounds behavior for tf.gather is device-dependent. On CPU, an error should be raised.

In my case, the compiled path returned [10, 30] for params=[10, 20, 30] and indices=[0, 7], so the out-of-bounds index produced 30 instead of raising an error or returning 0.

Standalone code to reproduce the issue

import tensorflow as tf

@tf.function(jit_compile=True)
def compiled(params, indices):
    return tf.gather(params, indices)

params = tf.constant([10, 20, 30], dtype=tf.int32)
indices = tf.constant([0, 7], dtype=tf.int32)

try:
    eager_out = tf.gather(params, indices).numpy()
    print("eager:", eager_out)
except Exception as e:
    print("eager error:", e)

try:
    compiled_out = compiled(params, indices).numpy()
    print("compiled:", compiled_out)
except Exception as e:
    print("compiled error:", e)

Relevant log output

eager error: {{function_node __wrapped__GatherV2_device_/job:localhost/replica:0/task:0/device:CPU:0}} indices[1] = 7 is not in [0, 3) [Op:GatherV2] name: 
compiled: [10 30]

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions