Repository: tensorflow
Issue: Sparse segment mean/sum gives random result on empty tensor
Labels: stat:awaiting tensorflower,type:bug,comp:ops,TF 2.12

### Issue type

Bug

### Have you reproduced the bug with TensorFlow Nightly?

Yes

### Source

binary

### TensorFlow version

2.12.1

### Custom code

No

### OS platform and distribution

Linux GPU

### 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?

When inputs to `math_ops.sparse_segment_mean` or `math_ops.sparse_segment_sum` are empty. The gradient of the OP is not 0, but some random values from previous tensors. The gradient should be zero when inputs are empty

### Standalone code to reproduce the issue

```shell
import tensorflow as tf
from tensorflow.python.client import timeline
from tensorflow.python.ops import math_ops

tf.compat.v1.disable_eager_execution()


def construct_model():
  embed_dim = 128
  cache_size = 2**18 + 1
  with tf.device("/GPU:0"):
    params = tf.compat.v1.Variable(
        shape=(cache_size, embed_dim),
        dtype=tf.float32,
        initial_value=tf.ones(shape=(cache_size, embed_dim), dtype=tf.float32))

  ids = tf.constant([], dtype=tf.int32)
  segment_ids = tf.constant([], dtype=tf.int32)

  embed_pooling = math_ops.sparse_segment_sum(
      params,
      ids,
      segment_ids,
      num_segments=8192,
      name="sss",
  )

  #print(embed_pooling)
  loss = tf.reduce_sum(embed_pooling)
  trainable_vars = tf.compat.v1.trainable_variables()
  grads = tf.gradients(loss, trainable_vars)
  grads_and_vars = [(g, v) for g, v in zip(grads, trainable_vars)]

  sanity_check_ops = [
      #tf.print(grads[0]),
      tf.debugging.check_numerics(grads[0], message=""),
      tf.debugging.assert_equal(tf.reduce_sum(grads[0]), tf.constant(0.)),
      #CRITICAL step to reproduce
      tf.random.uniform((81920, 1280), 100, 101)
  ]
  adam_opt = tf.compat.v1.train.AdamOptimizer(
      learning_rate=0.001, beta1=0.8, beta2=0.88)
  with tf.control_dependencies(sanity_check_ops):

    step = adam_opt.apply_gradients(grads_and_vars)

  return step


tf.config.threading.set_inter_op_parallelism_threads(32)
tf.config.threading.set_intra_op_parallelism_threads(32)
run_op = construct_model()

profile_options = tf.compat.v1.RunOptions(
    trace_level=tf.compat.v1.RunOptions.FULL_TRACE)
run_metadata = tf.compat.v1.RunMetadata()

with tf.compat.v1.Session() as sess:
  sess.run(tf.compat.v1.global_variables_initializer())
  print(sess._config)

  for i in range(10):
    sess.run(run_op, run_metadata=run_metadata)
```


### Relevant log output

```shell
2024-07-30 14:39:23.458752: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-07-30 14:39:23.505787: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: SSE3 SSE4.1 SSE4.2 AVX AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2024-07-30 14:39:25.698665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1635] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 79078 MB memory:  -> device: 0, name: NVIDIA A100 80GB PCIe, pci bus id: 0000:e1:00.0, compute capability: 8.0
2024-07-30 14:39:25.701973: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:353] MLIR V1 optimization pass is not enabled
2024-07-30 14:39:27.165519: I tensorflow/core/common_runtime/executor.cc:1197] [/job:localhost/replica:0/task:0/device:GPU:0] (DEBUG INFO) Executor start aborting (this does not indicate an error and you can ignore this message): INVALID_ARGUMENT: assertion failed: [Condition x == y did not hold element-wise:] [x (Sum_1:0) = ] [16775995] [y (Const_4:0) = ] [0]
	 [[{{function_node assert_equal_1_Assert_AssertGuard_false_41}}{{node Assert}}]]
device_count {
  key: "CPU"
  value: 1
}
device_count {
  key: "GPU"
  value: 1
}
intra_op_parallelism_threads: 32
inter_op_parallelism_threads: 32
gpu_options {
  visible_device_list: "0"
  experimental {
  }
}
experimental {
}

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1378, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1361, in _run_fn
    return self._call_tf_sessionrun(options, feed_dict, fetch_list,
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1454, in _call_tf_sessionrun
    return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict,
tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [Condition x == y did not hold element-wise:] [x (Sum_1:0) = ] [16775995] [y (Const_4:0) = ] [0]
	 [[{{function_node assert_equal_1_Assert_AssertGuard_false_41}}{{node Assert}}]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/tmp/t.py", line 65, in <module>
    sess.run(run_op, run_metadata=run_metadata)
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 968, in run
    result = self._run(None, fetches, feed_dict, options_ptr,
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1191, in _run
    results = self._do_run(handle, final_targets, final_fetches,
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1371, in _do_run
    return self._do_call(_run_fn, feeds, fetches, targets, options,
  File "/usr/local/lib/python3.10/dist-packages/tensorflow/python/client/session.py", line 1397, in _do_call
    raise type(e)(node_def, op, message)  # pylint: disable=no-value-for-parameter
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

assertion failed: [Condition x == y did not hold element-wise:] [x (Sum_1:0) = ] [16775995] [y (Const_4:0) = ] [0]
	 [[{{node Assert}}]]
```