Repository navigation
Fix signed integer overflow in TFLite Div op (INT32_MIN / -1) (#124409) - #124567
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request adds protobuf dependencies across several BUILD files, updates debug ops to log warnings instead of failing on tensor publication errors, and adds a negative index check in TensorListSetItem. It also introduces guards against signed integer overflow (INT_MIN / -1) in reference division kernels. The review feedback correctly identifies a bug in these overflow guards where they would incorrectly trigger for unsigned integer types, and suggests adding a signedness check to ensure correct behavior.
|
Hi @genius-0963 , Can you kindly sign the CLA? Thank you! |
c9b65bd to
856ae3f
Compare
|
Hey @genius-0963 I see u didn't sign the https://cla.developers.google.com/ that causes this merging failed see https://github.com/tensorflow/tensorflow/pull/124567/checks?check_run_id=91800668340 Thank you, |
856ae3f to
ff8a15c
Compare
|
Finally, the CLA flow is working! 🎉 |
|
Still no merge :( |
There was a problem hiding this comment.
Scope of Changes
- In Scope: The changes in
tensorflow/lite/kernels/internal/reference/div.hare in scope because theDivoperator is reachable via the WebNN delegate.
Feedback on div.h (In Scope)
The overflow guard in tensorflow/lite/kernels/internal/reference/div.h contains a bug for unsigned integer types.
The condition std::is_integral<T>::value && val2 == static_cast<T>(-1) && val1 == std::numeric_limits<T>::min() will trigger for unsigned types when val1 == 0 and val2 == UINT_MAX (or equivalent max value), returning UINT_MAX instead of 0 (since 0 / UINT_MAX is 0).
The condition should verify that T is signed, for example by adding std::is_signed<T>::value.
Please also include unit tests in div_test to verify the overflow guards work as expected and cover the bug mentioned above.
Discrepancy
The PR description mentions fixing TensorListSetItem in tensorflow/core/kernels/list_kernels.cc. This file is not included in the files changed in this PR, and such changes would be considered out of security hardening scope for TFLite in any case.
a6701f4 to
1ba7d1d
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
CI Build Checks Failure
The latest CI workflow runs failed on the following jobs due to compilation errors:
Root Causes & Code Solutions
1. Compilation Error in tensorflow/lite/kernels/internal/reference/div.h
In BroadcastDivSlow, the lambda was defined as div_func while op was passed to BroadcastBinaryOpSimple, resulting in:
error: use of undeclared identifier 'op'
Solution:
Keep op concise and add the signed integer overflow check directly:
template <typename T, int N = 5>
void BroadcastDivSlow(const ArithmeticParams& params,
const RuntimeShape& unextended_input1_shape,
const T* input1_data,
const RuntimeShape& unextended_input2_shape,
const T* input2_data,
const RuntimeShape& unextended_output_shape,
T* output_data) {
T output_activation_min;
T output_activation_max;
GetActivationParams(params, &output_activation_min, &output_activation_max);
auto op = [output_activation_min, output_activation_max](T a, T b) {
T div_result;
if (std::is_integral<T>::value && std::is_signed<T>::value &&
b == static_cast<T>(-1) &&
a == std::numeric_limits<T>::min()) {
div_result = std::numeric_limits<T>::max();
} else {
div_result = a / b;
}
return ActivationFunctionWithMinMax(div_result, output_activation_min,
output_activation_max);
};
BroadcastBinaryOpSimple(unextended_input1_shape, input1_data,
unextended_input2_shape, input2_data,
unextended_output_shape, output_data, op);
}2. Overflow Protection in tensorflow/lite/kernels/internal/optimized/optimized_ops.h
BroadcastDivSlow in optimized_ops.h is duplicated from reference/div.h for generic optimized execution on CPU targets. To prevent hardware SIGFPE traps during broadcast evaluation of INT32_MIN / -1, apply the same guard:
template <typename T, int N = 5>
void BroadcastDivSlow(const ArithmeticParams& params,
const RuntimeShape& unextended_input1_shape,
const T* input1_data,
const RuntimeShape& unextended_input2_shape,
const T* input2_data,
const RuntimeShape& unextended_output_shape,
T* output_data) {
ruy::profiler::ScopeLabel label("BroadcastDivSlow");
T output_activation_min;
T output_activation_max;
GetActivationParams(params, &output_activation_min, &output_activation_max);
auto op = [output_activation_min, output_activation_max](T a, T b) {
T div_result;
if (std::is_integral<T>::value && std::is_signed<T>::value &&
b == static_cast<T>(-1) &&
a == std::numeric_limits<T>::min()) {
div_result = std::numeric_limits<T>::max();
} else {
div_result = a / b;
}
return ActivationFunctionWithMinMax(div_result, output_activation_min,
output_activation_max);
};
reference_ops::BroadcastBinaryOpSimple(
unextended_input1_shape, input1_data, unextended_input2_shape,
input2_data, unextended_output_shape, output_data, op);
}3. Syntax Error in tensorflow/lite/kernels/div_test.cc
TEST(IntegerDivOpTest, NormalNegOneDivision) is missing its closing brace } before TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck).
Solution:
Ensure all tests are properly closed:
TEST(IntegerDivOpTest, Int32MinDivNegOne_Saturates) {
IntegerDivOpModel m({TensorType_INT32, {1, 1, 4, 1}},
{TensorType_INT32, {1, 1, 4, 1}}, {TensorType_INT32, {}},
ActivationFunctionType_NONE);
const int32_t int32_min = std::numeric_limits<int32_t>::min();
const int32_t int32_max = std::numeric_limits<int32_t>::max();
m.PopulateTensor<int32_t>(m.input1(), {int32_min, int32_min, -10, 10});
m.PopulateTensor<int32_t>(m.input2(), {-1, 1, -1, -1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutput(),
ElementsAreArray({int32_max, int32_min, 10, -10}));
}
TEST(IntegerDivOpTest, Int32MinDivNegOne_Broadcast) {
IntegerDivOpModel m({TensorType_INT32, {1, 1, 4, 1}},
{TensorType_INT32, {}},
{TensorType_INT32, {}}, ActivationFunctionType_NONE);
const int32_t int32_min = std::numeric_limits<int32_t>::min();
const int32_t int32_max = std::numeric_limits<int32_t>::max();
m.PopulateTensor<int32_t>(m.input1(), {int32_min, -100, 0, 100});
m.PopulateTensor<int32_t>(m.input2(), {-1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutput(), ElementsAreArray({int32_max, 100, 0, -100}));
}
TEST(IntegerDivOpTest, NormalNegOneDivision) {
IntegerDivOpModel m({TensorType_INT32, {1, 2, 2, 1}},
{TensorType_INT32, {1, 2, 2, 1}}, {TensorType_INT32, {}},
ActivationFunctionType_NONE);
m.PopulateTensor<int32_t>(m.input1(), {-100, 50, 0, 2147483647});
m.PopulateTensor<int32_t>(m.input2(), {-1, -1, -1, -1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutput(), ElementsAreArray({100, -50, 0, -2147483647}));
}Local Verification
All tests in //tensorflow/lite/kernels:div_test passed successfully when tested with these solutions.
7b70954 to
d1a1302
Compare
|
@dmiltr3 |
dmiltr3
left a comment
There was a problem hiding this comment.
Compilation Error in tensorflow/lite/kernels/div_test.cc
There is a missing closing brace } at the end of the NormalNegOneDivision unit test in tensorflow/lite/kernels/div_test.cc (right before TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck)), which causes compilation errors when building div_test:
error: static data member 'test_info_' not allowed in local class 'QuantizedDivOpTest_AsymmetricQuantizedDivisorZeroCheck_Test'
error: function definition is not allowed here
Required Fix
Add the missing } to close TEST(IntegerDivOpTest, NormalNegOneDivision):
diff --git a/tensorflow/lite/kernels/div_test.cc b/tensorflow/lite/kernels/div_test.cc
index 9a048b9..a0453de 100644
--- a/tensorflow/lite/kernels/div_test.cc
+++ b/tensorflow/lite/kernels/div_test.cc
@@ -452,6 +452,8 @@ TEST(IntegerDivOpTest, NormalNegOneDivision) {
m.PopulateTensor<int32_t>(m.input2(), {-1, -1, -1, -1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutput(), ElementsAreArray({100, -50, 0, -2147483647}));
+}
+
TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck) {
// Case 1: Divisor is real 0.0 (quantized to -128). This should FAIL.
{Fixes tensorflow#124409 The TFLite reference Div kernel performs raw C++ division without guarding against signed integer overflow. When INT32_MIN is divided by -1, the result cannot be represented in int32_t, triggering undefined behavior per C++20 [expr.mul]/4. Fix: Add an overflow guard in the flat Div function, and in BroadcastDivSlow in both reference/div.h and optimized/optimized_ops.h. When the overflow case (T::min() / -1) is detected for signed integral types, the result is saturated to std::numeric_limits<T>::max(). The guard uses std::is_signed<T>::value to avoid false triggering on unsigned types (where static_cast<T>(-1) == T::max() and T::min() == 0, which would incorrectly match 0 / UINT_MAX). BroadcastDivSlow is refactored to use the op lambda pattern with BroadcastBinaryOpSimple to match the upstream API. Also adds unit tests covering: - INT32_MIN / -1 saturation (flat path) - INT32_MIN / -1 saturation (broadcast path) - Normal -1 division still works correctly
… -1) (#124409) Imported from GitHub PR tensorflow/tensorflow#124567 Summary: > Fixes tensorflow/tensorflow#124409 > > Guards against signed integer overflow (`INT_MIN / -1`) in TFLite `Div` and `BroadcastDivSlow` reference and optimized kernels by saturating to `std::numeric_limits<T>::max()`. Copybara import of the project: -- f149119dbc9a59cacce0f16299b4062cb261c29b by Saurabh Sungh <[email protected]>: Fix signed integer overflow in TFLite Div op (INT32_MIN / -1) Fixes tensorflow/tensorflow#124409 The TFLite reference Div kernel performs raw C++ division without guarding against signed integer overflow. When INT32_MIN is divided by -1, the result cannot be represented in int32_t, triggering undefined behavior per C++20 [expr.mul]/4. Fix: Add an overflow guard in the flat Div function, and in BroadcastDivSlow in both reference/div.h and optimized/optimized_ops.h. When the overflow case (T::min() / -1) is detected for signed integral types, the result is saturated to std::numeric_limits<T>::max(). The guard uses std::is_signed<T>::value to avoid false triggering on unsigned types (where static_cast<T>(-1) == T::max() and T::min() == 0, which would incorrectly match 0 / UINT_MAX). BroadcastDivSlow is refactored to use the op lambda pattern with BroadcastBinaryOpSimple to match the upstream API. Also adds unit tests covering: - INT32_MIN / -1 saturation (flat path) - INT32_MIN / -1 saturation (broadcast path) - Normal -1 division still works correctly Merging this change closes #124567 PiperOrigin-RevId: 970687124
…ation. This ensures that the constants created by ZeroSizedHloElimination are folded into their users immediately. Also remove unnecessary call to `ZeroSizedHloElimination` and only keep the one from `RunPreSPMDPartitionerPasses`. FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b PiperOrigin-RevId: 970440469
Fix crash when CreateFromProto encounters proto types not linked into the binary (e.g. from libtpu.so). Unknown entries are now stored as opaque google.protobuf.Any values and re-emitted by ToProto(), enabling lossless round-tripping without requiring the proto definitions. FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b PiperOrigin-RevId: 969554949
- Fix bit-size calculation for quantized and complex types in const_tensor_utils to account for element count. - Add QI4 support to TFL_QConstOp results in tfl_ops.td. - Allow folding TransposeOp and ReshapeOp on resource constants in ShouldFoldOperation. - Add GetPhysicalBufferHash using xxHash for DenseResourceElementsAttr in FlatBuffer exporters. - Support direct DenseResourceElementsAttr reading and low-bit packing (INT4/UINT4/INT2) during FlatBuffer serialization. - Ensure unique name assignment in Translator::InitializeNamesFromAttribute and BuildSignatureDefData. FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b PiperOrigin-RevId: 970156012
Summary: