CVE-2021-41206: Improper Validation of Integrity Check Value (CWE-354)
value: TensorFlow is an open source platform for machine learning. In affected versions several TensorFlow operations are missing validation for the shapes of the tensor arguments involved in the call. Depending on the API, this can result in undefined behavior and segfault or `CHECK`-fail related crashes but in some scenarios writes and reads from heap populated arrays are also possible. We have discovered these issues internally via tooling while working on improving/testing GPU op determinism. As such, we don't have reproducers and there will be multiple fixes for these issues. These fixes will be included in TensorFlow 2.7.0. We will also cherrypick these commits on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
CWE description: The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
CVSS v3 base score: 7.8
Published: 2021-11-05T22:15Z
Repository: https://github.com/tensorflow/tensorflow
Language: C++
Files changed: tensorflow/core/kernels/maxpooling_op.cc, tensorflow/core/kernels/pooling_ops_3d.cc, tensorflow/core/kernels/pooling_ops_common.cc, tensorflow/core/kernels/pooling_ops_common.h, tensorflow/python/kernel_tests/pooling_ops_3d_test.py, tensorflow/python/kernel_tests/pooling_ops_test.py
Commit date: 2021-10-08 20:30:17 -0700
Commit message: Roll forward https://github.com/tensorflow/tensorflow/commit/ab0ca4bbc66a476aea305f81c69e0201b5876d0a. The internal test that it broke has been fixed.

PiperOrigin-RevId: 401913101
Change-Id: I67f095899187e38101fbb10289c5e444b0a9e8c0

Diff: diff --git a/tensorflow/core/kernels/maxpooling_op.cc b/tensorflow/core/kernels/maxpooling_op.cc
index ce89b025ec558..9edd5cf6a6d52 100644
--- a/tensorflow/core/kernels/maxpooling_op.cc
+++ b/tensorflow/core/kernels/maxpooling_op.cc
@@ -323,10 +323,18 @@ class MaxPoolingGradOp : public OpKernel {
                           FORMAT_NHWC,
                           tensor_in.shape()};
     if (!context->status().ok()) {
       return;
     }
+    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected orig_output shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", tensor_out.shape()));
+    OP_REQUIRES(context, out_backprop.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected grad shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", out_backprop.shape()));
 
     Tensor* output = nullptr;
     OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
                                 {0}, 0, output_shape, &output));
 
@@ -536,10 +544,22 @@ class MaxPoolingGradGradOp : public OpKernel {
                           stride,
                           padding_,
                           /*explicit_paddings=*/{},
                           FORMAT_NHWC,
                           tensor_in.shape()};
+    if (!context->status().ok()) {
+      return;
+    }
+    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected orig_output shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", tensor_out.shape()));
+    OP_REQUIRES(
+        context, out_grad_backprop.shape() == tensor_in.shape(),
+        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
+                                ", but got ", out_grad_backprop.shape()));
+
     Tensor* output = nullptr;
     OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
                                 {2}, 0, tensor_out.shape(), &output));
 
     SpatialMaxPoolGradGrad(context, output, tensor_in, tensor_out,
@@ -740,10 +760,21 @@ class MaxPoolingGradGradOp<Eigen::GpuDevice, T> : public OpKernel {
                           stride,
                           padding_,
                           /*explicit_paddings=*/{},
                           data_format_,
                           tensor_in.shape()};
+    if (!context->status().ok()) {
+      return;
+    }
+    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected orig_output shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", tensor_out.shape()));
+    OP_REQUIRES(
+        context, out_grad_backprop.shape() == tensor_in.shape(),
+        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
+                                ", but got ", out_grad_backprop.shape()));
 
     functor::MaxPoolGradBackwardNoMask<T>()(
         data_format_, tensor_in.flat<T>().data(), tensor_out.flat<T>().data(),
         params.tensor_in_batch, params.out_height, params.out_width,
         params.depth, params.tensor_in_rows, params.tensor_in_cols,
@@ -1094,10 +1125,18 @@ class MaxPoolingGradWithArgmaxOp : public OpKernel {
                           FORMAT_NHWC,
                           tensor_in.shape()};
     if (!context->status().ok()) {
       return;
     }
+    OP_REQUIRES(context, grad_in.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected grad shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", grad_in.shape()));
+    OP_REQUIRES(context, argmax.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected argmax shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", argmax.shape()));
 
     TensorShape out_shape({params.tensor_in_batch, params.tensor_in_rows,
                            params.tensor_in_cols, params.depth});
     Tensor* grad_out = nullptr;
     OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
@@ -1154,10 +1193,18 @@ class MaxPoolingGradGradWithArgmaxOp : public OpKernel {
                           FORMAT_NHWC,
                           tensor_in.shape()};
     if (!context->status().ok()) {
       return;
     }
+    OP_REQUIRES(
+        context, grad_in.shape() == tensor_in.shape(),
+        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
+                                ", but got ", grad_in.shape()));
+    OP_REQUIRES(context, argmax.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected argmax shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", argmax.shape()));
 
     TensorShape out_shape({params.tensor_in_batch, params.out_height,
                            params.out_width, params.depth});
 
     Tensor* grad_out = nullptr;
diff --git a/tensorflow/core/kernels/pooling_ops_3d.cc b/tensorflow/core/kernels/pooling_ops_3d.cc
index d4dc87c7e3f86..d4444b677a950 100644
--- a/tensorflow/core/kernels/pooling_ops_3d.cc
+++ b/tensorflow/core/kernels/pooling_ops_3d.cc
@@ -364,10 +364,23 @@ class MaxPooling3dGradOp : public OpKernel {
                                    GetTensorDim(stride_, data_format_, '0')}};
     std::array<int64_t, 3> out, padding;
 
     OP_REQUIRES_OK(context, Get3dOutputSize(input_size, window, stride,
                                             padding_, &out, &padding));
+
+    const int64_t depth = GetTensorDim(tensor_in, data_format_, 'C');
+    const int64_t in_batch = GetTensorDim(tensor_in, data_format_, 'N');
+    TensorShape out_shape = ShapeFromFormat(data_format_, in_batch,
+                                            {{out[2], out[1], out[0]}}, depth);
+    OP_REQUIRES(
+        context, tensor_out.shape() == out_shape,
+        errors::InvalidArgument("Expected orig_output shape to be ", out_shape,
+                                ", but got ", tensor_out.shape()));
+    OP_REQUIRES(context, out_backprop.shape() == out_shape,
+                errors::InvalidArgument("Expected grad shape to be ", out_shape,
+                                        ", but got ", out_backprop.shape()));
+
     LaunchMaxPooling3dGradOp<Device, T>::launch(
         context, tensor_in, tensor_out, out_backprop, window, stride, out,
         padding, data_format_, input_backprop);
   }
 
@@ -710,10 +723,18 @@ class MaxPooling3dGradGradOp : public OpKernel {
         errors::InvalidArgument("out_grad_backprop must be 5-dimensional"));
 
     Pool3dParameters params{context,  ksize_,       stride_,
                             padding_, data_format_, tensor_in.shape()};
     if (!context->status().ok()) return;  // params is invalid
+    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected orig_output shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", tensor_out.shape()));
+    OP_REQUIRES(
+        context, out_grad_backprop.shape() == tensor_in.shape(),
+        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
+                                ", but got ", out_grad_backprop.shape()));
 
     Tensor* output = nullptr;
     OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
                                 {2}, 0, tensor_out.shape(), &output));
 
diff --git a/tensorflow/core/kernels/pooling_ops_common.cc b/tensorflow/core/kernels/pooling_ops_common.cc
index 817072cc7617d..d621e77790c62 100644
--- a/tensorflow/core/kernels/pooling_ops_common.cc
+++ b/tensorflow/core/kernels/pooling_ops_common.cc
@@ -463,10 +463,20 @@ void DnnPoolingGradOp<T>::Compute(
   PoolParameters params{context,           size,        stride,         padding,
                         explicit_paddings, data_format, tensor_in_shape};
   if (!context->status().ok()) {
     return;
   }
+  if (tensor_out) {
+    OP_REQUIRES(context, tensor_out->shape() == params.forward_output_shape(),
+                errors::InvalidArgument("Expected orig_output shape to be ",
+                                        params.forward_output_shape(),
+                                        ", but got ", tensor_out->shape()));
+  }
+  OP_REQUIRES(context, out_backprop.shape() == params.forward_output_shape(),
+              errors::InvalidArgument("Expected grad shape to be ",
+                                      params.forward_output_shape(),
+                                      ", but got ", out_backprop.shape()));
 
   TensorFormat transformed_input_data_format = data_format;
 
 #if CUDNN_VERSION < 7300
   /// For now, cudnn does not support NHWC format, so we need to convert it
diff --git a/tensorflow/core/kernels/pooling_ops_common.h b/tensorflow/core/kernels/pooling_ops_common.h
index 5e6f2e46944a9..1a41a5adca5d2 100644
--- a/tensorflow/core/kernels/pooling_ops_common.h
+++ b/tensorflow/core/kernels/pooling_ops_common.h
@@ -81,15 +81,10 @@ struct PoolParameters {
   int pad_depth;
 
   TensorFormat data_format;
 };
 
-// Checks if the sizes of the paddings are less than the size of window.
-// This is required for MaxPool because it pads with -inf, so the pooling
-// window cannot fully cover the padded area.
-Status CheckPaddingSize(PoolParameters& params);
-
 // An implementation of MaxPooling (forward).
 // TODO (yongtang): Remove MaxPoolingOp and use MaxPoolingV2Op,
 //     QuantizedMaxPoolingOp depends on MaxPoolingOp so keep intact for now
 template <typename Device, typename T>
 class MaxPoolingOp : public OpKernel {
diff --git a/tensorflow/python/kernel_tests/pooling_ops_3d_test.py b/tensorflow/python/kernel_tests/pooling_ops_3d_test.py
index 203d3ad2f280f..12710c47a4a3d 100644
--- a/tensorflow/python/kernel_tests/pooling_ops_3d_test.py
+++ b/tensorflow/python/kernel_tests/pooling_ops_3d_test.py
@@ -14,13 +14,17 @@
 # ==============================================================================
 """Functional tests for 3d pooling operations."""
 
 import numpy as np
 
+from tensorflow.python.eager import context
 from tensorflow.python.framework import constant_op
 from tensorflow.python.framework import errors
+from tensorflow.python.framework import errors_impl
 from tensorflow.python.framework import test_util
+from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import gen_nn_ops
 from tensorflow.python.ops import gradient_checker
 from tensorflow.python.ops import gradients_impl
 from tensorflow.python.ops import nn_ops
 import tensorflow.python.ops.nn_grad  # pylint: disable=unused-import
 from tensorflow.python.platform import test
@@ -513,8 +517,46 @@ class PoolingTest(test.TestCase):
           input_tensor = constant_op.constant(
               input_data, shape=input_sizes, name="input")
           pool_3d = f(input_tensor, ksize=[2, 2, 0], strides=1, padding="VALID")
           self.evaluate(pool_3d)
 
+  def testMaxPoolGradEagerShapeErrors(self):
+    with context.eager_mode():
+      orig_in = array_ops.ones((1, 1, 1, 1, 1))
+
+      # Test invalid orig_out shape
+      orig_out = array_ops.ones((1, 1, 1, 1, 2))
+      grad = array_ops.ones((1, 1, 1, 1, 1))
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected orig_output shape to be \[1,1,1,1,1\], but got "
+          r"\[1,1,1,1,2\]"):
+        gen_nn_ops.max_pool3d_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
+            strides=[1, 1, 1, 1, 1], padding="VALID")
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected orig_output shape to be \[1,1,1,1,1\], but got "
+          r"\[1,1,1,1,2\]"):
+        gen_nn_ops.max_pool3d_grad_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
+            strides=[1, 1, 1, 1, 1], padding="VALID")
+
+      # Test invalid grad shape
+      orig_out = array_ops.ones((1, 1, 1, 1, 1))
+      grad = array_ops.ones((1, 1, 1, 1, 2))
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected grad shape to be \[1,1,1,1,1\], but got \[1,1,1,1,2\]"):
+        gen_nn_ops.max_pool3d_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
+            strides=[1, 1, 1, 1, 1], padding="VALID")
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected grad shape to be \[1,1,1,1,1\], but got \[1,1,1,1,2\]"):
+        gen_nn_ops.max_pool3d_grad_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
+            strides=[1, 1, 1, 1, 1], padding="VALID")
+
 
 if __name__ == "__main__":
   test.main()
diff --git a/tensorflow/python/kernel_tests/pooling_ops_test.py b/tensorflow/python/kernel_tests/pooling_ops_test.py
index 6f1b5ede1f3ad..79adfff643fd9 100644
--- a/tensorflow/python/kernel_tests/pooling_ops_test.py
+++ b/tensorflow/python/kernel_tests/pooling_ops_test.py
@@ -616,10 +616,11 @@ class PoolingTest(test.TestCase, parameterized.TestCase):
         expected=expected_output,
         **kwargs)
 
   @parameterized.parameters(
       GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))
+  @test_util.xla_allow_fallback("XLA doesn't support explicit padding")
   @test_util.run_deprecated_v1
   def testMaxPoolNegativeInputExpPaddingAdv(self, **kwargs):
     expected_output = [-1, -1, -3, -5, -7, -7, -9, -11, -19, -19, -21, -23, -31,
                        -31, -33, -35]
 
@@ -2388,10 +2389,86 @@ class PoolingTest(test.TestCase, parameterized.TestCase):
             strides=[1, 2, 2, 1],
             padding="EXPLICIT",
             explicit_paddings=[1, 1, 1, 1, 1, 1, 0, 0],
             data_format="NHWC"))
 
+  def testMaxPoolGradEagerShapeErrors(self):
+    with context.eager_mode():
+      orig_in = array_ops.ones((1, 1, 1, 1))
+
+      # Test invalid orig_out shape
+      orig_out = array_ops.ones((1, 1, 1, 2))
+      grad = array_ops.ones((1, 1, 1, 1))
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected orig_output shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected orig_output shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+
+      # Test invalid grad shape
+      orig_out = array_ops.ones((1, 1, 1, 1))
+      grad = array_ops.ones((1, 1, 1, 2))
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad_grad(
+            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+
+  def testMaxPoolGradWithArgmaxEagerShapeErrors(self):
+    with context.eager_mode():
+      inp = array_ops.ones((1, 1, 1, 1))
+
+      # Test invalid grad shape
+      grad = array_ops.ones((1, 1, 1, 2))
+      argmax = array_ops.zeros((1, 1, 1, 1), dtype=dtypes.int64)
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad_with_argmax(
+            inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+      # max_pool_grad_grad_with_argmax is only implemented for GPUs
+      if test.is_gpu_available():
+        with self.assertRaisesRegex(
+            errors_impl.InvalidArgumentError,
+            r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+          gen_nn_ops.max_pool_grad_grad_with_argmax(
+              inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+              padding="VALID")
+
+      # Test invalid argmax shape
+      grad = array_ops.ones((1, 1, 1, 1))
+      argmax = array_ops.ones((1, 1, 1, 2), dtype=dtypes.int64)
+      with self.assertRaisesRegex(
+          errors_impl.InvalidArgumentError,
+          r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+        gen_nn_ops.max_pool_grad_with_argmax(
+            inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+            padding="VALID")
+      # max_pool_grad_grad_with_argmax is only implemented for GPUs
+      if test.is_gpu_available():
+        with self.assertRaisesRegex(
+            errors_impl.InvalidArgumentError,
+            r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
+          gen_nn_ops.max_pool_grad_grad_with_argmax(
+              inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
+              padding="VALID")
+
 
 def GetMaxPoolFwdTest(input_size, filter_size, strides, padding):
 
   def Test(self):
     # MaxPoolWithArgMax is implemented only on CUDA.

Vulnerable code: // Checks if the sizes of the paddings are less than the size of window.
// This is required for MaxPool because it pads with -inf, so the pooling
// window cannot fully cover the padded area.
Status CheckPaddingSize(PoolParameters& params);

Fixed code:     OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected orig_output shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", tensor_out.shape()));
    OP_REQUIRES(context, out_backprop.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected grad shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", out_backprop.shape()));
    if (!context->status().ok()) {
      return;
    }
    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected orig_output shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", tensor_out.shape()));
    OP_REQUIRES(
        context, out_grad_backprop.shape() == tensor_in.shape(),
        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
                                ", but got ", out_grad_backprop.shape()));

    if (!context->status().ok()) {
      return;
    }
    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected orig_output shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", tensor_out.shape()));
    OP_REQUIRES(
        context, out_grad_backprop.shape() == tensor_in.shape(),
        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
                                ", but got ", out_grad_backprop.shape()));
    OP_REQUIRES(context, grad_in.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected grad shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", grad_in.shape()));
    OP_REQUIRES(context, argmax.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected argmax shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", argmax.shape()));
    OP_REQUIRES(
        context, grad_in.shape() == tensor_in.shape(),
        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
                                ", but got ", grad_in.shape()));
    OP_REQUIRES(context, argmax.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected argmax shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", argmax.shape()));

    const int64_t depth = GetTensorDim(tensor_in, data_format_, 'C');
    const int64_t in_batch = GetTensorDim(tensor_in, data_format_, 'N');
    TensorShape out_shape = ShapeFromFormat(data_format_, in_batch,
                                            {{out[2], out[1], out[0]}}, depth);
    OP_REQUIRES(
        context, tensor_out.shape() == out_shape,
        errors::InvalidArgument("Expected orig_output shape to be ", out_shape,
                                ", but got ", tensor_out.shape()));
    OP_REQUIRES(context, out_backprop.shape() == out_shape,
                errors::InvalidArgument("Expected grad shape to be ", out_shape,
                                        ", but got ", out_backprop.shape()));

    OP_REQUIRES(context, tensor_out.shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected orig_output shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", tensor_out.shape()));
    OP_REQUIRES(
        context, out_grad_backprop.shape() == tensor_in.shape(),
        errors::InvalidArgument("Expected grad shape to be ", tensor_in.shape(),
                                ", but got ", out_grad_backprop.shape()));
  if (tensor_out) {
    OP_REQUIRES(context, tensor_out->shape() == params.forward_output_shape(),
                errors::InvalidArgument("Expected orig_output shape to be ",
                                        params.forward_output_shape(),
                                        ", but got ", tensor_out->shape()));
  }
  OP_REQUIRES(context, out_backprop.shape() == params.forward_output_shape(),
              errors::InvalidArgument("Expected grad shape to be ",
                                      params.forward_output_shape(),
                                      ", but got ", out_backprop.shape()));
from tensorflow.python.eager import context
from tensorflow.python.framework import errors_impl
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_nn_ops
  def testMaxPoolGradEagerShapeErrors(self):
    with context.eager_mode():
      orig_in = array_ops.ones((1, 1, 1, 1, 1))

      # Test invalid orig_out shape
      orig_out = array_ops.ones((1, 1, 1, 1, 2))
      grad = array_ops.ones((1, 1, 1, 1, 1))
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected orig_output shape to be \[1,1,1,1,1\], but got "
          r"\[1,1,1,1,2\]"):
        gen_nn_ops.max_pool3d_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
            strides=[1, 1, 1, 1, 1], padding="VALID")
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected orig_output shape to be \[1,1,1,1,1\], but got "
          r"\[1,1,1,1,2\]"):
        gen_nn_ops.max_pool3d_grad_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
            strides=[1, 1, 1, 1, 1], padding="VALID")

      # Test invalid grad shape
      orig_out = array_ops.ones((1, 1, 1, 1, 1))
      grad = array_ops.ones((1, 1, 1, 1, 2))
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected grad shape to be \[1,1,1,1,1\], but got \[1,1,1,1,2\]"):
        gen_nn_ops.max_pool3d_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
            strides=[1, 1, 1, 1, 1], padding="VALID")
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected grad shape to be \[1,1,1,1,1\], but got \[1,1,1,1,2\]"):
        gen_nn_ops.max_pool3d_grad_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1, 1],
            strides=[1, 1, 1, 1, 1], padding="VALID")

  @test_util.xla_allow_fallback("XLA doesn't support explicit padding")
  def testMaxPoolGradEagerShapeErrors(self):
    with context.eager_mode():
      orig_in = array_ops.ones((1, 1, 1, 1))

      # Test invalid orig_out shape
      orig_out = array_ops.ones((1, 1, 1, 2))
      grad = array_ops.ones((1, 1, 1, 1))
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected orig_output shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected orig_output shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")

      # Test invalid grad shape
      orig_out = array_ops.ones((1, 1, 1, 1))
      grad = array_ops.ones((1, 1, 1, 2))
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad_grad(
            orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")

  def testMaxPoolGradWithArgmaxEagerShapeErrors(self):
    with context.eager_mode():
      inp = array_ops.ones((1, 1, 1, 1))

      # Test invalid grad shape
      grad = array_ops.ones((1, 1, 1, 2))
      argmax = array_ops.zeros((1, 1, 1, 1), dtype=dtypes.int64)
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad_with_argmax(
            inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")
      # max_pool_grad_grad_with_argmax is only implemented for GPUs
      if test.is_gpu_available():
        with self.assertRaisesRegex(
            errors_impl.InvalidArgumentError,
            r"Expected grad shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
          gen_nn_ops.max_pool_grad_grad_with_argmax(
              inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
              padding="VALID")

      # Test invalid argmax shape
      grad = array_ops.ones((1, 1, 1, 1))
      argmax = array_ops.ones((1, 1, 1, 2), dtype=dtypes.int64)
      with self.assertRaisesRegex(
          errors_impl.InvalidArgumentError,
          r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
        gen_nn_ops.max_pool_grad_with_argmax(
            inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
            padding="VALID")
      # max_pool_grad_grad_with_argmax is only implemented for GPUs
      if test.is_gpu_available():
        with self.assertRaisesRegex(
            errors_impl.InvalidArgumentError,
            r"Expected argmax shape to be \[1,1,1,1\], but got \[1,1,1,2\]"):
          gen_nn_ops.max_pool_grad_grad_with_argmax(
              inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],
              padding="VALID")