Skip to content

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

[PyOV] Raise in pack_data for values outside the target type range (#38810)

Somay kousis4ea2b845a100
diff --git a/src/bindings/python/src/openvino/helpers/packing.py b/src/bindings/python/src/openvino/helpers/packing.py
index 8ff664df5fc..59a6bcfbb2f 100644
--- a/src/bindings/python/src/openvino/helpers/packing.py
+++ b/src/bindings/python/src/openvino/helpers/packing.py
@@ -25,7 +25,11 @@ def pack_data(array: np.ndarray, type: Type) -> np.ndarray:
:type array: numpy array
:param type: Type to interpret the array values. Type must be u1, u2, u3, u4, u6, i4, nf4 or f4e2m1.
:type type: openvino.Type
+ :raises RuntimeError: if a value doesn't fit the type: [0, 2^bitwidth - 1] for unsigned types,
+ [-8, 7] for i4, 4-bit codes [0, 15] for nf4 and f4e2m1. u1 is not checked.
"""
+ _check_range(array, type)
+
# Handle u3 and u6 with linear LSB-first bit-stream packing
if type == Type.u3:
return _pack_linear(array, 3)
@@ -105,6 +109,27 @@ def unpack_data(array: np.ndarray, type: Type, shape: Union[list, Shape]) -> np.
return np.resize(packed, shape)
+def _check_range(array: np.ndarray, type: Type) -> None:
+ """Raise if a value doesn't fit the target type, as ops.constant does for the integer types and nf4.
+
+ nf4 and f4e2m1 values are 4-bit codes. u1 is left out: the core stores any non-zero value as 1.
+ """
+ if type not in [Type.u2, Type.u3, Type.u4, Type.u6, Type.i4, Type.nf4, Type.f4e2m1]:
+ return
+ if type == Type.i4:
+ low, high = -8, 7
+ else:
+ low, high = 0, (1 << type.bitwidth) - 1
+ # Compare elementwise: np.min/np.max return NaN when any value is NaN, which would hide out-of-range values.
+ # NaN itself is left to the existing checks, as before.
+ if np.any((array < low) | (array > high)):
+ min_value, max_value = np.nanmin(array), np.nanmax(array)
+ raise RuntimeError(
+ f"The values of the {array.dtype} array with shape {array.shape} (min {min_value}, max {max_value}) "
+ f"are out of the {type.get_type_name()} range [{low}, {high}]"
+ )
+
+
def _pack_linear(array: np.ndarray, bits: int) -> np.ndarray:
"""Pack values into a linear, LSB-first bit-stream (used for u3/u6): value i occupies bits
[i * bits, i * bits + bits), possibly straddling a byte boundary.
diff --git a/src/bindings/python/tests/test_runtime/test_tensor.py b/src/bindings/python/tests/test_runtime/test_tensor.py
index adccf994a04..9bd9acb10bf 100644
--- a/src/bindings/python/tests/test_runtime/test_tensor.py
+++ b/src/bindings/python/tests/test_runtime/test_tensor.py
@@ -7,6 +7,8 @@ import os
import subprocess
import sys
+import re
+
import numpy as np
import openvino as ov
@@ -468,6 +470,75 @@ def test_packing(shape, low, high, ov_type, dtype):
assert np.array_equal(unpacked, data)
+# ops.constant rejects these values for the integer types and nf4 (in_t_range);
+# f4e2m1 is checked as raw 4-bit codes
+ ("ov_type", "values", "dtype"),
+ [
+ (ov.Type.u2, [4, 1], np.uint8),
+ (ov.Type.u3, [8, 1], np.uint8),
+ (ov.Type.u3, [1, 256], np.int64),
+ (ov.Type.u3, [1.0, 8.0], np.float32),
+ (ov.Type.u4, [16, 1], np.uint8),
+ (ov.Type.u4, [1, 16], np.uint8),
+ (ov.Type.u4, [[1, 2], [3, 16]], np.uint8),
+ (ov.Type.u4, [16.0, 1.0], np.float32),
+ (ov.Type.u4, [-1, 1], np.int8),
+ (ov.Type.u6, [64, 1], np.uint8),
+ (ov.Type.i4, [8, 1], np.int8),
+ (ov.Type.i4, [1, -9], np.int8),
+ (ov.Type.nf4, [16, 1], np.uint8),
+ (ov.Type.f4e2m1, [16, 1], np.uint8),
+ # A NaN must not hide an out-of-range value next to it
+ (ov.Type.u3, [np.nan, 8.0], np.float32),
+ (ov.Type.u6, [np.nan, 64.0], np.float32),
+ ],
+)
+def test_pack_data_rejects_values_out_of_range(ov_type, values, dtype):
+ low, high = (-8, 7) if ov_type == ov.Type.i4 else (0, (1 << ov_type.bitwidth) - 1)
+ with pytest.raises(RuntimeError, match=re.escape(f"out of the {ov_type.get_type_name()} range [{low}, {high}]")):
+ pack_data(np.array(values, dtype=dtype), ov_type)
+
+
+def test_pack_data_range_error_reports_summary_not_values():
+ # The error names dtype, shape, min and max instead of printing the whole array
+ data = np.zeros(100_000, dtype=np.uint8)
+ data[-1] = 16
+ with pytest.raises(RuntimeError) as e:
+ pack_data(data, ov.Type.u4)
+ message = str(e.value)
+ assert len(message) < 300
+ assert "uint8" in message
+ assert "(100000,)" in message
+ assert "min 0" in message
+ assert "max 16" in message
+
+
+def test_pack_data_range_error_ignores_nan_in_summary():
+ with pytest.raises(RuntimeError) as e:
+ pack_data(np.array([np.nan, 1.0, 64.0], dtype=np.float32), ov.Type.u6)
+ assert "min 1.0" in str(e.value)
+ assert "max 64.0" in str(e.value)
+
+
+ ("ov_type", "low", "high", "dtype"),
+ [
+ (ov.Type.u2, 0, 3, np.uint8),
+ (ov.Type.u3, 0, 7, np.uint8),
+ (ov.Type.u4, 0, 15, np.uint8),
+ (ov.Type.u6, 0, 63, np.uint8),
+ (ov.Type.i4, -8, 7, np.int8),
+ (ov.Type.nf4, 0, 15, np.uint8),
+ (ov.Type.f4e2m1, 0, 15, np.uint8),
+ ],
+)
+def test_pack_data_accepts_range_bounds(ov_type, low, high, dtype):
+ data = np.array([low, high, high, low, high], dtype=dtype)
+ unpacked = unpack_data(pack_data(data, ov_type), ov_type, data.shape)
+ assert np.array_equal(unpacked, data)
+
+
@pytest.mark.parametrize(
"dtype",
[