Skip to content

Raise ValueError when nvfp4 pack tensor has odd number of columns #402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ def pack_fp4_to_uint8(x: torch.Tensor) -> torch.Tensor:
m, n = x.shape
device = x.device

if n % 2 != 0:
raise ValueError(
"tensor must have an even number of columns for nvfp4 compression"
)

# Create lookup table for FP4 values to indices
# Map the absolute values to 0-7 indices
kE2M1 = torch.tensor(FLOAT_TO_E2M1, device=device, dtype=x.dtype)
Expand All @@ -137,10 +142,6 @@ def pack_fp4_to_uint8(x: torch.Tensor) -> torch.Tensor:
# Reshape to prepare for packing pairs of values
indices = indices.reshape(-1)

# Handle odd length by padding if necessary
if indices.numel() % 2 != 0:
indices = torch.cat([indices, torch.zeros(1, dtype=torch.long, device=device)])

# Reshape to pair consecutive elements
indices = indices.reshape(-1, 2)

Expand Down
14 changes: 14 additions & 0 deletions tests/test_compressors/quantized_compressors/test_nvfp4_quant.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
import torch
from compressed_tensors.compressors.quantized_compressors.nvfp4_quantized import (
pack_fp4_to_uint8,
Expand Down Expand Up @@ -41,3 +42,16 @@ def test_pack_unpack():
sign_bitx = torch.signbit(x)
sign_bitout = torch.signbit(unpacked)
assert torch.equal(sign_bitout, sign_bitx)


def test_pack_unpack_odd_dims():
x = torch.Tensor(
[
[-0.5000, -6.0000, -0.5000, -1.5000, -1.0000, 6.0000, 0.0000],
[-1.0000, -6.0000, -0.5000, -0.0000, 0.5000, 0.5000, -0.0000],
[1.5000, 6.0000, -0.0000, -0.5000, 1.0000, 1.0000, -0.0000],
]
)

with pytest.raises((ValueError, torch._dynamo.exc.Unsupported)):
_packed = pack_fp4_to_uint8(x)