Repository navigation
Validate constant num_bits in XLA QuantizeAndDequantizeV3 - #128149
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds validation for the num_bits argument in the QuantizeAndDequantize XLA operator, ensuring it is within a valid range when provided as a constant input scalar. It also adds a corresponding unit test to verify that an InvalidArgumentError is raised for invalid num_bits values. The review feedback suggests updating the new unit test to use modern TensorFlow 2.x eager execution and self.evaluate() instead of legacy TensorFlow 1.x patterns like self.session() and array_ops.placeholder.
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the fix. The C++ kernel changes correctly replicate the CPU constant validation logic in XLA lowering without introducing dynamic runtime overhead. However, we need to adjust the unit tests to pass our continuous integration testing suites and ensure full boundary coverage.
1. Fix XLATestCase session evaluation (Blocker)
The added test fails during graph execution because self.evaluate() invokes test_session, which is not supported in XLATestCase. Please rewrite the evaluation execution using an explicit local session and a placeholder, simulating graph execution. For example:
with self.session() as sess:
x_val = np.array([-1, -0.5, 0, 0.3], dtype=np.float32)
x = array_ops.placeholder(dtypes.float32)
with self.assertRaisesRegex(
errors.InvalidArgumentError, "num_bits is out of range"
):
sess.run(quantize_and_dequantize_v3(x), {x: x_val})2. Cover all boundary conditions and flags
The current test validates the lower limits (0 and -1), but does not verify the upper bounds defined by the logic (signed_input_ ? 62 : 63). Please extend the test parameterization to evaluate both signed_input=True and signed_input=False, alongside the appropriate upper bound limits for each mode (e.g., 62/63 and 63/64).
Here is a comprehensive snippet that integrates both fixes:
def testQuantizeAndDequantizeV3InvalidNumBits(self):
for signed_input in (True, False):
invalid_num_bits = (0, -1, 62, 63) if signed_input else (0, -1, 63, 64)
for num_bits in invalid_num_bits:
@def_function.function(jit_compile=True)
def quantize_and_dequantize_v3(x, nb=num_bits, si=signed_input):
return array_ops.quantize_and_dequantize_v3(
x, -1.0, 1.0, num_bits=nb, signed_input=si
)
with self.session() as sess:
x_val = np.array([-1, -0.5, 0, 0.3], dtype=np.float32)
x = array_ops.placeholder(dtypes.float32)
with self.assertRaisesRegex(
errors.InvalidArgumentError, "num_bits is out of range"
):
sess.run(quantize_and_dequantize_v3(x), {x: x_val})
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for addressing the previous review comments and updating the pull request.
Summary of Changes
The pull request adds compile-time validation in tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc for QuantizeAndDequantizeV3 when num_bits folds to a constant integer scalar. This ensures that non-positive bit counts or bit counts exceeding representation limits raise an InvalidArgumentError during XLA JIT compilation, matching the existing behavior of the CPU and GPU runtime kernels.
Review Evaluation
- Parity and Correctness: The validation condition (
num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63)) intensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.ccmatches the CPU kernel intensorflow/core/kernels/quantize_and_dequantize_op.ccand the siblingQuantizeAndDequantizeV2Opkernel, preventing undefined behavior and 64-bit shift overflow. - Zero Steady-State Overhead: The check evaluates only at compile time via
ConstantInputAsIntScalarduring op lowering, introducing zero runtime cost or extra HLO instructions. Dynamic inputs remain unaffected. - Test Completeness: The updated unit test in
tensorflow/compiler/tests/unary_ops_test.pycovers all boundary conditions across bothsigned_input=True(0, -1, 62, 63) andsigned_input=False(0, -1, 63, 64). The test properly uses session execution with a placeholder input inXLATestCase. - Dependency and Style Hygiene: Build dependencies and imports (
def_function,errors) are properly declared and conform to TensorFlow standards.
The change is clean, well-tested, and ready to merge.
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for this PR! The XLA QuantizeAndDequantizeV3 constant bounds check looks solid and verified cleanly against our automated test suite.
We have a couple of minor test polish requests before final approval:
1. Replace deprecated self.test_scope() with self.device_scope()
In tensorflow/compiler/tests/unary_ops_test.py:
test_scope is a deprecated alias of device_scope (method names starting with test can be incorrectly collected by some test runners). Please update line 356:
<<<<
with self.session() as sess:
with self.test_scope():
x = array_ops.placeholder(dtypes.float32)
====
with self.session() as sess:
with self.device_scope():
x = array_ops.placeholder(dtypes.float32)
>>>>2. Add positive assertions for valid extreme boundary bitwidths
In testQuantizeAndDequantizeV3InvalidNumBits, we test invalid bounds (<= 0 and >= 62 or 63). To ensure the boundary conditions do not inadvertently reject valid extreme bitwidths, please consider also asserting that valid extreme boundaries execute successfully (e.g., num_bits = 1 and num_bits = 61 for signed_input=True; num_bits = 1 and num_bits = 62 for signed_input=False).
Once updated, please push the commit and we will verify the changes!
|
Thanks @dmiltr3. Review 5382693580 is addressed in 8a8f51d. device_scope. Line 356 of Valid boundary bitwidths. Testing. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The compile-time boundary validations and expanded tests look excellent. However, there are a couple of remaining changes required before we can approve and merge this PR.
Required Changes
- Test Naming (
tensorflow/compiler/tests/unary_ops_test.py:340): The test method is currently namedtestQuantizeAndDequantizeV3InvalidNumBits, but it now asserts both invalid bounds and valid extreme boundaries. Please rename it to something more representative, such astestQuantizeAndDequantizeV3NumBitsBoundaries.
<<<<
def testQuantizeAndDequantizeV3InvalidNumBits(self):
====
def testQuantizeAndDequantizeV3NumBitsBoundaries(self):
>>>>- IWYU Missing Include (
tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc): The codebase heavily relies onerrors::InvalidArgumenthere. While it compiles due to transitive includes, strict IWYU (Include What You Use) guidelines require explicitly including the header. Please add#include "tensorflow/core/platform/errors.h"near the top of the file.
<<<<
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "xla/hlo/builder/lib/constants.h"
====
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/platform/errors.h"
#include "xla/hlo/builder/lib/constants.h"
>>>>Once updated, please push the commit and we will verify the changes!
|
Thanks @dmiltr3. 57f76fa renames the test to
I ran |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The test boundaries look good and test method renaming is perfect.
However, the required C++ include was missed in your latest push.
As requested in the previous review, strict IWYU (Include What You Use) guidelines require us to explicitly include the header for errors::InvalidArgument. Please add the following include near the top of tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc:
#include "tensorflow/core/platform/errors.h"Once this missing include is added, please push the update so we can proceed with final testing and approval. Thanks!
|
@dmiltr3 the include is already in the file. Line 36 of |
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: we asked you to add #include "tensorflow/core/platform/errors.h" to tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc. You are right that the file already includes it at line 36, so no change is needed. We withdraw that request and apologize for repeating it and for the extra round. Please do not add a second include.
The change adds a compile-time range check for num_bits in the XLA lowering of QuantizeAndDequantizeV3. It uses the same predicate and error message as the existing V2/V4 check in the same file and as the CPU kernel. A dynamic num_bits still compiles exactly as before, and the check adds no runtime cost. The new test testQuantizeAndDequantizeV3NumBitsBoundaries covers invalid and valid extreme values in both signed_input modes and pins the expected error message.
No further changes are required. Approving.
There was a problem hiding this comment.
Thank you for the updates! Although GitHub shows this branch as mergeable, tensorflow/compiler/tests/BUILD has changed on master since your branch base, causing a merge conflict during automated merge verification.
Could you please rebase your branch onto the latest tensorflow:master and force-push? Once rebased, the automated checks will re-run so we can re-approve and merge. Thank you!
57f76fa to
a46cf99
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates!
As noted in the previous review, tensorflow/compiler/tests/BUILD has changed on master since your branch base, causing a merge conflict during automated merge verification. Our automated checks confirm that the branch has not yet been successfully rebased.
Outstanding final asks
- Could you please rebase your branch onto the latest
tensorflow:masterand force-push? Once rebased, the automated checks will re-run so we can re-approve and merge. Thank you!
a46cf99 to
d043192
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Outstanding final asks
- Could you please rebase your branch onto the latest
tensorflow:masterand force-push? Once rebased, the automated checks will re-run so we can re-approve and merge. Thank you!
It appears our internal sync is still failing to apply the diff cleanly on tensorflow/compiler/tests/BUILD and tensorflow/compiler/tests/unary_ops_test.py. Please ensure the branch is fully rebased on the latest master.
The tf2xla lowering of QuantizeAndDequantizeV3 reads num_bits from input 3 and uses it directly to compute the quantization bounds. The range check that the CPU kernel applies is missing, so with jit_compile=True a num_bits of 0 or a negative value returns a result instead of raising InvalidArgumentError. When input 3 folds to a constant, apply the same range check as the CPU kernel. Dynamic num_bits is left unchanged. Fixes tensorflow#127914
d043192 to
30c975e
Compare
|
@dmiltr3 CI note on 30c975e. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for addressing the final asks and ensuring the branch is up-to-date! We have verified that the branch is fully rebased onto the latest master and is fully mergeable on GitHub. The internal sync failures we encountered previously were caused by internal infrastructure differences rather than a true merge conflict in your pull request. No further rebasing is required on your end.
The compile-time range check for num_bits in the XLA lowering of QuantizeAndDequantizeV3 is mathematically correct and adds zero runtime cost. The accompanying boundary tests comprehensively exercise both signed and unsigned scenarios, confirming parity with the CPU kernel and strictly pinning the expected error messages. The test matrices also ensure that valid extreme boundary bitwidths evaluate smoothly.
The change is clean, well-tested, and fully aligned with our correctness and performance guidelines. We are ready to merge this in. Approving!
00669fc
into
tensorflow:master
Fixes #127914
Problem
With
jit_compile=True,tf.quantization.quantize_and_dequantize_v3acceptsnum_bitsof 0 or a negative value and returns a result. Eager and plain graph execution raiseInvalidArgumentError: num_bits is out of rangefor the same input.Cause
In
tf2xla/kernels/quantize_and_dequantize_op.cc, V3 is registered on the baseQuantizeAndDequantizeOp, which takesnum_bitsfrom input 3 and feeds it straight into the2^num_bitsbound computation. The CPU kernel checks0 < num_bits < (signed_input ? 62 : 63)first. The XLA lowering has no such check.Fix
When input 3 folds to a constant, apply the same range check as the CPU kernel and fail with
InvalidArgument. Whennum_bitsis truly dynamic, behavior is unchanged, and the op registration is not modified.Test
Added
UnaryOpsTest.testQuantizeAndDequantizeV3InvalidNumBitsincompiler/tests/unary_ops_test.py. It runs the op insidedef_function.function(jit_compile=True)with constantnum_bitsof 0 and -1 and expectsInvalidArgumentError.Without the kernel change, the new test fails with
InvalidArgumentError not raised. With it, the new test and the existingtestQuantizeAndDequantizeboth pass.