Skip to content

[LinSpace] Register half and bfloat16 OpKernels for LinSpace - #126450

Merged
copybara-service[bot] merged 10 commits into
tensorflow:masterfrom
adi-IL:fix/linspace-bfloat16-half
Oct 15, 2026
Merged

copybara-service[bot] merged 10 commits into
tensorflow:masterfrom
adi-IL:fix/linspace-bfloat16-half

Conversation

@adi-IL

@adi-IL adi-IL commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Description

The LinSpace op definition in tensorflow/core/ops/math_ops.cc declares support for T: {bfloat16, half, float, double}. However, kernel registrations in tensorflow/core/kernels/sequence_ops.cc only registered DT_FLOAT and DT_DOUBLE.

Calling tf.raw_ops.LinSpace with bfloat16 or half inputs failed with an OpKernel not found error.

Changes

  • Explicitly cast step calculations and loop indices in LinSpaceOp::Compute using static_cast<T> so Eigen::half and bfloat16 arithmetic compiles cleanly.
  • Register TF_CALL_half and TF_CALL_bfloat16 for LinSpaceOp on DEVICE_CPU and DEVICE_DEFAULT.
  • Add test coverage for DT_HALF and DT_BFLOAT16 in sequence_ops_test.cc.

@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Aug 30, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team August 31, 2026 06:43
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Aug 31, 2026
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Aug 31, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Aug 31, 2026
@dmiltr3
dmiltr3 self-requested a review August 31, 2026 22:22
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 31, 2026
@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Approved by Reviewer in PR Queue Aug 31, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 1, 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.

Internal presubmit checks failed because the changes in this pull request are based on an older commit and need to be synced with the latest changes on master in tensorflow/core/kernels/sequence_ops.cc.

Please rebase your branch on the latest master branch (or merge upstream/master) and push the update to trigger a fresh automated presubmit run:

git fetch upstream master
git checkout fix/linspace-bfloat16-half
git rebase upstream/master
git push --force-with-lease

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Sep 3, 2026
The LinSpace op definition in tensorflow/core/ops/math_ops.cc declares
support for T: {bfloat16, half, float, double}. However, the kernel
registrations in tensorflow/core/kernels/sequence_ops.cc only registered
DT_FLOAT and DT_DOUBLE.

Cast step calculations in LinSpaceOp::Compute to static_cast<T> so half
and bfloat16 arithmetic compile cleanly, register TF_CALL_half and
TF_CALL_bfloat16 on CPU and default devices, and add test cases in
sequence_ops_test.cc.
@adi-IL
adi-IL force-pushed the fix/linspace-bfloat16-half branch from 9f7f97e to 034aeba Compare September 3, 2026 13:19
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Sep 3, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 September 7, 2026 12:19
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 7, 2026
@adi-IL

adi-IL commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest master and force-pushed (466e4ba).

Public CI after the rebase:

  • linux cpu / cuda / cuda13 / arm64: green
  • windows-x86: still red (digging; may be self-hosted infra)

Ready for another look when you have a chance.

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

Hi @adi-IL,

Thanks for the update and for syncing with master!

It looks like the build-windows-x86 / build-and-test GitHub Actions CI check is currently failing on the latest commit. This is typically a compilation error caused by MSVC on Windows, which can be stricter about implicit type conversions and template instantiations than GCC/Clang.

Specifically, in sequence_ops.cc, casting the integer loop variables directly to Eigen::half or bfloat16 using static_cast<T>(num - 1) usually fails on MSVC due to missing direct constructors or ambiguous cast operators from int types to these custom float types.

Could you please check the build-windows-x86 workflow logs to confirm the error, and update the casts to route through a standard floating-point type first (e.g., double or float)?

For example, modifying the logic to something like this should resolve the ambiguous casts on MSVC:

const T step = (stop - start) / static_cast<T>(static_cast<double>(num - 1));
for (Tnum i = 1; i < num - 1; ++i) {
  flat(i) = start + step * static_cast<T>(static_cast<double>(i));
}

Once the code builds successfully across all CI environments, we can proceed with merging this PR. Thanks!

@adi-IL

adi-IL commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3 - updated the LinSpace casts to route ints through double before converting to T (for MSVC half/bfloat16):

const T step =
    (stop - start) / static_cast<T>(static_cast<double>(num - 1));
for (Tnum i = 1; i < num - 1; ++i) {
  flat(i) = start + step * static_cast<T>(static_cast<double>(i));
}

Pushed in 85d2ef2. Waiting on a fresh build-windows-x86 run.

@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! We appreciate your efforts to improve LinSpace support for half and bfloat16.

While internal testing in the internal codebase (Linux/Clang) compiled and passed successfully, the Windows MSVC builder on GitHub CI (CI/build-windows-x86 / build-and-test) reported compilation failures.

The build failure on MSVC is likely caused by the double casts introduced:

const T step = (stop - start) / static_cast<T>(static_cast<double>(num - 1));

MSVC may not support the static_cast<Eigen::half>(double) or static_cast<bfloat16>(double) operation in the same way clang does. A common fix for Eigen::half arithmetic compatibility is to either cast via float instead of double (since Eigen::half explicitly supports float conversions), or to use the constructor syntax like T(static_cast<double>(...)).

Could you please take a look at the failing Windows CI check here and update the casting syntax so it satisfies MSVC?
https://github.com/tensorflow/tensorflow/actions/runs/34190552835/job/101947733861

Once the Windows CI check is green, this should be ready to 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.

Unfortunately, it looks like build-windows-x86 is still failing on MSVC after the latest fix. We'll need to dig into the Windows CI logs to find a cast that works on that compiler (possibly related to Eigen's half constructor).

@adi-IL

adi-IL commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on the Windows check after the MSVC-safe cast push (85d2ef2):

The Windows job still fails, but not on the LinSpace change. Authenticated job logs show:

  • sequence_ops.cc builds
  • //tensorflow/core/kernels:sequence_ops_test PASSED
  • link then dies on unrelated TFLite: lld-link undefined FlatBufferFileToMlir@tflite while building tensorflow/python/_pywrap_tensorflow_common.dll

So the cast review feedback looks verified on that runner; the remaining red is shared Windows TFLite link infra, same class of failure seen on sibling PRs.

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

Thanks for digging into the Windows CI logs and verifying the linker error! You are correct — that TFLite MSVC link failure is an unrelated infrastructure issue currently affecting multiple PRs.

Since the internal tests and all other platforms are green, and your LinSpace implementation compiled successfully on MSVC, I'll go ahead and approve this PR. Thanks again for the contribution and the quick turnaround!

@google-ml-butler google-ml-butler Bot added the kokoro:force-run Tests on submitted change label Sep 8, 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 Sep 16, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 17, 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 registering the half and bfloat16 kernels for LinSpace!

During in-depth numerical and performance review of the step computation on low-precision types, an important numerical precision and overflow issue was identified:

1. Overflow, NaN Generation, and Quantization Plateaus in Low-Precision Step Math

In tensorflow/core/kernels/sequence_ops.cc:

      const T step =
          (stop - start) / static_cast<T>(static_cast<double>(num - 1));
      for (Tnum i = 1; i < num - 1; ++i) {
        flat(i) = start + step * static_cast<T>(static_cast<double>(i));
      }

Performing the linear interpolation math directly in T (Eigen::half or bfloat16) leads to severe numerical issues:

  1. half Catastrophic Overflow and NaN Generation:
    In IEEE 754 half-precision float (Eigen::half), the maximum finite representable value is 65504.0, and values $\ge 65520.0$ round to +Inf. When $num \ge 65520$:

    • static_cast<T>(num - 1) overflows to +Inf, causing step = (stop - start) / +Inf = 0.0.
    • In the loop, when $i \ge 65520$, static_cast<T>(i) also overflows to +Inf.
    • Multiplying step * static_cast<T>(i) evaluates 0.0 * (+Inf) = NaN, corrupting all elements from index 65520 to num - 2 with NaN!
    • Similarly, if start = -40000.0 and stop = 40000.0 (both representable in half), stop - start = 80000.0 overflows to +Inf, corrupting step even for small sequences.
  2. bfloat16 Staircase Quantization:
    bfloat16 has only 7 mantissa bits (integers are exact only up to 256). Casting i to bfloat16 inside the loop causes consecutive indices (e.g. 256 and 257) to round to the exact same float value, creating flat stair-stepping plateaus across the output tensor.

  3. CPU Conversion Overhead:
    On CPU, Eigen::half and bfloat16 lack native hardware arithmetic instructions and emulate scalar ops via software conversions. Performing the loop arithmetic in T incurs multiple software conversions per element.

Recommended Fix:

Compute the endpoints, step, and loop interpolation in double, casting to T only once when writing to the output:

      const double start_d = static_cast<double>(start);
      const double stop_d = static_cast<double>(stop);
      const double step = (stop_d - start_d) / static_cast<double>(num - 1);
      for (Tnum i = 1; i < num - 1; ++i) {
        flat(i) = static_cast<T>(start_d + step * static_cast<double>(i));
      }

This avoids all NaN and range overflows, prevents stair-step quantization, executes using hardware instructions on CPU, and is fully portable across MSVC, GCC, and Clang with clean constructor conversions.


2. Expanded Test Coverage in sequence_ops_test.cc

Please expand test coverage in sequence_ops_test.cc:

  1. Large sequence test for DT_HALF: Add a test with num = 70000 to ensure no NaN or +Inf values appear in interior elements.
  2. Tidx = DT_INT64 coverage: Add a test exercising DT_INT64 with DT_HALF or DT_BFLOAT16 to verify the 64-bit index kernel registrations.
  3. Singleton boundary test: Verify num = 1 returns [start] without division by zero.

Could you please update the PR with these adjustments? Once pushed, the automated presubmit test suite will run automatically. Thank you!

With the half and bfloat16 kernels registered, the interpolation ran in T.
For those types (stop - start), num - 1 and i all overflow to +Inf long
before the sequence does, so step collapsed to 0 and every interior element
became 0 * +Inf = NaN.

For tf.linspace(0, 1, 70000) with DT_HALF the old code returned 0.0 for
indices 1..65519 and NaN for 65520..69998. Interpolating in double and
narrowing once on store fixes both the range and the bfloat16 staircase at
indices past 256, and costs nothing for float/double.

Adds regression tests for the large-sequence case, the int64 index kernels,
and the num == 1 boundary.
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Sep 29, 2026
@adi-IL

adi-IL commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Confirmed on all three counts. The failure was broader than the review describes. step itself overflows, so the whole interior collapses to zero before the first NaN appears.

For tf.linspace(0, 1, 70000) with DT_HALF, the previous code produced:

indices value
0 0.0
1 … 65519 0.0
65520 … 69998 NaN
69999 1.0

h(69999) is +Inf, so step became 0. step * h(i) then stayed 0 until i also reached +Inf at 65520, where the product is 0 * Inf = NaN. That is 4479 NaNs, and separately every element from index 1 onward was wrong.

dab367cf interpolates in double and narrows once on store. Against the same sequence:

  • NaN 0, Inf 0
  • max abs error against i / 69999 is 2.44e-4, a quarter of the half ULP at 1.0 (9.77e-4)
  • for bfloat16 with 600 indices, every element equals the bfloat16 nearest to i / 599

The error figures above come from evaluating both variants against IEEE-754 binary16. The test results below are real runs of the kernel.

Pushed b918388 for the second review. It changes only sequence_ops_test.cc.

  • Monotonic_Bfloat16_Int64Index uses your ASSERT_GE loop as written. A second loop checks that every element equals the bfloat16 nearest to i / 599. That second loop is the check that separates the old arithmetic from the new one.
  • Single_Bfloat16 is added from your snippet.

Tests in the file now:

  • LargeSequence_Half, num 70000, asserts no non-finite values and spot-checks indices 1, 300, 65519, 65520, 65521, 69998
  • Monotonic_Bfloat16_Int64Index, DT_BFLOAT16 with DT_INT64, 600 indices, non-decreasing plus nearest-value check
  • Single_Half and Single_Bfloat16, num 1 returns [start]

I ran bazel test //tensorflow/core/kernels:sequence_ops_test --test_output=all at b918388 on Linux x86_64, CPU only:

[       OK ] LinSpaceOpTest.Simple_D32 (0 ms)
[       OK ] LinSpaceOpTest.Exact_Endpoints (0 ms)
[       OK ] LinSpaceOpTest.Single_D64 (0 ms)
[       OK ] LinSpaceOpTest.Simple_Double (0 ms)
[       OK ] LinSpaceOpTest.Simple_Half (0 ms)
[       OK ] LinSpaceOpTest.Simple_Bfloat16 (0 ms)
[       OK ] LinSpaceOpTest.LargeSequence_Half (0 ms)
[       OK ] LinSpaceOpTest.Monotonic_Bfloat16_Int64Index (0 ms)
[       OK ] LinSpaceOpTest.Single_Half (0 ms)
[       OK ] LinSpaceOpTest.Single_Bfloat16 (0 ms)
[  PASSED  ] 15 tests.

To check that the new tests detect the original bug, I restored the pre-fix arithmetic in sequence_ops.cc and kept the half and bfloat16 registrations. I did not commit that state. The same target printed:

[ RUN      ] LinSpaceOpTest.LargeSequence_Half
tensorflow/core/kernels/sequence_ops_test.cc:254: Failure
Expected equality of these values:
  0
  non_finite
    Which is: 4479
4479 of 70000 elements were NaN or Inf, first at index 65520

tensorflow/core/kernels/sequence_ops_test.cc:260: Failure
The difference between i * step and static_cast<float>(flat(i)) is 0.00428577551107873, which exceeds 1e-3, where
i * step evaluates to 0.00428577551107873,
static_cast<float>(flat(i)) evaluates to 0, and
1e-3 evaluates to 0.001.
index 300

tensorflow/core/kernels/sequence_ops_test.cc:260: Failure
The difference between i * step and static_cast<float>(flat(i)) is nan, which exceeds 1e-3, where
i * step evaluates to 0.93601337161959453,
static_cast<float>(flat(i)) evaluates to -nan, and
1e-3 evaluates to 0.001.
index 65520

[  FAILED  ] LinSpaceOpTest.LargeSequence_Half (1 ms)
[ RUN      ] LinSpaceOpTest.Monotonic_Bfloat16_Int64Index
tensorflow/core/kernels/sequence_ops_test.cc:289: Failure
Expected equality of these values:
  static_cast<float>( static_cast<bfloat16>(step * static_cast<double>(i)))
    Which is: 0.0016708374
  static_cast<float>(flat(i))
    Which is: 0.00166320801
flat(1) is not the nearest bfloat16 to 1/599

[  FAILED  ] LinSpaceOpTest.Monotonic_Bfloat16_Int64Index (0 ms)
[  PASSED  ] 13 tests.
[  FAILED  ] 2 tests, listed below:
[  FAILED  ] LinSpaceOpTest.LargeSequence_Half
[  FAILED  ] LinSpaceOpTest.Monotonic_Bfloat16_Int64Index

The index 65519, 65521 and 69998 spot checks also failed in that run. I trimmed them here. Single_Half and Single_Bfloat16 pass on both versions, because num == 1 returns before the interpolation runs. After restoring the file the suite passed 15 tests again.

This was a CPU run. I have not run a GPU build locally.

One scope note. Computing the step in double also changes float, which is now computed in double rather than float. That is more accurate, and the existing Simple_D32 and Exact_Endpoints cases use exactly representable values, so neither is affected.

@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 contributing this PR to register half and bfloat16 kernels for LinSpace! The kernel implementation in tensorflow/core/kernels/sequence_ops.cc is very clean, well-scoped, and numerically sound: evaluating intermediate interpolation in double cleanly prevents intermediate overflow to infinity and integer truncation issues for 16-bit float types.

However, there are two action items in the test suite that need to be addressed before this can be approved:

1. Update strict inequality assertion in Monotonic_Bfloat16_Int64Index

In tensorflow/core/kernels/sequence_ops_test.cc:

for (int64_t i = 1; i < num; ++i) {
  ASSERT_GT(static_cast<float>(flat(i)), static_cast<float>(flat(i - 1)))
      << "flat(" << i << ") did not exceed flat(" << i - 1
      << "); indices past 256 plateaued when i was cast to bfloat16";
}

The test generates 600 points between 0.0 and 1.0 in bfloat16.

The bfloat16 format has 1 sign bit, 8 exponent bits, and 7 explicit mantissa bits (machine epsilon $2^{-7} = 1/128$). In the interval [0.25, 0.5), the distance between consecutive representable numbers is:

$$2^{-2} \times 2^{-7} = 2^{-9} = 1/512 \approx 0.001953$$

However, with num = 600, the step size is:

$$1.0 / (600 - 1) = 1 / 599 \approx 0.001669$$

Because the step size is strictly smaller than the grid resolution in [0.25, 0.5), adjacent mathematical points round to the exact same bfloat16 representation under round-to-nearest:

  • i = 154: 154 / 599 approx. 0.257095 rounds to 0.2578125
  • i = 155: 155 / 599 approx. 0.258765 rounds to 0.2578125

Because flat(154) == flat(155), ASSERT_GT fails. In the interval [0.5, 1.0], the spacing widens further to $1/256 \approx 0.003906$, so plateaus are mathematically unavoidable across 600 points.

Required Fix:
Assert non-decreasing monotonicity (ASSERT_GE) across the sequence:

TEST_F(LinSpaceOpTest, Monotonic_Bfloat16_Int64Index) {
  MakeOp(DT_BFLOAT16, DT_INT64);

  // 600 indices exercise the int64 index kernels. With 7 mantissa bits in
  // bfloat16, step (1/599) is smaller than grid spacing (1/512 in [0.25, 0.5)),
  // so adjacent values can round to the same bfloat16 representation. We assert
  // non-decreasing monotonicity across the entire sequence.
  constexpr int64_t num = 600;
  AddInputFromArray<bfloat16>(TensorShape({}), {bfloat16(0.0f)});
  AddInputFromArray<bfloat16>(TensorShape({}), {bfloat16(1.0f)});
  AddInputFromArray<int64_t>(TensorShape({}), {num});
  TF_ASSERT_OK(RunOpKernel());

  const auto flat = GetOutput(0)->flat<bfloat16>();
  ASSERT_EQ(num, GetOutput(0)->NumElements());
  for (int64_t i = 1; i < num; ++i) {
    ASSERT_GE(static_cast<float>(flat(i)), static_cast<float>(flat(i - 1)))
        << "flat(" << i << ") was less than flat(" << i - 1 << ")";
  }
  EXPECT_EQ(0.0f, static_cast<float>(flat(0)));
  EXPECT_EQ(1.0f, static_cast<float>(flat(num - 1)));
}

2. Add Single_Bfloat16 for completeness

Single_Half was added to verify the num == 1 invariant, but Single_Bfloat16 was omitted. Please add Single_Bfloat16 to guarantee test coverage parity across both newly registered types:

TEST_F(LinSpaceOpTest, Single_Bfloat16) {
  MakeOp(DT_BFLOAT16, DT_INT32);

  // num == 1 must return [start] without dividing by num - 1 == 0.
  AddInputFromArray<bfloat16>(TensorShape({}), {bfloat16(9.0f)});
  AddInputFromArray<bfloat16>(TensorShape({}), {bfloat16(100.0f)});
  AddInputFromArray<int32_t>(TensorShape({}), {1});
  TF_ASSERT_OK(RunOpKernel());

  Tensor expected(allocator(), DT_BFLOAT16, TensorShape({1}));
  test::FillValues<bfloat16>(&expected, {bfloat16(9.0f)});
  test::ExpectTensorEqual<bfloat16>(expected, *GetOutput(0));
}

@nithyak0204
nithyak0204 requested a review from dmiltr3 September 30, 2026 05:59
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 30, 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.

The C++ kernel implementation successfully and elegantly resolves the numerical overflow bugs for half and bfloat16 large sequences. By interpolating in double, it provides a robust, portable fix. The previous review feedback regarding ASSERT_GE and Single_Bfloat16 was successfully addressed in sequence_ops_test.cc.

However, the change introduces new supported types to a public Python API without corresponding Python-level test coverage, which is required by our internal test integrity guidelines.

Action Items

1. Add Python API Test Coverage (Blocker)

While the C++ tests are extremely thorough, we need to ensure that the Python bindings properly dispatch the new types. Please add a test to the Python test suite (e.g., tensorflow/python/kernel_tests/math_ops/linspace_op_test.py) that explicitly verifies tf.linspace with tf.bfloat16 and tf.float16.

For example:

def testLinSpaceBfloat16AndHalf(self):
    from tensorflow.python.framework import dtypes
    from tensorflow.python.ops import math_ops
    from tensorflow.python.framework import constant_op
    
    for dtype in [dtypes.bfloat16, dtypes.float16]:
        start = constant_op.constant(3.0, dtype=dtype)
        stop = constant_op.constant(7.0, dtype=dtype)
        res = math_ops.linspace(start, stop, 3)
        self.assertAllClose([3.0, 5.0, 7.0], self.evaluate(res))

2. Include bfloat16.h (Nit)

The files tensorflow/core/kernels/sequence_ops.cc and tensorflow/core/kernels/sequence_ops_test.cc directly utilize the bfloat16 type (via the TF_CALL_bfloat16 macro and constructing bfloat16 variables). For Include-What-You-Use (IWYU) compliance, please explicitly add #include "tensorflow/core/framework/bfloat16.h" in both files.

Please apply these updates and push them to the branch!

@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 pull request. We have conducted a rigorous review to ensure consistency, backward compatibility, and mathematical correctness. Please address the following blocking findings.

1. Preserve Green-Path Performance and Semantics for float32

By changing the step calculation and inner loop in LinSpaceOp to unconditionally use double, the change inadvertently alters the output numerical semantics for existing float32 operations. Furthermore, forcing double math inside the loop for a float32 tensor halves vectorization throughput and incurs casting overhead, inhibiting SIMD auto-vectorization on the fast path.

To fix the half and bfloat16 overflow issue while preserving native performance and semantics for float and double, please use a type trait to compute in double only when the tensor type is smaller than float. Replace the modified loop with:

      // Interpolate in a higher precision type to avoid overflow for half/bfloat16,
      // while preserving native performance and numerical semantics for float/double.
      using ComputeT = typename std::conditional<sizeof(T) >= sizeof(float), T, double>::type;
      const ComputeT start_c = static_cast<ComputeT>(start);
      const ComputeT stop_c = static_cast<ComputeT>(stop);
      const ComputeT step = (stop_c - start_c) / static_cast<ComputeT>(num - 1);
      for (Tnum i = 1; i < num - 1; ++i) {
        flat(i) = static_cast<T>(start_c + step * static_cast<ComputeT>(i));
      }

2. Sibling Kernel Precision Parity for RangeOp

The change correctly fixes bfloat16 and half overflow and precision loss in LinSpaceOp. However, our Sibling Kernel Differential Parity directive requires identically validating sibling ops. RangeFunctor<CPUDevice, T> suffers from the exact same precision loss for low-precision types because it calculates output(i) = start + static_cast<T>(i) * delta;. For T = bfloat16, static_cast<bfloat16>(257) rounds to 256, causing duplicate interior values.

To maintain parity and numerical correctness, RangeFunctor must be updated to prevent precision loss for floating-point types, ideally applying the same ComputeT pattern so as not to penalize float and double:

template <typename T>
struct RangeFunctor<CPUDevice, T> {
  void operator()(OpKernelContext* context, int64_t size, T start, T delta,
                  typename TTypes<T>::Flat output) const {
    (void)context;
    if constexpr (std::is_integral<T>::value) {
      for (int64_t i = 0; i < size; ++i) {
        output(i) = start + static_cast<T>(i) * delta;
      }
    } else {
      using ComputeT = typename std::conditional<sizeof(T) >= sizeof(float), T, double>::type;
      const ComputeT start_c = static_cast<ComputeT>(start);
      const ComputeT delta_c = static_cast<ComputeT>(delta);
      for (int64_t i = 0; i < size; ++i) {
        output(i) = static_cast<T>(start_c + static_cast<ComputeT>(i) * delta_c);
      }
    }
  }
};

Additionally, please add a test TEST_F(RangeOpTest, Monotonic_Bfloat16) in tensorflow/core/kernels/sequence_ops_test.cc that allocates >256 elements (e.g. 600) to guarantee that outputs strictly increase without truncating the loop index.

3. Missing Canonical Headers

Under Include What You Use (IWYU) principles, any file that references bfloat16 and Eigen::half must explicitly include their canonical headers. Please add the following includes to both tensorflow/core/kernels/sequence_ops.cc and tensorflow/core/kernels/sequence_ops_test.cc:

#include "tensorflow/core/framework/bfloat16.h"
#include "tensorflow/core/framework/numeric_types.h"

@adi-IL

adi-IL commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3. Both reviews are addressed in fa46d76.

ComputeT. LinSpace now uses your ComputeT trait. Only half and bfloat16 compute in double. float and double keep native arithmetic.

RangeFunctor. The CPU RangeFunctor uses the same pattern. Integral types keep the original loop. I left the GPU RangeKernel alone to keep this diff small. It has the same static_cast<T>(i) * delta pattern, and I can send that as a follow-up if you want it.

Monotonic_Bfloat16. The test builds 600 elements with start 0 and delta 0.3. It checks each value against the double result narrowed to bfloat16, and it checks ASSERT_GE between neighbours. A strictly increasing check cannot hold here. Near 77 the bfloat16 spacing is 0.5, so 600 steps of 0.3 must repeat some values even with correct math. The exact check catches the bug. With the old loop, flat(257) is 77 where 77.5 is expected.

Includes. tensorflow/core/framework/bfloat16.h and tensorflow/core/framework/numeric_types.h are in both sequence_ops.cc and sequence_ops_test.cc.

Python coverage. testLinSpaceKernelHalfAndBfloat16 in math_ops_linspace_test.py covers float16 and bfloat16 with int32 and int64 num, including num=70000 and num=1. It calls gen_math_ops.lin_space directly. In TF2, tf.linspace goes through linspace_nd and does not reach the LinSpace kernel. The tf.linspace case is there as API coverage only. The BUILD file gains a :math_ops_gen dep.

Results. Local run of //tensorflow/core/kernels:sequence_ops_test on Linux x86_64 CPU:

  • With the fix, 16 of 16 tests pass.
  • With only the old LinSpace arithmetic, LargeSequence_Half fails with 4479 of 70000 elements NaN or Inf starting at index 65520. Monotonic_Bfloat16_Int64Index also fails.
  • With only the old Range loop, RangeOpTest.Monotonic_Bfloat16 fails at flat(257).

I did not run the Python test locally. The Python target build ran out of memory on my machine twice. CI will be its first run.

@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 adding half and bfloat16 support for LinSpace. During review, we identified a few issues with scope, performance, and formatting that need to be addressed before merging.

1. Fix PyLint Formatting Issue

Internal CI tests caught a line length formatting violation in tensorflow/python/ops/math_ops_linspace_test.py at line 95:

C0301: Line too long (81/80) (line-too-long)

Please wrap the line so it is at most 80 characters long. For example:

      expected = np.linspace(
          start, stop, num, dtype=np.float64
      ).astype(np.float32).astype(np_dtype)

2. Revert Unrelated Modifications to RangeFunctor

The PR modifies RangeFunctor<CPUDevice, T> in tensorflow/core/kernels/sequence_ops.cc and adds TEST_F(RangeOpTest, Monotonic_Bfloat16). Because this PR is scoped to LinSpace, modifying RangeOp introduces scope creep. Furthermore, the change introduces a numerical behavior discrepancy between CPU and GPU, as RangeKernel<GPUDevice, T> was not updated.

Please revert the modifications to RangeFunctor and remove the Monotonic_Bfloat16 test for RangeOpTest. If precision improvements for RangeOp are desired, please propose them in a separate PR that updates both CPU and GPU implementations simultaneously.

3. Use float Instead of double for 16-bit Float Interpolation

In LinSpaceOp::Compute (tensorflow/core/kernels/sequence_ops.cc), the fallback type ComputeT for half and bfloat16 is set to double. This unconditionally upcasts 16-bit types to 64-bit precision, which cuts vectorization width in half and incurs a significant performance penalty on hardware where FP64 is emulated or slower. A 32-bit float provides more than enough precision to interpolate 16-bit floats without overflow.

Please replace double with float:

      using ComputeT = typename std::conditional<sizeof(T) >= sizeof(float), T,
                                                 float>::type;

4. Update C++ Unit Tests for float Precision

In tensorflow/core/kernels/sequence_ops_test.cc for TEST_F(LinSpaceOpTest, Monotonic_Bfloat16_Int64Index), the expected values are manually calculated using double casts. Once ComputeT is changed to float as requested above, this test will fail because it asserts against double-precision rounding.

Please update the test to use float:

  const float step = 1.0f / static_cast<float>(num - 1);
  for (int64_t i = 1; i < num - 1; ++i) {
    ASSERT_EQ(static_cast<float>(
                  static_cast<bfloat16>(step * static_cast<float>(i))),
              static_cast<float>(flat(i)))
        << "flat(" << i << ") is not the nearest bfloat16 to " << i << "/"
        << num - 1;
  }

@adi-IL

adi-IL commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3. Review 5369869310 is addressed in a2a108e.

PyLint. No line in math_ops_linspace_test.py is over 80 characters now. I checked line lengths and ran py_compile. pylint itself was not run locally.

Range revert. RangeFunctor<CPUDevice, T> is back to its original code, and RangeOpTest.Monotonic_Bfloat16 is removed. This PR now covers LinSpace only. If I send the Range change later, it will be a separate PR that updates the CPU and GPU kernels together.

float ComputeT. The fallback for half and bfloat16 is now float, using your snippet. float holds every integer index up to 2^24 exactly, so the num=70000 half case no longer overflows.

C++ test. Monotonic_Bfloat16_Int64Index uses your float expected values verbatim.

Python test. The expected values now follow the kernel in float32 (start + step * i in float32, endpoints set as the kernel sets them, then narrowed to the dtype). The comparison is assertAllClose with atol=0 and an rtol of one ulp of the target dtype (2^-10 for float16, 2^-7 for bfloat16). I used a one ulp tolerance instead of exact equality because I could not run the test here to rule out fused multiply add differences. NaN, Inf and wrong values still fail it.

Results. Local run of //tensorflow/core/kernels:sequence_ops_test on Linux x86_64 CPU:

  • With the fix, 15 of 15 tests pass.
  • With the old LinSpace arithmetic, LargeSequence_Half fails with 4479 of 70000 elements NaN or Inf starting at index 65520. Monotonic_Bfloat16_Int64Index also fails at flat(1).

The Python test was not run locally because the Python target does not fit in memory on my machine. CI will be its first run.

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

The change properly addresses the issues with 16-bit interpolation. All C++ and Python tests pass correctly, and the mathematical logic correctly uses intermediate float computation to prevent overflow when the number of elements approaches 16-bit capacity. The code changes are minimal, properly scoped, and well-written. Thank you for addressing the feedback and adding thorough test coverage!

@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 2, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 2, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 5, 2026
@copybara-service
copybara-service Bot merged commit 7200926 into tensorflow:master Oct 15, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 15, 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 ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

5 participants