Repository navigation
[LinSpace] Register half and bfloat16 OpKernels for LinSpace - #126450
Conversation
dmiltr3
left a comment
There was a problem hiding this comment.
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-leaseThe 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.
9f7f97e to
034aeba
Compare
|
Rebased onto latest Public CI after the rebase:
Ready for another look when you have a chance. |
dmiltr3
left a comment
There was a problem hiding this comment.
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!
|
Thanks @dmiltr3 - updated the LinSpace casts to route ints through 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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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).
|
Follow-up on the Windows check after the MSVC-safe cast push ( The Windows job still fails, but not on the LinSpace change. Authenticated job logs show:
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
left a comment
There was a problem hiding this comment.
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!
dmiltr3
left a comment
There was a problem hiding this comment.
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:
-
halfCatastrophic Overflow and NaN Generation:
In IEEE 754 half-precision float (Eigen::half), the maximum finite representable value is65504.0, and values$\ge 65520.0$ round to+Inf. When$num \ge 65520$ :-
static_cast<T>(num - 1)overflows to+Inf, causingstep = (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)evaluates0.0 * (+Inf) = NaN, corrupting all elements from index 65520 tonum - 2withNaN! - Similarly, if
start = -40000.0andstop = 40000.0(both representable inhalf),stop - start = 80000.0overflows to+Inf, corruptingstepeven for small sequences.
-
-
bfloat16Staircase Quantization:
bfloat16has only 7 mantissa bits (integers are exact only up to 256). Castingitobfloat16inside 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. -
CPU Conversion Overhead:
On CPU,Eigen::halfandbfloat16lack native hardware arithmetic instructions and emulate scalar ops via software conversions. Performing the loop arithmetic inTincurs 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:
- Large sequence test for
DT_HALF: Add a test withnum = 70000to ensure noNaNor+Infvalues appear in interior elements. Tidx = DT_INT64coverage: Add a test exercisingDT_INT64withDT_HALForDT_BFLOAT16to verify the 64-bit index kernel registrations.- Singleton boundary test: Verify
num = 1returns[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.
|
Confirmed on all three counts. The failure was broader than the review describes. For
The error figures above come from evaluating both variants against IEEE-754 binary16. The test results below are real runs of the kernel. Pushed
Tests in the file now:
I ran To check that the new tests detect the original bug, I restored the pre-fix arithmetic in The index 65519, 65521 and 69998 spot checks also failed in that run. I trimmed them here. This was a CPU run. I have not run a GPU build locally. One scope note. Computing the step in |
dmiltr3
left a comment
There was a problem hiding this comment.
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 [0.25, 0.5), the distance between consecutive representable numbers is:
However, with num = 600, the step size is:
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.257095rounds to0.2578125i = 155:155 / 599 approx. 0.258765rounds to0.2578125
Because flat(154) == flat(155), ASSERT_GT fails. In the interval [0.5, 1.0], the spacing widens further to
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));
}
dmiltr3
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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"|
Thanks @dmiltr3. Both reviews are addressed in fa46d76. ComputeT. LinSpace now uses your RangeFunctor. The CPU 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 Includes. Python coverage. Results. Local run of
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
left a comment
There was a problem hiding this comment.
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;
}…eave Range unchanged
|
Thanks @dmiltr3. Review 5369869310 is addressed in a2a108e. PyLint. No line in Range revert. float ComputeT. The fallback for half and bfloat16 is now C++ test. Python test. The expected values now follow the kernel in float32 ( Results. Local run of
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
left a comment
There was a problem hiding this comment.
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!
Description
The
LinSpaceop definition intensorflow/core/ops/math_ops.ccdeclares support forT: {bfloat16, half, float, double}. However, kernel registrations intensorflow/core/kernels/sequence_ops.cconly registeredDT_FLOATandDT_DOUBLE.Calling
tf.raw_ops.LinSpacewithbfloat16orhalfinputs failed with anOpKernel not founderror.Changes
LinSpaceOp::Computeusingstatic_cast<T>soEigen::halfandbfloat16arithmetic compiles cleanly.TF_CALL_halfandTF_CALL_bfloat16forLinSpaceOponDEVICE_CPUandDEVICE_DEFAULT.DT_HALFandDT_BFLOAT16insequence_ops_test.cc.