Commit 4c7344447 for llama.cpp
commit 4c7344447cb1727f1e2f982febc99a8f88dcb77f
Author: Pedro Cuenca <pedro@huggingface.co>
Date: Fri Nov 27 15:44:37 2026 +0100
[Inkling 2] Support nvfp4 pass-through (#33062)
diff --git a/conversion/inkling2.py b/conversion/inkling2.py
index 3b4b140e3..0184c9990 100644
--- a/conversion/inkling2.py
+++ b/conversion/inkling2.py
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
return values
+def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
+ if np.any(scales & 0x80) or np.any(scales == 0x7F):
+ raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
+ n_rows = packed.shape[0]
+ n_blocks = scales.shape[1]
+ nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
+ qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
+ n_super = n_blocks // 4
+ blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
+ return blocks.reshape(n_rows, n_super * 36)
+
+
+def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
+ packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
+ scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
+ if not w13:
+ return _repack_nvfp4_rows(packed, scales, name, expert)
+ return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
+
+
def _is_inkling2(dir_model: Path) -> bool:
if not (dir_model / "config.json").is_file():
return False
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
class Inkling2Model(TextModel):
model_arch = gguf.MODEL_ARCH.INKLING2
- def __init__(self, dir_model: Path, *args, **kwargs):
+ def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
self._expert_quant: dict[str, dict] = {}
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
+ self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
+ self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
quant_path = dir_model / "hf_quant_config.json"
if quant_path.is_file():
with open(quant_path, encoding="utf-8") as f:
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
if name in self._expert_quant:
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
self._expert_quant[name] = group
- super().__init__(dir_model, *args, **kwargs)
+ super().__init__(dir_model, ftype, *args, **kwargs)
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
hp = self.hparams
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
t = gen()
if t.dtype != torch.float32 or tuple(t.shape) != expected:
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
- chunks: list[Callable[[], np.ndarray]] = []
- for expert in range(experts):
- for half in range(2 if w13 else 1):
- for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
- stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
- # The same packed row slice selects the weight and its scale groups.
- row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
- chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
- self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
+ preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
+ if preserve_nvfp4 and cols % 64 != 0:
+ logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
+ preserve_nvfp4 = False
+ chunks: list[Callable[[], np.ndarray]]
+ if preserve_nvfp4:
+ assert amax is not None and denominator is not None
+ a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
+ d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
+ if not np.isfinite(a).all() or (a < 0).any():
+ raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
+ if not np.isfinite(d).all() or (d <= 0).any():
+ raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
+ with np.errstate(over="ignore", invalid="ignore"):
+ outer_scale = a / d
+ if not np.isfinite(outer_scale).all():
+ raise ValueError(f"Inkling2: {name}: non-finite outer scale")
+ chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
+ byte_shape = (experts, rows, cols // 64 * 36)
+ self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
+ else:
+ chunks = []
+ for expert in range(experts):
+ for half in range(2 if w13 else 1):
+ for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
+ stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
+ # The same packed row slice selects the weight and its scale groups.
+ row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
+ chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
+ self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
+ if not nvfp4 and self._fp8_as_q8:
+ self._fp8_dequantized.add(name)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
for companion in required:
del self.model_tensors[companion]
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
t = gen()
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
+ self._is_nvfp4 = bool(self._native_experts)
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
@@ -254,6 +300,16 @@ class Inkling2Model(TextModel):
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
+ if name in self._native_experts:
+ target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
+ new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
+ packed, scale = self._native_experts[name]
+ shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
+ shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
+ logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
+ self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
+ self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
+ return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
diff --git a/tests/test_conversion_fp8.py b/tests/test_conversion_fp8.py
index 0345c75b1..ffc5f6966 100644
--- a/tests/test_conversion_fp8.py
+++ b/tests/test_conversion_fp8.py
@@ -648,11 +648,12 @@ class TestInkling2PackedConversion(unittest.TestCase):
decoded = packed.float() * torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
return {"": packed, "_scale": scales}, decoded
- def packed_checkpoint(self):
+ def packed_checkpoint(self, n_ff=None):
"""Layer 0 is NVFP4, layer 1 is MXFP8. Returns the checkpoint tensors, the hf_quant_config groups and the expected GGUF tensors."""
+ n_ff = self.N_FF if n_ff is None else n_ff
tensors, quant_groups, expected = {}, [], {}
- w13_shape = (self.N_EXPERT, 2 * self.N_FF, self.N_EMBD)
- w2_shape = (self.N_EXPERT, self.N_EMBD, self.N_FF)
+ w13_shape = (self.N_EXPERT, 2 * n_ff, self.N_EMBD)
+ w2_shape = (self.N_EXPERT, self.N_EMBD, n_ff)
for layer, scheme in enumerate(("nvfp4_nearest", "mxfp8_nearest")):
names = []
for projection, shape, target in (("w13", w13_shape, "gate_up"), ("w2", w2_shape, "down")):
@@ -672,13 +673,16 @@ class TestInkling2PackedConversion(unittest.TestCase):
quant_groups.append({"tensors": names, "weight_transform": scheme, "weight_scale_format": "amax_denominator", "weight_block_shape": block_shape})
return tensors, quant_groups, expected
- def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False):
+ def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False, n_ff=None, fp8_as_q8=False, quant_config=None):
"""Writes the checkpoint to path and returns an Inkling2Model on it."""
- hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": self.N_FF, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
+ n_ff = self.N_FF if n_ff is None else n_ff
+ hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": n_ff, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
+ if quant_config is not None:
+ hp["quantization_config"] = quant_config
(path / "config.json").write_text(json.dumps(hp))
(path / "hf_quant_config.json").write_text(json.dumps({"model": {"parameter_groups": quant_groups}}))
save_file(tensors, path / "model.safetensors")
- return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager)
+ return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager, fp8_as_q8=fp8_as_q8)
def test_lookup_semantics(self):
"""The converter decode tables agree with torch.float8_e4m3fn; bytes 127 and 255 are NaN; E2M1 code 8 is -0."""
@@ -688,22 +692,24 @@ class TestInkling2PackedConversion(unittest.TestCase):
self.assertTrue(np.signbit(_E2M1[8]))
def test_mixed_schemes_and_streaming_outtypes(self):
- """Both schemes convert bit-exact to every outtype, lazily, in chunks of at most 128 rows."""
+ """Explicit outtypes dequantize both schemes bit-exact, lazily, in chunks of at most 128 rows."""
tensors, quant_groups, expected = self.packed_checkpoint()
outtypes = (
- (gguf.LlamaFileType.GUESSED, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.ALL_F32, gguf.GGMLQuantizationType.F32),
(gguf.LlamaFileType.MOSTLY_F16, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.MOSTLY_BF16, gguf.GGMLQuantizationType.BF16),
+ (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.GGMLQuantizationType.Q8_0),
)
+ quant_config = {"quant_method": "modelopt", "quant_algo": "NVFP4"}
for eager in (False, True):
for ftype, qtype in outtypes:
with self.subTest(eager=eager, outtype=qtype), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
- model = self.converter(path, tensors, quant_groups, ftype, eager)
+ model = self.converter(path, tensors, quant_groups, ftype, eager, quant_config=quant_config)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
model.prepare_tensors()
self.assertTrue(any("[32, 32]" in m and "[1, 32]" in m for m in logs.output))
+ self.assertFalse(model._is_nvfp4)
infos = model.gguf_writer.tensors[0]
self.assertEqual(infos.keys(), expected.keys())
for name, info in infos.items():
@@ -718,6 +724,83 @@ class TestInkling2PackedConversion(unittest.TestCase):
reference = gguf.quantize(expected[name], qtype)
self.assertEqual(self.written_bytes(info.tensor, path / "tensor.bin"), reference.tobytes(), name)
+ def test_auto_preserves_nvfp4_and_fp8_as_q8(self):
+ """--outtype auto repacks NVFP4 experts lazily with per-expert scales; --fp8-as-q8 stores MXFP8 as Q8_0."""
+ n_ff = 192
+ tensors, quant_groups, expected = self.packed_checkpoint(n_ff=n_ff)
+ for eager in (False, True):
+ for fp8_as_q8 in (False, True):
+ with self.subTest(eager=eager, fp8_as_q8=fp8_as_q8), tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, eager, n_ff=n_ff, fp8_as_q8=fp8_as_q8)
+ with self.assertLogs("hf-to-gguf", level="WARNING"):
+ model.prepare_tensors()
+ self.assertTrue(model._is_nvfp4)
+ infos = model.gguf_writer.tensors[0]
+ expected_keys = set(expected.keys()) | {"blk.0.ffn_gate_up_exps.scale", "blk.0.ffn_down_exps.scale"}
+ self.assertEqual(infos.keys(), expected_keys)
+ for target in ("gate_up", "down"):
+ w_name = f"blk.0.ffn_{target}_exps.weight"
+ s_name = f"blk.0.ffn_{target}_exps.scale"
+ w_info, s_info = infos[w_name], infos[s_name]
+ self.assertEqual(w_info.dtype, gguf.GGMLQuantizationType.NVFP4)
+ self.assertEqual(tuple(w_info.shape), expected[w_name].shape)
+ self.assertIsInstance(w_info.tensor, gguf.LazyChunkedTensor)
+ self.assertEqual(len(w_info.tensor._chunks), self.N_EXPERT)
+ with self.assertRaises(TypeError):
+ np.asarray(w_info.tensor)
+ raw = np.frombuffer(self.written_bytes(w_info.tensor, path / "tensor.bin"), dtype=np.uint8)
+ byte_shape = (expected[w_name].shape[0], expected[w_name].shape[1], expected[w_name].shape[2] // 64 * 36)
+ dequant = gguf.dequantize(raw.reshape(byte_shape), gguf.GGMLQuantizationType.NVFP4)
+ scale = np.asarray(s_info.tensor, dtype=np.float32)
+ self.assertEqual(s_info.dtype, gguf.GGMLQuantizationType.F32)
+ self.assertEqual(tuple(s_info.shape), (self.N_EXPERT,))
+ np.testing.assert_array_equal(dequant * scale[:, None, None], expected[w_name])
+
+ mxfp8_name = f"blk.1.ffn_{target}_exps.weight"
+ mxfp8_info = infos[mxfp8_name]
+ expected_qtype = gguf.GGMLQuantizationType.Q8_0 if fp8_as_q8 else gguf.GGMLQuantizationType.F16
+ self.assertEqual(mxfp8_info.dtype, expected_qtype)
+ reference = gguf.quantize(expected[mxfp8_name], expected_qtype)
+ self.assertEqual(self.written_bytes(mxfp8_info.tensor, path / "tensor.bin"), reference.tobytes(), mxfp8_name)
+
+ def test_auto_falls_back_when_nvfp4_cols_not_multiple_of_64(self):
+ """NVFP4 projections whose row width is not a multiple of 64 fall back to dequantization on --outtype auto."""
+ tensors, quant_groups, _ = self.packed_checkpoint(n_ff=160)
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=160)
+ with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
+ model.prepare_tensors()
+ self.assertTrue(any("not a multiple of 64" in m for m in logs.output))
+ infos = model.gguf_writer.tensors[0]
+ self.assertEqual(infos["blk.0.ffn_gate_up_exps.weight"].dtype, gguf.GGMLQuantizationType.NVFP4)
+ self.assertIn("blk.0.ffn_gate_up_exps.scale", infos)
+ self.assertEqual(infos["blk.0.ffn_down_exps.weight"].dtype, gguf.GGMLQuantizationType.F16)
+ self.assertNotIn("blk.0.ffn_down_exps.scale", infos)
+
+ def test_auto_nvfp4_rejects_invalid_scales(self):
+ """Native NVFP4 preservation rejects negative or NaN block scales and invalid outer scales."""
+ for bad_byte in (0x80, 0x7F, 0xFF):
+ tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
+ name = quant_groups[0]["tensors"][0]
+ tensors[name + "_scale"].view(torch.uint8)[1, 0, 0] = bad_byte
+ with self.subTest(bad_byte=hex(bad_byte)), tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
+ model.prepare_tensors()
+ tensor = model.gguf_writer.tensors[0]["blk.0.ffn_gate_up_exps.weight"].tensor
+ with self.assertRaisesRegex(ValueError, r"w13_weight_scale expert 1"):
+ self.written_bytes(tensor, path / "tensor.bin")
+ for suffix, bad_val in (("_amax", -1.0), ("_amax", float("nan")), ("_outer_scale_denominator", 0.0)):
+ tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
+ name = quant_groups[0]["tensors"][0]
+ tensors[name + suffix][-1] = bad_val
+ with self.subTest(suffix=suffix, bad_val=bad_val), tempfile.TemporaryDirectory() as directory:
+ model = self.converter(Path(directory), tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
+ with self.assertRaisesRegex(ValueError, "Inkling2:"):
+ model.prepare_tensors()
+
def test_projection_and_companions_in_separate_shards(self):
"""A packed weight and its scale, amax and denominator can be in different safetensors shards."""
tensors, quant_groups, expected = self.packed_checkpoint()