Repository navigation
Fix GPU bucketize op truncation when boundaries contain fractional values - #128013
bodapatisaikrishna wants to merge 2 commits into
Conversation
…lues In tensorflow/core/kernels/bucketize_op_gpu.cu.cc, BucketizeCustomKernel previously cast each floating-point boundary to the input type T: static_cast<T>(boundaries[l]). When T is an integer type (int32 or int64), any fractional boundary values were truncated towards zero (e.g. 0.1f was truncated to 0, 1.1f to 1), leading to incorrect bucket assignments on GPU. In contrast, CPU and XLA kernels promote input types to floating point so that fractional boundaries are accurately evaluated. This change determines the comparison type CompType (double for double inputs, float for float and integer inputs) and promotes operands to CompType before comparison. This matches CPU and XLA semantics and preserves fractional boundary precision. Fixes tensorflow#70343
There was a problem hiding this comment.
Code Review
This pull request ensures that fractional boundaries are not truncated when bucketizing integer inputs on GPU, aligning the GPU kernel behavior with CPU and XLA. It introduces a comparison type (CompType) to cast inputs and boundaries appropriately during the bucketization process, and adds comprehensive unit tests for various data types and fractional boundaries. The review feedback suggests modernizing the C++ code using C++17 template aliases (std::conditional_t and std::is_same_v) and optimizing performance by casting the loop-invariant value to CompType outside of the binary search loop.
| using CompType = typename std::conditional<std::is_same<T, double>::value, | ||
| double, float>::type; |
There was a problem hiding this comment.
| if (!(static_cast<CompType>(value) < | ||
| static_cast<CompType>(boundaries[l]))) { |
There was a problem hiding this comment.
Casting value to CompType inside the binary search loop is redundant because value is loop-invariant. To optimize performance in this GPU kernel, consider casting value once outside the while loop (e.g., by declaring const CompType comp_value = static_cast<CompType>(value); before the loop) and using comp_value in the comparison.
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for your pull request!
We appreciate the fix for issue #70343 to correctly handle fractional boundaries when bucketizing integer inputs on the GPU. The implementation accurately bridges the discrepancy with CPU and XLA behavior.
To ensure the kernel runs efficiently and cleanly built across our internal infrastructure, we would like to formally request the changes identified by our automated code review tool: modernizing the C++ templates to C++17 and hoisting the CompType cast completely outside the GPU_1D_KERNEL_LOOP's inner binary search loop. Additionally, the file lacks <type_traits>, which causes a compilation error internally when using the newly added std::conditional_t and std::is_same_v templates.
Please apply the following optimized code block to tensorflow/core/kernels/bucketize_op_gpu.cu.cc:
#include <type_traits> // Please add this to the includes at the top
// ... (in the BucketizeCustomKernel function) ...
// For double input, compare as double. For float and integer inputs, compare
// as float to match CPU and XLA behavior without truncating fractional
// boundaries.
using CompType = std::conditional_t<std::is_same_v<T, double>, double, float>;
GPU_1D_KERNEL_LOOP(i, size_in) {
T value = in[i];
CompType value_cast = static_cast<CompType>(value);
int32_t bucket = 0;
int32_t count = size_boundaries;
while (count > 0) {
int32_t l = bucket;
int32_t step = count / 2;
l += step;
if (!(value_cast < static_cast<CompType>(boundaries[l]))) {
bucket = ++l;
count -= step + 1;
} else {
count = step;
}
}
out[i] = bucket;
}Once updated, we will gladly kick off our internal automated test suite again.
Address review feedback on GPU bucketize kernel: - Modernize CompType alias using C++17 std::conditional_t and std::is_same_v. - Hoist static_cast<CompType>(value) outside the inner binary search loop to avoid redundant casts per search iteration.
|
Thanks for the review and suggestions, @dmiltr3! I've updated
Ready for the automated test suite to run. Thanks! |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for your pull request and for correctly updating the C++ template types as requested! The implementation looks great and correctly avoids fractional truncation on GPU.
The internal automated test suite has completed successfully. I have reviewed the build-windows-x86 failure on the GitHub CI and verified it is a known infrastructure issue with the CI script, not related to your code changes.
We are moving forward with the approval. Thank you for your contribution!
…roject` after [this commit](openxla/xla@5070936). `tf_http_archive` with the version `5.8.3` is preferred over Bazel module because the latest available version in Bazel is `"5.4.5.bcr.9"` which has bugs. Reverts changelist 989582731 FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34 PiperOrigin-RevId: 988528432
…roject` after [this commit](openxla/xla@5070936). `tf_http_archive` with the version `5.8.3` is preferred over Bazel module because the latest available version in Bazel is `"5.4.5.bcr.9"` which has bugs. Reverts changelist 989582731 FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34 PiperOrigin-RevId: 988528432
… < 1 ULP. Previously, `ElementalIrEmitter::EmitExpm1` and `RewriteExpm1Pattern` in `expand_float_ops.cc` lowered `expm1(x)` as a piecewise expression: - `|x| > 0.5`: `exp(x) - 1` - `|x| <= 0.5`: `tanh(x / 2) * (exp(x) + 1)` This achieved a worst-case error of 6 ULP in float32 and > 5 ULP in float64. Replace this piecewise lowering with a dedicated intrinsic (`xla::codegen::intrinsics::Expm1`) for float32 and float64. The new implementation reduces `x = n * ln(2) + r` into `[-ln(2)/2, ln(2)/2]`, approximates `e^r - 1` with a Sollya minimax polynomial (degree 7 for `float32`, degree 12 for `float64`), and reconstructs `expm1(x) = (2^n - 1) + 2^n * (e^r - 1)` without catastrophic cancellation. FMA instructions are used to preserve low-order bits across the quadratic term (`0.5 * r_hi^2`) and intermediate sums, preventing double rounding across power-of-two spacing boundaries. This bounds worst-case error to < 0.83 ULP for `float32` (verified exhaustively across all 2^32 inputs) and < 1 ULP for `float64`, while using fewer instructions than evaluating both `tanh(x / 2)` and `exp(x)`. Tighten the CPU `Expm1` error bound in `exhaustive_unary_test_functions.cc` to 1 ULP (`distance_err(1)`). Reverts changelist 989582731 FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34 PiperOrigin-RevId: 979775450
…ramming.
Introduces `jax.experimental.thunky`, a DSL and MLIR dialect for inspecting, authoring, splicing, and executing XLA:GPU `ThunkExecutor` programs directly from Python:
- Adds the `thunky` MLIR dialect (`thunky_dialect.td`, `thunky_ops.td`, C-API, and nanobind extension `_thunky_ext`) to CPU-safe `jaxlib` (`jax._src.lib.thunky_dialect`), providing `dissect_executable`, `jax_executable_to_mlir`, buffer/token types (`!thunky.buffer<size>`, `!thunky.token`), and operations for memory ops, PTX/Mosaic kernels, control flow (`cond`, `while`), multi-stream execution (`async_start`, `async_done`), and multi-GPU NCCL collectives (`all_reduce`, `reduce_scatter`, `all_gather`, `all_to_all`, `collective_permute`).
- Adds XLA:GPU custom call thunk lowering ("thunky.inline_module") to the CUDA PJRT plugin (`//third_party/py/jax/jaxlib/thunky:thunky_support`), lowering `thunky` MLIR blocks directly into XLA `SequentialThunk`, `ConditionalThunk`, `WhileThunk`, `AsyncStartThunk`/`AsyncDoneThunk`, and NCCL collective thunks at compile time.
- Adds the Python Jaxpr DSL (`jax.experimental.thunky` / `jax._src.thunky.thunky`) with `@thunky.jit`, scratch buffer allocation, zero-copy buffer slicing and `Ref` indexing, thunk splicing (`thunky.call_jax`), and top-level eager execution (`CompiledThunkModule.execute`) via `@jax.jit` + "thunky.inline_module".
- Adds user guide documentation (`docs/thunky.md`) and comprehensive unit tests (`tests/thunky_test.py`).
Reverts changelist 989582731
FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34
PiperOrigin-RevId: 980526939
…ramming.
Introduces `jax.experimental.thunky`, a DSL and MLIR dialect for inspecting, authoring, splicing, and executing XLA:GPU `ThunkExecutor` programs directly from Python:
- Adds the `thunky` MLIR dialect (`thunky_dialect.td`, `thunky_ops.td`, C-API, and nanobind extension `_thunky_ext`) to CPU-safe `jaxlib` (`jax._src.lib.thunky_dialect`), providing `dissect_executable`, `jax_executable_to_mlir`, buffer/token types (`!thunky.buffer<size>`, `!thunky.token`), and operations for memory ops, PTX/Mosaic kernels, control flow (`cond`, `while`), multi-stream execution (`async_start`, `async_done`), and multi-GPU NCCL collectives (`all_reduce`, `reduce_scatter`, `all_gather`, `all_to_all`, `collective_permute`).
- Adds XLA:GPU custom call thunk lowering ("thunky.inline_module") to the CUDA PJRT plugin (`//third_party/py/jax/jaxlib/thunky:thunky_support`), lowering `thunky` MLIR blocks directly into XLA `SequentialThunk`, `ConditionalThunk`, `WhileThunk`, `AsyncStartThunk`/`AsyncDoneThunk`, and NCCL collective thunks at compile time.
- Adds the Python Jaxpr DSL (`jax.experimental.thunky` / `jax._src.thunky.thunky`) with `@thunky.jit`, scratch buffer allocation, zero-copy buffer slicing and `Ref` indexing, thunk splicing (`thunky.call_jax`), and top-level eager execution (`CompiledThunkModule.execute`) via `@jax.jit` + "thunky.inline_module".
- Adds user guide documentation (`docs/thunky.md`) and comprehensive unit tests (`tests/thunky_test.py`).
Reverts changelist 989582731
FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34
PiperOrigin-RevId: 980526939
…ramming.
Introduces `jax.experimental.thunky`, a DSL and MLIR dialect for inspecting, authoring, splicing, and executing XLA:GPU `ThunkExecutor` programs directly from Python:
- Adds the `thunky` MLIR dialect (`thunky_dialect.td`, `thunky_ops.td`, C-API, and nanobind extension `_thunky_ext`) to CPU-safe `jaxlib` (`jax._src.lib.thunky_dialect`), providing `dissect_executable`, `jax_executable_to_mlir`, buffer/token types (`!thunky.buffer<size>`, `!thunky.token`), and operations for memory ops, PTX/Mosaic kernels, control flow (`cond`, `while`), multi-stream execution (`async_start`, `async_done`), and multi-GPU NCCL collectives (`all_reduce`, `reduce_scatter`, `all_gather`, `all_to_all`, `collective_permute`).
- Adds XLA:GPU custom call thunk lowering ("thunky.inline_module") to the CUDA PJRT plugin (`//third_party/py/jax/jaxlib/thunky:thunky_support`), lowering `thunky` MLIR blocks directly into XLA `SequentialThunk`, `ConditionalThunk`, `WhileThunk`, `AsyncStartThunk`/`AsyncDoneThunk`, and NCCL collective thunks at compile time.
- Adds the Python Jaxpr DSL (`jax.experimental.thunky` / `jax._src.thunky.thunky`) with `@thunky.jit`, scratch buffer allocation, zero-copy buffer slicing and `Ref` indexing, thunk splicing (`thunky.call_jax`), and top-level eager execution (`CompiledThunkModule.execute`) via `@jax.jit` + "thunky.inline_module".
- Adds user guide documentation (`docs/thunky.md`) and comprehensive unit tests (`tests/thunky_test.py`).
Reverts changelist 989582731
FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34
PiperOrigin-RevId: 980526939
…ort with OR-Tools AutoRadixSort. Replaces unconditional `std::sort` in `HeapSimulator::MakeFreeChunksList` with an adaptive 3-tier sort: 1. Small arrays (<3000) - `absl::c_sort` 2. Nearly-sorted data use `absl::c_sort` with zero swaps. 3. Large unordered arrays (N >= 3000): Dispatches to zero-allocation `operations_research::AutoRadixSort`, reusing scratch buffer without dynamic heap reallocs. Reverts changelist 989582731 FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34 PiperOrigin-RevId: 986080812
…ort with OR-Tools AutoRadixSort. Replaces unconditional `std::sort` in `HeapSimulator::MakeFreeChunksList` with an adaptive 3-tier sort: 1. Small arrays (<3000) - `absl::c_sort` 2. Nearly-sorted data use `absl::c_sort` with zero swaps. 3. Large unordered arrays (N >= 3000): Dispatches to zero-allocation `operations_research::AutoRadixSort`, reusing scratch buffer without dynamic heap reallocs. Reverts changelist 989582731 FUTURE_COPYBARA_INTEGRATE_REVIEW=#128013 from bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries 0732d34 PiperOrigin-RevId: 986080812
|
Seems auto-merge is not happening but the changes are merged into master via commit e2c7dee, so we can close this PR. Thank you for the contribution and helping improve TensorFlow!. |
tf.raw_ops.Bucketize/math_ops._bucketizereturns incorrect results on GPU when boundaries contain fractional values and the input tensor has integer dtype (int32orint64). Reported in #70343.Reproducer
Root Cause
In
tensorflow/core/kernels/bucketize_op_gpu.cu.cc,BucketizeCustomKernelperformed boundary comparison at line 66 as follows:The boundaries attribute in
Bucketizeis typedlist(float), andboundaries[l]is afloat. When the input typeTis an integer type (int32_torint64_t),static_cast<T>(boundaries[l])truncated the floating-point boundary towards zero:static_cast<int32_t>(0.1f)truncated to0static_cast<int32_t>(1.1f)truncated to1This converted the boundaries$\to$ $0 \ge 0.1$ and assigning
[0.1, 1.1]into[0, 1]. Forvalue = 0, the kernel evaluated!(0 < 0)true, falsely concluding that0to bucket 1 instead of bucket 0.In contrast:
tensorflow/core/kernels/bucketize_op.cc),std::upper_boundcomparesinput(i)(typeT) againstboundaries_vector(typefloat), which under C++ arithmetic promotions converts integer inputs tofloat(andfloatboundaries todoubleif input isdouble), preserving fractional boundary precision.tensorflow/compiler/tf2xla/kernels/bucketize_op.cc), inputs are explicitly converted toF32(orF64ifDT_DOUBLE).Solution
This PR determines the appropriate comparison type
CompTypebased on input typeT:and evaluates the boundary comparison in
CompType:doubleinputs,boundaries[l]is promoted todouble.float,int32_t, andint64_tinputs, values are promoted tofloat.This eliminates boundary truncation on GPU and aligns GPU behavior with CPU and XLA implementations.
Testing
tensorflow/python/kernel_tests/math_ops/bucketize_op_test.py:testIntWithFloatBoundariesverifyingint32andint64inputs with fractional boundaries[0.1, 1.1](issue bucketize -function wrong results on GPU #70343 reproducer), negative and positive fractional boundaries[-1.5, -0.5, 0.5, 1.5], and near-integer fractional boundaries[0.999, 1.001].testInt64andtestDoubleto cover all supported dtypes.use_gpu=Truein test sessions.tensorflow/compiler/tests/bucketize_op_test.py:testIntWithFloatBoundariestestingint32andint64under XLA.bucketize_op_test.pypass cleanly.Fixes #70343.