Skip to content
Merged
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
26 changes: 20 additions & 6 deletions python/ftmetal/layers/quantization/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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."""
Expand Down
15 changes: 13 additions & 2 deletions python/ftmetal/models/flint/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -16,6 +17,7 @@
RotaryConfig,
SWAAttentionGroupConfig,
)
from ftmetal.models.flint.weight import bare_name
from ftmetal.models.loader import (
config_bool,
config_dict,
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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),
Expand Down
46 changes: 37 additions & 9 deletions python/ftmetal/models/flint/weight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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"]
24 changes: 22 additions & 2 deletions python/ftmetal/models/quant_export.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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"]
7 changes: 5 additions & 2 deletions python/ftmetal/models/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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", "")
Expand Down
Loading
Loading