Repository navigation
fix(gpu): prevent integer overflow in RollKernel on large tensors - #126448
Conversation
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for your pull request!
While reviewing the changes in tensorflow/core/kernels/roll_op_gpu.cu.cc, we noticed that while RollKernel has been updated to support int64_t nthreads and 64-bit indexing, Roll<GPUDevice, T>::operator() still calls GetGpuLaunchConfig(num_elements, d). GetGpuLaunchConfig only supports a 32-bit element count (cfg.virtual_thread_count is 32-bit).
To properly support more than INT32_MAX elements, please switch to GetGpuLaunchConfig64:
absl::StatusOr<GpuLaunchConfig64> config =
GetGpuLaunchConfig64(num_elements, d);
OP_REQUIRES_OK(context, config.status());
TF_CHECK_OK(
GpuLaunchKernel(RollKernel<T>, config->block_count,
config->thread_per_block, 0, d.stream(),
config->virtual_thread_count, num_dims, input, output,
reinterpret_cast<const int32_t*>(dim_buf),
reinterpret_cast<const int32_t*>(thres_buf),
reinterpret_cast<const int64_t*>(range_buf)));Could you please update Roll<GPUDevice, T>::operator() to use GetGpuLaunchConfig64?
|
Updated |
5bc7666 to
98c43e8
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for updating the PR to use GetGpuLaunchConfig64!
There are two issues that need to be addressed before we can proceed:
1. CUDA Compilation Error with OP_REQUIRES_OK
In tensorflow/core/kernels/roll_op_gpu.cu.cc, Roll<GPUDevice, T>::operator() has the signature:
void operator()(const OpKernelContext* context, ...)Because context is a pointer to const OpKernelContext, calling OP_REQUIRES_OK(context, config.status()) causes a compilation error with CUDA compilers because OP_REQUIRES_OK invokes non-const methods (CtxFailureWithWarning / SetStatus) on the context:
tensorflow/core/framework/op_requires.h: error: no matching member function for call to 'CtxFailureWithWarning'
note: 'this' argument has type 'const tensorflow::OpKernelContext', but method is not marked const
Required Fix
Please cast away the const qualifier when passing context to OP_REQUIRES_OK:
absl::StatusOr<GpuLaunchConfig64> config =
GetGpuLaunchConfig64(num_elements, d);
OP_REQUIRES_OK(const_cast<OpKernelContext*>(context), config.status());2. Rebase on Latest master
The GitHub Actions CI builds failed across all platforms due to an outdated base commit. Please rebase your branch on the latest master to resolve the build errors:
git fetch upstream master
git rebase upstream/master
git push --force-with-lease98c43e8 to
af44d6e
Compare
|
Addressed both points:
|
af44d6e to
5c78fe5
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Rebase on Latest master
The code changes in tensorflow/core/kernels/roll_op_gpu.cu.cc look good and address the previous comments. However, the GitHub Actions CI builds failed across all platforms (Linux CPU, Linux CUDA, Linux CUDA 13, ARM64, Windows):
ERROR: Error computing the main repository mapping: no such package '@@llvm-raw//utils/bazel': Error applying patch .../third_party/llvm/build.patch: could not apply patch due to CONTENT_DOES_NOT_MATCH_TARGET
This failure occurred because the branch's base commit (08d66ff30ce61b09ac5ab0fffec08b1ab088ba65) predates commit bb6b3b8937baca2a29446c27f84046d168ffac4d ("Update LLVM patches for XLA") on master that resolved this build patch issue.
Please rebase your branch on the latest upstream master and force-push to trigger a clean CI run:
git fetch upstream master
git rebase upstream/master
git push --force-with-lease5c78fe5 to
d83337a
Compare
|
Rebased on upstream |
dmiltr3
left a comment
There was a problem hiding this comment.
LGTM. Thank you for addressing the review comments and switching to GetGpuLaunchConfig64 to prevent integer overflow on large tensors. All tests passed.
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The 64-bit logic correctly addresses the integer overflow issue on large tensors, and the example shape update is spot on.
However, we need to correct the error handling introduced in the previous round. The prior review incorrectly recommended using TF_CHECK_OK(config.status()). TF_CHECK_OK will crash the entire TensorFlow host process if the status is not OK, which is strictly prohibited inside OpKernel implementations.
Errors must be gracefully propagated back to the caller via OP_REQUIRES_OK(context, ...).
Blocking Changes
-
Fatal Error Handling in OpKernel:
To useOP_REQUIRES_OKwithout running intoconst_castissues, please remove theconstqualifier fromconst OpKernelContext* contextin theRollfunctoroperator()signature across all three files:tensorflow/core/kernels/roll_op.h,tensorflow/core/kernels/roll_op.cc, andtensorflow/core/kernels/roll_op_gpu.cu.cc.Then, replace the
TF_CHECK_OKusage. For the launch configuration:absl::StatusOr<GpuLaunchConfig64> config = GetGpuLaunchConfig64(num_elements, d); OP_REQUIRES_OK(context, config.status());For the kernel launch, capture the status, ensure device buffers are deallocated, and then propagate the status so memory does not leak upon failure:
absl::Status launch_status = GpuLaunchKernel( RollKernel<T>, config->block_count, config->thread_per_block, 0, d.stream(), config->virtual_thread_count, num_dims, input, output, reinterpret_cast<const int32_t*>(dim_buf), reinterpret_cast<const int32_t*>(thres_buf), reinterpret_cast<const int64_t*>(range_buf)); d.deallocate(dim_buf); d.deallocate(thres_buf); d.deallocate(range_buf); OP_REQUIRES_OK(context, launch_status); -
Missing Header:
Please add#include "absl/status/statusor.h"totensorflow/core/kernels/roll_op_gpu.cu.ccsinceabsl::StatusOris being used.
Optional Performance Suggestion (Non-Blocking)
- Hoist Redundant GPU Divisions: The
RollKernelperforms a 64-bit division (dim_range[i] / dim_size[i]) and a subtraction (dim_size[i] - threshold[i]) inside its inner loop for every thread. Since these values only depend on the dimension indexi, they are loop-invariant with respect toout_idx. Doing a 64-bit division inside a hot loop on the GPU is expensive. Consider precomputing astridearray and ashiftarray on the host and passing those to the kernel instead ofdim_rangeandthreshold. (This optimizes pre-existing code, so feel free to tackle it in a separate follow-up PR if you prefer).
|
Thanks @dmiltr3. Review 5369938232 is addressed in c841948. Error handling. Header. Hoisting the division. I left this out to keep the diff small. I can send it as a separate PR. Testing. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for your pull request! We reviewed the changes to fix GPU integer overflow in RollKernel on large tensors. While the changes resolve the issue on the GPU grid scale by transitioning to 64-bit boundaries (GpuGridRangeX and 64-bit bounds checking), there are remaining 32-bit truncation points on the host side, as well as missing dependencies and test assertions.
Please address the following findings:
-
Integer Truncation & Cast Wrapping on Tensor Dimensions: In
RollOp::Compute(tensorflow/core/kernels/roll_op.cc), the tensor dimensioninput.dim_size(i)(which isint64_t) is cast tointviastatic_cast<int>(input.dim_size(i)). For tensors with a dimension exceedingINT32_MAX, this silently wraps to a negative value.std::max<int>(..., 1)then incorrectly clamps this to1. Consequently,dim_size,threshold, andshift_mod_sumpropagate this corrupted dimension size down to the GPU and CPU kernels, resulting in broken index arithmetic and out-of-bounds memory accesses. Please update the dimension tracking vectors (shift_mod_sum,dim_size,threshold) to useint64_t, and removestatic_cast<int>casting. Additionally, update the functor and kernel signatures acrossroll_op.h,roll_op.cc, androll_op_gpu.cu.ccto acceptint64_tarrays fordim_sizeandthreshold. -
Missing BUILD Dependencies for ABSL Status: The C++ file
tensorflow/core/kernels/roll_op_gpu.cu.ccusesabsl::StatusOrandabsl::Status. However, theroll_optarget intensorflow/core/kernels/BUILDdoes not explicitly declare these dependencies. Relying on transitive dependencies violates BUILD hygiene. Please add@com_google_absl//absl/status:statusand@com_google_absl//absl/status:statusorto thedepsarray of theroll_optarget. -
Missing N=0 Empty Input Test Verification: Explicit verification of graceful fallback on empty (N=0) inputs is necessary to prevent crashes. There are no Python tests that exercise
tf.rollwith a size-0 tensor. Please add a test case intensorflow/python/kernel_tests/array_ops/manip_ops_test.pyto ensure the 0-element boundary is robustly handled, for example:
def testRollEmptyInput(self):
with self.cached_session():
empty_tensor = array_ops.zeros([0, 5], dtype=dtypes.float32)
result = manip_ops.roll(empty_tensor, shift=1, axis=0)
self.assertEqual(result.eval().shape, (0, 5))- Missing Include for
absl::Status: The code explicitly usesabsl::Status, but only includes"absl/status/statusor.h". Please add#include "absl/status/status.h"totensorflow/core/kernels/roll_op_gpu.cu.cc.
(Note: We acknowledge your comment about deferring the GPU division optimization to a separate PR to keep this diff small. That is perfectly fine.)
|
Thanks @dmiltr3. f2f63cf addresses all four points.
Local run. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for your pull request! We reviewed the changes to fix GPU integer overflow in RollKernel on large tensors. The updates correctly address the previous feedback around const_cast removal and device memory leaks. However, there are remaining issues related to signed integer overflow in shift accumulation, missing test coverage for eager mode, and a redundant 64-bit division on the GPU fast path.
Please address the following findings:
1. Signed Integer Overflow (Undefined Behavior) in Shift Accumulation
In tensorflow/core/kernels/roll_op.cc:83-84, the shift_flat(i) value is cast to int64_t and directly added to shift_mod_sum[axis]. If shift_flat(i) is very large (e.g., INT64_MAX), this accumulation causes a signed integer overflow. In C++, signed integer overflow is Undefined Behavior. Since shift is an untrusted tensor input, we must apply the modulo ds to the shift value before accumulation to guarantee it stays within bounds.
Please replace the shift accumulation with:
const int64_t ds = std::max<int64_t>(input.dim_size(axis), 1);
const int64_t shift_val = static_cast<int64_t>(shift_flat(i)) % ds;
const int64_t sum = shift_mod_sum[axis] + shift_val;
// modulo that works with negatives: ((x % y) + y) % y
shift_mod_sum[axis] = (sum % ds + ds) % ds;Additionally, please add a test case in tensorflow/python/kernel_tests/array_ops/manip_ops_test.py to exercise a shift that would overflow int64_t accumulation on duplicate axes:
@test_util.run_in_graph_and_eager_modes
def testRollLargeShiftOverflow(self):
tensor = array_ops.arange(5, dtype=dtypes.float32)
result = manip_ops.roll(tensor, shift=[1, 9223372036854775807], axis=[0, 0])
self.assertEqual(self.evaluate(result).shape, (5,))2. Missing Graph & Eager Mode Test Coverage
The newly added testRollEmptyInput in tensorflow/python/kernel_tests/array_ops/manip_ops_test.py:103-107 uses with self.cached_session():, which forces the test to execute exclusively in graph mode. New tests must cover both graph and eager modes.
Please remove with self.cached_session(): and decorate the test method with @test_util.run_in_graph_and_eager_modes:
@test_util.run_in_graph_and_eager_modes
def testRollEmptyInput(self):
empty_tensor = array_ops.zeros([0, 5], dtype=dtypes.float32)
result = manip_ops.roll(empty_tensor, shift=1, axis=0)
self.assertEqual(self.evaluate(result).shape, (0, 5))3. Redundant 64-bit Division in GPU Inner Loop (Carry-over Missed)
In tensorflow/core/kernels/roll_op_gpu.cu.cc:43-44, RollKernel performs a 64-bit integer division (dim_range[i] / dim_size[i]) inside its inner loop for every thread. Since dim_range stores the cumulative product of dimensions, dim_range[i] / dim_size[i] is mathematically equivalent to dim_range[i + 1] (or 1 for the last dimension). Doing this 64-bit division inside a GPU hot loop is extremely expensive and must be replaced by an array lookup.
Please replace the stride and shift computation with:
const int64_t stride = (i + 1 < num_dims) ? dim_range[i + 1] : 1;
const int64_t shift = dim_size[i] - threshold[i];4. Unchecked Device Memory Allocations (Optional Follow-up)
In tensorflow/core/kernels/roll_op_gpu.cu.cc:71-78, d.allocate() may return a null pointer if the GPU is out of memory. Passing a null pointer to memcpyHostToDevice or the kernel can cause an asynchronous fault. Consider checking for null and returning a ResourceExhaustedError, though we recognize this is a pre-existing pattern in this op.
|
Thanks @dmiltr3. 0dd2536 addresses the review.
I left out the optional On CPU, I did not compile the GPU kernel change because I have no CUDA setup here, and I did not run |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates and for your patience. Sorry for the churn on this PR: we changed our minds on several requests over the past few days, which made the change bigger than it needed to be.
The current head fixes the overflow: shifts are reduced modulo the dimension size before they are summed in 64-bit, the GPU kernel indexes with int64_t, the launch configuration is checked before any device buffer is allocated, and launch errors are reported after the buffers are freed. The new C++ and Python tests cover the large-shift case in both graph and eager modes.
Retractions
- 2026-09-29: Our ask to use
TF_CHECK_OKfor the launch configuration. Inside anOpKernelthat would crash the process;OP_REQUIRES_OK, which you now use, is correct. - 2026-09-30: Our suggestion to precompute a separate host-side
shiftarray. It would add a device buffer and copy for no gain. - 2026-10-04: Blocking on eager coverage of
testRollEmptyInput. Thecached_session()snippet that lacked it was ours, from 2026-10-03. - 2026-10-04: Blocking on the 64-bit division in
RollKernelafter we had said on 2026-10-03 that a follow-up was fine.
Optional
- The PR description becomes the commit message. If you have a moment, please update it to match the final code (
OP_REQUIRES_OKwithGetGpuLaunchConfig64, theint64_thost-side changes, and the new tests). We are not blocking on this.
LGTM. Thank you for seeing this through!
|
Hi @adi-IL, Can you please resolve the conflicts? Thank you! |
Avoid truncating dimensions larger than INT32_MAX, add the absl status deps and include for roll_op, and cover rolling an empty tensor.
Take each shift modulo the dimension size before adding it to the per-axis sum, so repeated-axis int64 shifts cannot overflow. Read the GPU kernel stride from dim_range[i + 1] instead of dividing. Run testRollEmptyInput in graph and eager modes, and add large repeated-axis shift tests to roll_op_test.cc and manip_ops_test.py.
0dd2536 to
7ac5687
Compare
|
@nithyak0204 Rebased onto current master. The conflicts were upstream modernizations of the same code (CUDA_1D_KERNEL_LOOP with int64 index, new GetGpuLaunchConfig64 StatusOr API). I kept the upstream forms and replayed the fix on top. Net effect is unchanged from the approved version. Fresh CI runs now. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates and for your patience. Sorry for the churn on this PR: we changed our minds on several requests over the past few days, which made the change bigger than it needed to be.
The current head fixes the overflow: shifts are reduced modulo the dimension size before they are summed in 64-bit, the GPU kernel indexes with int64_t, the launch configuration is checked before any device buffer is allocated, and launch errors are reported after the buffers are freed. The new C++ and Python tests cover the large-shift case in both graph and eager modes.
Retractions
- 2026-09-29: Our ask to use
TF_CHECK_OKfor the launch configuration. - 2026-09-30: Our suggestion to precompute a separate host-side
shiftarray. - 2026-10-04: Blocking on eager coverage of
testRollEmptyInput. - 2026-10-04: Blocking on the 64-bit division in
RollKernel.
Optional
- The PR description becomes the commit message. If you have a moment, please update it to match the final code (
OP_REQUIRES_OKwithGetGpuLaunchConfig64, theint64_thost-side changes, and the new tests). We are not blocking on this. - Not introduced by this PR, so it is fine as a follow-up: in
roll_op.cc,int axis = axis_flat(i);narrows anint64axis tointbefore the bounds check, so a value such as2**32 + 1would wrap to a valid axis instead of being rejected.const int64_t axis_in = axis_flat(i);with the bounds check on that value (then casting toint) would close it.
- Keep master's int64_t dim_size and threshold. - Keep this branch's host-computed shift and stride and allocate_temp buffers. The shifts buffer is now int64_t. - Keep the Roll tests from both sides.
Fixes #109520
RollKernelusedint32_tfor the thread count and for the host launch side. A tensor with more thanINT32_MAXelements (for example shape[46341, 46341]) overflows that type, so the kernel walks negative indices and the GPU faults withcudaErrorIllegalAddress.This change:
int64_tthread counts intoRollKerneland iterates withGpuGridRangeX.int64_ton the host and on the device.dim_range[i + 1].GetGpuLaunchConfig64before any device buffer is allocated and checks it withOP_REQUIRES_OK. Launch errors are checked after the buffers are freed.Tests:
LargeShifts_SameAxis64inroll_op_test.cc.testRollLargeShiftsSameAxisinmanip_ops_test.py(graph and eager).@test_util.run_in_graph_and_eager_modesontestRollEmptyInput.The GPU kernel was not compiled locally. This box has no CUDA toolchain, so the GPU CI job is the first build of that file.