Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Support for INT4 decompression patterns from NNCF (#27048)

Alexander Suslovf1dc976a0ab2
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
index a99fdb4ebc6..bb272b4f9ad 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
@@ -114,9 +114,28 @@ class Partitioner:
for pattern_op in enabled_ops:
self.supported_ops.enable_by_name(pattern_op)
+ def capture_nncf_patterns(self, graph_module: GraphModule):
+ const_node = PatternNode
+ const_node.op_types["get_attr"] = None
+ bitwise_right_shift_node = PatternNode
+ bitwise_right_shift_node.op_types["call_function:aten.bitwise_right_shift.Tensor_Scalar"] = [const_node]
+ bitwise_and_node = PatternNode
+ bitwise_and_node.op_types["call_function:aten.bitwise_and.Scalar"] = [const_node,]
+ stack_node = PatternNode
+ stack_node.op_types["call_function:aten.stack.default"] = [bitwise_and_node, bitwise_right_shift_node]
+
+ for node in graph_module.graph.nodes:
+ if str(node.op) == "call_function" and str(node.target) == "aten.stack.default":
+ enabled_ops = []
+ pattern_match = self.check_pattern(node, bitwise_and_node, enabled_ops)
+ if pattern_match:
+ for pattern_op in enabled_ops:
+ self.supported_ops.enable_by_name(pattern_op)
+
def make_partitions(self, graph_module: GraphModule, options) -> GraphModule:
allow_single_node_partition = _is_testing(options)
self.capture_gptq_patterns(graph_module)
+ self.capture_nncf_patterns(graph_module)
partitioner = CapabilityBasedPartitioner(
graph_module, self.supported_ops, allows_single_node_partition=allow_single_node_partition)
partitions = partitioner.propose_partitions()
diff --git a/src/frontends/pytorch/src/frontend.cpp b/src/frontends/pytorch/src/frontend.cpp
index 5906043e512..2b0ab6db9d3 100644
--- a/src/frontends/pytorch/src/frontend.cpp
+++ b/src/frontends/pytorch/src/frontend.cpp
@@ -320,6 +320,7 @@ void FrontEnd::normalize(const std::shared_ptr<ov::Model>& model) const {
model->get_rt_info().erase("symmetric_quantization");
}
manager.register_pass<ov::frontend::pytorch::pass::U4BlockRepack>(sym);
+ manager.register_pass<ov::frontend::pytorch::pass::U4ConvertReshape>();
manager.register_pass<ov::pass::RemoveMultiSubGraphOpDanglingParamsResults>();
manager.run_passes(model);
diff --git a/src/frontends/pytorch/src/op/cat.cpp b/src/frontends/pytorch/src/op/cat.cpp
index 4ae2c4ebc81..d4f12cae258 100644
--- a/src/frontends/pytorch/src/op/cat.cpp
+++ b/src/frontends/pytorch/src/op/cat.cpp
@@ -146,9 +146,17 @@ OutputVector translate_stack_fx(const NodeContext& context) {
num_elements -= 1;
}
+ OutputVector stack_inputs;
for (size_t i = 0; i < num_elements; i++) {
- auto stack_input =
- context.mark_node(std::make_shared<v0::Unsqueeze>(context.get_input(static_cast<int>(i)), dim));
+ stack_inputs.push_back(context.get_input(static_cast<int>(i)));
+ }
+
+ // returns the u4 constant if the stack operation is a part of the decompression pattern
+ if (const auto& u4_const = u4_compression_stack(stack_inputs, axis))
+ return {u4_const};
+
+ for (size_t i = 0; i < num_elements; i++) {
+ auto stack_input = context.mark_node(std::make_shared<v0::Unsqueeze>(stack_inputs[i], dim));
list_elems.push_back(stack_input);
}
return translate_cat_common(context, list_elems, axis, true);
diff --git a/src/frontends/pytorch/src/transforms/u4_block_repack.cpp b/src/frontends/pytorch/src/transforms/u4_block_repack.cpp
index 5130424d0c6..797fa531c43 100644
--- a/src/frontends/pytorch/src/transforms/u4_block_repack.cpp
+++ b/src/frontends/pytorch/src/transforms/u4_block_repack.cpp
@@ -6,10 +6,12 @@
#include "openvino/core/rt_info.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "utils.hpp"
#include "utils_quantize.hpp"
@@ -122,6 +124,79 @@ U4BlockRepack::U4BlockRepack(bool is_symmetrical) {
});
};
+U4ConvertReshape::U4ConvertReshape() {
+ const auto& m_constant = wrap_type<v0::Constant>(type_matches(element::u4));
+ const auto& m_convert = wrap_type<v0::Convert>({m_constant});
+
+ const auto& m_constant_1 = wrap_type<v0::Constant>();
+ const auto& m_convert_1 = wrap_type<v0::Convert>({m_constant_1});
+ const auto& m_constant_8 = wrap_type<v0::Constant>();
+ const auto& m_convert_8 = wrap_type<v0::Convert>({m_constant_8});
+ const auto& m_multiply = wrap_type<v1::Multiply>({m_convert_8, m_convert_1});
+
+ const auto& m_converted_constant_8 =
+ std::make_shared<ov::pass::pattern::op::Or>(ov::OutputVector{m_multiply, m_convert_8});
+ const auto& m_subtract = wrap_type<v1::Subtract>({m_convert, m_converted_constant_8});
+ const auto& m_converted_constant =
+ std::make_shared<ov::pass::pattern::op::Or>(ov::OutputVector{m_subtract, m_constant});
+ const auto& m_reshape = wrap_type<v1::Reshape>({m_converted_constant, any_input()});
+
+ register_matcher(
+ std::make_shared<Matcher>(m_reshape, "ov::frontend::pytorch::pass::U4ConvertReshape"),
+ [=](Matcher& m) {
+ auto& pattern_to_output = m.get_pattern_value_map();
+ auto u4_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(pattern_to_output[m_constant].get_node_shared_ptr());
+ if (!u4_const)
+ return false;
+
+ if (u4_const->get_element_type() != element::u4)
+ return false;
+
+ auto reshape = pattern_to_output[m_reshape].get_node_shared_ptr();
+ auto dst_shape = reshape->get_output_shape(0);
+
+ std::shared_ptr<v0::Constant> new_const;
+ if (pattern_to_output.count(m_constant_8)) {
+ auto constant_8 = std::dynamic_pointer_cast<ov::op::v0::Constant>(
+ pattern_to_output[m_constant_8].get_node_shared_ptr());
+ if (ov::shape_size(constant_8->get_output_shape(0)) != 1 ||
+ constant_8->get_output_element_type(0).is_real() || constant_8->cast_vector<int64_t>()[0] != 8)
+ return false;
+
+ if (pattern_to_output.count(m_constant_1)) {
+ auto constant_1 = std::dynamic_pointer_cast<ov::op::v0::Constant>(
+ pattern_to_output[m_constant_1].get_node_shared_ptr());
+ if (ov::shape_size(constant_1->get_output_shape(0)) != 1 ||
+ constant_1->get_output_element_type(0).is_real() || constant_1->cast_vector<int64_t>()[0] != 1)
+ return false;
+ }
+
+ new_const = std::make_shared<v0::Constant>(element::i4, dst_shape);
+ auto dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));
+
+ auto src = u4_const->get_data_ptr<uint8_t>();
+ auto num_elements = ov::shape_size(u4_const->get_output_shape(0));
+
+ for (size_t i = 0; i < num_elements / 2; ++i) {
+ // subtracting 8 from 2 int4 elements
+ dst[i] = src[i] ^ 0b10001000;
+ }
+ } else {
+ new_const = std::make_shared<v0::Constant>(*u4_const, dst_shape);
+ }
+
+ NodeVector pattern_nodes;
+ for (auto const& iout : pattern_to_output)
+ pattern_nodes.push_back(std::move(iout.first));
+
+ copy_runtime_info(pattern_nodes, new_const);
+ replace_node(reshape, new_const);
+
+ return true;
+ });
+};
+
} // namespace pass
} // namespace pytorch
} // namespace frontend
diff --git a/src/frontends/pytorch/src/transforms/u4_block_repack.hpp b/src/frontends/pytorch/src/transforms/u4_block_repack.hpp
index 6ab65a5d1c3..99742ff1488 100644
--- a/src/frontends/pytorch/src/transforms/u4_block_repack.hpp
+++ b/src/frontends/pytorch/src/transforms/u4_block_repack.hpp
@@ -18,6 +18,12 @@ public:
U4BlockRepack(bool is_symmetrical = false);
};
+class U4ConvertReshape : public ov::pass::MatcherPass {
+public:
+ OPENVINO_RTTI("ov::frontend::pytorch::pass::U4ConvertReshape");
+ U4ConvertReshape();
+};
+
} // namespace pass
} // namespace pytorch
} // namespace frontend
diff --git a/src/frontends/pytorch/src/utils_quantize.cpp b/src/frontends/pytorch/src/utils_quantize.cpp
index e48c61314f4..ad8f91bcda2 100644
--- a/src/frontends/pytorch/src/utils_quantize.cpp
+++ b/src/frontends/pytorch/src/utils_quantize.cpp
@@ -237,12 +237,15 @@ std::shared_ptr<Node> u4_compression_stack(const OutputVector& list_elems, int64
return nullptr;
}
- auto bitwise_shift = cast_fw_node(list_elems[1].get_node_shared_ptr(), "aten::bitwise_right_shift");
+ auto bitwise_shift = cast_fw_node(list_elems[1].get_node_shared_ptr(),
+ {"aten::bitwise_right_shift", "aten.bitwise_right_shift.Tensor_Scalar"});
if (!bitwise_shift)
return nullptr;
auto weights_u8 = std::dynamic_pointer_cast<v0::Constant>(bitwise_and->get_input_node_shared_ptr(0));
- if (weights_u8 != std::dynamic_pointer_cast<v0::Constant>(bitwise_shift->get_input_node_shared_ptr(0)))
+ auto weights_u8_bitwise_shift =
+ std::dynamic_pointer_cast<v0::Constant>(bitwise_shift->get_input_node_shared_ptr(0));
+ if (weights_u8->get_data_ptr() != weights_u8_bitwise_shift->get_data_ptr())
return nullptr;
if (weights_u8->get_output_element_type(0) != element::u8)
diff --git a/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py b/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py
index a44ca8c0117..0672ad05dec 100644
--- a/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py
+++ b/tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py
@@ -151,6 +151,8 @@ class PytorchLayerTest:
config = {}
if ie_device == "GPU" and precision == "FP32":
config[hints.inference_precision] = Type.f32
+ if "dynamic_quantization_group_size" in kwargs:
+ config["DYNAMIC_QUANTIZATION_GROUP_SIZE"] = str(kwargs["dynamic_quantization_group_size"])
compiled = core.compile_model(converted_model, ie_device, config)
infer_res = compiled(deepcopy(ov_inputs))
@@ -289,6 +291,8 @@ class PytorchLayerTest:
options={"testing": 1,}
if ("aot_autograd" in kwargs):
options.update({"aot_autograd": True,})
+ if "dynamic_quantization_group_size" in kwargs:
+ options["config"] = {"DYNAMIC_QUANTIZATION_GROUP_SIZE": str(kwargs["dynamic_quantization_group_size"])}
dynamic = False
if ("dynamic" in kwargs):
dynamic = kwargs["dynamic"]
diff --git a/tests/layer_tests/pytorch_tests/test_compressed_mm.py b/tests/layer_tests/pytorch_tests/test_compressed_mm.py
new file mode 100644
index 00000000000..a4261f90e2d
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_compressed_mm.py
@@ -0,0 +1,170 @@
+# Copyright (C) 2018-2024 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import pytest
+import torch
+
+from pytorch_layer_test_class import PytorchLayerTest
+
+
+def pack_uint4(tensor):
+ packed_tensor = tensor.contiguous()
+ packed_tensor = packed_tensor.reshape(-1, 2)
+ packed_tensor = torch.bitwise_and(packed_tensor[..., ::2], 15) | packed_tensor[..., 1::2] << 4
+ return packed_tensor
+
+
+def unpack_uint4(packed_tensor):
+ return torch.stack((torch.bitwise_and(packed_tensor, 15), torch.bitwise_right_shift(packed_tensor, 4)), dim=-1)
+
+
+def pack_int4(tensor):
+ tensor = tensor + 8
+ return pack_uint4(tensor.type(torch.uint8))
+
+
+def unpack_int4(packed_tensor):
+ t = unpack_uint4(packed_tensor)
+ return t.type(torch.int8) - 8
+
+
+def decompress_asymmetric(input, scale, zero_point):
+ input = input.type(dtype=scale.dtype)
+ zero_point = zero_point.type(dtype=scale.dtype)
+ decompressed_input = (input - zero_point) * scale
+ return decompressed_input
+
+
+def decompress_symmetric(input, scale):
+ input = input.type(dtype=scale.dtype)
+ decompressed_input = input * scale
+ return decompressed_input
+
+
+class TestMatMulU4Weights(PytorchLayerTest):
+ rng = np.random.default_rng(seed=123)
+
+ def _prepare_input(self):
+ return (np.round(5.00 * self.rng.random([2, 4], dtype=np.float32) - 2.50, 4),)
+
+ def create_model(self, group_size):
+ class aten_mm_u4(torch.nn.Module):
+ def __init__(self, compressed_weight, scale, zero_point, weight_shape):
+ super(aten_mm_u4, self).__init__()
+ self.compressed_weight_shape = compressed_weight.shape
+ self.packed_weight = torch.nn.Parameter(pack_uint4(compressed_weight), requires_grad=False)
+
+ self.register_buffer("_scale", scale.type(dtype=torch.float16))
+
+ self.zero_point_shape = zero_point.shape
+ self.register_buffer("_zero_point", pack_uint4(zero_point))
+
+ self.weight_shape = weight_shape
+
+ def forward(self, x):
+ # NNCF UINT4 asymmetric decompression pattern
+ # https://github.com/openvinotoolkit/nncf/blob/develop/nncf/torch/quantization/layers.py
+ compressed_weight = unpack_uint4(self.packed_weight)
+ compressed_weight = compressed_weight.reshape(self.compressed_weight_shape)
+
+ zero_point = unpack_uint4(self._zero_point)
+ zero_point = zero_point.reshape(self.zero_point_shape)
+
+ weight = decompress_asymmetric(compressed_weight, self._scale, zero_point)
+ weight = weight.reshape(self.weight_shape)
+ weight = weight.type(dtype=torch.float32)
+
+ return torch.matmul(x, weight)
+
+ ref_net = None
+
+ weight_shape = (4, 2)
+ ngroups = weight_shape[0] // group_size
+ compressed_weight_shape = (ngroups, group_size, weight_shape[1])
+ zero_point_shape = scale_shape = (ngroups, 1, weight_shape[1])
+
+ compressed_weight = (15.00 * self.rng.random(compressed_weight_shape, dtype=np.float32)).astype(dtype=np.uint8)
+ scale = np.round(10.00 * self.rng.random(scale_shape, dtype=np.float32) - 5.00)
+ zero_point = (15.00 * self.rng.random(zero_point_shape, dtype=np.float32)).astype(dtype=np.uint8)
+
+ t_compressed_weight = torch.from_numpy(compressed_weight)
+ t_scale = torch.from_numpy(scale)
+ t_zero_point = torch.from_numpy(zero_point)
+
+ return aten_mm_u4(t_compressed_weight, t_scale, t_zero_point, weight_shape), ref_net, ["aten::matmul"]
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_fx_backend
+ @pytest.mark.parametrize("group_size", [2, 4])
+ def test_matmul_u4(self, group_size, ie_device, precision, ir_version):
+ self._test(
+ *self.create_model(group_size),
+ ie_device,
+ precision,
+ ir_version,
+ trace_model=True,
+ dynamic_quantization_group_size=0
+ )
+
+
+class TestMatMulI4Weights(PytorchLayerTest):
+ rng = np.random.default_rng(seed=123)
+
+ def _prepare_input(self):
+ return (np.round(5.00 * self.rng.random([2, 4], dtype=np.float32) - 2.50, 4),)
+
+ def create_model(self, group_size):
+ class aten_mm_i4(torch.nn.Module):
+ def __init__(self, compressed_weight, scale, weight_shape):
+ super(aten_mm_i4, self).__init__()
+ self.compressed_weight_shape = compressed_weight.shape
+ self.packed_weight = torch.nn.Parameter(pack_int4(compressed_weight), requires_grad=False)
+
+ self.register_buffer("_scale", scale.type(dtype=torch.float16))
+
+ self.weight_shape = weight_shape
+
+ def forward(self, x):
+ # NNCF INT4 symmetric decompression pattern
+ # https://github.com/openvinotoolkit/nncf/blob/develop/nncf/torch/quantization/layers.py
+ compressed_weight = unpack_int4(self.packed_weight)
+ compressed_weight = compressed_weight.reshape(self.compressed_weight_shape)
+
+ weight = decompress_symmetric(compressed_weight, self._scale)
+ weight = weight.reshape(self.weight_shape)
+ weight = weight.type(dtype=torch.float32)
+
+ return torch.matmul(x, weight)
+
+ ref_net = None
+
+ weight_shape = (4, 2)
+ ngroups = weight_shape[0] // group_size
+ compressed_weight_shape = (ngroups, group_size, weight_shape[1])
+ scale_shape = (ngroups, 1, weight_shape[1])
+
+ compressed_weight = (16.00 * self.rng.random(compressed_weight_shape, dtype=np.float32) - 8.00).astype(
+ dtype=np.int8
+ )
+ scale = np.round(10.00 * self.rng.random(scale_shape, dtype=np.float32) - 5.00)
+
+ t_compressed_weight = torch.from_numpy(compressed_weight)
+ t_scale = torch.from_numpy(scale)
+
+ return aten_mm_i4(t_compressed_weight, t_scale, weight_shape), ref_net, ["aten::matmul"]
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_fx_backend
+ @pytest.mark.parametrize("group_size", [2, 4])
+ def test_matmul_i4(self, group_size, ie_device, precision, ir_version):
+ self._test(
+ *self.create_model(group_size),
+ ie_device,
+ precision,
+ ir_version,
+ trace_model=True,
+ dynamic_quantization_group_size=0
+ )