Skip to content

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

[PT FE] Fix repacking bitnet weights in frontend (#32244)

Maxim Vafin496772db75dd
diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cpp
index 020e6e59179..278a4472879 100644
--- a/src/frontends/pytorch/src/op/linear.cpp
+++ b/src/frontends/pytorch/src/op/linear.cpp
@@ -101,22 +101,6 @@ 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.");
@@ -170,23 +154,51 @@ OutputVector translate_linear_awq(const NodeContext& context) {
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);
+ const auto x = context.get_input(0);
+ const auto weight = context.get_input(1);
+ const auto scales = context.get_input(2);
- auto constant = ov::as_type_ptr<v0::Constant>(weight.get_node_shared_ptr());
+ const 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();
+ const auto src = reinterpret_cast<const uint8_t*>(constant->get_data_ptr());
+ const 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]);
+ const uint8_t values_per_pack = 4; // Number of 2-bit values packed into a byte
+ const size_t rows = initial_shape[0];
+ const size_t cols = initial_shape[1];
+ FRONT_END_OP_CONVERSION_CHECK(cols % values_per_pack == 0,
+ "The second dimension of weight must be divisible by 4.");
+ const auto new_shape = Shape{rows * values_per_pack, cols};
+ auto new_weight = std::make_shared<v0::Constant>(element::u2, new_shape, 0);
+ auto dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_weight->get_data_ptr()));
+ const size_t row_len = cols / values_per_pack;
+ // This lambda extracts 2 bits from each of 4 consecutive bytes at a given bit position,
+ // then packs them into a single byte, placing each 2-bit value in its respective position (6, 4, 2, 0).
+ const auto reorder_bitnet_2bit_values =
+ [](const uint8_t* const src, const size_t src_idx, const size_t pos) -> uint8_t {
+ const uint8_t values_per_byte = 4;
+ const uint8_t value_mask = 0x3;
+ const uint8_t value_size = 2; // Size of each value is 2 bits
+ uint8_t value{}; // Should be zeroed
+
+ for (size_t value_idx = 0; value_idx != values_per_byte; ++value_idx) {
+ value |= ((src[src_idx + value_idx] >> pos) & value_mask) << value_idx * value_size;
+ }
+ return value;
+ };
+ // In each 8bit value we have 4 2-bit values, first value contains first element, second value first element of a
+ // next row. We need to repack them in contiguous way.
+ for (size_t i = 0; i < rows; ++i) {
+ for (size_t j = 0; j < row_len; ++j) {
+ const size_t src_idx = values_per_pack * j + i * cols;
+ dst[j + (i + 0 * rows) * row_len] = reorder_bitnet_2bit_values(src, src_idx, 0);
+ dst[j + (i + 1 * rows) * row_len] = reorder_bitnet_2bit_values(src, src_idx, 2);
+ dst[j + (i + 2 * rows) * row_len] = reorder_bitnet_2bit_values(src, src_idx, 4);
+ dst[j + (i + 3 * rows) * row_len] = reorder_bitnet_2bit_values(src, src_idx, 6);
+ }
}
new_weight->set_friendly_name(constant->get_friendly_name());
- auto zero_point = context.mark_node(std::make_shared<v0::Constant>(element::u2, Shape{}, 1));
+ const 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));
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
index 2c194ccf62b..eef56a54781 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -7,6 +7,7 @@ import itertools
import math
import os
import re
+import sys
import logging
import platform
from pathlib import Path
@@ -18,9 +19,14 @@ import pytest
from openvino.frontend import FrontEndManager, ConversionExtension, NodeContext
from openvino import PartialShape, Type
import openvino.opset10 as ops
+import openvino.properties.hint as hints
logging.basicConfig(level=logging.DEBUG)
+orig_compile = torch.compile
+torch.compile = lambda func: func
+default_cfg = {hints.inference_precision: Type.f32}
+
class aten_relu(torch.nn.Module):
def forward(self, x):
@@ -471,7 +477,7 @@ def verify_model(model, example_input, expected_ops):
# Convert and compile the model
converted_model = ov.convert_model(model, example_input=(example_input,))
assert converted_model, "Model conversion failed."
- compiled_model = ov.compile_model(converted_model, "CPU")
+ compiled_model = ov.compile_model(converted_model, "CPU", default_cfg)
assert compiled_model, "Model compilation failed."
# Verify model operations
@@ -890,7 +896,7 @@ def test_patched_16bit_model_converts():
with torch.no_grad():
converted_model = convert_model(model_fp16, example_input=example)
assert converted_model
- cm_fp16 = compile_model(converted_model, "CPU")
+ cm_fp16 = compile_model(converted_model, "CPU", default_cfg)
res_fp16 = cm_fp16([x.numpy() for x in example])
np.testing.assert_allclose(res_fp16[0], res_ref[0].numpy(), atol=1e-2)
np.testing.assert_allclose(res_fp16[1], res_ref[1].numpy(), atol=1e-2)
@@ -901,7 +907,7 @@ def test_patched_16bit_model_converts():
with torch.no_grad():
converted_model = convert_model(model_bf16, example_input=example)
assert converted_model
- cm_bf16 = compile_model(converted_model, "CPU")
+ cm_bf16 = compile_model(converted_model, "CPU", default_cfg)
res_bf16 = cm_bf16([x.numpy() for x in example])
np.testing.assert_allclose(res_bf16[0], res_ref[0].numpy(), atol=1e-2)
np.testing.assert_allclose(res_bf16[1], res_ref[1].numpy(), atol=1e-2)
@@ -976,7 +982,7 @@ def test_patched_8bit_model_converts():
with torch.no_grad():
converted_model = convert_model(model_f8_e4m3, example_input=example)
assert converted_model
- cm_f8_e4m3 = compile_model(converted_model, "CPU")
+ cm_f8_e4m3 = compile_model(converted_model, "CPU", default_cfg)
res_f8_e4m3 = cm_f8_e4m3([x.numpy() for x in example])
np.testing.assert_allclose(res_f8_e4m3[0], res_ref[0].numpy(), atol=1e-2)
np.testing.assert_allclose(res_f8_e4m3[1], res_ref[1].numpy(), atol=1e-2)
@@ -990,12 +996,49 @@ def test_patched_8bit_model_converts():
with torch.no_grad():
converted_model = convert_model(model_f8_e5m2, example_input=example)
assert converted_model
- cm_f8_e5m2 = compile_model(converted_model, "CPU")
+ cm_f8_e5m2 = compile_model(converted_model, "CPU", default_cfg)
res_f8_e5m2 = cm_f8_e5m2([x.numpy() for x in example])
np.testing.assert_allclose(res_f8_e5m2[0], res_ref[0].numpy(), atol=1e-2)
np.testing.assert_allclose(res_f8_e5m2[1], res_ref[1].numpy(), atol=1e-2)
[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")
+def test_patched_bitnet_model_converts():
+ from openvino import convert_model, compile_model
+ from transformers.integrations.bitnet import AutoBitLinear, pack_weights
+ from transformers import PretrainedConfig, BitNetQuantConfig
+
+ rng = torch.Generator().manual_seed(42)
+
+ class TestModel(torch.nn.Module):
+ def __init__(self, size):
+ super().__init__()
+ self.config = PretrainedConfig(quantization_config=BitNetQuantConfig(linear_class="autobitlinear"))
+ self.linear = AutoBitLinear(size[0], size[1], bias=True, use_rms_norm=True)
+ w = torch.randint(-1, 2, (size[1], size[0]), dtype=torch.float32, generator=rng)
+ self.linear.weight = torch.nn.Parameter(w)
+ self.linear.original_weight = pack_weights(self.linear.weight.data.clone())
+
+ def forward(self, x):
+ return self.linear(x)
+
+ size = (32, 64)
+ x = torch.randn(1, size[0], generator=rng)
+ model = TestModel(size)
+ with torch.no_grad():
+ res_ref = model(x)
+
+ with torch.no_grad():
+ converted_model = convert_model(model, example_input=(torch.randn(1, size[0], generator=rng),))
+ assert converted_model
+ cm = compile_model(converted_model, "CPU", default_cfg)
+ res = cm([x.numpy()])
+ rtol, atol = 1e-4, 1e-4
+ if platform.machine() in ('arm', 'armv7l', 'aarch64', 'arm64', 'ARM64'):
+ rtol, atol = 0.5, 0.1
+ np.testing.assert_allclose(res[0], res_ref.numpy(), rtol=rtol, atol=atol)
+
+
class InlinedInputsModel(torch.nn.Module):
def __init__(self):
super().__init__()
@@ -1007,5 +1050,5 @@ class InlinedInputsModel(torch.nn.Module):
def test_inlined_inputs():
model = InlinedInputsModel()
model.eval()
- model = torch.compile(model, backend="openvino", options={"testing": 1})
+ model = orig_compile(model, backend="openvino", options={"testing": 1})
model()