Skip to content

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

[PyOV] Match core bit order in pack_data and unpack_data (#38778)

Somay kousis58e2038f5816
diff --git a/src/bindings/python/src/openvino/helpers/packing.py b/src/bindings/python/src/openvino/helpers/packing.py
index 59a6bcfbb2f..9a1aaf5ffc1 100644
--- a/src/bindings/python/src/openvino/helpers/packing.py
+++ b/src/bindings/python/src/openvino/helpers/packing.py
@@ -9,17 +9,18 @@ from openvino import Type, Shape
def pack_data(array: np.ndarray, type: Type) -> np.ndarray:
- """Represent array values as u1, u2, u3, u4, u6 or i4 openvino element type and pack them into uint8 numpy array.
+ """Represent array values as u1, u2, u3, u4, u6, i4, nf4 or f4e2m1 element type and pack them into uint8 numpy array.
- For u1, u2, u4, i4: Standard bit packing where 8 % bitwidth == 0
+ For u1: Bit packing from the most significant bit, like the core
+ For u2, u4, i4, nf4, f4e2m1: Bit packing from the least significant bits, like the core
For u3, u6: Linear LSB-first bit-stream packing, values may straddle a byte boundary
- If the number of elements in array is odd we pad them with zero value to be able to fit the bit
- sequence into the uint8 array.
+ For the byte-aligned types (u1, u2, u4, i4, nf4, f4e2m1) the values are padded with zeros up to a
+ multiple of the number of values that fit into one byte (8 // bitwidth).
- Example: two uint8 values - [7, 8] can be represented as uint4 values and be packed into one int8
- value - [120], because [7, 8] bit representation is [0111, 1000] will be viewed
- as [01111000], which is bit representation of [120].
+ Example: two uint8 values - [7, 8] can be represented as uint4 values and be packed into one uint8
+ value - [135]. The first value takes the low 4 bits and the second the high 4 bits,
+ so [0111, 1000] is viewed as [10000111], which is bit representation of [135].
:param array: numpy array with values to pack.
:type array: numpy array
@@ -55,21 +56,24 @@ def pack_data(array: np.ndarray, type: Type) -> np.ndarray:
assert padded.size % num_values_fitting_into_uint8 == 0
bit_order_little = (padded[:, None] & (1 << np.arange(num_bits)) > 0).astype(minimum_regular_dtype)
- bit_order_big = np.flip(bit_order_little, axis=1) # type: ignore
- bit_order_big_flattened = bit_order_big.flatten()
- return np.packbits(bit_order_big_flattened)
+ # Same layout as the core: u1 is packed from the most significant bit,
+ # u2, u4, i4, nf4 and f4e2m1 from the least significant bits.
+ if type == Type.u1:
+ return np.packbits(bit_order_little.flatten(), bitorder="big")
+ return np.packbits(bit_order_little.flatten(), bitorder="little")
def unpack_data(array: np.ndarray, type: Type, shape: Union[list, Shape]) -> np.ndarray:
"""Extract openvino element type values from array into new uint8/int8 array given shape.
- For u1, u2, u4, i4: Standard bit unpacking where 8 % bitwidth == 0
+ For u1: Bit unpacking from the most significant bit, like the core
+ For u2, u4, i4, nf4, f4e2m1: Bit unpacking from the least significant bits, like the core
For u3, u6: Linear LSB-first bit-stream unpacking, values may straddle a byte boundary
- Example: uint8 value [120] can be represented as two u4 values and be unpacked into [7, 8]
- because [120] bit representation is [01111000] will be viewed as [0111, 1000],
- which is bit representation of [7, 8].
+ Example: uint8 value [135] can be represented as two u4 values and be unpacked into [7, 8]
+ because [135] bit representation is [10000111]: the low 4 bits [0111] are the first
+ value and the high 4 bits [1000] the second.
:param array: numpy array to unpack.
:type array: numpy array
@@ -85,28 +89,14 @@ def unpack_data(array: np.ndarray, type: Type, shape: Union[list, Shape]) -> np.
return _unpack_linear(array, 6, shape)
assert type in [Type.u1, Type.u2, Type.u4, Type.i4, Type.nf4, Type.f4e2m1], "Unpacking algorithm for the" "data types stored in 1, 2 or 4 bits"
- unpacked = np.unpackbits(array.view(np.uint8))
- shape = list(shape)
- if type.bitwidth == 1:
- return np.resize(unpacked, shape)
- else:
- unpacked = unpacked.reshape(-1, type.bitwidth)
- padding_shape = (unpacked.shape[0], 8 - type.bitwidth)
- padding = np.ndarray(padding_shape, np.uint8) # type: np.ndarray
- if type == Type.i4:
- for axis, bits in enumerate(unpacked):
- if bits[0] == 1:
- padding[axis] = np.ones((padding_shape[1],), np.uint8)
- else:
- padding[axis] = np.zeros((padding_shape[1],), np.uint8)
- else:
- padding = np.zeros(padding_shape, np.uint8)
- padded = np.concatenate((padding, unpacked), 1) # type: ignore
- packed = np.packbits(padded, 1)
- if type == Type.i4:
- return np.resize(packed, shape).astype(dtype=np.int8)
- else:
- return np.resize(packed, shape)
+ if type == Type.u1:
+ return np.resize(np.unpackbits(array.view(np.uint8)), list(shape))
+
+ unpacked = _unpack_linear(array, type.bitwidth, shape)
+ if type == Type.i4:
+ # Sign-extend: codes 8..15 are -8..-1
+ return (unpacked.astype(np.int8) << 4) >> 4
+ return unpacked
def _check_range(array: np.ndarray, type: Type) -> None:
@@ -140,7 +130,7 @@ def _pack_linear(array: np.ndarray, bits: int) -> np.ndarray:
def _unpack_linear(array: np.ndarray, bits: int, shape: Union[list, Shape]) -> np.ndarray:
- """Unpack values from a linear, LSB-first bit-stream (used for u3/u6), inverse of _pack_linear."""
+ """Unpack values from a linear, LSB-first bit-stream (used for every type except u1), inverse of _pack_linear."""
array = array.view(np.uint8)
shape = list(shape)
num_values = int(np.prod(shape))
diff --git a/src/bindings/python/tests/test_graph/test_constant.py b/src/bindings/python/tests/test_graph/test_constant.py
index 09b5320772f..59da1245f4d 100644
--- a/src/bindings/python/tests/test_graph/test_constant.py
+++ b/src/bindings/python/tests/test_graph/test_constant.py
@@ -310,6 +310,41 @@ def test_pack_data_matches_core_layout(ov_type, high, num_elements):
assert np.array_equal(ov_const.data, pack_data(data, ov_type))
+ ("ov_type", "low", "high", "dtype"),
+ [
+ (Type.u1, 0, 2, np.uint8),
+ (Type.u2, 0, 4, np.uint8),
+ (Type.u4, 0, 16, np.uint8),
+ (Type.i4, -8, 8, np.int8),
+ (Type.nf4, 0, 16, np.uint8),
+ ],
+)
[email protected]("shape", [(1,), (3,), (13,), (64,), (3, 5)])
+def test_pack_unpack_data_match_core_layout(ov_type, low, high, dtype, shape):
+ # The core packs element 0 into the most significant bit for u1
+ # and into the least significant bits for u2, u4, i4 and nf4.
+ values = np.arange(np.prod(shape)) % (high - low) + low
+ data = values.astype(dtype).reshape(shape)
+
+ ov_const = ops.constant(data, dtype=ov_type)
+
+ assert np.array_equal(ov_const.data.view(np.uint8), pack_data(data, ov_type))
+ assert np.array_equal(unpack_data(ov_const.data, ov_type, data.shape), data)
+
+
[email protected]("num_elements", [7, 16])
+def test_pack_data_f4e2m1_matches_core_layout(num_elements):
+ codes = np.arange(16, dtype=np.uint8)[:num_elements]
+ all_values = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6], dtype=np.float32)
+ values = all_values[:num_elements]
+
+ ov_const = ops.constant(values, dtype=Type.f4e2m1)
+
+ assert np.array_equal(ov_const.data.view(np.uint8), pack_data(codes, Type.f4e2m1))
+ assert np.array_equal(unpack_data(ov_const.data, Type.f4e2m1, codes.shape), codes)
+
+
@pytest.mark.parametrize(
("shared_flag"),
[