Skip to content

Fix integer overflow in GPU kernel loops for large tensors - #126698

Open
kokol16 wants to merge 9 commits into
tensorflow:masterfrom
kokol16:fix/roll-populationCount
Open

kokol16 wants to merge 9 commits into
tensorflow:masterfrom
kokol16:fix/roll-populationCount

Conversation

@kokol16

@kokol16 kokol16 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Extended GPU_1D_KERNEL_LOOP / CUDA_1D_KERNEL_LOOP with an optional index type,
updated population_count and roll GPU kernels to use int64_t sizes and
GetGpuLaunchConfig64, and adds gpu_kernel_helper_test coverage.

Addressed review feedback on #112249:

  • kernel size parameters use int64_t
  • host launch uses GetGpuLaunchConfig64 / GpuLaunchConfig64
  • unit test for the 3-argument int64_t macro variant in gpu_kernel_helper_test.cu.cc

Fixes #109520
Fixes #104077
Supersedes #112249

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Sep 2, 2026
@nithyak0204
nithyak0204 requested a review from a team September 3, 2026 10:21
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 3, 2026
@nithyak0204 nithyak0204 added comp:core issues related to core part of tensorflow prtype:bugfix PR to fix a bug labels Sep 3, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 3, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1. Fix Preprocessor Macro Overloading for GPU_1D_KERNEL_LOOP and CUDA_1D_KERNEL_LOOP

In tensorflow/core/util/gpu_kernel_helper.h, defining GPU_1D_KERNEL_LOOP_SELECT and CUDA_1D_KERNEL_LOOP_SELECT twice:

#define GPU_1D_KERNEL_LOOP_SELECT(i, n, T, ...) \
  for (T i : ::tensorflow::GpuGridRangeX<T>(n))
#define GPU_1D_KERNEL_LOOP_SELECT(i, n, ...) \
  for (int i : ::tensorflow::GpuGridRangeX<int>(n))

does not overload the macro by arity. In C and C++, the second #define triggers a -Wmacro-redefined warning/error and unconditionally overrides the first definition. Consequently, invocations like GPU_1D_KERNEL_LOOP(i, size, int64_t) expand using the second definition, discarding int64_t and generating for (int i : ::tensorflow::GpuGridRangeX<int>(n)). The loop variable remains a 32-bit int, which fails to resolve integer overflow for tensors with > 2^31 elements.

Please update the macro definitions in tensorflow/core/util/gpu_kernel_helper.h to use standard preprocessor arity dispatch:

// Deprecated, use 'for(int i : GpuGridRangeX(n))' instead.
#define TF_GPU_1D_KERNEL_LOOP_2(i, n) \
  for (int i : ::tensorflow::GpuGridRangeX<int>(n))
#define TF_GPU_1D_KERNEL_LOOP_3(i, n, T) \
  for (T i : ::tensorflow::GpuGridRangeX<T>(n))
#define TF_GPU_1D_KERNEL_LOOP_GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define GPU_1D_KERNEL_LOOP(...) \
  TF_GPU_1D_KERNEL_LOOP_GET_MACRO( \
      __VA_ARGS__, TF_GPU_1D_KERNEL_LOOP_3, TF_GPU_1D_KERNEL_LOOP_2)(__VA_ARGS__)

#define TF_CUDA_1D_KERNEL_LOOP_2(i, n) \
  for (int i : ::tensorflow::GpuGridRangeX<int>(n))
#define TF_CUDA_1D_KERNEL_LOOP_3(i, n, T) \
  for (T i : ::tensorflow::GpuGridRangeX<T>(n))
#define TF_CUDA_1D_KERNEL_LOOP_GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define CUDA_1D_KERNEL_LOOP(...) \
  TF_CUDA_1D_KERNEL_LOOP_GET_MACRO( \
      __VA_ARGS__, TF_CUDA_1D_KERNEL_LOOP_3, TF_CUDA_1D_KERNEL_LOOP_2)(__VA_ARGS__)

2. Remove Redundant #include "tensorflow/core/util/gpu_launch_config.h"

In tensorflow/core/kernels/population_count_op_gpu.cu.cc and tensorflow/core/kernels/roll_op_gpu.cu.cc:

#include "tensorflow/core/util/gpu_launch_config.h" was added directly, but gpu_launch_config.h is already included by tensorflow/core/util/gpu_kernel_helper.h. Furthermore, directly including gpu_launch_config.h causes build layering check violations because the respective kernel targets in tensorflow/core/kernels/BUILD do not declare direct dependencies on //tensorflow/core/util:gpu_launch_config.

Please remove #include "tensorflow/core/util/gpu_launch_config.h" from both tensorflow/core/kernels/population_count_op_gpu.cu.cc and tensorflow/core/kernels/roll_op_gpu.cu.cc.


3. Add Type Assertion to Unit Test

In tensorflow/core/util/gpu_kernel_helper_test.cu.cc, please add a compile-time check in Count1DInt64 to guarantee that the loop index variable is indeed int64_t:

__global__ void Count1DInt64(GpuLaunchConfig64 config, int bufsize,
                             int* __restrict__ outbuf) {
  GPU_1D_KERNEL_LOOP(x, config.virtual_thread_count, int64_t) {
    static_assert(std::is_same<decltype(x), int64_t>::value,
                  "Expected int64_t index");
    if (x < 0) {  // x might overflow when testing extreme case
      break;
    }
    atomicAdd(&outbuf[x % bufsize], 1);
  }
}

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Sep 3, 2026
@dmiltr3
dmiltr3 self-requested a review September 3, 2026 15:23
@kokol16

kokol16 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

done, thanks for catching this. i fixed the macro definitions so the 2-argument form uses int and the 3-argument form correctly uses the provided type.
i also removed the two redundant includes and added the int64_t static assertion.

@kokol16
kokol16 force-pushed the fix/roll-populationCount branch from f3b2e8b to 96c0f0a Compare September 3, 2026 19:38

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks for addressing the feedback.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 3, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Sep 3, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 4, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for addressing the feedback and adding 64-bit GPU kernel loop support! The macro overloading design in tensorflow/core/util/gpu_kernel_helper.h is clean and preserves backward compatibility.

Before this pull request can be approved and merged, please address the following required change:

1. Graceful Status Handling and Resource Leak Prevention in Roll OpKernel (Blocking)

In tensorflow/core/kernels/roll_op_gpu.cu.cc:

    auto config_or = GetGpuLaunchConfig64(num_elements, d);
    CHECK_OK(config_or.status());  // Crash OK
    const GpuLaunchConfig64& cfg = *config_or;

In TensorFlow op kernels, using CHECK_OK is not permitted because any launch configuration failure will terminate the entire process unconditionally rather than returning a clean error status to the calling session.

Additionally, device buffers (dim_buf, thres_buf, and range_buf) are currently allocated via d.allocate before GetGpuLaunchConfig64 is called. If GetGpuLaunchConfig64 fails or returns early, those buffers leak on the device since d.deallocate is only called after the kernel launch.

Required Action:
Move GetGpuLaunchConfig64 before the buffer allocations (immediately after checking if (!num_elements) return;), and propagate the error status through OpKernelContext:

    if (!num_elements) return;
    const GPUDevice& d = context->eigen_device<GPUDevice>();

    auto config_or = GetGpuLaunchConfig64(num_elements, d);
    if (!config_or.ok()) {
      const_cast<OpKernelContext*>(context)->SetStatus(config_or.status());
      return;
    }
    const GpuLaunchConfig64& cfg = *config_or;

    auto dim_bytes = sizeof(int32_t) * dim_size.size();
    auto dim_buf = d.allocate(dim_bytes);

    auto thres_bytes = sizeof(int32_t) * threshold.size();
    auto thres_buf = d.allocate(thres_bytes);

    auto range_bytes = sizeof(int64_t) * dim_range.size();
    auto range_buf = d.allocate(range_bytes);

    d.memcpyHostToDevice(dim_buf, dim_size.data(), dim_bytes);
    d.memcpyHostToDevice(thres_buf, threshold.data(), thres_bytes);
    d.memcpyHostToDevice(range_buf, dim_range.data(), range_bytes);

(Alternatively, you may update Roll::operator() in tensorflow/core/kernels/roll_op.h to accept OpKernelContext* context without const if you prefer strict const-correctness).


2. Recommended Polish and Test Enhancements

We also recommend the following improvements:

  1. 64-bit Accumulator in Test:
    In tensorflow/core/util/gpu_kernel_helper_test.cu.cc, change std::accumulate(outbuf_host, outbuf_host + bufsize, 0) to pass int64_t{0} as the initial accumulator value to prevent potential signed 32-bit integer overflow if work_element_count exceeds 2^31 - 1 elements.

  2. Test Coverage for CUDA_1D_KERNEL_LOOP:
    In tensorflow/core/util/gpu_kernel_helper_test.cu.cc, consider adding a test kernel verifying CUDA_1D_KERNEL_LOOP(out_idx, nthreads, int64_t) and exercising edge element counts (work_element_count = 0 and work_element_count = 1).

  3. Modernize Deprecation Comment:
    In tensorflow/core/util/gpu_kernel_helper.h, update the comment above GPU_1D_KERNEL_LOOP to reflect the template parameter:
    // Deprecated, use 'for(T i : GpuGridRangeX<T>(n))' instead.

  4. Clean up Test Kernel:
    In tensorflow/core/util/gpu_kernel_helper_test.cu.cc, remove the redundant if (x < 0) break; guard in Count1DInt64 since x is int64_t.

  5. Canonical Error Macro in population_count_op_gpu.cu.cc:
    In tensorflow/core/kernels/population_count_op_gpu.cu.cc, consider using OP_REQUIRES_OK(c, config_or.status()); for idiomatic error handling.

Report configuration failures through the kernel context before
allocating temporary buffers, so Roll returns an error instead of
aborting the process.

Use the same error handling in PopulationCount and extend the typed
loop tests to cover both aliases, edge cases, and 64-bit totals.
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Oct 2, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for addressing the feedback and refining the PR. The new int64_t macro overloading, isolated status propagation via OP_REQUIRES_OK, and explicit unit test boundary validations are implemented flawlessly. We only have a few minor Include-What-You-Use (IWYU) requirements before we can merge this cleanly.

Required Polish & Nits

1. Missing <type_traits> Include (IWYU)
In tensorflow/core/util/gpu_kernel_helper_test.cu.cc:
You correctly added static_assert(std::is_same<...>::value) checks, but <type_traits> isn't directly included. Please add it to maintain IWYU hygiene:

#include <time.h>

#include <algorithm>
#include <cstdint>
#include <numeric>
#include <type_traits>

#include "tensorflow/core/lib/core/status_test_util.h"

2. Missing canonical op_kernel.h header
In tensorflow/core/kernels/roll_op_gpu.cu.cc:
You are now invoking OP_REQUIRES_OK, but its canonical header isn't explicitly included (only transitively). Please add it explicitly:

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor_types.h"

The Roll kernel uses OP_REQUIRES_OK, and the GPU helper tests use
std::is_same. Include their public headers directly so the dependencies
are explicit and the files follow TensorFlow's IWYU requirements.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the updates! The macro overloading is elegant and robust, preserving exact backward compatibility for all existing callers across the repository while safely handling 64-bit boundaries. The isolated status propagation via OP_REQUIRES_OK and the missing headers have been flawlessly resolved.

Before we can approve and merge this PR, there are a few issues in the surrounding code that must be addressed:

  1. Loop-Invariant Calculations: In tensorflow/core/kernels/roll_op_gpu.cu.cc:41-47, stride and shift are recomputed inside the hot loop. Moving them out is required to save expensive device-side integer divisions.
  2. Process Termination on Launch Failure: In roll_op_gpu.cu.cc:83 and population_count_op_gpu.cu.cc:84, GpuLaunchKernel is wrapped in TF_CHECK_OK, which crashes the process if launch fails. Using OP_REQUIRES_OK (and managing temporary allocations with context->allocate_temp()) is required to propagate errors gracefully.
  3. Namespace Encapsulation: In population_count_op_gpu.cu.cc:35-66, the file-scope PopulationCountKernel must be placed within an anonymous namespace namespace { ... } inside namespace functor to prevent potential ODR violations.

Please apply these changes so we can proceed with the final review and merge.

Compute Roll strides and shifts on the host instead of repeating the
work for every GPU element. Use temporary tensors so error returns
release the buffers, and return launch errors instead of stopping the
whole process.

Keep PopulationCount kernel symbols local to the source file so they
cannot conflict with other files. Add a GPU Roll test covering graph
and eager execution with all four combinations of shift and axis types.
These files use int64_t but only got <cstdint> through other headers.
Reviewers asked for the direct include on TopK and ResizeBilinear
because relying on the indirect one broke their Windows build.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the quick updates, and sorry for the number of review rounds on this PR. Moving stride and shift out of the loop and using allocate_temp() is exactly what we asked for.

To finish this, we've gone through the whole review history and narrowed it down to one last item.

Retractions

None. All earlier asks are addressed, and we're not adding any of the further style or allocation suggestions we considered.

Final asks

This is the only remaining item. We won't add new asks once it lands.

  1. 32-bit overflow in RollKernel. In tensorflow/core/kernels/roll_op_gpu.cu.cc, shift, indx and shifted_indx are still int. shift can be as large as dim_size[i] and indx up to dim_size[i] - 1. For a dimension with more than about 2^30 elements, indx + shift overflows int. That is the large-tensor case this PR is fixing. Please make them int64_t:

          const int64_t stride = strides[i];
          const int64_t shift = shifts[i];
          const int64_t indx = (out_idx / stride) % dim_size[i];
          const int64_t shifted_indx = (indx + shift) % dim_size[i];
          offset += (shifted_indx - indx) * stride;

@nithyak0204 nithyak0204 added the stat:awaiting response Status - Awaiting response from author label Oct 5, 2026
TensorFlow merged the first version of this PR while later review
fixes were still pending. Keep the expanded GPU loop test when
merging master so the Roll and PopulationCount fixes apply cleanly.

Include Abseil’s span header directly in roll_op.h because that
header uses absl::Span.
@nithyak0204 nithyak0204 removed the stat:awaiting response Status - Awaiting response from author label Oct 8, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 October 8, 2026 08:53
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 8, 2026
@dmiltr3

dmiltr3 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Thank you for the quick updates and for addressing the final binding asks flawlessly! The 32-bit integer overflow in RollKernel has been safely eliminated by upgrading the inner loop variables to int64_t. In addition, the int64_t macro overloading for the GPU kernel loop has been implemented elegantly and behaves exactly as expected, preserving backward compatibility while providing the necessary 64-bit precision for large tensors. The inclusion of isolated status propagation using OP_REQUIRES_OK is also implemented perfectly. The logic is approved!

However, your branch currently has merge conflicts with the latest master branch and no longer applies cleanly to the codebase (specifically in files like tensorflow/core/kernels/roll_op_gpu.cu.cc, tensorflow/core/kernels/BUILD, etc.).

Could you please merge/rebase the latest master into your branch and resolve the conflicts? Once that's done, we will run the internal presubmit tests and proceed with the merge.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! The fix correctly resolves the 32-bit overflow by using int64_t in RollKernel, and all internal presubmit tests have passed cleanly.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 8, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 9, 2026
@nithyak0204

Copy link
Copy Markdown

Hi @kokol16, Can you please resolve the conflicts? Thank you!

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed ready to pull PR ready for merge process labels Oct 13, 2026
- 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.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up on the earlier comments: this pull request currently has merge conflicts with master in tensorflow/core/kernels/roll_op_gpu.cu.cc and tensorflow/core/kernels/BUILD. Marking the review status as requesting changes while awaiting the rebase and conflict resolution so we can re-run checks and proceed with merging.

Final asks

  1. Rebase the branch onto the latest master and resolve the merge conflicts in tensorflow/core/kernels/roll_op_gpu.cu.cc and tensorflow/core/kernels/BUILD.

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Oct 20, 2026
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 23, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 23, 2026
@nithyak0204 nithyak0204 removed stat:awaiting response Status - Awaiting response from author kokoro:force-run Tests on submitted change labels Oct 26, 2026
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Nov 5, 2026
@dmiltr3 dmiltr3 added the ready to pull PR ready for merge process label Nov 5, 2026
@nithyak0204 nithyak0204 removed the ready to pull PR ready for merge process label Nov 5, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 November 5, 2026 04:52
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Nov 5, 2026
@keerthanakadiri keerthanakadiri removed the awaiting review Pull request awaiting review label Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow prtype:bugfix PR to fix a bug size:M CL Change Size: Medium

Projects

Status: Approved by Reviewer

Development

Successfully merging this pull request may close these issues.

[CUDA] illegal memory read on Roll [CUDA] illegal memory write on PopulationCount

5 participants