Runtime & Typing

tensorflow/tensorflow · Python, C API

Fixed dynamic TypeError in tf.nn.weighted_moments when axes are Tensor instances, ensured PosixPath compatibility in runtime imports, and standardized specific exception typing across tensorflow/python and tensorflow/tools.

Verify with Bazel

Run the upstream regression suite in tensorflow/tensorflow for this subsystem.

$bazel test //tensorflow/python/ops:nn_batchnorm_test

Changed Files (1)

tensorflow/python/ops/nn_batchnorm_test.py11 lines
# PR #122402 — Normalize constant tf.Tensor axes in tf.nn.weighted_moments
def testTensorAxesKeepdimsFalse(self):
  x = constant_op.constant(
      [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=dtypes.float32)
  w = constant_op.constant(
      [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=dtypes.float32)

  # axes as a tf.Tensor — previously raised TypeError in squeeze_eager_fallback
  axes_tensor = constant_op.constant([1], dtype=dtypes.int32)
  mean, var = nn_impl.weighted_moments(x, axes_tensor, w, keep_dims=False)
  self.assertAllClose(mean, [2.0, 5.0])

1. Introduction & Motivation

In TensorFlow's neural network normalization ops, tf.nn.weighted_moments reduces across user-specified axes. When keep_dims=False, the implementation calls array_ops.squeeze(x, axis=axes). In eager mode, squeeze_eager_fallback strictly requires axis to be a Python list or tuple, causing a dynamic TypeError whenever axes was passed as a tf.Tensor.

2. Mathematical & Shape Flow

weighted_moments computes the weighted mean and variance over axes:

μw=∑i∈axeswixi∑i∈axeswi,σw2=∑i∈axeswi(xi−μw)2∑i∈axeswi(1)\mu_w = \frac{\sum_{i \in \text{axes}} w_i x_i}{\sum_{i \in \text{axes}} w_i}, \qquad \sigma_w^2 = \frac{\sum_{i \in \text{axes}} w_i (x_i - \mu_w)^2}{\sum_{i \in \text{axes}} w_i} \tag{1}
# In tensorflow/python/ops/nn_impl.py:
const_axes = tensor_util.constant_value(axes)
if const_axes is not None:
  axes = np.asarray(const_axes).tolist()

3. Verification & References

Added testTensorAxesKeepdimsFalse in nn_batchnorm_test.py (regression test for GitHub issue #101580).

  1. Ioffe & Szegedy, Batch Normalization: Accelerating Deep Network Training, ICML 2015.
Read technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.