PR #122402

tensorflow/tensorflow · NN Ops · Merged · 3 files changed

Fixed a dynamic TypeError in tf.nn.weighted_moments when axes is passed as a constant tf.Tensor instead of a Python list, normalizing axes via tensor_util.constant_value before squeeze.

Checkout Pull Request

Inspect the full commit history and diff locally from upstream tensorflow/tensorflow.

$gh pr checkout 122402 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #122402)NN Ops / Merged
INPUT / TRIGGERNN Ops Edge CaseROOT CAUSEMissing InvariantPATCHED (3 FILES)BUILDnn_batchnorm_test.pynn_impl.pyOUTCOMEMerged

Fixed a dynamic TypeError in tf.nn.weighted_moments when axes is passed as a constant tf.Tensor instead of a Python list, normalizing axes via tensor_util.constant_value before squeeze.

File-by-File Modification Breakdown (3)

  • tensorflow/python/ops/BUILD

    Bazel build dependencies and test targets

    +1 / -0
  • tensorflow/python/ops/nn_batchnorm_test.py

    Python/XLA regression test suite verifying edge-case behavior

    +64 / -0
  • tensorflow/python/ops/nn_impl.py

    Neural network Python op implementation and axis normalization

    +16 / -2

Changed Files (3)

tensorflow/python/ops/BUILD8 lines
@@ -4372,6 +4372,7 @@ py_library(
         "//tensorflow/python/framework:constant_op",
         "//tensorflow/python/framework:dtypes",
         "//tensorflow/python/framework:ops",
+        "//tensorflow/python/framework:tensor_util",
         "//tensorflow/python/platform:device_context",
         "//tensorflow/python/util:deprecation",
         "//tensorflow/python/util:dispatch",

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.
View PR #122402 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.