Skip to content

Validate constant num_bits in XLA QuantizeAndDequantizeV3 - #128149

Merged
copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
adi-IL:bot/tensorflow-127914
Oct 15, 2026
Merged

copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
adi-IL:bot/tensorflow-127914

Conversation

@adi-IL

@adi-IL adi-IL commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Fixes #127914

Problem

With jit_compile=True, tf.quantization.quantize_and_dequantize_v3 accepts num_bits of 0 or a negative value and returns a result. Eager and plain graph execution raise InvalidArgumentError: num_bits is out of range for the same input.

Cause

In tf2xla/kernels/quantize_and_dequantize_op.cc, V3 is registered on the base QuantizeAndDequantizeOp, which takes num_bits from input 3 and feeds it straight into the 2^num_bits bound computation. The CPU kernel checks 0 < 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. When num_bits is truly dynamic, behavior is unchanged, and the op registration is not modified.

Test

Added UnaryOpsTest.testQuantizeAndDequantizeV3InvalidNumBits in compiler/tests/unary_ops_test.py. It runs the op inside def_function.function(jit_compile=True) with constant num_bits of 0 and -1 and expects InvalidArgumentError.

bazel test //tensorflow/compiler/tests:unary_ops_test_cpu \
  --test_sharding_strategy=disabled \
  --test_filter='UnaryOpsTest.testQuantizeAndDequantize' --nocache_test_results

Without the kernel change, the new test fails with InvalidArgumentError not raised. With it, the new test and the existing testQuantizeAndDequantize both pass.

@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Sep 27, 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 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.

@keerthanakadiri
keerthanakadiri requested a review from a team September 28, 2026 03:49
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 28, 2026
@keerthanakadiri keerthanakadiri self-assigned this Sep 28, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Sep 28, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 28, 2026
@dmiltr3
dmiltr3 self-requested a review September 28, 2026 12:07

@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 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 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 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)) in tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc matches the CPU kernel in tensorflow/core/kernels/quantize_and_dequantize_op.cc and the sibling QuantizeAndDequantizeV2Op kernel, preventing undefined behavior and 64-bit shift overflow.
  • Zero Steady-State Overhead: The check evaluates only at compile time via ConstantInputAsIntScalar during 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.py covers all boundary conditions across both signed_input=True (0, -1, 62, 63) and signed_input=False (0, -1, 63, 64). The test properly uses session execution with a placeholder input in XLATestCase.
  • 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.

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

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!

@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Oct 3, 2026
@adi-IL

adi-IL commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3. Review 5382693580 is addressed in 8a8f51d.

device_scope. Line 356 of unary_ops_test.py now uses self.device_scope(). I only changed that call. The other test_scope() calls in the file are untouched.

Valid boundary bitwidths. testQuantizeAndDequantizeV3InvalidNumBits now also runs num_bits 1 and 61 with signed_input=True, and 1 and 62 with signed_input=False. Each one must succeed. The invalid cases are unchanged.

Testing. //tensorflow/compiler/tests:unary_ops_test_cpu with --test_filter=testQuantizeAndDequantizeV3InvalidNumBits passes locally on Linux x86_64. As a check that the new cases catch a bound that is too strict, I changed the kernel check to reject 61 and 62. The test then failed with num_bits is out of range: 61 with signed_input_ 1. I reverted that change before committing.

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

  1. Test Naming (tensorflow/compiler/tests/unary_ops_test.py:340): The test method is currently named testQuantizeAndDequantizeV3InvalidNumBits, but it now asserts both invalid bounds and valid extreme boundaries. Please rename it to something more representative, such as testQuantizeAndDequantizeV3NumBitsBoundaries.
<<<<
  def testQuantizeAndDequantizeV3InvalidNumBits(self):
====
  def testQuantizeAndDequantizeV3NumBitsBoundaries(self):
>>>>
  1. IWYU Missing Include (tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc): The codebase heavily relies on errors::InvalidArgument here. 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!

@adi-IL

adi-IL commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3. 57f76fa renames the test to testQuantizeAndDequantizeV3NumBitsBoundaries.

quantize_and_dequantize_op.cc already includes tensorflow/core/platform/errors.h at line 36, with the other tensorflow/core headers. It has been there since 3266dd0, so I did not add it a second time.

I ran unary_ops_test_cpu filtered to the renamed test on 57f76fa and it passed. With the tf2xla bounds tightened back to 61 and 62, the same test fails with "num_bits is out of range".

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

@adi-IL

adi-IL commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 the include is already in the file. Line 36 of tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc at 57f76fa is #include "tensorflow/core/platform/errors.h". This PR does not change that line, so it does not show in the diff. See line 36 at 57f76fa. Adding it again would duplicate the include.

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

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.

@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Oct 5, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 5, 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 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!

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed ready to pull PR ready for merge process labels Oct 6, 2026
@adi-IL
adi-IL force-pushed the bot/tensorflow-127914 branch from 57f76fa to a46cf99 Compare October 6, 2026 07:38
@adi-IL

adi-IL commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 rebased onto latest master and pushed a46cf99. I resolved the conflict in tensorflow/compiler/tests/BUILD. The diff is the same 3 files as before. testQuantizeAndDequantizeV3NumBitsBoundaries passes locally on //tensorflow/compiler/tests:unary_ops_test_cpu.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 6, 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 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:master and force-push? Once rebased, the automated checks will re-run so we can re-approve and merge. Thank you!

@nithyak0204 nithyak0204 added the stat:awaiting response Status - Awaiting response from author label Oct 8, 2026
@adi-IL

adi-IL commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 rebased onto master fb76d99 and pushed d043192. The diff is still 3 files. testQuantizeAndDequantizeV3NumBitsBoundaries passes locally on //tensorflow/compiler/tests:unary_ops_test_cpu. A test merge with master 5ec4bb2 has no conflicts.

@adi-IL
adi-IL force-pushed the bot/tensorflow-127914 branch from a46cf99 to d043192 Compare October 13, 2026 05:50
@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 13, 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.

Outstanding final asks

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

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.

@nithyak0204 nithyak0204 added the stat:awaiting response Status - Awaiting response from author label Oct 13, 2026
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
@adi-IL

adi-IL commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 rebased onto master 6908a11 and pushed 30c975e. Same 3 files. Trial merge with current master is clean (no conflicts on BUILD or unary_ops_test.py).

@adi-IL
adi-IL force-pushed the bot/tensorflow-127914 branch from d043192 to 30c975e Compare October 13, 2026 11:44
@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 13, 2026
@adi-IL

adi-IL commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 CI note on 30c975e. build-linux-x86-cpu is red, but not from this PR. //tensorflow/compiler/tests:unary_ops_test_cpu and unary_ops_test_cpu_mlir_bridge_test both PASSED. The failure is //tensorflow/python/tools:aot_compiled_test failing to build with RuntimeError: Unsupported thunk type: ynn-fusion in the aot_compiled_x_matmul_y_large genrules. CUDA, arm64, and Windows CPU checks passed. Ready for re-review when you are.

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

@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 13, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 13, 2026
@copybara-service
copybara-service Bot merged commit 00669fc into tensorflow:master Oct 15, 2026
16 of 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

kokoro:force-run Tests on submitted change prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

4 participants