-
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,123 @@ | ||
| /* | ||
| * 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>(); | ||
|
|
||
| constexpr int32_t kActivationMin = std::numeric_limits<T>::min(); | ||
| constexpr int32_t kActivationMax = 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; | ||
|
|
||
| const float quotient = (denominator != 0) | ||
| ? static_cast<float>(numerator) / static_cast<float>(denominator) | ||
| : 0.0f; | ||
|
|
||
| int32_t result = | ||
| static_cast<int32_t>(std::round(quotient * effective_scale)) + out_zp; | ||
|
Contributor
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. If we're not worried about performance here, we might want to keep this and the clamp in float to avoid any risk of exceeding int32 bounds.
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. +1 |
||
| result = std::max(kActivationMin, std::min(kActivationMax, result)); | ||
| out_ptr[i] = static_cast<T>(result); | ||
| } | ||
| } | ||
|
|
||
| } // namespace | ||
|
|
||
| using KernelRuntimeContext = torch::executor::KernelRuntimeContext; | ||
|
|
||
| // CMSIS-NN has no integer elementwise-division primitive, so the quotient is | ||
| // evaluated in float. The effective scale (scale_in1 / (scale_in2 * scale_out)) | ||
| // is carried in the AoT-computed output_multiplier/output_shift and | ||
| // reconstructed here, mirroring the softmax kernel's fixed-point-to-float | ||
| // reconstruction. 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 int64_t output_multiplier, | ||
| const int64_t output_shift, | ||
| 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); | ||
|
|
||
| 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, | ||
| output_multiplier, | ||
| output_shift); | ||
|
|
||
| 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 = std::ldexp( | ||
| static_cast<float>(output_multiplier) / static_cast<float>(1LL << 31), | ||
| static_cast<int>(output_shift)); | ||
|
|
||
| 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 |
|---|---|---|
|
|
@@ -960,6 +960,36 @@ def _get_mul_replacement( | |
| return DialectNodeSpec(exir_ops.edge.cortex_m.quantized_mul.default, args) | ||
|
|
||
|
|
||
| @AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.div.Tensor) | ||
| def _get_div_replacement( | ||
| node: Node, dialect_pass: AtenToDialectPass | ||
| ) -> DialectNodeSpec | None: | ||
| del dialect_pass | ||
| if not _has_qparams(node): | ||
| return None | ||
|
|
||
| scale1 = node.meta["input_qparams"][0].scale | ||
| zero_point1 = node.meta["input_qparams"][0].zp | ||
| scale2 = node.meta["input_qparams"][1].scale | ||
| zero_point2 = node.meta["input_qparams"][1].zp | ||
| output_scale = node.meta["output_qparams"][0].scale | ||
| output_zero_point = node.meta["output_qparams"][0].zp | ||
|
|
||
| output_mult, output_shift = quantize_multiplier_aot( | ||
|
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. Why do this an then reverse in the kernel? Is this just to mirror other operators? |
||
| scale1 / (scale2 * output_scale) | ||
| ) | ||
| args = ( | ||
| node.args[0], | ||
| zero_point1, | ||
| node.args[1], | ||
| zero_point2, | ||
| output_zero_point, | ||
| output_mult, | ||
| output_shift, | ||
| ) | ||
| return DialectNodeSpec(exir_ops.edge.cortex_m.quantized_div.default, args) | ||
|
|
||
|
|
||
| @AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten._softmax.default) | ||
| def _get_softmax_replacement( | ||
| node: Node, dialect_pass: AtenToDialectPass | ||
|
|
||
| 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,12 @@ 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? |
||
| # Per-tensor activation config used for the "global" (non-conv) ops such | ||
|
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. Hm, I have not heard of "global" ops. What does that mean? |
||
| # as elementwise div/mul/add. Defaults to int8; pass INT16_PER_TENSOR_CONFIG | ||
| # to quantize supported ops (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 +73,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?