Repository navigation
Validate batch_index slice bounds and shapes in Unbatch - #129230
copybara-service[bot] merged 2 commits into
Conversation
Add bounds validation for start/end slice indices and cumulative split sizes in UnbatchResource and concat_split_util to prevent fatal CHECK aborts during tensor slicing. Also validate batch_index and id ranks and dimensions in Unbatch and UnbatchGrad shape inference functions. Fixes tensorflow#65633
There was a problem hiding this comment.
Code Review
This pull request adds validation checks to the Unbatch and UnbatchGrad operations to prevent invalid slice bounds, incorrect shapes, and negative split sizes, addressing potential crashes and adding comprehensive unit tests. The review feedback identifies critical opportunities to prevent potential integer overflows in concat_split_util.h and batch_kernels.cc by performing subtraction-based boundary checks before accumulating split sizes.
| for (const int64_t size : sizes) { | ||
| if (size < 0) { | ||
| return absl::InvalidArgumentError( | ||
| absl::StrCat("Split size must be non-negative, got ", size)); | ||
| } | ||
| total_size += size; | ||
| } |
There was a problem hiding this comment.
To prevent potential integer overflow when summing up the split sizes, we should check if size exceeds the remaining capacity of the input tensor's dimension 0 before performing the addition. If sizes contains extremely large values, total_size could overflow and wrap around to a negative value, bypassing the subsequent boundary check.
for (const int64_t size : sizes) {
if (size < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Split size must be non-negative, got ", size));
}
if (size > input.shape().dim_size(0) - total_size) {
return absl::InvalidArgumentError(
"Sum of split sizes must not exceed dim0-size of input tensor");
}
total_size += size;
}| for (const int64_t size : sizes) { | ||
| if (size < 0) { | ||
| return absl::InvalidArgumentError( | ||
| absl::StrCat("Split size must be non-negative, got ", size)); | ||
| } |
There was a problem hiding this comment.
Similarly, we should prevent potential integer overflow when accumulating the split sizes in SplitCPU. Checking if size exceeds the remaining capacity of the input tensor's dimension 0 before adding it to position ensures safe execution.
for (const int64_t size : sizes) {
if (size < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Split size must be non-negative, got ", size));
}
if (size > input.shape().dim_size(0) - position) {
return absl::InvalidArgumentError(
"Sum of split sizes must not exceed dim0-size of input tensor");
}| const int64_t size = end - start; | ||
| total_size += size; | ||
| if (total_size > data_t.shape().dim_size(0)) { | ||
| return absl::InvalidArgumentError( | ||
| "Sum of split sizes must not exceed dim0-size of input tensor"); | ||
| } |
There was a problem hiding this comment.
To prevent any potential integer overflow when accumulating total_size, perform the boundary check using subtraction (size > data_t.shape().dim_size(0) - total_size) instead of addition.
const int64_t size = end - start;
if (size > data_t.shape().dim_size(0) - total_size) {
return absl::InvalidArgumentError(
"Sum of split sizes must not exceed dim0-size of input tensor");
}
total_size += size;
dmiltr3
left a comment
There was a problem hiding this comment.
1. Fix the failing cumulative-size test case, run in both graph and eager mode, and wrap lines to 80 columns (tensorflow/python/ops/batch_ops_test.py)
In testUnbatchInvalidSliceBounds, the fourth test case passes batch_index=[[0, 0, 2], [1, 2, 4]] for a batched_tensor whose first dimension has size 3. Because row 1 has end = 4 > 3, the kernel rejects it at the per-row end > data_t.shape().dim_size(0) check ("exceeds dimension 0 size 3") before reaching the cumulative split-size check, causing assertRaisesRegex(..., "Sum of split sizes must not exceed") to fail when batch_ops_test is executed. Use overlapping slice ranges whose end indices stay within dimension 0 (such as [[0, 0, 2], [1, 1, 3]]).
In addition, remove the if context.executing_eagerly(): guard and wrap each batch_ops.unbatch(...) call in self.evaluate(...) so these runtime checks are exercised in both graph and eager mode, and wrap lines to 80 columns so the PyLint check passes (lines 701, 714, 727, 740, and 741 currently exceed 80 characters):
def testUnbatchInvalidSliceBounds(self):
# Regression test for GitHub issue 65633: invalid slice bounds or
# cumulative sizes in batch_index caused fatal CHECK failures.
# Inverted slice range (end < start)
with self.assertRaisesRegex(
errors.InvalidArgumentError, "Expected 0 <= start <= end"
):
self.evaluate(
batch_ops.unbatch(
batched_tensor=constant_op.constant(
[[1, 2], [3, 4]], dtype=dtypes.int32
),
batch_index=constant_op.constant(
[[0, 2, 1]], dtype=dtypes.int64
),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
container="",
shared_name="",
)
)
# Negative start index
with self.assertRaisesRegex(
errors.InvalidArgumentError, "Expected 0 <= start <= end"
):
self.evaluate(
batch_ops.unbatch(
batched_tensor=constant_op.constant(
[[1, 2], [3, 4]], dtype=dtypes.int32
),
batch_index=constant_op.constant(
[[0, -1, 1]], dtype=dtypes.int64
),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
container="",
shared_name="",
)
)
# End index exceeds dim0
with self.assertRaisesRegex(
errors.InvalidArgumentError, "exceeds dimension 0 size"
):
self.evaluate(
batch_ops.unbatch(
batched_tensor=constant_op.constant(
[[1, 2], [3, 4]], dtype=dtypes.int32
),
batch_index=constant_op.constant(
[[0, 1, 5]], dtype=dtypes.int64
),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
container="",
shared_name="",
)
)
# Cumulative split sizes exceed dim0 (overlapping rows)
with self.assertRaisesRegex(
errors.InvalidArgumentError, "Sum of split sizes must not exceed"
):
self.evaluate(
batch_ops.unbatch(
batched_tensor=constant_op.constant(
[[1], [2], [3]], dtype=dtypes.int32
),
batch_index=constant_op.constant(
[[0, 0, 2], [1, 1, 3]], dtype=dtypes.int64
),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
container="",
shared_name="",
)
)2. Drop the UnbatchGrad changes and update the PR title and description (tensorflow/core/kernels/batch_kernels.cc, tensorflow/core/ops/batch_ops.cc, tensorflow/python/ops/batch_ops_test.py)
BatchOpsTest runs all test methods in both graph and eager mode. Adding static shape-inference checks to UnbatchGrad causes graph-mode op construction to raise ValueError in the existing tests testUnbatchGradInvalidId, testUnbatchGradInvalidBatchId, and testUnbatchGradInvalidArgs, which only catch errors.InvalidArgumentError and therefore fail in graph mode. Furthermore, the UnbatchGrad kernel and shape-function changes (along with the corresponding updates to those existing tests) are already handled in open PR #128345.
Please remove:
- the
batch_index_t.shape().dim_size(1) != 3block inUnbatchGradResource::Compute(tensorflow/core/kernels/batch_kernels.cc:1193-1198); - the new shape-inference checks in
REGISTER_OP("UnbatchGrad")(tensorflow/core/ops/batch_ops.cc:199-204); testUnbatchGradShapeInference(tensorflow/python/ops/batch_ops_test.py:782-806).
Please also update the PR title and description so they describe Unbatch only.
3. Make the cumulative split-size check overflow-safe and add a regression test (tensorflow/core/kernels/batching_util/concat_split_util.h, tensorflow/python/ops/batch_ops_test.py)
In SplitEasyCases, total_size += size is computed before checking total_size > input.shape().dim_size(0). A zero-element tensor can legitimately have a large first dimension (for example shape [INT64_MAX, 0]). With rows [0, 0, INT64_MAX] and [1, 0, 1], each row passes the per-row bounds checks, but total_size + size overflows signed int64_t (undefined behavior) and wraps past the sum check into Tensor::Slice. Because total_size <= input.shape().dim_size(0) holds at the start of each iteration, check size > input.shape().dim_size(0) - total_size before adding size in SplitEasyCases (tensorflow/core/kernels/batching_util/concat_split_util.h):
int64_t total_size = 0;
for (const int64_t size : sizes) {
if (size < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Split size must be non-negative, got ", size));
}
if (size > input.shape().dim_size(0) - total_size) {
return absl::InvalidArgumentError(
"Sum of split sizes must not exceed dim0-size of input tensor");
}
total_size += size;
}Please also add a regression test in tensorflow/python/ops/batch_ops_test.py covering this overflow boundary:
def testUnbatchSplitSizesOverflow(self):
# Two valid rows whose sizes sum past INT64_MAX on a zero-element input.
int64_max = np.iinfo(np.int64).max
shape = constant_op.constant([int64_max, 0], dtype=dtypes.int64)
with self.assertRaisesRegex(
errors.InvalidArgumentError, "Sum of split sizes must not exceed"
):
self.evaluate(
batch_ops.unbatch(
batched_tensor=array_ops.zeros(shape, dtypes.int32),
batch_index=constant_op.constant(
[[0, 0, int64_max], [1, 0, 1]], dtype=dtypes.int64
),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
container="",
shared_name="",
)
)4. Remove unreachable and duplicate checks (tensorflow/core/kernels/batch_kernels.cc, tensorflow/core/kernels/batching_util/concat_split_util.h)
- In
UnbatchResource::Compute(tensorflow/core/kernels/batch_kernels.cc:893-897), delete thebatch_index_t.NumElements() != batch_index_t.dim_size(0) * 3check. OnceTensorShapeUtils::IsMatrix(batch_index_t.shape())andbatch_index_t.shape().dim_size(1) == 3have passed,NumElements()equalsdim_size(0) * 3by definition, making this branch unreachable. - In
UnbatchResource::Compute(tensorflow/core/kernels/batch_kernels.cc:931-936), remove the duplicatetotal_sizeaccumulation and check.Split(batch_kernels.cc:941) always runsSplitEasyCasesfirst on the samesizesvector and returns the exact same error message ("Sum of split sizes must not exceed dim0-size of input tensor"). Keep only the per-rowstartandendchecks inUnbatchResource::Compute:
if (nonempty_input) {
auto batch_indices =
batch_index_t.shaped<int64_t, 2>({batch_index_t.dim_size(0), 3});
for (int i = 0; i < batch_index_t.dim_size(0); ++i) {
const int64_t start = batch_indices(i, 1);
const int64_t end = batch_indices(i, 2);
if (start < 0 || end < start) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid start/end indices in batch_index at row ", i, ": start=",
start, ", end=", end, ". Expected 0 <= start <= end."));
}
if (end > data_t.shape().dim_size(0)) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid end index in batch_index at row ", i, ": end=", end,
" exceeds dimension 0 size ", data_t.shape().dim_size(0), "."));
}
sizes.push_back(end - start);
batch_keys.push_back(batch_indices(i, 0));
}
TF_RETURN_IF_ERROR(Split(context, data_t, sizes, &split_inputs));
}- In
SplitCPU(tensorflow/core/kernels/batching_util/concat_split_util.h:175-178), delete theif (size < 0)check.SplitCPUis only called fromSplitafterSplitEasyCaseshas already validated that every element ofsizesis non-negative.
5. Build testUnbatchShapeInference inside a graph and pin the error messages (tensorflow/python/ops/batch_ops_test.py)
In testUnbatchShapeInference, with self.assertRaises((ValueError, errors.InvalidArgumentError)): accepts any error of either type and, in eager mode, hits the existing runtime kernel checks rather than the C++ shape function. Construct the ops inside with ops.Graph().as_default(): and use self.assertRaisesRegex(ValueError, ...) to pin each shape-function error message:
def testUnbatchShapeInference(self):
# Shape functions run only when the op is added to a graph.
with ops.Graph().as_default():
with self.assertRaisesRegex(ValueError, "Shape must be at least rank 1"):
gen_batch_ops.unbatch(
batched_tensor=constant_op.constant(1.0),
batch_index=constant_op.constant([[0, 0, 1]], dtype=dtypes.int64),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
)
with self.assertRaisesRegex(ValueError, "Shape must be rank 2"):
gen_batch_ops.unbatch(
batched_tensor=constant_op.constant([1.0, 2.0]),
batch_index=constant_op.constant([0, 0, 1], dtype=dtypes.int64),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
)
with self.assertRaisesRegex(ValueError, "Dimension must be 3"):
gen_batch_ops.unbatch(
batched_tensor=constant_op.constant([1.0, 2.0]),
batch_index=constant_op.constant([[0, 1]], dtype=dtypes.int64),
id=constant_op.constant(0, dtype=dtypes.int64),
timeout_micros=0,
)
with self.assertRaisesRegex(ValueError, "Shape must be rank 0"):
gen_batch_ops.unbatch(
batched_tensor=constant_op.constant([1.0, 2.0]),
batch_index=constant_op.constant([[0, 0, 1]], dtype=dtypes.int64),
id=constant_op.constant([0], dtype=dtypes.int64),
timeout_micros=0,
)…flow Make cumulative split size checks in SplitEasyCases overflow-safe against signed int64 wrap-around, remove duplicate bounds checks, drop UnbatchGrad shape-inference changes, and update tests to evaluate under both graph and eager modes with pinned shape-function errors.
|
Updated to scope everything to Unbatch, made the cumulative size check overflow-safe with a regression test, and fixed the test cases and formatting. Thanks for the thorough review! |
Passing invalid
batch_indexentries (such asend < start, negative indices, or out-of-bounds ranges) totf.raw_ops.Unbatchcurrently aborts the process with fatalCHECKfailures insideTensor::Sliceandshaped.This PR adds slice bounds and cumulative size checks in
UnbatchResource::Computeandconcat_split_util, and tightens shape inference forUnbatchto reject malformedbatch_indexandidinputs withInvalidArgumentError.Fixes #65633