From 7c5b17ddf303c73abd1b61b6037a0a08d8e93f60 Mon Sep 17 00:00:00 2001 From: Xiaoze Fan Date: Sun, 15 Nov 2026 00:13:54 -0800 Subject: [PATCH 1/2] fix(models): load flint checkpoints nested under language_model --- python/ftmetal/models/flint/config.py | 15 +++++- python/ftmetal/models/flint/weight.py | 46 +++++++++++++---- tests/models/test_parity_flint.py | 72 ++++++++++++++++++++++++--- tests/tiny_flint_model.py | 45 +++++++++++++++-- 4 files changed, 155 insertions(+), 23 deletions(-) diff --git a/python/ftmetal/models/flint/config.py b/python/ftmetal/models/flint/config.py index a6d9b6e..f9e4982 100644 --- a/python/ftmetal/models/flint/config.py +++ b/python/ftmetal/models/flint/config.py @@ -2,7 +2,8 @@ Port of FreeToken models/flint/config.py. Divergences: reads the checkpoint dictionary and its MLX scheme map, in which the release's export section also declares the embedding's bits (its -quantization section names only the default); no GGUF metadata shim. +quantization section names only the default) and a conversion that nests the text model under +language_model. names its modules with that prefix; no GGUF metadata shim. """ from __future__ import annotations @@ -16,6 +17,7 @@ RotaryConfig, SWAAttentionGroupConfig, ) +from ftmetal.models.flint.weight import bare_name from ftmetal.models.loader import ( config_bool, config_dict, @@ -102,6 +104,15 @@ def parse_config(config: dict[str, object], quant: QuantConfig | None = None) -> base=config_float(config, "rope_theta", 10000.0) if rope_theta is None else rope_theta, ) architectures = config_str_list(config, "architectures") or ["FlintForCausalLM"] + # The section names modules as the checkpoint does; mlx_layout gave them bare names. + bare_quant = ( + None + if quant is None + else replace( + quant, + overrides={bare_name(module): scheme for module, scheme in quant.overrides.items()}, + ) + ) return ModelConfig( num_layers=num_layers, num_qo_heads=config_int(config, "num_attention_heads"), @@ -137,7 +148,7 @@ def parse_config(config: dict[str, object], quant: QuantConfig | None = None) -> rotary_config=replace(swa_rotary, rotary_dim=0), ), ), - quant=with_embedding_bits(config, quant), + quant=with_embedding_bits(config, bare_quant), moe_enabled=True, shared_expert_intermediate_size=config_int(config, "shared_expert_intermediate_size"), first_k_dense_replace=len(dense_ids), diff --git a/python/ftmetal/models/flint/weight.py b/python/ftmetal/models/flint/weight.py index c18a64c..a526ffc 100644 --- a/python/ftmetal/models/flint/weight.py +++ b/python/ftmetal/models/flint/weight.py @@ -2,8 +2,9 @@ Port of FreeToken models/flint/weight.py. Divergences: the rules read the MLX layout, which stores the experts stacked per layer, so they are renames and fusions only; mlx_layout turns the packed -bytes of the flint-int4 release into the words the quantized matmuls read, and refuses the Hugging -Face layout, so the ModelOpt exports in it too; GGUF is not served. +bytes of the flint-int4 release into the words the quantized matmuls read, takes the text model +out from under language_model., where some conversions nest it, and refuses the Hugging Face +layout, so the ModelOpt exports in it too; GGUF is not served. """ from __future__ import annotations @@ -12,34 +13,61 @@ from ftmetal.layers.shared_expert_moe import GATE_UP_PARTS from ftmetal.models.config import ModelConfig -from ftmetal.models.loader import ExpertBytes, FuseRule, WeightRules +from ftmetal.models.loader import ExpertBytes, FuseRule, WeightRules, stacked_slices # Checkpoint module paths of the quantization map, per fused model leaf. QKV_PARTS = ("q_proj", "k_proj", "v_proj") WEIGHT_SUFFIX = ".weight" -# What a layer's experts sit under in the Hugging Face layout; the MLX layout has switch_mlp. +# What a layer's experts sit under in the Hugging Face layout and in the MLX layout. HF_EXPERTS = ".mlp.experts." +MLX_EXPERTS = ".mlp.switch_mlp." +# Some conversions nest the text model's roots under this prefix; the release does not. +LANGUAGE_MODEL_PREFIX = "language_model." +TEXT_ROOTS = ("model", "lm_head") +# Those conversions also store a router bias, all zeros: no Flint config enables one, so a zero +# one is left out and any other refused. +EXPERT_BIAS_SUFFIX = ".mlp.expert_bias" + + +def bare_name(name: str) -> str: + """A checkpoint tensor or module name under the release's names: a text model root out from + under language_model.; any other name as it is.""" + stripped = name.removeprefix(LANGUAGE_MODEL_PREFIX) + return stripped if stripped.partition(".")[0] in TEXT_ROOTS else name def mlx_layout( state: dict[str, mx.array], ) -> tuple[dict[str, mx.array], dict[str, ExpertBytes]]: - """The checkpoint with its packed weights as uint32 words, which flint-int4 stores as bytes: - the bytes stay where they are, so no expert moves. Refuses any other layout.""" + """The checkpoint under the release's names (bare_name), without the zero router bias, and + with its packed weights as uint32 words, which flint-int4 stores as bytes: the bytes stay + where they are, so no expert moves; and where each expert of a renamed bank lies in the + checkpoint. Refuses any other layout, a nonzero router bias and a tensor stored under both + names.""" if any(HF_EXPERTS in key for key in state): raise ValueError( "Flint serves MLX layout checkpoints only (mlp.switch_mlp experts), " "not the Hugging Face layout or an export in it" ) out: dict[str, mx.array] = {} + expert_bytes: dict[str, ExpertBytes] = {} for key, tensor in state.items(): + if key.endswith(EXPERT_BIAS_SUFFIX): + if mx.any(tensor != 0).item(): + raise ValueError(f"{key}: a nonzero router expert bias is not served") + continue + name = bare_name(key) + if name in out: + raise ValueError(f"{name}: the checkpoint stores it both under language_model. and not") is_packed_bytes = ( tensor.dtype == mx.uint8 and key.endswith(WEIGHT_SUFFIX) and f"{key.removesuffix(WEIGHT_SUFFIX)}.scales" in state ) - out[key] = tensor.view(mx.uint32) if is_packed_bytes else tensor - return out, {} + out[name] = tensor.view(mx.uint32) if is_packed_bytes else tensor + if name != key and MLX_EXPERTS in key: + expert_bytes[name] = stacked_slices(key, tensor) + return out, expert_bytes def weight_rules(model_config: ModelConfig) -> WeightRules: @@ -50,4 +78,4 @@ def weight_rules(model_config: ModelConfig) -> WeightRules: ) -__all__ = ["QKV_PARTS", "mlx_layout", "weight_rules"] +__all__ = ["QKV_PARTS", "bare_name", "mlx_layout", "weight_rules"] diff --git a/tests/models/test_parity_flint.py b/tests/models/test_parity_flint.py index 50ba55c..ab8d72b 100644 --- a/tests/models/test_parity_flint.py +++ b/tests/models/test_parity_flint.py @@ -4,10 +4,11 @@ the sliding layers) and ftmetal (both pools, both attention backends, the scheduler with overlap and decode graphs, the SWA radix cache) run the same random weights: prefill logits must match and greedy decode must agree token for token, with the window crossed in prefill, in decode and at -chunk seams, batched, resumed from the prefix cache and quantized as flint-int4 stores it. Under -MoE offload, whose layer indices start past the dense layers and whose shared expert has no gate: -replayed decode with and without split lookup, eager decode, an overlap prefill, two requests, and -an expert pack. +chunk seams, batched, resumed from the prefix cache, quantized as flint-int4 stores it and stored +as the conversions that nest the text model under language_model. do. Under MoE offload, whose +layer indices start past the dense layers and whose shared expert has no gate: replayed decode with +and without split lookup, eager decode, an overlap prefill, two requests, an expert pack and a +conversion's experts read from their stored names. """ from __future__ import annotations @@ -33,17 +34,20 @@ from ftmetal.layers.quantization.moe_pending import PendingOutputs from ftmetal.models.config import MoeStrategy from ftmetal.models.flint.config import parse_config +from ftmetal.models.flint.weight import mlx_layout from ftmetal.models.register import read_checkpoint from ftmetal.moe.offload_cache import IssuedLookup from ftmetal.scheduler.scheduler import Scheduler from tiny_flint_model import ( EOS_TOKEN_ID, + ROUTER_BITS, TINY_FLINT_CONFIG, WINDOW, build_reference, quantize, reference_greedy, save_checkpoint, + save_conversion, ) LOGITS_TOLERANCE = 1e-4 @@ -104,6 +108,8 @@ class GreedyCase: max_extend_tokens: int = 64 is_quantized: bool = False command_graph: bool = True + # Stored as a conversion under language_model. (save_conversion); quantized, its router too. + is_conversion: bool = False GREEDY_CASES = [ @@ -117,6 +123,9 @@ class GreedyCase: GreedyCase("metal-chunk-seams", "metal", 4, 29, 6, max_extend_tokens=12), GreedyCase("mlx-flint-int4", "mlx", 1, 19, 16, is_quantized=True), GreedyCase("metal-flint-int4", "metal", 1, 19, 16, is_quantized=True), + GreedyCase("mlx-conversion", "mlx", 1, 19, 16, is_quantized=True, is_conversion=True), + GreedyCase("metal-conversion", "metal", 1, 19, 16, is_quantized=True, is_conversion=True), + GreedyCase("metal-bf16-conversion", "metal", 1, 19, 16, is_conversion=True), ] @@ -124,8 +133,11 @@ class GreedyCase: def test_greedy_decode_matches_reference(tmp_path: Path, case: GreedyCase) -> None: model = build_reference(seed=11) if case.is_quantized: - quantize(model) - save_checkpoint(model, tmp_path, case.is_quantized) + quantize(model, router_bits=ROUTER_BITS if case.is_conversion else None) + if case.is_conversion: + save_conversion(model, tmp_path) + else: + save_checkpoint(model, tmp_path, case.is_quantized) prompt = random_prompt(case.prompt_len, case.prompt_len) _, expected = reference_greedy(model, prompt, case.steps) assert len(set(expected)) > 1 or case.steps < 6, "a token stream too flat to tell paths apart" @@ -211,6 +223,7 @@ class OffloadCase: command_graph: bool = True split_lookup: bool = True is_packed: bool = False + is_conversion: bool = False OFFLOAD_CASES = [ @@ -221,6 +234,7 @@ class OffloadCase: OffloadCase("chunks-across-the-threshold", (100,), overlap_min_tokens=48), OffloadCase("two-requests", (13, 29)), OffloadCase("expert-pack", (9,), is_packed=True), + OffloadCase("conversion", (9,), is_conversion=True), ] @@ -230,8 +244,12 @@ def test_offload_matches_reference( ) -> None: monkeypatch.setenv("FTMETAL_MOE_PREFILL_OVERLAP_MIN_TOKENS", str(case.overlap_min_tokens)) model = build_reference(seed=18, config=OFFLOAD_CONFIG) - quantize(model) - save_checkpoint(model, tmp_path, is_quantized=True, config=OFFLOAD_CONFIG) + if case.is_conversion: + quantize(model, router_bits=ROUTER_BITS) + save_conversion(model, tmp_path, config=OFFLOAD_CONFIG) + else: + quantize(model) + save_checkpoint(model, tmp_path, is_quantized=True, config=OFFLOAD_CONFIG) if case.is_packed: assert run_pack(["--model", str(tmp_path)]) == 0 prompts = [random_prompt(n, n) for n in case.prompt_lens] @@ -268,6 +286,44 @@ def recorded_apply_pending( cache.check_healthy() +MTP_NORM = "language_model.mtp.layers.0.input_layernorm.weight" +NESTED_TOWER_NORM = "language_model.vision_tower.blocks.0.norm1.weight" +TOWER_NORM = "vision_tower.blocks.0.norm1.weight" +# (a checkpoint tensor name, its name in the MLX layout; None: left out) +LAYOUT_NAME_CASES: list[tuple[str, str | None]] = [ + ("model.layers.0.mlp.down_proj.weight", "model.layers.0.mlp.down_proj.weight"), + ("language_model.model.layers.2.mlp.gate.scales", "model.layers.2.mlp.gate.scales"), + ("language_model.lm_head.weight", "lm_head.weight"), + ("language_model.model.layers.2.mlp.expert_bias", None), + (MTP_NORM, MTP_NORM), + (NESTED_TOWER_NORM, NESTED_TOWER_NORM), + (TOWER_NORM, TOWER_NORM), +] + + +@pytest.mark.parametrize(("name", "expected"), LAYOUT_NAME_CASES) +def test_layout_takes_only_the_text_model_out_from_under_language_model( + name: str, expected: str | None +) -> None: + """An MTP head or a tower beside the text model keeps its name, so it fails the strict load + instead of passing for a module of the text model.""" + state, _ = mlx_layout({name: mx.zeros((2, 2))}) + assert list(state) == ([] if expected is None else [expected]) + + +def test_layout_refuses_a_nonzero_router_bias() -> None: + bias = "language_model.model.layers.2.mlp.expert_bias" + with pytest.raises(ValueError, match=f"{bias}: a nonzero router expert bias"): + mlx_layout({bias: mx.array([0.0, 0.5])}) + + +def test_layout_refuses_a_tensor_stored_under_both_names() -> None: + """Either copy would otherwise replace the other unseen.""" + state = {"model.norm.weight": mx.zeros((2,)), "language_model.model.norm.weight": mx.ones((2,))} + with pytest.raises(ValueError, match="model.norm.weight: the checkpoint stores it both"): + mlx_layout(state) + + def test_the_hugging_face_layout_is_refused(tmp_path: Path) -> None: """The release's bf16 layout, and an export in it, fail by name, not at the strict load.""" tensor = {"model.layers.2.mlp.experts.0.up_proj.weight": mx.zeros((2, 2))} diff --git a/tests/tiny_flint_model.py b/tests/tiny_flint_model.py index 6f3a063..7a4019f 100644 --- a/tests/tiny_flint_model.py +++ b/tests/tiny_flint_model.py @@ -6,7 +6,8 @@ shared expert. Sinks and norms are perturbed, since an initial zero sink would hide a kernel that drops it. save_checkpoint writes the MLX layout; quantized, as flint-int4 stores it: group-64 affine 4-bit, the embedding in 8 bits only its export section declares, the router unquantized and -the packed weights as bytes. +the packed weights as bytes. save_conversion writes it as the conversions that nest the text model +under language_model. do. """ from __future__ import annotations @@ -28,6 +29,9 @@ GROUP_SIZE = 64 BITS = 4 EMBEDDING_BITS = 8 +# The conversions quantize the router, in 8 bits, and nest the text model under this prefix. +ROUTER_BITS = 8 +CONVERSION_PREFIX = "language_model." SINK_SCALE = 2.0 NORM_NOISE = 0.1 LAYER_TYPES = [ @@ -215,14 +219,19 @@ def build_reference(seed: int, config: dict[str, object] | None = None) -> Model return model -def quantize(model: Model) -> None: - """The flint-int4 recipe: 4-bit in groups of 64, the embedding in 8, the router unquantized.""" +def quantize(model: Model, router_bits: int | None = None) -> None: + """The flint-int4 recipe: 4-bit in groups of 64, the embedding in 8, the router unquantized, + or in router_bits.""" def predicate(path: str, module: nn.Module) -> bool | dict[str, object]: - if not hasattr(module, "to_quantized") or path.endswith("mlp.gate"): + if not hasattr(module, "to_quantized") or ( + path.endswith("mlp.gate") and router_bits is None + ): return False if path.endswith("embed_tokens"): return {"group_size": GROUP_SIZE, "bits": EMBEDDING_BITS} + if path.endswith("mlp.gate"): + return {"group_size": GROUP_SIZE, "bits": router_bits} return True nn.quantize(model, GROUP_SIZE, BITS, class_predicate=predicate) @@ -248,6 +257,34 @@ def save_checkpoint( (path / "config.json").write_text(json.dumps(saved_config)) +def save_conversion(model: Model, path: Path, config: dict[str, object] | None = None) -> None: + """The MLX layout as conversions store it: every name under language_model., a zero router + bias per MoE layer, packed weights as words and, quantized, the modules not in the default + scheme named under the prefix in the quantization section, with no export section.""" + saved_config = dict(TINY_FLINT_CONFIG if config is None else config) + state = {CONVERSION_PREFIX + key: value for key, value in tree_flatten(model.parameters())} + dense_ids = saved_config["mlp_only_layers"] + assert isinstance(dense_ids, list) + for layer_id in range(config_int(saved_config, "num_hidden_layers")): + if layer_id not in dense_ids: + bias = mx.zeros((config_int(saved_config, "num_experts"),)) + state[f"{CONVERSION_PREFIX}model.layers.{layer_id}.mlp.expert_bias"] = bias + quantized = [ + (module_path, module) + for module_path, module in model.named_modules() + if isinstance(module, (nn.QuantizedLinear, nn.QuantizedEmbedding)) + ] + if quantized: + quantization: dict[str, object] = {"group_size": GROUP_SIZE, "bits": BITS} + for module_path, module in quantized: + if module.bits != BITS: + entry = {"group_size": module.group_size, "bits": module.bits} + quantization[CONVERSION_PREFIX + module_path] = entry + saved_config["quantization"] = quantization + mx.save_safetensors(str(path / "model.safetensors"), state, metadata={"format": "mlx"}) + (path / "config.json").write_text(json.dumps(saved_config)) + + def reference_greedy(model: Model, prompt: list[int], steps: int) -> tuple[mx.array, list[int]]: """The prefill's logits [prompt, vocab] and the greedy tokens.""" cache = model.make_cache() From c27d7e666e03554cda0b10a6cf9f795988a7f5c1 Mon Sep 17 00:00:00 2001 From: Xiaoze Fan Date: Sun, 15 Nov 2026 00:18:44 -0800 Subject: [PATCH 2/2] fix(models): serve nvfp4 weight_scale_2 in mlx checkpoints --- python/ftmetal/layers/quantization/config.py | 26 +++++++-- python/ftmetal/models/quant_export.py | 24 +++++++- python/ftmetal/models/register.py | 7 ++- tests/models/test_parity_flint.py | 41 +++++++++++++- tests/tiny_flint_model.py | 59 +++++++++++++++++--- 5 files changed, 138 insertions(+), 19 deletions(-) diff --git a/python/ftmetal/layers/quantization/config.py b/python/ftmetal/layers/quantization/config.py index 2cb287d..eff9434 100644 --- a/python/ftmetal/layers/quantization/config.py +++ b/python/ftmetal/layers/quantization/config.py @@ -5,7 +5,8 @@ modes mxfp4, nvfp4 and mxfp8 (FpBlockScheme). A module is quantized when the checkpoint holds its scales tensor; the per-module entries of the quantization section override the default and are affine unless they name a mode. A ModelOpt or compressed-tensors export, rewritten by -models/quant_export.py, brings the scheme of each module it rewrote instead (from_export). A +models/quant_export.py, brings the scheme of each module it rewrote instead (from_export); an +MLX nvfp4 module that stores a global scale as such an export does is output-scaled. A scheme is one dataclass per kind (the kind is its type) and QuantScheme names any of them. A scheme's layout is the arrays it stores an [output, input] weight in, which the methods of layers/quantization/{linear,embedding,moe}.py allocate and read; FreeToken's methods and @@ -17,7 +18,7 @@ from __future__ import annotations import math -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import Literal import mlx.core as mx @@ -119,6 +120,9 @@ class QuantConfig: default: QuantScheme | None overrides: dict[str, QuantScheme] quantized_modules: frozenset[str] + # Modules whose global scale became their output_scale (rewrite_global_scales); each must be + # declared nvfp4. + output_scaled_modules: frozenset[str] = frozenset() @classmethod def from_checkpoint( @@ -145,11 +149,21 @@ def from_export(cls, schemes: dict[str, QuantScheme]) -> QuantConfig: def scheme_for(self, checkpoint_name: str) -> QuantScheme | None: """Scheme of one module by its checkpoint name; None means bf16.""" if checkpoint_name in self.overrides: - return self.overrides[checkpoint_name] - if checkpoint_name in self.quantized_modules: + declared = self.overrides[checkpoint_name] + elif checkpoint_name in self.quantized_modules: assert self.default is not None, f"{checkpoint_name} has scales but no default scheme" - return self.default - return None + declared = self.default + else: + declared = None + if checkpoint_name not in self.output_scaled_modules: + return declared + elif declared == FpBlockScheme("nvfp4"): + return replace(declared, has_output_scale=True) + else: + raise ValueError( + f"{checkpoint_name}: a global scale (weight_scale_2) scales nvfp4 weights only, " + f"not {declared}" + ) def schemes_for(self, checkpoint_names: list[str]) -> list[QuantScheme | None]: """The scheme of each part of a fused module; the parts fuse only when all agree.""" diff --git a/python/ftmetal/models/quant_export.py b/python/ftmetal/models/quant_export.py index 223c6e7..7586cfb 100644 --- a/python/ftmetal/models/quant_export.py +++ b/python/ftmetal/models/quant_export.py @@ -1,4 +1,5 @@ -"""ModelOpt and compressed-tensors exports rewritten into MLX quantized tensors. +"""ModelOpt and compressed-tensors exports rewritten into MLX quantized tensors, and the global +scales an MLX nvfp4 checkpoint keeps as ModelOpt does rewritten into output scales. Port of the weight-only part of FreeToken layers/quantization/configs/modelopt.py and compressed_tensors.py. Divergences: the export's NVFP4 and per-tensor FP8 modules are rewritten @@ -56,6 +57,25 @@ def output_scale(module: str, scale: mx.array, weight: mx.array) -> mx.array: return mx.full((weight.shape[0], 1), scale.astype(mx.float32).reshape(())) +def rewrite_global_scales( + state: dict[str, mx.array], +) -> tuple[dict[str, mx.array], frozenset[str]]: + """An MLX checkpoint whose nvfp4 modules each store the dequantization-side global scale + ModelOpt NVFP4 does (weight_scale_2: one per tensor, or per expert of a bank), with each such + scale as its module's output_scale; and the modules rewritten, for QuantConfig to check that + each is declared nvfp4.""" + out: dict[str, mx.array] = {} + modules: set[str] = set() + for key, tensor in state.items(): + if key.endswith(".weight_scale_2"): + module = key.removesuffix(".weight_scale_2") + out[f"{module}.output_scale"] = output_scale(module, tensor, state[f"{module}.weight"]) + modules.add(module) + else: + out[key] = tensor + return out, frozenset(modules) + + def rewrite_export( state: dict[str, mx.array], quantization_config: dict[str, object], @@ -160,4 +180,4 @@ def carry(out_key: str, key: str) -> None: return out, schemes, out_expert_bytes -__all__ = ["rewrite_export"] +__all__ = ["rewrite_export", "rewrite_global_scales"] diff --git a/python/ftmetal/models/register.py b/python/ftmetal/models/register.py index e24fe0b..0f8f933 100644 --- a/python/ftmetal/models/register.py +++ b/python/ftmetal/models/register.py @@ -28,7 +28,7 @@ mixed_fuses, read_model_config, ) -from ftmetal.models.quant_export import rewrite_export +from ftmetal.models.quant_export import rewrite_export, rewrite_global_scales @dataclass(frozen=True) @@ -176,7 +176,8 @@ class Checkpoint: def read_checkpoint(architecture: str, model_path: str) -> Checkpoint: """The checkpoint as an MLX one: a Hugging Face layout rewritten by the family's - mlx_layout, then a ModelOpt or compressed-tensors export's tensors by rewrite_export.""" + mlx_layout, then a ModelOpt or compressed-tensors export's tensors by rewrite_export, or an + MLX checkpoint's nvfp4 global scales by rewrite_global_scales.""" spec = get_model_spec(architecture) config = read_model_config(model_path) state = load_checkpoint(model_path) @@ -187,7 +188,9 @@ def read_checkpoint(architecture: str, model_path: str) -> Checkpoint: quantization = config_dict(config, "quantization") export_config = config_dict(config, "quantization_config") if quantization is not None or export_config is None: + state, scaled = rewrite_global_scales(state) quant = QuantConfig.from_checkpoint(quantization, list(state)) + quant = replace(quant, output_scaled_modules=scaled) return Checkpoint(state=state, quant=quant, expert_bytes=expert_bytes) elif spec.mlx_layout is None: method = config_str(export_config, "quant_method", "") diff --git a/tests/models/test_parity_flint.py b/tests/models/test_parity_flint.py index ab8d72b..f7746d8 100644 --- a/tests/models/test_parity_flint.py +++ b/tests/models/test_parity_flint.py @@ -8,7 +8,8 @@ as the conversions that nest the text model under language_model. do. Under MoE offload, whose layer indices start past the dense layers and whose shared expert has no gate: replayed decode with and without split lookup, eager decode, an overlap prefill, two requests, an expert pack and a -conversion's experts read from their stored names. +conversion's experts read from their stored names. The nvfp4 conversion, each linear under a +global scale, must serve like the reference on its dequantized weights, fused and offloaded. """ from __future__ import annotations @@ -35,7 +36,7 @@ from ftmetal.models.config import MoeStrategy from ftmetal.models.flint.config import parse_config from ftmetal.models.flint.weight import mlx_layout -from ftmetal.models.register import read_checkpoint +from ftmetal.models.register import create_model, read_checkpoint from ftmetal.moe.offload_cache import IssuedLookup from ftmetal.scheduler.scheduler import Scheduler from tiny_flint_model import ( @@ -45,6 +46,7 @@ WINDOW, build_reference, quantize, + quantize_nvfp4, reference_greedy, save_checkpoint, save_conversion, @@ -286,6 +288,41 @@ def recorded_apply_pending( cache.check_healthy() +@pytest.mark.parametrize("strategy", ["fused", "offload"]) +def test_nvfp4_conversion_matches_its_dequantized_weights( + tmp_path: Path, strategy: MoeStrategy +) -> None: + model = build_reference(seed=19, config=OFFLOAD_CONFIG) + nvfp4_tensors = quantize_nvfp4(model) + save_conversion(model, tmp_path, config=OFFLOAD_CONFIG, nvfp4_tensors=nvfp4_tensors) + prompt = random_prompt(10, 19) + _, expected = reference_greedy(model, prompt, OFFLOAD_STEPS) + scheduler = make_scheduler(tmp_path, page_size=4, strategy=strategy) + assert generate(scheduler, [prompt], OFFLOAD_STEPS) == [expected] + + +# A module the nvfp4 conversion stores with a global scale, declared otherwise under its own name. +SCALED_MODULE = "model.layers.2.self_attn.q_proj" +NOT_NVFP4_ENTRIES: list[dict[str, object]] = [ + {"group_size": 64, "bits": 4, "mode": "affine"}, + {"group_size": 32, "bits": 8, "mode": "mxfp8"}, +] + + +@pytest.mark.parametrize("entry", NOT_NVFP4_ENTRIES, ids=lambda entry: str(entry["mode"])) +def test_a_global_scale_on_a_module_not_declared_nvfp4_is_refused( + tmp_path: Path, entry: dict[str, object] +) -> None: + model = build_reference(seed=20) + save_conversion(model, tmp_path, nvfp4_tensors=quantize_nvfp4(model)) + config = json.loads((tmp_path / "config.json").read_text()) + config["quantization"][f"language_model.{SCALED_MODULE}"] = entry + (tmp_path / "config.json").write_text(json.dumps(config)) + engine_config = EngineConfig(model_path=str(tmp_path), dtype=mx.float32) + with pytest.raises(ValueError, match=f"{SCALED_MODULE}: a global scale"): + create_model(engine_config.architecture, engine_config.model_config, mx.float32) + + MTP_NORM = "language_model.mtp.layers.0.input_layernorm.weight" NESTED_TOWER_NORM = "language_model.vision_tower.blocks.0.norm1.weight" TOWER_NORM = "vision_tower.blocks.0.norm1.weight" diff --git a/tests/tiny_flint_model.py b/tests/tiny_flint_model.py index 7a4019f..6768e7d 100644 --- a/tests/tiny_flint_model.py +++ b/tests/tiny_flint_model.py @@ -7,7 +7,7 @@ drops it. save_checkpoint writes the MLX layout; quantized, as flint-int4 stores it: group-64 affine 4-bit, the embedding in 8 bits only its export section declares, the router unquantized and the packed weights as bytes. save_conversion writes it as the conversions that nest the text model -under language_model. do. +under language_model. do, the nvfp4 one (quantize_nvfp4) included. """ from __future__ import annotations @@ -32,6 +32,11 @@ # The conversions quantize the router, in 8 bits, and nest the text model under this prefix. ROUTER_BITS = 8 CONVERSION_PREFIX = "language_model." +# The nvfp4 conversion's linears: e2m1 in groups of 16 with an e4m3 scale each, under a global +# scale per tensor (per expert in a bank) of absmax / 2688, e2m1's largest value times e4m3's. +NVFP4_ENTRY: dict[str, object] = {"group_size": 16, "bits": 4, "mode": "nvfp4"} +NVFP4_SCALE_DIVISOR = 6.0 * 448.0 +AFFINE_ENTRY: dict[str, object] = {"group_size": GROUP_SIZE, "bits": BITS, "mode": "affine"} SINK_SCALE = 2.0 NORM_NOISE = 0.1 LAYER_TYPES = [ @@ -238,6 +243,38 @@ def predicate(path: str, module: nn.Module) -> bool | dict[str, object]: mx.eval(model.parameters()) +def quantize_nvfp4(model: Model) -> dict[str, mx.array]: + """Quantize model as the nvfp4 conversion does: the router and the embedding in 8-bit affine, + every other linear to its nvfp4 dequantization under its global scales. Returns those + linears' stored tensors by name: the packed weight, its scales and weight_scale_2.""" + stored: dict[str, mx.array] = {} + dequantized: list[tuple[str, mx.array]] = [] + for key, weight in tree_flatten(model.parameters()): + assert isinstance(weight, mx.array) + module = key.removesuffix(".weight") + if weight.ndim < 2 or module.endswith(("mlp.gate", "embed_tokens")): + continue + global_scale = mx.max(mx.abs(weight), axis=(-2, -1), keepdims=True) / NVFP4_SCALE_DIVISOR + packed, scales = mx.quantize(weight / global_scale, **NVFP4_ENTRY) + stored[key] = packed + stored[f"{module}.scales"] = scales + stored[f"{module}.weight_scale_2"] = global_scale.reshape(weight.shape[:-2]) + values = mx.dequantize(packed, scales, **NVFP4_ENTRY, dtype=mx.float32) + dequantized.append((key, values * global_scale)) + model.load_weights(dequantized, strict=False) + + def predicate(path: str, module: nn.Module) -> bool | dict[str, object]: + if path.endswith("embed_tokens"): + return {"group_size": GROUP_SIZE, "bits": EMBEDDING_BITS} + if path.endswith("mlp.gate"): + return {"group_size": GROUP_SIZE, "bits": ROUTER_BITS} + return False + + nn.quantize(model, class_predicate=predicate) + mx.eval(model.parameters(), stored) + return stored + + def save_checkpoint( model: Model, path: Path, is_quantized: bool, config: dict[str, object] | None = None ) -> None: @@ -257,12 +294,19 @@ def save_checkpoint( (path / "config.json").write_text(json.dumps(saved_config)) -def save_conversion(model: Model, path: Path, config: dict[str, object] | None = None) -> None: +def save_conversion( + model: Model, + path: Path, + config: dict[str, object] | None = None, + nvfp4_tensors: dict[str, mx.array] | None = None, +) -> None: """The MLX layout as conversions store it: every name under language_model., a zero router bias per MoE layer, packed weights as words and, quantized, the modules not in the default - scheme named under the prefix in the quantization section, with no export section.""" + scheme named under the prefix in the quantization section, with no export section. + nvfp4_tensors (quantize_nvfp4's) replace their linears' weights, nvfp4 then the default.""" saved_config = dict(TINY_FLINT_CONFIG if config is None else config) - state = {CONVERSION_PREFIX + key: value for key, value in tree_flatten(model.parameters())} + params = dict(tree_flatten(model.parameters())) | (nvfp4_tensors or {}) + state = {CONVERSION_PREFIX + key: value for key, value in params.items()} dense_ids = saved_config["mlp_only_layers"] assert isinstance(dense_ids, list) for layer_id in range(config_int(saved_config, "num_hidden_layers")): @@ -275,10 +319,11 @@ def save_conversion(model: Model, path: Path, config: dict[str, object] | None = if isinstance(module, (nn.QuantizedLinear, nn.QuantizedEmbedding)) ] if quantized: - quantization: dict[str, object] = {"group_size": GROUP_SIZE, "bits": BITS} + default = AFFINE_ENTRY if nvfp4_tensors is None else NVFP4_ENTRY + quantization: dict[str, object] = dict(default) for module_path, module in quantized: - if module.bits != BITS: - entry = {"group_size": module.group_size, "bits": module.bits} + entry = {"group_size": module.group_size, "bits": module.bits, "mode": module.mode} + if entry != default: quantization[CONVERSION_PREFIX + module_path] = entry saved_config["quantization"] = quantization mx.save_safetensors(str(path / "model.safetensors"), state, metadata={"format": "mlx"})