Skip to content

Commit fdbf282

Browse files
c
1 parent a7ce6e0 commit fdbf282

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

src/nncf/torch/quantization/quantize_functions.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,8 +435,11 @@ def pack_uint4(tensor: torch.Tensor) -> torch.Tensor:
435435
:raises nncf.errors.ValidationError: If the input tensor is not of type `torch.uint8`.
436436
"""
437437
if tensor.dtype != torch.uint8:
438-
msg = f"Invalid tensor dtype {tensor.type}. torch.uint8 type is supported."
438+
msg = f"Invalid tensor dtype {tensor.dtype}. torch.uint8 type is supported."
439439
raise ValidationError(msg)
440+
if torch.any((tensor < 0) | (tensor > 15)):
441+
msg = "Tensor values are not in [0, 15]."
442+
raise ValueError(msg)
440443
packed_tensor = tensor.contiguous()
441444
packed_tensor = packed_tensor.reshape(-1, 2)
442445
packed_tensor = torch.bitwise_and(packed_tensor[..., ::2], 15) | packed_tensor[..., 1::2] << 4
@@ -476,8 +479,11 @@ def pack_int4(tensor: torch.Tensor) -> torch.Tensor:
476479
:raises nncf.errors.ValidationError: If the input tensor is not of type `torch.int8`.
477480
"""
478481
if tensor.dtype != torch.int8:
479-
msg = f"Invalid tensor dtype {tensor.type}. torch.int8 type is supported."
482+
msg = f"Invalid tensor dtype {tensor.dtype}. torch.int8 type is supported."
480483
raise ValidationError(msg)
484+
if torch.any((tensor < -8) | (tensor > 7)):
485+
msg = "Tensor values are not in [-8, 7]."
486+
raise ValueError(msg)
481487
tensor = tensor + 8
482488
return pack_uint4(tensor.type(torch.uint8))
483489

tests/torch/quantization/test_functions.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,18 @@ def test_pack_invalid_dtype_raises(desc: PackUnpackDesc):
880880
desc.pack_fn(tensor)
881881

882882

883+
@pytest.mark.parametrize("desc", PACK_UNPACK_DESCS, ids=str)
884+
def test_pack_invalid_value(desc: PackUnpackDesc):
885+
tensor = torch.tensor([desc.max_value + 1, 0, 0, 0], dtype=desc.input_dtype)
886+
with pytest.raises(ValueError, match=r"Tensor values are not in"):
887+
desc.pack_fn(tensor)
888+
889+
if desc.input_dtype.is_signed:
890+
tensor = torch.tensor([desc.min_value - 1, 0, 0, 0], dtype=desc.input_dtype)
891+
with pytest.raises(ValueError, match=r"Tensor values are not in"):
892+
desc.pack_fn(tensor)
893+
894+
883895
def test_pack_uint4_layout():
884896
tensor = torch.tensor([1, 2, 3, 4], dtype=torch.uint8)
885897
# Two consecutive values [low, high] are packed into one byte as: low | (high << 4).

0 commit comments

Comments
 (0)