Repository navigation
Conversation
quantize_per_tensor and quantize_per_channel dispatched their input over Float, Double and Half only, and dequantize_per_tensor and dequantize_per_channel their output, so a bfloat16 input or out_dtype hit the ET_CHECK_MSG default branch and aborted the process. Add BFloat16 to these dispatches, the same way Half is handled. The 1-D branch of dequantize_per_channel cast the integer difference to the output type before scaling, so it rounded twice. bfloat16 holds integers exactly only up to 256, which makes this visible with 16-bit inputs; multiply first, as the other branches do.
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25824
Note: Links to docs will display an error until the docs builds have been completed. ❌ 3 New Failures, 1 PendingAs of commit e7fa5bc with merge base aeeeb20 ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@pytorchbot label "release notes: ops & kernels" |
JakeStevens
left a comment
There was a problem hiding this comment.
Reviewed with Codex. All 44 tests in the two affected C++ suites passed locally. Additional comparisons against eager PyTorch 2.14.0 reproduced one regression for existing float64 output and four discrepancies on the newly enabled bfloat16 paths. Each thread includes the inputs and observed results.
| out_data_ptr[current_ix] = static_cast<CTYPE_OUT>( \ | ||
| (input_data_ptr[current_ix] - \ | ||
| static_cast<int32_t>(zero_point)) * \ | ||
| _scale); \ |
There was a problem hiding this comment.
Moving the cast after the product also changes existing Double outputs. With a 1-D int32 input [16777217], zero point [0], and scale [1.0], the multiplication in float32 rounds the result to 16777216 before it widens to double. Both the previous kernel and eager return 16777217. Could you keep a double intermediate for Double output and cover this case alongside the bfloat16 rounding test?
There was a problem hiding this comment.
Thanks, confirmed. Both per-channel branches now subtract in int64 and multiply in the precision of the scale tensor (double for a float64 scale, float otherwise), as the eager op does, then round once. The N-D branch already returned 16777216 for a float64 scale on main, so it gets the same change, and the optimized int8 path, which multiplies in float, is now only taken for a float scale so that the result does not depend on the layout. Your case is in DequantizePerChannelWideIntermediates, for 1-D and 2-D inputs.
| case ScalarType::in_dtype: \ | ||
| switch (out.scalar_type()) { \ | ||
| ET_FORALL_FLOATH_TYPES_WITH(IN_CTYPE, DEQUANTIZE_IMPL); \ | ||
| DEQUANTIZE_IMPL(IN_CTYPE, ::executorch::aten::BFloat16, BFloat16) \ |
There was a problem hiding this comment.
The per-tensor eager operator rounds the input to out_dtype before subtracting the zero point. With int16 input [257], zero point 256, and scale 1, eager rounds 257 to bfloat16 256 and returns 0. This specialization subtracts in integer arithmetic and returns 1. Could the bfloat16 per-tensor path follow eager’s cast order and cover this case? PyTorch reference
There was a problem hiding this comment.
Done: for a bfloat16 output the per-tensor path now rounds the input and the zero point to bfloat16 before subtracting, as eager does, and for a Double output it works in double. Half keeps the integer subtraction: in eager order the existing HalfOutput case (zero point 100000) gives -inf, while the test expects -49995. Float also keeps it, so it still differs from eager for int32 inputs above 2^24. The cases are in DequantizePerTensorFollowsEagerArithmetic.
| _scale; \ | ||
| out_data_ptr[current_ix] = static_cast<CTYPE_OUT>( \ | ||
| (input_data_ptr[current_ix] - \ | ||
| static_cast<int32_t>(zero_point)) * \ |
There was a problem hiding this comment.
For int32 input, narrowing the zero point here makes the subtraction itself overflow. With input [2147483647], int64 zero point [-1], and scale [1.0], the new bfloat16 path returned -2147483648 locally. Eager returns +2147483648, which bfloat16 represents exactly. Please widen the subtraction in both the 1-D and N-D paths before multiplying.
There was a problem hiding this comment.
Fixed in both per-channel branches and in the per-tensor path. Float32 output had the same overflow on main.
|
|
||
| switch (input.scalar_type()) { | ||
| ET_FORALL_FLOATH_TYPES(CALCULATE_FLOAT_TYPE); | ||
| ET_FORALL_FLOATHBF16_TYPES(CALCULATE_FLOAT_TYPE); |
There was a problem hiding this comment.
The scalar fallback selects the channel using the product of the trailing logical sizes. That assigns the wrong scale on channels-last input. For bfloat16 ones of shape [1,2,1,2], axis 1, scales [1.0,0.5], and zero points [0,0], the kernel gives [1,2] in each logical channel. Eager gives [1,1] in channel 0 and [2,2] in channel 1. Could you use the physical stride along axis and add a channels-last case?
There was a problem hiding this comment.
This one predates the PR: float32 input gives the same wrong channels on main. The scalar path now takes the channel from strides()[axis], which is right as long as out has the same dim order as the input (as before, nothing checks that), and the NEON per-channel path only runs on contiguous inputs, since it walks contiguous blocks. QuantizePerChannelChannelsLast covers float32 and bfloat16. I could not run the NEON path myself (x86 only).
|
|
||
| switch (input.scalar_type()) { | ||
| ET_FORALL_FLOATH_TYPES(CALCULATE_FLOAT_TYPE); | ||
| ET_FORALL_FLOATHBF16_TYPES(CALCULATE_FLOAT_TYPE); |
There was a problem hiding this comment.
Both new bfloat16 quantization paths call quantize_val, which narrows the scale before computing its reciprocal. For bfloat16 input [3], scale 0.24 (a float64 scale tensor for per-channel), zero point 0, and int8 output, the scaled value becomes 12.500000953674316 and rounds to 13. Eager returns 12 for both operators. Could you preserve the scale precision through the reciprocal and cover this rounding boundary?
There was a problem hiding this comment.
Also present for float32 input on main. Both ops now take the reciprocal in double and narrow it once, which matches the eager per-tensor op. The eager per-channel op multiplies by a float64 tensor; I kept the product in float so that the scalar path agrees with the NEON one, so a per-channel result can still be off by one at a rounding boundary. I updated the reference in VeryLargePerChannel2DUInt8 to the new reciprocal. The cases are in ScaleReciprocalPrecision. quantized_add still has its own 1.0f / scale in op_add.cpp; I left it alone since #25794 is changing that file.
dequantize_per_channel now subtracts the zero point in int64, so an int32 input no longer overflows, and multiplies in the precision of the scale tensor, so a Double output keeps a double intermediate for a float64 scale. The optimized int8 path, which multiplies in float, is now only taken for a float scale. dequantize_per_tensor follows the eager order for a bfloat16 output, rounding the input and the zero point to bfloat16 before subtracting, and works in double for a Double output; Float and Half keep the integer subtraction, now in int64. quantize_per_tensor and quantize_per_channel take the reciprocal of the scale in double before narrowing it to float. The product stays in float, which matches the eager per-tensor op; the eager per-channel op multiplies in double, so a per-channel result can still differ by one at a rounding boundary. The scalar per-channel path finds the channel from the stride of the axis, so a channels-last input gets the right scale when the output has the same dim order, and the NEON per-channel path is limited to contiguous inputs.
|
Thanks for the careful review. I pushed 0199d9c on top of the original commit, addressing the five threads. Issues 3 to 5 also affected float32 on main, so the fixes apply there too. Locally, |
| value, | ||
| quant_min, | ||
| quant_max); | ||
| static_cast<float>(1.0 / scale), zero_point, value, quant_min, quant_max); |
There was a problem hiding this comment.
The float reciprocal introduces a regression for existing float32 inputs. With input [13], float64 scale [0.208], zero point [0], and int8 output, the base and eager per-channel kernels return 62. This version returns 63 for both float32 and bfloat16 because the product moves from 62.5 to 62.5000038. Eager per-tensor returns 63 for the same values. Could you keep the per-channel reciprocal and product in double through rounding on both the scalar and NEON paths, and add this case to ScaleReciprocalPrecision?
There was a problem hiding this comment.
You are right, that came from my previous commit. quantize_per_channel now keeps the reciprocal and the product in double through rounding, on the scalar path and in a new AArch64 NEON loop (quantize_arm_double). 32-bit ARM has no double vectors, so per-channel takes the scalar path there. Your case is in ScaleReciprocalPrecision with 16 values, so that it reaches the vector loop, next to the per-tensor result (63). The reference in VeryLargePerChannel2DUInt8 now uses a double product too.
| // Distance between consecutive channels in memory, for any dim order. An | ||
| // ATen tensor can have a zero stride on a size-1 axis. | ||
| const int64_t axis_stride = | ||
| std::max<int64_t>(static_cast<int64_t>(input.strides()[axis]), 1); |
There was a problem hiding this comment.
A portable tensor built with TensorImpl(type, rank, sizes, data) has empty strides() and dim_order(). I verified that the base quantizes a float32 input constructed this way. Indexing strides()[axis] here can now crash, and the NEON eligibility check below also dereferences the missing dimension order. Could you retain the size-derived contiguous stride when layout metadata is absent and cover the four-argument constructor in a kernel test?
There was a problem hiding this comment.
Fixed, also from my previous commit. Without strides, the stride is the product of the trailing sizes again, and a tensor without a dim order counts as contiguous. InputWithoutLayoutMetadata builds the input with the four-argument constructor and runs the per-tensor, per-channel (both axes) and per-token ops on it.
|
|
||
| switch (input.scalar_type()) { | ||
| ET_FORALL_FLOATH_TYPES(CALCULATE_FLOAT_TYPE); | ||
| ET_FORALL_FLOATHBF16_TYPES(CALCULATE_FLOAT_TYPE); |
There was a problem hiding this comment.
This dispatch also enables bfloat16 in quantize_per_token_out, which delegates to the per-channel kernel. For input [[0.5]], scale [[1.0]], zero point [[1]], and int8 output, the compiled kernel returns 1. Eager per-token adds the zero point before rounding, so round(0.5 + 1) gives 2. Could you preserve that order in the per-token entry point and add a test with this tie?
There was a problem hiding this comment.
Fixed. quantize_per_token no longer goes through the per-channel kernel: it rounds x * (1 / scale) + zero_point, with the product in double, on the scalar path and on the AArch64 NEON path. This also affected float32 input on main. QuantizePerToken has your tie for float32 and bfloat16, two nine-value tokens that reach the vector loop and its tail, and a 512-value Byte case for the parallel path. NaN still maps to the zero point, as in the other two ops.
| case ScalarType::in_dtype: \ | ||
| switch (out.scalar_type()) { \ | ||
| ET_FORALL_FLOATH_TYPES_WITH(CTYPE_IN, DEQUANTIZE_IMPL); \ | ||
| DEQUANTIZE_IMPL(CTYPE_IN, ::executorch::aten::BFloat16, BFloat16) \ |
There was a problem hiding this comment.
The newly enabled bfloat16 paths expose a layout issue in both per-token wrappers. With channels-last ones of shape [1,2,1,2], matching output layout, and zero points of zero, I tested dequantization with token scales [1,2] and quantization with [1,0.5]. Both kernels returned logical values [1,2,1,2]. Eager returned [1,1,2,2] in both cases. The wrappers reinterpret the buffer as contiguous 2-D storage, which mixes tokens. Could you use the original strides to identify each token and cover both wrappers with this layout?
There was a problem hiding this comment.
Fixed in both wrappers; float32 on main had the same result. quantize_per_token finds each token through the strides. dequantize_per_token keeps the 2-D view for a contiguous input, so the int8 fast path still applies, and otherwise walks each token with an ApplyOverDimListPlan over the last dimension. QuantizePerTokenChannelsLast and DequantizePerTokenChannelsLast cover your layout and a [2,2,2,3] one where each token has its own zero point. As before, out is assumed to have the same dim order as the input, and in ATen mode the input must be dense.
| int64_t zero_point, | ||
| double scale, | ||
| bool double_scale) { | ||
| const int64_t shifted = static_cast<int64_t>(value) - zero_point; |
There was a problem hiding this comment.
The zero-point tensor’s dtype determines the subtraction width in eager. With int32 input [2147483647], zero point [-1], unit scale, and bfloat16 output, eager returns -2147483648 for an int32 zero point and +2147483648 for an int64 zero point. The compiled kernel returns the positive value for both. Could you preserve the promoted integer width with defined wraparound and exercise both zero-point dtypes in DequantizePerChannelWideIntermediates?
There was a problem hiding this comment.
Done. The per-channel subtraction is now unsigned and narrowed to int32 for an Int zero point tensor, or int64 for a Long one, so it wraps as eager does. DequantizePerChannelWideIntermediates runs your case with both zero point dtypes, for 1-D and 2-D inputs, and adds an int64 wrap (int16 input 1, zero point INT64_MIN).
| return (static_cast<double>(value) - zero_point) * scale; | ||
| } else { | ||
| return static_cast<CTYPE_OUT>( | ||
| (static_cast<int64_t>(value) - zero_point) * static_cast<float>(scale)); |
There was a problem hiding this comment.
The scalar zero point accepts the full int64 range. For int8 input 1 and zero_point=INT64_MIN, this evaluates 1 - INT64_MIN in signed int64 before conversion, which is undefined in C++. Eager gives +2^63 for float32 output at unit scale. Could you handle differences outside the int64 range before subtracting and add a boundary test?
There was a problem hiding this comment.
Fixed. For Float and Half outputs, the per-tensor path now checks that value - zero_point fits in int64 and otherwise subtracts in the output type, as eager does. BFloat16 and Double outputs already subtracted in floating point. DequantizePerTensorFollowsEagerArithmetic has zero points INT64_MIN and INT64_MAX for the four output dtypes.
| // The optimized path multiplies in float, which is only exact for a float | ||
| // scale. | ||
| if (!is_contiguous || (in_dtype != ScalarType::Char) || | ||
| (scales.scalar_type() != ScalarType::Float) || |
There was a problem hiding this comment.
This guard disables the contiguous NEON path for the Llama KV cache. It stores its scales in float32, then widens them to float64 immediately before dequantizing each cache, so those scales are exactly representable in float32. On an Apple M4 Max, contiguous int8 input [1,2048,8,64] with scale 0.125 and float32 output took a median of 68 µs on the base and 250 µs here. Could you retain the fast path for exactly representable scales and use double multiplication for scales that need it? KV-cache caller
There was a problem hiding this comment.
Thanks for measuring it. The scale dtype guard is gone, so a contiguous int8 input takes the optimized path again. Its vector loop runs when float represents the scale exactly, where the float product equals the double product rounded to float, and when the zero point fits in int8 (it was truncated before); anything else goes through the scalar loop, which multiplies in double. I have no ARM hardware: the NEON paths pass the test suite under qemu-aarch64, and on x86, where there is no vector loop, your shape through dequantize_per_token takes about 0.6 ms on main, 1.1 ms on the previous commit and 0.7 ms now (median of 201 calls).
Keep the per-channel and per-token quantize products in double, add the per-token zero point before rounding, and locate channels and tokens through the strides, including for tensors without layout metadata. Subtract the per-channel zero point in the type eager promotes to, handle zero points near the int64 limits per tensor, and keep the int8 fast path for scales that float represents exactly.
|
Thanks again. I pushed e7fa5bc on top of 0199d9c for the seven new threads. The first two came from my previous commit; the per-token ones also affected float32 on main. This time I could run the NEON paths: |
Summary
quantize_per_tensorandquantize_per_channel(input) anddequantize_per_tensoranddequantize_per_channel(output) dispatched over Float, Double and Half only, so bfloat16 reached theET_CHECK_MSGdefault branch and aborted the process (#25822). This adds BFloat16 to the four ops and to the per-token ones.The review compared the kernels with the eager
quantized_decomposedops, so the PR also removes the differences it found, most of which affected float32 on main. Quantize takes the reciprocal of the scale in double, keeps the per-channel and per-token products in double (with an AArch64 NEON loop), adds the per-token zero point before rounding, and finds channels and tokens through the strides. Dequantize subtracts per channel in the integer type eager promotes to, multiplies in the precision of the scale tensor, follows eager per tensor for BFloat16 and Double outputs, and handles non-contiguous per-token inputs. Half per-tensor output keeps its integer subtraction.Reading order:
dequantize_per_tensor_valanddequantize_per_channel_val, then their callers;quantize_val_with_inv_scaleandquantize_arm_double, then per-channel and per-token; then the tests.git diff -whides the clang-format realignment of the macros.Fixes #25822
Test plan
Through the Python runtime, the bfloat16 calls from the issue and the cases from the review match eager PyTorch, and 149 of 153 dtype, layout and path combinations match on 4096 random values (the other 4 are Half per tensor).
pytest exir runtime/test kernels/quantized/testfails only where it already fails on main in my build (XNNPACK and demo backends, not built).This PR was authored with the help of Claude Code (Anthropic); I reviewed and tested it.
cc @nil-is-all