OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
feat(pytorch): add support for aten::_fake_quantize_learnable_per_channel_affine (#34577)
Reese Liao10864ee713c0
diff --git a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csvindex 001f7fbbf2e..27e9e270482 100644--- a/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv+++ b/docs/sphinx_setup/_static/conformance_files/pytorch_ops.csv@@ -8,6 +8,7 @@ aten::__range_length,aten::__xor__,aten::_convolution,aten::_convolution_mode,+aten::_fake_quantize_learnable_per_channel_affine,grad_factor is ignored: it only affects gradients.aten::_native_multi_head_attention,aten::_pack_padded_sequence,aten::_pad_packed_sequence,diff --git a/src/frontends/pytorch/src/op/fake_quantize.cpp b/src/frontends/pytorch/src/op/fake_quantize.cppindex 5134b36e707..2e3256d7012 100644--- a/src/frontends/pytorch/src/op/fake_quantize.cpp+++ b/src/frontends/pytorch/src/op/fake_quantize.cpp@@ -7,16 +7,21 @@#include "openvino/frontend/pytorch/node_context.hpp"#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"+#include "openvino/op/clamp.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/maximum.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/round.hpp"#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/subtract.hpp"#include "utils.hpp"-namespace ov::frontend::pytorch::op {+namespace ov {+namespace frontend {+namespace pytorch {+namespace op {using namespace ov::op;@@ -45,19 +50,17 @@ OutputVector translate_fake_quantize_per_tensor_affine(const NodeContext& contexstd::make_shared<v0::FakeQuantize>(input_node, bound_low, bound_high, bound_low, bound_high, levels))};}-OutputVector translate_fake_quantize_per_channel_affine(const NodeContext& context) {- num_inputs_check(context, 6, 6);- auto input_node = context.get_input(0);- auto scale = std::make_shared<v0::Convert>(context.get_input(1), element::f32);- auto zero_point = std::make_shared<v0::Convert>(context.get_input(2), element::f32);- auto axis = get_input_as_i32(context, 3);- auto out_low_const = context.const_input<int64_t>(4);- auto out_high_const = context.const_input<int64_t>(5);- // Calculate levels value - distance between bounds.- auto levels = std::abs(out_high_const - out_low_const) + 1;- auto out_low = std::make_shared<v0::Convert>(context.get_input(4), element::f32);- auto out_high = std::make_shared<v0::Convert>(context.get_input(5), element::f32);-+namespace {+// Build a per-channel FakeQuantize. Scale and zero point are 1D tensors that are broadcast along axis of the input,+// out_low and out_high are the scalar quantization bounds (quant_min and quant_max).+OutputVector make_fake_quantize_per_channel(const NodeContext& context,+ const Output<Node>& input_node,+ const Output<Node>& scale,+ const Output<Node>& zero_point,+ const Output<Node>& axis,+ const Output<Node>& out_low,+ const Output<Node>& out_high,+ size_t levels) {auto const_neg_1 = v0::Constant::create(element::i32, Shape{1}, {-1});auto const_0 = v0::Constant::create(element::i32, Shape{}, {0});auto const_1 = v0::Constant::create(element::i32, Shape{}, {1});@@ -84,5 +87,52 @@ OutputVector translate_fake_quantize_per_channel_affine(const NodeContext& contereturn {context.mark_node(std::make_shared<v0::FakeQuantize>(input_node, bound_low, bound_high, bound_low, bound_high, levels))};}+} // namespace++OutputVector translate_fake_quantize_per_channel_affine(const NodeContext& context) {+ num_inputs_check(context, 6, 6);+ auto out_low_const = context.const_input<int64_t>(4);+ auto out_high_const = context.const_input<int64_t>(5);+ // Calculate levels value - distance between bounds.+ auto levels = static_cast<size_t>(std::abs(out_high_const - out_low_const) + 1);+ return make_fake_quantize_per_channel(context,+ context.get_input(0),+ std::make_shared<v0::Convert>(context.get_input(1), element::f32),+ std::make_shared<v0::Convert>(context.get_input(2), element::f32),+ get_input_as_i32(context, 3),+ std::make_shared<v0::Convert>(context.get_input(4), element::f32),+ std::make_shared<v0::Convert>(context.get_input(5), element::f32),+ levels);+}++OutputVector translate_fake_quantize_learnable_per_channel_affine(const NodeContext& context) {+ // aten::_fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis,+ // int quant_min, int quant_max, float grad_factor=1.0) -> Tensor+ // grad_factor (input 6) only rescales gradients during training, it has no effect on the forward pass,+ // so it is accepted and ignored here.+ num_inputs_check(context, 6, 7);+ auto out_low_const = context.const_input<int64_t>(4);+ auto out_high_const = context.const_input<int64_t>(5);+ // Calculate levels value - distance between bounds.+ auto levels = static_cast<size_t>(std::abs(out_high_const - out_low_const) + 1);+ // Unlike the non-learnable variant, zero point is a float (learnable) tensor here. PyTorch rounds it to the+ // nearest integer and clamps it into [quant_min, quant_max] before quantizing, see _get_rounded_zero_point.+ auto zero_point = std::make_shared<v0::Convert>(context.get_input(2), element::f32);+ auto zero_point_rounded = std::make_shared<v5::Round>(zero_point, v5::Round::RoundMode::HALF_TO_EVEN);+ auto zero_point_clamped = std::make_shared<v0::Clamp>(zero_point_rounded,+ static_cast<double>(out_low_const),+ static_cast<double>(out_high_const));+ return make_fake_quantize_per_channel(context,+ context.get_input(0),+ std::make_shared<v0::Convert>(context.get_input(1), element::f32),+ zero_point_clamped,+ get_input_as_i32(context, 3),+ std::make_shared<v0::Convert>(context.get_input(4), element::f32),+ std::make_shared<v0::Convert>(context.get_input(5), element::f32),+ levels);+}-} // namespace ov::frontend::pytorch::op+} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 857b61db311..5ab5a7931a0 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -96,6 +96,7 @@ OP_CONVERTER(translate_exp);OP_CONVERTER(translate_expm1);OP_CONVERTER(translate_eye);OP_CONVERTER(translate_fake_quantize_per_channel_affine);+OP_CONVERTER(translate_fake_quantize_learnable_per_channel_affine);OP_CONVERTER(translate_fake_quantize_per_tensor_affine);OP_CONVERTER(translate_fft_fft);OP_CONVERTER(translate_fft_fft2);@@ -390,6 +391,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::__ixor__", op::inplace_op<op::translate_bitwise_xor>},{"aten::_convolution", op::translate_convolution},{"aten::_convolution_mode", op::translate_convolution_mode},+ {"aten::_fake_quantize_learnable_per_channel_affine", op::translate_fake_quantize_learnable_per_channel_affine},{"aten::_native_multi_head_attention", op::translate_native_multi_head_attention},{"aten::_pack_padded_sequence", op::translate_pack_padded_sequence},{"aten::_pad_packed_sequence", op::translate_pad_packed_sequence},@@ -870,6 +872,8 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"aten._cdist_forward.default", op::translate_cdist},{"aten._embedding_bag.default", op::translate_embedding_bag},{"aten._embedding_bag_forward_only.default", op::translate_embedding_bag},+ {"aten._fake_quantize_learnable_per_channel_affine.default",+ op::translate_fake_quantize_learnable_per_channel_affine},{"aten._fake_quantize_per_tensor_affine_cachemask_tensor_qparams.default",op::translate_fake_quantize_per_tensor_affine_fx},{"aten._local_scalar_dense.default", op::skip_node},diff --git a/tests/layer_tests/pytorch_tests/test_fake_quantize.py b/tests/layer_tests/pytorch_tests/test_fake_quantize.pyindex 5d4e69bcf57..84ebb8701d0 100644--- a/tests/layer_tests/pytorch_tests/test_fake_quantize.py+++ b/tests/layer_tests/pytorch_tests/test_fake_quantize.py@@ -167,3 +167,57 @@ class TestFakeQuantizePerChannelAffine(PytorchLayerTest):freeze_model=False,fx_kind="aten.fake_quantize_per_channel_affine")+++class TestFakeQuantizeLearnablePerChannelAffine(PytorchLayerTest):+ def _prepare_input(self):+ return (self.random.randn(3, 2, 2),)++ def create_model(self, scale, zero_point, axis, quant_min, quant_max):+ class FakeQuantizeLearnablePerChannelAffine(torch.nn.Module):+ def __init__(self, scale, zero_point, axis, quant_min, quant_max):+ super().__init__()+ self.scale = scale+ self.zero_point = zero_point+ self.axis = axis+ self.quant_min = quant_min+ self.quant_max = quant_max+ self.grad_factor = 1.0++ def forward(self, x):+ return torch._fake_quantize_learnable_per_channel_affine(+ x, self.scale, self.zero_point, self.axis, self.quant_min, self.quant_max, self.grad_factor+ )++ return (+ FakeQuantizeLearnablePerChannelAffine(scale, zero_point, axis, quant_min, quant_max),+ "aten::_fake_quantize_learnable_per_channel_affine",+ )++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.precommit_fx_backend+ @pytest.mark.parametrize(+ "scale, zero_point, axis, quant_min, quant_max",+ [+ # scale and zero_point are learnable parameters, so both must be float tensors.+ (torch.tensor([0.005, 0.7]), torch.zeros(2), 1, 0, 255),+ # fractional zero_point exercises the rounding applied by the aten op+ (torch.tensor([0.5, 0.25]), torch.tensor([1.4, 2.6]), 1, 0, 255),+ # zero_point outside of [quant_min, quant_max] exercises the clamping applied by the aten op+ (torch.tensor([0.5, 0.25]), torch.tensor([-3.0, 400.0]), 1, 0, 255),+ (torch.tensor([1.5, -0.7, -0.1]), torch.tensor([1.0, 0.0, -1.0]), 0, -128, 127),+ ],+ )+ def test_fake_quantize_learnable_per_channel_affine(+ self, ie_device, precision, ir_version, scale, zero_point, axis, quant_min, quant_max+ ):+ self._test(+ *self.create_model(scale, zero_point, axis, quant_min, quant_max),+ ie_device,+ precision,+ ir_version,+ freeze_model=False,+ fx_kind="aten._fake_quantize_learnable_per_channel_affine"+ )