Repository navigation
Conversation
dmiltr3
left a comment
There was a problem hiding this comment.
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);
}
}|
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. |
f3b2e8b to
96c0f0a
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
LGTM! Thanks for addressing the feedback.
dmiltr3
left a comment
There was a problem hiding this comment.
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:
-
64-bit Accumulator in Test:
Intensorflow/core/util/gpu_kernel_helper_test.cu.cc, changestd::accumulate(outbuf_host, outbuf_host + bufsize, 0)to passint64_t{0}as the initial accumulator value to prevent potential signed 32-bit integer overflow ifwork_element_countexceeds 2^31 - 1 elements. -
Test Coverage for
CUDA_1D_KERNEL_LOOP:
Intensorflow/core/util/gpu_kernel_helper_test.cu.cc, consider adding a test kernel verifyingCUDA_1D_KERNEL_LOOP(out_idx, nthreads, int64_t)and exercising edge element counts (work_element_count = 0andwork_element_count = 1). -
Modernize Deprecation Comment:
Intensorflow/core/util/gpu_kernel_helper.h, update the comment aboveGPU_1D_KERNEL_LOOPto reflect the template parameter:
// Deprecated, use 'for(T i : GpuGridRangeX<T>(n))' instead. -
Clean up Test Kernel:
Intensorflow/core/util/gpu_kernel_helper_test.cu.cc, remove the redundantif (x < 0) break;guard inCount1DInt64sincexisint64_t. -
Canonical Error Macro in
population_count_op_gpu.cu.cc:
Intensorflow/core/kernels/population_count_op_gpu.cu.cc, consider usingOP_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.
dmiltr3
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:
- Loop-Invariant Calculations: In
tensorflow/core/kernels/roll_op_gpu.cu.cc:41-47,strideandshiftare recomputed inside the hot loop. Moving them out is required to save expensive device-side integer divisions. - Process Termination on Launch Failure: In
roll_op_gpu.cu.cc:83andpopulation_count_op_gpu.cu.cc:84,GpuLaunchKernelis wrapped inTF_CHECK_OK, which crashes the process if launch fails. UsingOP_REQUIRES_OK(and managing temporary allocations withcontext->allocate_temp()) is required to propagate errors gracefully. - Namespace Encapsulation: In
population_count_op_gpu.cu.cc:35-66, the file-scopePopulationCountKernelmust be placed within an anonymous namespacenamespace { ... }insidenamespace functorto 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
left a comment
There was a problem hiding this comment.
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.
-
32-bit overflow in
RollKernel. Intensorflow/core/kernels/roll_op_gpu.cu.cc,shift,indxandshifted_indxare stillint.shiftcan be as large asdim_size[i]andindxup todim_size[i] - 1. For a dimension with more than about 2^30 elements,indx + shiftoverflowsint. That is the large-tensor case this PR is fixing. Please make themint64_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;
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.
|
Thank you for the quick updates and for addressing the final binding asks flawlessly! The 32-bit integer overflow in However, your branch currently has merge conflicts with the latest Could you please merge/rebase the latest |
dmiltr3
left a comment
There was a problem hiding this comment.
LGTM! The fix correctly resolves the 32-bit overflow by using int64_t in RollKernel, and all internal presubmit tests have passed cleanly.
|
Hi @kokol16, Can you please resolve the conflicts? Thank you! |
- 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
left a comment
There was a problem hiding this comment.
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
- Rebase the branch onto the latest
masterand resolve the merge conflicts intensorflow/core/kernels/roll_op_gpu.cu.ccandtensorflow/core/kernels/BUILD.
Extended
GPU_1D_KERNEL_LOOP/CUDA_1D_KERNEL_LOOPwith an optional index type,updated
population_countandrollGPU kernels to useint64_tsizes andGetGpuLaunchConfig64, and addsgpu_kernel_helper_testcoverage.Addressed review feedback on #112249:
int64_tGetGpuLaunchConfig64/GpuLaunchConfig64int64_tmacro variant ingpu_kernel_helper_test.cu.ccFixes #109520
Fixes #104077
Supersedes #112249