Files
OBLITERATUS/tests/test_requantize.py

227 lines
9.9 KiB
Python

"""Deterministic unit tests for MXFP4 decoding (OBL4-02) and requantization (OBLX-03)."""
from __future__ import annotations
import json
import pytest
import torch
from obliteratus.models.quant_dequant import (
E2M1_LUT,
QuantDetection,
QuantScheme,
dequantize_fp8_blockwise,
dequantize_mxfp4,
dequantize_state_dict,
detect_quant_scheme,
)
from obliteratus.models.requantize import (
evaluate_g_quant,
requantize_fp8_blockwise,
requantize_mxfp4,
)
class TestMxfp4Detection:
def test_detects_nested_text_config_mxfp4_ct(self, tmp_path):
cfg = {
"model_type": "kimi_k3",
"text_config": {
"model_type": "kimi_linear",
"quantization_config": {
"quant_method": "compressed-tensors",
"format": "mxfp4-pack-quantized",
"config_groups": {
"group_0": {
"format": "mxfp4-pack-quantized",
"weights": {
"num_bits": 4,
"type": "float",
"group_size": 32,
"scale_dtype": "torch.uint8",
"symmetric": True,
},
}
},
},
},
}
(tmp_path / "config.json").write_text(json.dumps(cfg), encoding="utf-8")
det = detect_quant_scheme(str(tmp_path))
assert det.scheme is QuantScheme.MXFP4_CT
assert det.group_size == 32
def test_rejects_mxfp4_ct_invalid_group_size(self, tmp_path):
cfg = {
"quantization_config": {
"quant_method": "compressed-tensors",
"format": "mxfp4-pack-quantized",
"config_groups": {
"group_0": {
"weights": {"num_bits": 4, "type": "float", "group_size": 16}
}
},
}
}
(tmp_path / "config.json").write_text(json.dumps(cfg), encoding="utf-8")
det = detect_quant_scheme(str(tmp_path))
assert det.scheme is QuantScheme.UNSUPPORTED
assert "group_size=16" in det.reason
def test_native_quant_method_mxfp4_is_unsupported_not_none(self, tmp_path):
cfg = {"quantization_config": {"quant_method": "mxfp4"}}
(tmp_path / "config.json").write_text(json.dumps(cfg), encoding="utf-8")
det = detect_quant_scheme(str(tmp_path))
assert det.scheme is QuantScheme.UNSUPPORTED
assert "mxfp4" in det.reason
class TestMxfp4Dequantize:
def test_bit_exact_all_nibbles_and_e8m0_scales(self):
# Construct 2 groups of 32 elements = 64 elements = 32 packed bytes.
# Group 0: nibbles 0..15 repeated twice, scale code 127 (2**0 = 1.0).
# Group 1: nibbles 15..0 repeated twice, scale code 129 (2**2 = 4.0).
g0 = torch.tensor(list(range(16)) * 2, dtype=torch.uint8)
g1 = torch.tensor(list(range(15, -1, -1)) * 2, dtype=torch.uint8)
nibbles = torch.cat([g0, g1]).unsqueeze(0) # (1, 64)
packed = nibbles[:, 0::2] | (nibbles[:, 1::2] << 4) # (1, 32)
scales = torch.tensor([[127, 129]], dtype=torch.uint8)
out = dequantize_mxfp4(packed, scales, force_manual=True)
expected = torch.cat([
E2M1_LUT[g0.long()] * 1.0,
E2M1_LUT[g1.long()] * 4.0,
]).unsqueeze(0)
assert out.dtype == torch.float32
assert torch.equal(out, expected)
def test_e8m0_scale_extremes(self):
# Single non-zero nibble 2 (+1.0) in each group with code 0 (2^-127) and 254 (2^127).
packed = torch.zeros((1, 32), dtype=torch.uint8)
packed[0, 0] = 0x02 # col 0 = +1.0
packed[0, 16] = 0x02 # col 32 = +1.0
scales = torch.tensor([[0, 254]], dtype=torch.uint8)
out = dequantize_mxfp4(packed, scales, force_manual=True)
assert out[0, 0].item() == pytest.approx(2.0 ** -127, rel=0, abs=0)
assert out[0, 32].item() == pytest.approx(2.0 ** 127, rel=0, abs=0)
def test_rejects_reserved_nan_scale_code_255(self):
packed = torch.zeros((1, 16), dtype=torch.uint8)
scales = torch.tensor([[255]], dtype=torch.uint8)
with pytest.raises(RuntimeError, match="reserved NaN code 255"):
dequantize_mxfp4(packed, scales)
def test_rejects_bad_scale_shape_and_dtype(self):
packed = torch.zeros((2, 16), dtype=torch.uint8)
with pytest.raises(RuntimeError, match="shape"):
dequantize_mxfp4(packed, torch.full((2, 2), 127, dtype=torch.uint8))
with pytest.raises(RuntimeError, match="torch.uint8"):
dequantize_mxfp4(packed, torch.ones((2, 1), dtype=torch.float32))
def test_dequantize_state_dict_handles_mxfp4_and_preserves_bf16(self):
packed = torch.full((4, 16), 0x22, dtype=torch.uint8) # all +1.0
scale = torch.full((4, 1), 128, dtype=torch.uint8) # 2.0
bf16_w = torch.randn((4, 8), dtype=torch.bfloat16)
sd = {
"layer.experts.0.w1.weight_packed": packed,
"layer.experts.0.w1.weight_scale": scale,
"layer.self_attn.o_proj.weight": bf16_w,
}
det = QuantDetection(QuantScheme.MXFP4_CT, group_size=32)
out = dequantize_state_dict(sd, det, out_dtype=torch.bfloat16)
assert "layer.experts.0.w1.weight" in out
assert "layer.experts.0.w1.weight_scale" not in out
assert torch.equal(out["layer.experts.0.w1.weight"], torch.full((4, 32), 2.0, dtype=torch.bfloat16))
assert torch.equal(out["layer.self_attn.o_proj.weight"], bf16_w)
class TestRequantizeFp8Blockwise:
def test_roundtrip_exact_and_ceiling_edge_dimensions(self):
if getattr(torch, "float8_e4m3fn", None) is None:
pytest.skip("float8_e4m3fn unavailable")
torch.manual_seed(42)
w = torch.randn((130, 135), dtype=torch.float32) * 0.5
w_fp8, scale_inv = requantize_fp8_blockwise(w, block_size=(128, 128))
assert w_fp8.shape == (130, 135)
assert w_fp8.dtype == torch.float8_e4m3fn
assert scale_inv.shape == (2, 2)
assert scale_inv.dtype == torch.float32
recon = dequantize_fp8_blockwise(w_fp8, scale_inv, block_size=(128, 128))
rel_err = torch.linalg.matrix_norm(recon - w) / torch.linalg.matrix_norm(w)
assert rel_err.item() < 0.04
def test_zero_blocks_remain_exact_zero_without_nan(self):
if getattr(torch, "float8_e4m3fn", None) is None:
pytest.skip("float8_e4m3fn unavailable")
w = torch.zeros((64, 64), dtype=torch.float32)
w_fp8, scale_inv = requantize_fp8_blockwise(w, block_size=(32, 32))
assert torch.isfinite(scale_inv).all()
recon = dequantize_fp8_blockwise(w_fp8, scale_inv, block_size=(32, 32))
assert torch.equal(recon, w)
class TestRequantizeMxfp4:
def test_exact_representable_values_roundtrip_bit_exact(self):
# Every E2M1 value scaled by 2**3 = 8.0 in row 0 and 2**-2 = 0.25 in row 1.
row0 = torch.cat([E2M1_LUT, E2M1_LUT]) * 8.0
row1 = torch.cat([E2M1_LUT, -E2M1_LUT]) * 0.25
w = torch.stack([row0, row1], dim=0)
packed, scales = requantize_mxfp4(w, group_size=32)
assert packed.shape == (2, 16)
assert scales.shape == (2, 1)
recon = dequantize_mxfp4(packed, scales, group_size=32)
assert torch.equal(recon, w)
def test_ties_to_even_midpoints(self):
# Scale will be 1.0 (since max is 6.0 in the group).
midpoints = [0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0, 6.0]
expected_vals = [0.0, 1.0, 1.0, 2.0, 2.0, 4.0, 4.0, 6.0]
row = torch.zeros(32, dtype=torch.float32)
row[:8] = torch.tensor(midpoints)
packed, scales = requantize_mxfp4(row.unsqueeze(0), group_size=32)
recon = dequantize_mxfp4(packed, scales, group_size=32)[0, :8]
assert recon.tolist() == expected_vals
def test_zero_group_and_invalid_shape(self):
w = torch.zeros((2, 32), dtype=torch.float32)
packed, scales = requantize_mxfp4(w, group_size=32)
assert torch.equal(dequantize_mxfp4(packed, scales), w)
with pytest.raises(ValueError, match="divisible"):
requantize_mxfp4(torch.zeros((2, 30), dtype=torch.float32))
class TestEvaluateGQuant:
def test_fp8_edit_passes_g_quant_gate(self):
if getattr(torch, "float8_e4m3fn", None) is None:
pytest.skip("float8_e4m3fn unavailable")
torch.manual_seed(7)
w_orig = torch.randn((256, 256), dtype=torch.float32)
r = torch.randn(256, dtype=torch.float32)
r = r / torch.linalg.vector_norm(r)
# Rank-1 output-side orthogonal projection: W' = (I - r r^T) W
w_edit = w_orig - torch.outer(r, r @ w_orig)
w_edit_fp8, s_edit = requantize_fp8_blockwise(w_edit)
w_orig_fp8, s_orig = requantize_fp8_blockwise(w_orig)
req_edit = dequantize_fp8_blockwise(w_edit_fp8, s_edit)
req_orig = dequantize_fp8_blockwise(w_orig_fp8, s_orig)
rep = evaluate_g_quant(w_orig, w_edit, req_edit, req_orig, r, side="output")
assert rep.passed, rep.reason
assert rep.directional_residual_ratio is not None
assert rep.directional_residual_ratio <= 0.05
assert rep.frobenius_error_ratio is not None
assert rep.frobenius_error_ratio <= 1.10
def test_fails_closed_when_directional_residual_exceeds_budget(self):
torch.manual_seed(11)
w_orig = torch.randn((64, 64), dtype=torch.float32)
r = torch.randn(64, dtype=torch.float32)
r = r / torch.linalg.vector_norm(r)
w_edit = w_orig - torch.outer(r, r @ w_orig)
# Simulate a broken requantizer that leaves the original unedited tensor intact.
rep = evaluate_g_quant(w_orig, w_edit, w_orig, w_orig + 0.01, r, side="output")
assert not rep.passed
assert "directional_residual_ratio" in rep.reason