-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add quantized_div op (#21294) #21294
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| /* | ||
| * Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| * All rights reserved. | ||
| * | ||
| * This source code is licensed under the BSD-style license found in the | ||
| * LICENSE file in the root directory of this source tree. | ||
| */ | ||
|
|
||
| #include <algorithm> | ||
| #include <cmath> | ||
|
|
||
| #include "cortex_m_ops_common.h" | ||
|
|
||
| namespace cortex_m { | ||
| namespace native { | ||
| namespace { | ||
|
|
||
| template <typename T> | ||
| void quantized_div_typed( | ||
| const Tensor& input1, | ||
| const int32_t zp1, | ||
| const Tensor& input2, | ||
| const int32_t zp2, | ||
| const int32_t out_zp, | ||
| const float effective_scale, | ||
| Tensor& out) { | ||
| const T* input1_ptr = input1.data_ptr<T>(); | ||
| const T* input2_ptr = input2.data_ptr<T>(); | ||
| T* out_ptr = out.mutable_data_ptr<T>(); | ||
|
|
||
| // Saturation bounds kept in float: a denominator quantized to a single step | ||
| // off its zero point yields a very large quotient, so rounding and clamping | ||
| // in float avoids overflowing int32 before the saturating cast below. | ||
| constexpr float kActivationMin = | ||
| static_cast<float>(std::numeric_limits<T>::min()); | ||
| constexpr float kActivationMax = | ||
| static_cast<float>(std::numeric_limits<T>::max()); | ||
|
|
||
| const int64_t num_elements = out.numel(); | ||
| for (int64_t i = 0; i < num_elements; ++i) { | ||
| const int32_t numerator = static_cast<int32_t>(input1_ptr[i]) - zp1; | ||
| const int32_t denominator = static_cast<int32_t>(input2_ptr[i]) - zp2; | ||
|
|
||
| // A zero-point-corrected denominator of 0 has no representable reciprocal; | ||
| // emit a 0 quotient so the op stays total (callers keep divisors off the | ||
| // zero point). | ||
| const float quotient = (denominator != 0) | ||
| ? static_cast<float>(numerator) / static_cast<float>(denominator) | ||
| : 0.0f; | ||
|
|
||
| const float scaled = | ||
| std::round(quotient * effective_scale) + static_cast<float>(out_zp); | ||
| const float clamped = | ||
| std::max(kActivationMin, std::min(kActivationMax, scaled)); | ||
| out_ptr[i] = static_cast<T>(clamped); | ||
| } | ||
| } | ||
|
|
||
| } // namespace | ||
|
|
||
| using KernelRuntimeContext = torch::executor::KernelRuntimeContext; | ||
|
|
||
| // CMSIS-NN has no integer elementwise-division primitive, so the quotient is | ||
| // evaluated in float. Unlike quantized_mul/add there is no fixed-point path to | ||
| // feed, so the effective scale (scale_in1 / (scale_in2 * scale_out)) is | ||
| // computed AoT and carried directly as a float rather than as a | ||
| // multiplier/shift pair. Both int8 and int16 activations are supported. | ||
| // cppcheck-suppress unusedFunction | ||
| Tensor& quantized_div_out( | ||
| KernelRuntimeContext& context, | ||
| const Tensor& input1, | ||
| const int64_t input1_zero_point, | ||
| const Tensor& input2, | ||
| const int64_t input2_zero_point, | ||
| const int64_t output_zero_point, | ||
| const double output_scale, | ||
| Tensor& out) { | ||
| const ScalarType dtype = out.scalar_type(); | ||
| if (dtype != ScalarType::Char && dtype != ScalarType::Short) { | ||
| ET_LOG( | ||
| Error, | ||
| "quantized_div: only int8 and int16 are supported, got %d", | ||
| static_cast<int>(dtype)); | ||
| context.fail(Error::InvalidArgument); | ||
| return out; | ||
| } | ||
|
|
||
| // Division is not commutative, so channel broadcasting (which relies on | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is not a mathematical blocker right? I don't see a good reason for not supporting broadcasting, the loop just needs to be a bit smarter about how it selects indices. |
||
| // operand swapping in quantized_mul) is unsupported: require equal shapes. | ||
| validate_cmsis_nn_tensor_requirements( | ||
| input1, | ||
| input2, | ||
| out, | ||
| dtype, | ||
| /*require_channels_last=*/false, | ||
| /*require_same_sizes=*/true); | ||
|
|
||
| // The rescale is carried entirely by effective_scale (float), so the shared | ||
| // validator only needs to sanity-check the three zero points; pass identity | ||
| // multiplier/shift for each operand. | ||
| const int32_t kIdentityMultiplier(/*value=*/1); | ||
| const int32_t kZeroShift(/*value=*/0); | ||
| validate_quantization_params( | ||
| input1_zero_point, | ||
| kIdentityMultiplier, | ||
| kZeroShift, | ||
| input2_zero_point, | ||
| kIdentityMultiplier, | ||
| kZeroShift, | ||
| output_zero_point, | ||
| kIdentityMultiplier, | ||
| kZeroShift); | ||
|
|
||
| const int32_t zp1 = static_cast<int32_t>(input1_zero_point); | ||
| const int32_t zp2 = static_cast<int32_t>(input2_zero_point); | ||
| const int32_t out_zp = static_cast<int32_t>(output_zero_point); | ||
|
|
||
| const float effective_scale = static_cast<float>(output_scale); | ||
|
|
||
| if (dtype == ScalarType::Char) { | ||
| quantized_div_typed<int8_t>( | ||
| input1, zp1, input2, zp2, out_zp, effective_scale, out); | ||
| } else { | ||
| quantized_div_typed<int16_t>( | ||
| input1, zp1, input2, zp2, out_zp, effective_scale, out); | ||
| } | ||
|
|
||
| return out; | ||
| } | ||
|
|
||
| } // namespace native | ||
| } // namespace cortex_m | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,6 +12,7 @@ | |
| PatternQuantizer, | ||
| SharedQspecQuantizer, | ||
| ) | ||
| from executorch.backends.arm.quantizer.quantization_config import QuantizationConfig | ||
| from executorch.backends.cortex_m.passes.cortex_m_pass_manager import CortexMPassManager | ||
| from executorch.backends.cortex_m.quantizer.node_finders import ( | ||
| GlobalNodeFinder, | ||
|
|
@@ -45,7 +46,20 @@ def mark_node_as_annotated( | |
|
|
||
| class CortexMQuantizer(ComposableQuantizer): | ||
|
|
||
| def __init__(self) -> None: | ||
| def __init__(self, per_tensor_config: Optional[QuantizationConfig] = None) -> None: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changes public API, but looks reasonable to me. Can you add a proper docstring? |
||
| """Cortex-M PT2E quantizer. | ||
|
|
||
| Args: | ||
| per_tensor_config: Per-tensor activation config applied to the | ||
| non-conv elementwise ops (div/mul/add/...) that | ||
| ``GlobalNodeFinder`` matches anywhere in the graph. Convolutions | ||
| are always quantized with the per-channel config. Defaults to | ||
| ``INT8_PER_TENSOR_CONFIG``; pass ``INT16_PER_TENSOR_CONFIG`` to | ||
| quantize the ops that support it (e.g. ``quantized_div``) with | ||
| int16 activations. | ||
| """ | ||
| per_tensor_config = per_tensor_config or INT8_PER_TENSOR_CONFIG | ||
|
|
||
| conv_targets: set[OpOverload] = set() | ||
| for key in CONV_OP_PATTERNS.keys() | CONV_TRANSPOSE_OP_PATTERNS.keys(): | ||
| conv_targets.update(key) | ||
|
|
@@ -67,7 +81,7 @@ def __init__(self) -> None: | |
| pattern_matcher=pattern_matcher, | ||
| ), | ||
| PatternQuantizer( | ||
| INT8_PER_TENSOR_CONFIG, | ||
| per_tensor_config, | ||
| node_finder=GlobalNodeFinder(), | ||
| pattern_matcher=pattern_matcher, | ||
| ), | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you motivate the choice of 0 here?