Skip to content

Clamp quantized_add_out results before integer conversion - #25794

Open
professor-moody wants to merge 1 commit into
pytorch:mainfrom
professor-moody:fix-quantized-add-nonfinite-out-scale-att-608254ae9e3876f7
Open

professor-moody wants to merge 1 commit into
pytorch:mainfrom
professor-moody:fix-quantized-add-nonfinite-out-scale-att-608254ae9e3876f7

Conversation

@professor-moody

@professor-moody professor-moody commented Nov 30, 2026 •

Copy link
Copy Markdown

Summary

quantize_val in kernels/quantized/cpu/op_add.cpp converts zero_point + std::nearbyint(inv_scale * value) directly to int64_t before clamping to the quantized range and divides by static_cast<float>(scale) without guarding zero scales. Because quantized_add_out does not constrain scales, a zero, float-subnormal, NaN, or very small out_scale (or large input scales) makes inv_scale infinite or NaN or pushes the scaled sum past the int64_t range, causing float-to-integer conversion undefined behavior, float divide-by-zero undefined behavior, and silent output corruption in release builds when reached through .pte execution of quantized_decomposed::add.out. UBSan reports "op_add.cpp:33:33: runtime error: inf is outside the range of representable values of type 'long'" and, under float-divide-by-zero checks, "op_add.cpp:32:26: runtime error: division by zero".

Three related boundary issues sit on the same path in kernels/quantized/cpu/op_add.cpp. First, quantized_add_out checks quant_min and quant_max against [0, 255] for every integer dtype, which allows quant_max up to 255 for ScalarType::Char (int8_t, max 127) and causes float-to-int8_t conversion overflow or wraparound. Second, quantized_add_out truncates a_zero_point_l, b_zero_point_l, and out_zero_point_l from int64_t to int32_t before calling add_tensors, flipping the sign of out-of-range zero points before clamping. Third, dequantize_val computes value - zero_point in signed int64_t for ScalarType::Long, triggering signed integer overflow on extreme inputs.

#22811 defined non-finite quantization semantics in kernels/quantized/cpu/op_quantize.cpp: NaN maps to the clamped zero point, and values are clamped in double before integer conversion. This applies those semantics to quantize_val in kernels/quantized/cpu/op_add.cpp while avoiding division by zero on zero scales (preserving the sign of zero via std::copysign), converting the clamped double via int64_t, capping quant_max to 127 for ScalarType::Char, preserving int64_t zero points into add_tensors, and performing the subtraction in dequantize_val in double. Finite in-range results are unchanged.

Test plan

Added four tests to kernels/quantized/test/op_add_test.cpp: OutScaleOverflowSaturatesBeforeIntegerConversion, OutZeroPointClampedOnNaN, CharDtypeSaturatesWithinSignedRangeAndRejectsOutOfRangeQuantMax, and LongDtypeDequantizeExtremeValuesDoNotOverflow.

cmake -S . -B build-san \
  -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
  -DEXECUTORCH_BUILD_TESTS=ON \
  -DEXECUTORCH_BUILD_KERNELS_OPTIMIZED=ON \
  -DEXECUTORCH_BUILD_KERNELS_QUANTIZED=ON \
  -DEXECUTORCH_USE_SANITIZER=ON \
  -DEXECUTORCH_ENABLE_LOGGING=OFF
cmake --build build-san -j --target quantized_kernels_test
./build-san/kernels/test/quantized_kernels_test

Built and ran quantized_kernels_test unfiltered on Linux x86_64 with Clang 21.1.8 across three configurations: EXECUTORCH_USE_CPP_CODE_COVERAGE, EXECUTORCH_USE_SANITIZER (ASan+UBSan), and ASan+UBSan with float-divide-by-zero checks. All 98 tests pass in all three configurations with zero sanitizer diagnostics, and coverage confirms every touched line and branch in quantize_val, dequantize_val, and quantized_add_out executes. Without the kernels/quantized/cpu/op_add.cpp changes, all four new tests fail and UBSan reports the overflow and divide-by-zero errors above.

Also verified end-to-end .pte execution of quantized_decomposed::add.out through both executor_runner and the C++ Module API on Linux x86_64 in ASan+UBSan with float-divide-by-zero checks and stock Release (-O2 -DNDEBUG), using InternalConsistency program verification in the sanitizer Module build (where program verification is enabled) and default Minimal verification in executor_runner and stock Release (where program verification is off by default and Module falls back to Minimal). Across a benign finite control and ten non-finite/boundary .pte programs covering zero, negative-zero, float-underflow, subnormal, NaN, infinite, out-of-int32 zero-point, signed-Char, and extreme-Long inputs, the benign control produces identical outputs before and after the fix, unpatched builds reproduce the UBSan failures (and silent output corruption or int8_t wraparound in Release), and patched builds produce the expected saturated outputs and reject ScalarType::Char quant_max above 127 with zero sanitizer diagnostics.

AI assistance was used in drafting and validating this change; the patch and tests were reviewed and verified by the author.

cc @nil-is-all

@pytorch-bot

pytorch-bot Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25794

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 926f6be with merge base 48afcd7 (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 30, 2026
@executorch-triage executorch-triage Bot added the community: contribution PRs coming from community (excluding hardware partners) label Nov 30, 2026
@JakeStevens
JakeStevens self-requested a review November 30, 2026 15:16
@JakeStevens JakeStevens added the release notes: ops & kernels Changes to the opset and any new / changed kernel implementations label Nov 30, 2026
@JakeStevens

Copy link
Copy Markdown
Contributor

@claude review effort=max

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Claude finished @JakeStevens's task in 31m 55s —— View job


Request Changes (no blockers): widening the a/b zero points breaks the documented Dq → add → Q equivalence with dequantize_per_tensor_out, the Char bounds fix only covers the upper end and leaves the PREREQ docstring stale, quantize_val is a copy of the op_quantize.cpp helper that already differs from it, and a few new test cases can't catch a missing write.

Detailed review

PR Review: #25794

Summary

This PR changes quantized_decomposed::add.out in kernels/quantized/cpu/op_add.cpp:

  • NaN maps to the zero point, and values are clamped before the integer conversion.
  • quant_max is capped at 127 for ScalarType::Char.
  • int64_t zero points are passed through to add_tensors.
  • The dequantize subtraction is done in double.

Nothing blocks merging. The problems are:

  • an unintended semantic change for the a/b zero points;
  • an incomplete Char bounds fix;
  • a duplicated helper;
  • a few test gaps.

I reviewed both changed files by reading the code and working the arithmetic by hand. I did not build or run the tests in this job.

API Design

  • Widening a_zero_point/b_zero_point breaks the documented Dq → add → Q equivalence (op_add.cpp:56, :93-94, :157, :160).
    • dequantize_per_tensor_out still narrows the zero point to int32_t (op_dequantize.cpp:304) and doesn't validate it.
    • Before this PR, both paths truncated the same way. Now they disagree once |zero_point| > INT32_MAX.
    • Example: Byte a = b = 200, a_zero_point = 3000000000, b_zero_point = out_zero_point = 128, all scales 0.1, range [0, 255]. The reference Dq → add → Q path and the pre-PR kernel both give 255; this PR gives 0.
    • The description's sign-flip argument only holds for out_zero_point. That is the only zero point that gets clamped, and its int64_t handling matches quantize_val_with_inv_scale.
    • The narrowing this PR removes sat under // downsize to maintain numerical consistency with fbgemm (:147).
    • No test covers a/b zero points outside the int32 range: OutZeroPointClampedOnNaN (op_add_test.cpp:543) only varies out_zero_point, and only on the NaN path.
    • Suggested fix: keep narrowing a/b to int32_t and widen only out_zero_point_l, or also widen op_dequantize.cpp. Either way, add a test that compares against the reference path, like ConsitencyWithReferencePattern. Fix this →
  • The Char bounds fix only covers the upper end (op_add.cpp:116-145).
    • Char still requires quant_min >= 0, so the kernel accepts [0, 127]. check_quantize_per_tensor_args uses [-128, 127] for Char (op_quantize.cpp:60-64).
    • Standard int8 ranges such as [-128, 127] and [-127, 127] are therefore still rejected.
    • The new messages give Char's bounds as [0,127].
    • The PREREQ docstring (:96-97) still says [0,255] for every dtype.
    • The test name CharDtypeSaturatesWithinSignedRange... (op_add_test.cpp:566-568) suggests the signed range is supported.
    • The double clamp at :42-44 already handles negative bounds, so only the check needs to change: use [-128, 127] for Char and keep [0, 255] for the other dtypes. Also update the docstring and messages, and add a Char case with a negative quant_min. Fix this →

Code Quality

  • quantize_val (op_add.cpp:25-46) copies quantize_val_with_inv_scale (op_quantize.cpp:95-112), and the copy already differs from the original.
    • It adds a zero-scale guard (:33-35).
    • It adds an extra cast through int64_t (:45), where the original uses static_cast<T>(clamped_value) (:111).
    • With two copies, a future fix to one won't reach the other.
    • The guard returns the same value as IEEE 1.0f / ±0.0f. Its only effect is to silence the opt-in float-divide-by-zero check cited in the description, and only in this file. quantize_val in op_quantize.cpp:122, which quantize_per_tensor_out uses on the reference path, still divides without a guard, so a float-divide-by-zero build still reports a zero scale there.
    • Suggested fix: move the helper into a shared header and call it from add_tensors, computing inv_scale once before the loop. The header needs a small Buck target, like embeddingxb in kernels/quantized/cpu/targets.bzl. Fix this →
  • Each of the 13 new quantized_add_out calls takes 15 positional arguments, mostly bare literals, so the argument under test is hard to spot.
    • For example, in the death tests at op_add_test.cpp:614-667 you have to count arguments to find the invalid bound.
    • The existing tests use named locals (DifferentQParams, InvalidMinMaxDies).
    • Suggested fix: a small local helper that takes only the arguments that vary. Fix this →

Testing

  • qoutput is reused across calls without being reset. When a call expects the same output as the previous call, it can't detect a missing write.
    • This affects every iteration after the first in the loops at op_add_test.cpp:425, :448, :471 and :574.
    • It also affects zero_point = 3000000000 at :543, which follows 300 and expects the same 240.
    • Suggested fix: fill qoutput with a sentinel before each call.
  • The Char test checks the 128 boundary on the wrong tensors.
    • The a/b death tests use 128 (:638, :661), but the a/b bounds never reach add_tensors.
    • The out-side death test guards the actual int8 cast but uses 255 (:629), so an off-by-one in the out check wouldn't be caught.
    • There is also no Char case with an ordinary finite out_scale: every case either saturates or uses NaN. AllDtypesSupported (:94-96) only runs Byte. Fix this →
  • Question for maintainers (low confidence): the negative-scale loop (:447-468) fixes the expected outputs for a negative out_scale, which is not a valid affine qparam, as sign-flipped values. Should that be part of the contract? If scale validation is added later, these cases would have to become death tests.

Specific Comments

  • op_add_test.cpp:413: the test name only mentions OutScale, but :496-532 test input-scale overflow.
  • op_add_test.cpp:422-424: "map 0 * inf (NaN) to the zero point" doesn't hold for 1e-30. There inv_scale is a finite 1e30, so the zero sum stays 0 and maps to the zero point through normal rounding.
  • PR description: "Finite in-range results are unchanged" isn't strictly true. The old code added the zero point in float, and the new code adds it in double, so results change for |out_zero_point| > 2^24. For example, out_zero_point = 16777217 with a scaled sum of -16777000 gave 216 before this PR and gives 217 now.
  • PR description: the AI disclosure doesn't name the tool, which CLAUDE.md asks for.

Recommendation

Request Changes. Nothing blocks merging, but two things should be settled first:

  • The a/b zero-point change is a behaviour change introduced by this PR.
  • The Char bounds and docstring are in code this PR touches.

The test fixes are small.


  • Gather PR context and diff
  • Run three independent reviews
  • Consolidate and fact-check findings
  • Post final review

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. community: contribution PRs coming from community (excluding hardware partners) release notes: ops & kernels Changes to the opset and any new / changed kernel implementations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants