Skip to content

Fix GPU bucketize op truncation when boundaries contain fractional values - #128013

Closed
bodapatisaikrishna wants to merge 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries
Closed

bodapatisaikrishna wants to merge 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/70343-bucketize-gpu-boundaries

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

tf.raw_ops.Bucketize / math_ops._bucketize returns incorrect results on GPU when boundaries contain fractional values and the input tensor has integer dtype (int32 or int64). Reported in #70343.

Reproducer

import tensorflow as tf
from tensorflow.python.ops.gen_math_ops import bucketize

# input=[0, 1, 2, 3], boundaries=[0.1, 1.1]
with tf.device('/CPU:0'):
  print(bucketize(input=[0, 1, 2, 3], boundaries=[0.1, 1.1]))
  # Returns: [0, 1, 2, 2] (Correct)

with tf.device('/GPU:0'):
  print(bucketize(input=[0, 1, 2, 3], boundaries=[0.1, 1.1]))
  # Returned: [1, 2, 2, 2] (Bug: 0 was placed into bucket 1 instead of 0)

Root Cause

In tensorflow/core/kernels/bucketize_op_gpu.cu.cc, BucketizeCustomKernel performed boundary comparison at line 66 as follows:

if (!(value < static_cast<T>(boundaries[l]))) {

The boundaries attribute in Bucketize is typed list(float), and boundaries[l] is a float. When the input type T is an integer type (int32_t or int64_t), static_cast<T>(boundaries[l]) truncated the floating-point boundary towards zero:

  • static_cast<int32_t>(0.1f) truncated to 0
  • static_cast<int32_t>(1.1f) truncated to 1

This converted the boundaries [0.1, 1.1] into [0, 1]. For value = 0, the kernel evaluated !(0 < 0) $\to$ true, falsely concluding that $0 \ge 0.1$ and assigning 0 to bucket 1 instead of bucket 0.

In contrast:

  • On CPU (tensorflow/core/kernels/bucketize_op.cc), std::upper_bound compares input(i) (type T) against boundaries_vector (type float), which under C++ arithmetic promotions converts integer inputs to float (and float boundaries to double if input is double), preserving fractional boundary precision.
  • In XLA (tensorflow/compiler/tf2xla/kernels/bucketize_op.cc), inputs are explicitly converted to F32 (or F64 if DT_DOUBLE).

Solution

This PR determines the appropriate comparison type CompType based on input type T:

using CompType = typename std::conditional<std::is_same<T, double>::value,
                                           double, float>::type;

and evaluates the boundary comparison in CompType:

if (!(static_cast<CompType>(value) <
      static_cast<CompType>(boundaries[l]))) {
  • For double inputs, boundaries[l] is promoted to double.
  • For float, int32_t, and int64_t inputs, values are promoted to float.

This eliminates boundary truncation on GPU and aligns GPU behavior with CPU and XLA implementations.

Testing

  • In tensorflow/python/kernel_tests/math_ops/bucketize_op_test.py:
    • Added testIntWithFloatBoundaries verifying int32 and int64 inputs 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].
    • Added testInt64 and testDouble to cover all supported dtypes.
    • Enabled use_gpu=True in test sessions.
  • In tensorflow/compiler/tests/bucketize_op_test.py:
    • Added testIntWithFloatBoundaries testing int32 and int64 under XLA.
  • All 10 tests in bucketize_op_test.py pass cleanly.

Fixes #70343.

…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
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Sep 24, 2026

@gemini-code-assist gemini-code-assist Bot 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.

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.

Comment on lines +63 to +64
using CompType = typename std::conditional<std::is_same<T, double>::value,
double, float>::type;

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.

medium

Since TensorFlow requires C++17, we can use the more concise and modern template aliases std::conditional_t and std::is_same_v instead of the verbose C++11 typename std::conditional<...>::type and ...::value.

  using CompType = std::conditional_t<std::is_same_v<T, double>, double, float>;

Comment on lines +74 to +75
if (!(static_cast<CompType>(value) <
static_cast<CompType>(boundaries[l]))) {

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.

medium

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.

@nithyak0204 nithyak0204 self-assigned this Sep 25, 2026
@nithyak0204
nithyak0204 requested a review from a team September 25, 2026 06:02
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 25, 2026
@nithyak0204 nithyak0204 added the prtype:bugfix PR to fix a bug label Sep 25, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 25, 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 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.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Thanks for the review and suggestions, @dmiltr3!

I've updated tensorflow/core/kernels/bucketize_op_gpu.cu.cc in commit 0732d34:

  1. Modernized CompType using C++17 template aliases (std::conditional_t and std::is_same_v).
  2. Hoisted CompType value_cast = static_cast<CompType>(value); outside the inner binary search while loop to eliminate redundant casting on each search step.
  3. Verified #include <type_traits> is present at the top of the file.

Ready for the automated test suite to run. Thanks!

@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 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!

@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 25, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 28, 2026
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
… < 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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
copybara-service Bot pushed a commit that referenced this pull request Sep 28, 2026
…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
@nithyak0204

Copy link
Copy Markdown

Hi @bodapatisaikrishna,

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!.

bodapatisaikrishna added a commit to bodapatisaikrishna/bodapatisaikrishna that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Closed/Rejected

Development

Successfully merging this pull request may close these issues.

bucketize -function wrong results on GPU

3 participants