Skip to content

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

[PT FE] Support bitnet quantized models (#30900)

Maxim Vafin4617e75ad929
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py b/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
index f584408ce14..3d242b2dde5 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
@@ -34,9 +34,12 @@ def patch_quantized(model: torch.nn.Module) -> None:
Raises:
RuntimeError: If the quantization type is unknown.
"""
+ def fp32_tensor(*shape: int) -> torch.Tensor:
+ return torch.full(shape, 0.5, dtype=torch.float32)
+
quant_type = detect_quantized_model(model)
+ extensions = {}
if quant_type == "awq":
- extensions = {}
try:
from awq.modules.linear import WQLinear_GEMM
extensions[WQLinear_GEMM] = ModuleExtension(
@@ -45,19 +48,35 @@ def patch_quantized(model: torch.nn.Module) -> None:
args[0], module.qweight, module.qzeros, module.scales,
torch.tensor(module.group_size),
torch.tensor(module.w_bit), module.bias),
- evaluate=lambda module, *args, **kwargs: torch.full(
- list(args[0].shape[:-1]) + [module.out_features], 0.5,
- dtype=torch.float32)) # type: ignore
+ evaluate=lambda module, *args, **kwargs: fp32_tensor(
+ *args[0].shape[:-1], module.out_features)) # type: ignore
+ except ImportError:
+ pass
+ elif quant_type == "bitnet":
+ try:
+ from transformers.integrations.bitnet import AutoBitLinear
+ extensions[AutoBitLinear] = ModuleExtension(
+ AutoBitLinear, "ov_ext::bit_linear",
+ convert=lambda module, target_op, *args, **kwargs: target_op(
+ module.rms_norm(
+ args[0]) if module.rms_norm is not None else args[0],
+ getattr(module, "original_weight", module.weight),
+ module.weight_scale,
+ module.bias),
+ evaluate=lambda module, *args, **kwargs: fp32_tensor(
+ *args[0].shape[:-1], module.out_features)) # type: ignore
except ImportError:
pass
- patch_model(model, extensions,
- "_openvino_quantized_patch_orig_forward") # type: ignore
elif quant_type == "gptq":
model._openvino_gptq_patched = True # type: ignore[assignment]
gptq.patch_model(model) # type: ignore
+ return
else:
raise RuntimeError(f"Unknown quantization type: {quant_type}.")
+ patch_model(model, extensions,
+ "_openvino_quantized_patch_orig_forward") # type: ignore
+
def unpatch_quantized(model: torch.nn.Module) -> None:
"""Reverts the patching applied to a quantized PyTorch model.
diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cpp
index 55bd7a4c3d7..020e6e59179 100644
--- a/src/frontends/pytorch/src/op/linear.cpp
+++ b/src/frontends/pytorch/src/op/linear.cpp
@@ -64,6 +64,26 @@ OutputVector translate_linear_ext(const NodeContext& context) {
};
namespace {
+
+Output<Node> low_precision_subgraph(const NodeContext& context,
+ const Output<Node>& x,
+ const Output<Node>& weights,
+ const Output<Node>& zero_points,
+ const Output<Node>& scales,
+ const Output<Node>& out_shape) {
+ auto new_qweight = context.mark_node(std::make_shared<v0::Convert>(weights, scales.get_element_type()));
+ auto new_qzeros = context.mark_node(std::make_shared<v0::Convert>(zero_points, scales.get_element_type()));
+
+ auto w_s = context.mark_node(std::make_shared<v1::Subtract>(new_qweight, new_qzeros));
+ auto weight = context.mark_node(std::make_shared<v1::Multiply>(w_s, scales));
+ auto weight_shape = weights.get_shape();
+ if (out_shape.get_node() != nullptr) {
+ weight = context.mark_node(std::make_shared<v1::Reshape>(weight, out_shape, false));
+ }
+ weight = context.mark_node(std::make_shared<v1::ConvertLike>(weight, x));
+ return weight;
+}
+
uint32_t rearrange_awq_bits(uint32_t num) {
uint32_t result = 0;
uint32_t mask = 0xF;
@@ -81,6 +101,22 @@ uint32_t rearrange_awq_bits(uint32_t num) {
return result;
}
+uint16_t rearrange_bitnet_bits(uint16_t num) {
+ uint16_t result = 0;
+ const uint16_t mask = 0x0003;
+
+ result |= (num & (mask << 0)) << 0;
+ result |= (num & (mask << 8)) >> 6;
+ result |= (num & (mask << 4)) << 0;
+ result |= (num & (mask << 10)) >> 4;
+ result |= (num & (mask << 6)) << 2;
+ result |= (num & (mask << 12)) >> 2;
+ result |= (num & (mask << 8)) << 4;
+ result |= (num & (mask << 14)) << 0;
+
+ return result;
+}
+
Output<Node> rearrange_constant(const Output<Node>& c, uint32_t groups) {
auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());
FRONT_END_OP_CONVERSION_CHECK(constant, "weight must be Constant.");
@@ -93,6 +129,7 @@ Output<Node> rearrange_constant(const Output<Node>& c, uint32_t groups) {
for (size_t i = 0; i < shape_size(constant->get_shape()); i++) {
dst[i] = rearrange_awq_bits(src[i]);
}
+ new_qweight->set_friendly_name(constant->get_friendly_name());
return new_qweight;
}
} // namespace
@@ -110,20 +147,14 @@ OutputVector translate_linear_awq(const NodeContext& context) {
auto new_qweight = rearrange_constant(qweight, static_cast<uint32_t>(groups));
auto new_qzeros = rearrange_constant(qzeros, 1);
- new_qweight = context.mark_node(std::make_shared<v0::Convert>(new_qweight, scales.get_element_type()));
- new_qzeros = context.mark_node(std::make_shared<v0::Convert>(new_qzeros, scales.get_element_type()));
-
- auto w_s = context.mark_node(std::make_shared<v1::Subtract>(new_qweight, new_qzeros));
FRONT_END_OP_CONVERSION_CHECK(scales.get_partial_shape().is_static(), "Scales must be constant.");
auto scales_shape = scales.get_shape();
auto new_scales_shape =
v0::Constant::create(element::i32, {3}, std::vector<uint64_t>{scales_shape[0], 1, scales_shape[1]});
- scales = context.mark_node(std::make_shared<v1::Reshape>(scales, new_scales_shape, false));
- auto weight = context.mark_node(std::make_shared<v1::Multiply>(w_s, scales));
+ auto new_scales = context.mark_node(std::make_shared<v1::Reshape>(scales, new_scales_shape, false));
auto out_shape =
v0::Constant::create(element::i32, {2}, std::vector<int32_t>{static_cast<int32_t>(qweight.get_shape()[0]), -1});
- weight = context.mark_node(std::make_shared<v1::Reshape>(weight, out_shape, false));
- weight = context.mark_node(std::make_shared<v1::ConvertLike>(weight, x));
+ auto weight = low_precision_subgraph(context, x, new_qweight, new_qzeros, new_scales, out_shape);
auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, false));
if (!context.input_is_none(6)) {
@@ -137,6 +168,39 @@ OutputVector translate_linear_awq(const NodeContext& context) {
return {matmul};
};
+OutputVector translate_linear_bitnet(const NodeContext& context) {
+ num_inputs_check(context, 3, 4);
+ auto x = context.get_input(0);
+ auto weight = context.get_input(1);
+ auto scales = context.get_input(2);
+
+ auto constant = ov::as_type_ptr<v0::Constant>(weight.get_node_shared_ptr());
+ FRONT_END_OP_CONVERSION_CHECK(constant, "weight must be Constant.");
+ auto src = reinterpret_cast<const uint16_t*>(constant->get_data_ptr());
+ auto initial_shape = constant->get_shape();
+ FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D constants are supported.");
+ auto new_shape = Shape{initial_shape[0] * 4, initial_shape[1]};
+ auto new_weight = std::make_shared<v0::Constant>(element::u2, new_shape);
+ auto dst = const_cast<uint16_t*>(reinterpret_cast<const uint16_t*>(new_weight->get_data_ptr()));
+ for (size_t i = 0; i < shape_size(initial_shape) / 2; i++) {
+ dst[i] = rearrange_bitnet_bits(src[i]);
+ }
+ new_weight->set_friendly_name(constant->get_friendly_name());
+ auto zero_point = context.mark_node(std::make_shared<v0::Constant>(element::u2, Shape{}, 1));
+ auto mm_weight = low_precision_subgraph(context, x, new_weight, zero_point, scales, {});
+
+ auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, mm_weight, false, true));
+ if (!context.input_is_none(3)) {
+ auto bias = context.get_input(3);
+
+ if (bias.get_element_type() == element::f16 || bias.get_element_type() == element::bf16) {
+ bias = context.mark_node(std::make_shared<v1::ConvertLike>(bias, x));
+ }
+ matmul = context.mark_node(std::make_shared<v1::Add>(matmul, bias));
+ }
+ return {matmul};
+};
+
} // namespace op
} // namespace pytorch
} // namespace frontend
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index b75c1082e6d..1694e7a0645 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -357,6 +357,7 @@ OP_CONVERTER(translate_zeros_like_fx);
OP_CONVERTER(translate_conv1d_ext);
OP_CONVERTER(translate_embedding_ext);
OP_CONVERTER(translate_linear_awq);
+OP_CONVERTER(translate_linear_bitnet);
OP_CONVERTER(translate_linear_ext);
} // namespace op
@@ -768,6 +769,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::zeros", op::translate_zeros},
{"aten::zeros_like", op::translate_zeros_like},
{"ov_ext::awq_gemm", op::translate_linear_awq},
+ {"ov_ext::bit_linear", op::translate_linear_bitnet},
{"ov_ext::embedding", op::translate_embedding_ext},
{"ov_ext::conv1d", op::translate_conv1d_ext},
{"ov_ext::linear", op::translate_linear_ext},