mirror of
https://github.com/FlashML-org/FreeToken.git
synced 2026-12-03 20:04:02 +08:00
feat(qwen3_5_moe): read every checkpoint layout through the QuantConfig (#438)
* feat(qwen3_5_moe): read every checkpoint layout through the QuantConfig NVFP4 dense layers now declare the input_scale their scheme carries, so an FTW written by an older build from an NVFP4 dense checkpoint needs scripts/ftw_hotfix.py before it loads again. * fix(quant): address scheme reader review: hotfix dialect names, gemma4 cross-shard scales, ct block-fp8 experts
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from ..linear import LinearConfig
|
||||
@@ -36,8 +37,18 @@ def quantization_config_of(hf_config: Any) -> dict[str, Any] | None:
|
||||
return dict(vars(q))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Stored:
|
||||
"""One checkpoint tensor behind a role: its suffix, and whether it holds the quant-side scale whose reciprocal the layer wants."""
|
||||
|
||||
name: str
|
||||
reciprocal: bool = False
|
||||
|
||||
|
||||
class QuantConfig(ABC):
|
||||
dialect: ClassVar[str]
|
||||
# per kind the dialect exports, role -> the checkpoint tensor suffix (or Stored) that feeds it
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]]
|
||||
|
||||
def __init__(self, name_map: NameMap | None = None, unquantized: tuple[str, ...] = ()):
|
||||
self.name_map = name_map or NameMap()
|
||||
@@ -65,6 +76,14 @@ class QuantConfig(ABC):
|
||||
self._schemes[prefix] = scheme
|
||||
return scheme
|
||||
|
||||
def stored_tensors(self, kind: QuantKind) -> dict[str, Stored]:
|
||||
"""role -> checkpoint tensor for every role the dialect stores for ``kind``."""
|
||||
return {role: entry if isinstance(entry, Stored) else Stored(entry) for role, entry in self.STORAGE[kind].items()}
|
||||
|
||||
def storage(self, scheme: QuantScheme) -> dict[str, Stored]:
|
||||
"""role -> checkpoint tensor for one scheme's tensors."""
|
||||
return {role: entry for role, entry in self.stored_tensors(scheme.kind).items() if scheme.has(role)}
|
||||
|
||||
def get_quant_method(self, layer: Any, prefix: str):
|
||||
scheme = self.scheme_for(prefix)
|
||||
layer_kind = layer.quant_layer_kind
|
||||
@@ -101,6 +120,7 @@ class NoQuantConfig(QuantConfig):
|
||||
"""No ``quantization_config``: every module is bf16."""
|
||||
|
||||
dialect = "none"
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]] = {}
|
||||
|
||||
@classmethod
|
||||
def claims(cls, q: dict[str, Any]) -> bool:
|
||||
|
||||
@@ -4,9 +4,9 @@ from typing import Any, ClassVar
|
||||
|
||||
from ..names import Matcher, ct_set
|
||||
from ..registry import register_dialect
|
||||
from ..scheme import QuantScheme
|
||||
from ..scheme import QuantKind, QuantScheme
|
||||
from ..scheme import fp8_block_scheme, fp8_tensor_scheme, nvfp4_scheme
|
||||
from .base import QuantConfig
|
||||
from .base import QuantConfig, Stored
|
||||
|
||||
|
||||
@register_dialect
|
||||
@@ -23,6 +23,15 @@ class CompressedTensorsConfig(QuantConfig):
|
||||
"FP8_CHANNEL": fp8_tensor_scheme("bf16", per_row=True),
|
||||
"FP8_BLOCK": fp8_block_scheme("float"),
|
||||
}
|
||||
# the NVFP4 globals are the quant-side scales (vLLM: alpha = 1 / (input_global_scale * weight_global_scale))
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]] = {
|
||||
QuantKind.NVFP4: {
|
||||
"weight": "weight_packed", "weight_scale": "weight_scale",
|
||||
"weight_global": Stored("weight_global_scale", reciprocal=True), "input_scale": Stored("input_global_scale", reciprocal=True),
|
||||
},
|
||||
QuantKind.FP8_TENSOR: {"weight": "weight", "weight_scale": "weight_scale", "input_scale": "input_scale"},
|
||||
QuantKind.FP8_BLOCK: {"weight": "weight", "weight_scale_inv": "weight_scale"},
|
||||
}
|
||||
|
||||
def __init__(self, q: dict[str, Any], hf_config: Any = None, *, name_map=None, unquantized=()):
|
||||
super().__init__(name_map, unquantized)
|
||||
|
||||
@@ -4,9 +4,9 @@ from typing import Any, ClassVar
|
||||
|
||||
from ..names import is_routed_expert, name_set, substr_set
|
||||
from ..registry import register_dialect
|
||||
from ..scheme import QuantScheme
|
||||
from ..scheme import QuantKind, QuantScheme
|
||||
from ..scheme import FP8_BLOCK, fp8_block_scheme, fp8_tensor_scheme, mxfp4_scheme
|
||||
from .base import QuantConfig, cfg_get
|
||||
from .base import QuantConfig, Stored, cfg_get
|
||||
|
||||
|
||||
@register_dialect
|
||||
@@ -22,6 +22,12 @@ class Fp8BlockConfig(QuantConfig):
|
||||
"TABLE": fp8_tensor_scheme("float"),
|
||||
"EXPERT_MXFP4": mxfp4_scheme(),
|
||||
}
|
||||
# transformers' fp8 names; DeepSeek-V4's e8m0 export calls every scale ``scale`` (see storage)
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]] = {
|
||||
QuantKind.FP8_BLOCK: {"weight": "weight", "weight_scale_inv": "weight_scale_inv"},
|
||||
QuantKind.FP8_TENSOR: {"weight": "weight", "weight_scale": "weight_scale"},
|
||||
QuantKind.MXFP4: {"weight": "weight", "weight_scale": "scale"},
|
||||
}
|
||||
|
||||
def __init__(self, q: dict[str, Any], hf_config: Any = None, *, name_map=None, unquantized=()):
|
||||
super().__init__(name_map, unquantized)
|
||||
@@ -36,6 +42,12 @@ class Fp8BlockConfig(QuantConfig):
|
||||
self.e8m0 = str(q.get("scale_fmt") or "").lower() == "ue8m0"
|
||||
self.expert_fp4 = str(cfg_get(hf_config, "expert_dtype") or "").lower() == "fp4"
|
||||
|
||||
def storage(self, scheme: QuantScheme) -> dict[str, Stored]:
|
||||
names = super().storage(scheme)
|
||||
if self.e8m0 and scheme.kind is QuantKind.FP8_BLOCK:
|
||||
names["weight_scale_inv"] = Stored("scale")
|
||||
return names
|
||||
|
||||
def scheme_for_name(self, name: str) -> QuantScheme | None:
|
||||
if self.convert_tables(name):
|
||||
return self.SCHEMES["TABLE"]
|
||||
|
||||
@@ -4,9 +4,9 @@ from typing import Any, ClassVar
|
||||
|
||||
from ..names import ancestors, name_set
|
||||
from ..registry import register_dialect
|
||||
from ..scheme import QuantScheme
|
||||
from ..scheme import QuantKind, QuantScheme
|
||||
from ..scheme import fp8_block_scheme, fp8_tensor_scheme, mxfp8_scheme, nvfp4_scheme
|
||||
from .base import QuantConfig
|
||||
from .base import QuantConfig, Stored
|
||||
|
||||
|
||||
@register_dialect
|
||||
@@ -24,6 +24,12 @@ class ModelOptConfig(QuantConfig):
|
||||
"FP8_PB_WO": fp8_block_scheme("fp32"),
|
||||
"MXFP8": mxfp8_scheme(),
|
||||
}
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]] = {
|
||||
QuantKind.FP8_TENSOR: {"weight": "weight", "weight_scale": "weight_scale", "input_scale": "input_scale"},
|
||||
QuantKind.FP8_BLOCK: {"weight": "weight", "weight_scale_inv": "weight_scale_inv"},
|
||||
QuantKind.MXFP8: {"weight": "weight", "weight_scale_inv": "weight_scale_inv"},
|
||||
QuantKind.NVFP4: {"weight": "weight", "weight_scale": "weight_scale", "weight_global": "weight_scale_2", "input_scale": "input_scale"},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def claims(cls, q: dict[str, Any]) -> bool:
|
||||
|
||||
@@ -4,9 +4,9 @@ from typing import Any, ClassVar
|
||||
|
||||
from ..names import name_set
|
||||
from ..registry import register_dialect
|
||||
from ..scheme import QuantScheme
|
||||
from ..scheme import QuantKind, QuantScheme
|
||||
from ..scheme import mxfp4_scheme
|
||||
from .base import QuantConfig
|
||||
from .base import QuantConfig, Stored
|
||||
|
||||
|
||||
@register_dialect
|
||||
@@ -16,6 +16,8 @@ class Mxfp4Config(QuantConfig):
|
||||
dialect = "mxfp4"
|
||||
|
||||
SCHEME: ClassVar[QuantScheme] = mxfp4_scheme()
|
||||
# the experts are stacked per layer (``gate_up_proj_blocks`` / ``_scales``), not per-Linear tensors; gpt_oss reads them itself
|
||||
STORAGE: ClassVar[dict[QuantKind, dict[str, str | Stored]]] = {}
|
||||
|
||||
def __init__(self, q: dict[str, Any], hf_config: Any = None, *, name_map=None, unquantized=()):
|
||||
super().__init__(name_map, unquantized)
|
||||
|
||||
@@ -120,4 +120,5 @@ class Nvfp4LinearMethod(LinearMethod):
|
||||
layer.weight = torch.empty(g.out_features, g.in_features // 2, dtype=torch.uint8)
|
||||
layer.weight_scale = torch.empty(g.out_features, g.in_features // GROUP, dtype=FP8)
|
||||
layer.weight_global = torch.empty(g.out_features, dtype=torch.float16)
|
||||
# input_scale stays undeclared: the W4A16 kernels never read it and today's readers drop it
|
||||
# no W4A16 kernel reads it; declared so a W4A4 checkpoint loads complete and a W4A4 kernel finds it in place
|
||||
layer.input_scale = torch.empty((), dtype=torch.float32) if self.scheme.has("input_scale") else None
|
||||
|
||||
@@ -38,12 +38,18 @@ def substr_set(patterns: tuple[str, ...]) -> Matcher:
|
||||
|
||||
|
||||
def ct_set(patterns: tuple[str, ...], *, class_names: bool) -> Matcher:
|
||||
"""compressed-tensors ``targets`` / ``ignore``: module names, ``re:`` regexes, or the class name Linear."""
|
||||
names = name_set(tuple(p for p in patterns if not p.startswith("re:") and p != "Linear"))
|
||||
"""compressed-tensors ``targets`` / ``ignore``: module names, ``re:`` regexes, or the class name Linear.
|
||||
|
||||
A name covers that module alone, not its children: llm-compressor lists every skipped module, containers included, so an ``ignore`` entry for ``linear_attn`` says nothing about ``linear_attn.in_proj_qkv``."""
|
||||
names = frozenset(p for p in patterns if not p.startswith("re:") and p != "Linear")
|
||||
# a class name other than Linear cannot be matched from a module name alone; fail here rather than serve the module bf16
|
||||
unknown = [p for p in names if "." not in p and p[:1].isupper()] if class_names else []
|
||||
if unknown:
|
||||
raise NotImplementedError(f"compressed-tensors target class {unknown[0]!r} is not supported; only Linear is")
|
||||
regexes = [p[3:] for p in patterns if p.startswith("re:")]
|
||||
rx = re.compile("|".join(f"(?:{r})" for r in regexes)) if regexes else None
|
||||
any_linear = class_names and "Linear" in patterns
|
||||
return lambda name: any_linear or names(name) or (rx is not None and rx.match(name) is not None)
|
||||
return lambda name: any_linear or name in names or (rx is not None and rx.match(name) is not None)
|
||||
|
||||
|
||||
_ROUTED_EXPERT = re.compile(r"\.experts\.\d+(\.|$)")
|
||||
|
||||
@@ -9,6 +9,7 @@ from freetoken.distributed import get_tp_info
|
||||
from freetoken.models.config import FullAttentionGroupConfig
|
||||
from freetoken.models.loader import (
|
||||
MergeRule,
|
||||
ShardReader,
|
||||
drop_page_cache,
|
||||
iter_weight_files,
|
||||
)
|
||||
@@ -59,50 +60,53 @@ _FEED_FORWARD_PREFIXES = (
|
||||
|
||||
# modelopt-NVFP4 dense MLP (nvidia/Gemma-4-31B-IT-NVFP4): mlp.{gate,up,down}_proj are W4A16
|
||||
# FP4 -- uint8 weight + fp8-e4m3 block weight_scale + per-tensor weight_scale_2 + input_scale.
|
||||
# The scales are consumed with their .weight; input_scale is unused (W4A16). Mirrors the
|
||||
# qwen3_5_moe native-NVFP4 dense loader.
|
||||
# The scales are consumed with their .weight.
|
||||
_NVFP4_DENSE_SCALE_SUFFIXES = (".weight_scale", ".weight_scale_2", ".input_scale")
|
||||
_NVFP4_DENSE_MLP_RE = re.compile(r"\.mlp\.(gate_proj|up_proj|down_proj)\.weight$")
|
||||
|
||||
|
||||
def _nvfp4_dense_parts(f, raw_base: str):
|
||||
"""Load an NVFP4 dense weight as the W4A16 kernel's buffers: (weight uint8 [O, IN//2],
|
||||
weight_scale fp8-e4m3 block [O, IN//16], weight_global fp16 [O] from the per-tensor
|
||||
weight_scale_2 broadcast per output row)."""
|
||||
w = f.get_tensor(raw_base + ".weight")
|
||||
s = f.get_tensor(raw_base + ".weight_scale")
|
||||
g = f.get_tensor(raw_base + ".weight_scale_2").reshape(1).to(torch.float16)
|
||||
def _nvfp4_dense_parts(reader: ShardReader, raw_base: str):
|
||||
"""Load an NVFP4 dense weight as the NVFP4 linear method's buffers: weight uint8 [O, IN//2], weight_scale fp8-e4m3 block [O, IN//16], weight_global fp16 [O] (the per-tensor weight_scale_2 per output row), input_scale fp32 scalar or None when the export has none."""
|
||||
w = reader.get_tensor(raw_base + ".weight")
|
||||
s = reader.get_tensor(raw_base + ".weight_scale")
|
||||
g = reader.get_tensor(raw_base + ".weight_scale_2").reshape(1).to(torch.float16)
|
||||
g = g.expand(w.shape[0]).contiguous()
|
||||
assert (
|
||||
w.dtype is torch.uint8
|
||||
and s.dtype is torch.float8_e4m3fn
|
||||
and g.dtype is torch.float16
|
||||
), f"unexpected NVFP4 dense dtypes at {raw_base}: {w.dtype}/{s.dtype}/{g.dtype}"
|
||||
return w, s, g
|
||||
a = reader.get_tensor(raw_base + ".input_scale").reshape(()).to(torch.float32) if reader.has(raw_base + ".input_scale") else None
|
||||
return w, s, g, a
|
||||
|
||||
|
||||
def _emit_nvfp4_dense_mlp(f, base: str, raw_base: str, buf: dict):
|
||||
"""(key, tensor) triples for an NVFP4 dense MLP projection: down_proj standalone;
|
||||
def _emit_nvfp4_dense_mlp(reader: ShardReader, base: str, raw_base: str, buf: dict):
|
||||
"""(key, tensor) pairs for an NVFP4 dense MLP projection: down_proj standalone;
|
||||
gate_proj/up_proj merged output-wise into gate_up_proj (each keeps its own scales, so the
|
||||
fused weight is exact). Returns [] while a gate/up merge is still buffered."""
|
||||
w, s, g = _nvfp4_dense_parts(f, raw_base)
|
||||
w, s, g, a = _nvfp4_dense_parts(reader, raw_base)
|
||||
if base.endswith(".down_proj"):
|
||||
return [(base + ".weight", w), (base + ".weight_scale", s), (base + ".weight_global", g)]
|
||||
out = [(base + ".weight", w), (base + ".weight_scale", s), (base + ".weight_global", g)]
|
||||
return out + ([(base + ".input_scale", a)] if a is not None else [])
|
||||
is_gate = base.endswith(".gate_proj")
|
||||
prefix = base[: -len(".gate_proj")] if is_gate else base[: -len(".up_proj")]
|
||||
slots = buf.setdefault(prefix, {})
|
||||
slots["gate" if is_gate else "up"] = (w, s, g)
|
||||
slots["gate" if is_gate else "up"] = (w, s, g, a)
|
||||
if "gate" not in slots or "up" not in slots:
|
||||
return []
|
||||
gw, gs, gg = slots["gate"]
|
||||
uw, us, ug = slots["up"]
|
||||
gw, gs, gg, ga = slots["gate"]
|
||||
uw, us, ug, ua = slots["up"]
|
||||
del buf[prefix]
|
||||
pre = prefix + ".gate_up_proj"
|
||||
return [
|
||||
out = [
|
||||
(pre + ".weight", torch.cat([gw, uw], dim=0)),
|
||||
(pre + ".weight_scale", torch.cat([gs, us], dim=0)),
|
||||
(pre + ".weight_global", torch.cat([gg, ug], dim=0)),
|
||||
]
|
||||
if ga is not None and ua is not None:
|
||||
# both parts read the same activation; the larger range covers both
|
||||
out.append((pre + ".input_scale", torch.maximum(ga, ua)))
|
||||
return out
|
||||
|
||||
|
||||
def _rename_language_key(raw_name: str) -> str:
|
||||
@@ -165,77 +169,79 @@ def iter_weights(
|
||||
}
|
||||
merge_buf: dict[str, dict[str, torch.Tensor]] = {}
|
||||
gateup_buf: dict[str, dict[str, tuple]] = {}
|
||||
for file in tqdm(
|
||||
iter_weight_files(model_path),
|
||||
desc="Loading weights",
|
||||
disable=not tp_info.is_primary(),
|
||||
):
|
||||
with safetensors.safe_open(file, framework="pt", device=str(device)) as f:
|
||||
keyset = set(f.keys())
|
||||
for raw_name in f.keys():
|
||||
name = rename_key(raw_name, include_vision=include_vision)
|
||||
if name is None:
|
||||
continue
|
||||
reader = ShardReader(model_path, device)
|
||||
try:
|
||||
for file in tqdm(
|
||||
iter_weight_files(model_path),
|
||||
desc="Loading weights",
|
||||
disable=not tp_info.is_primary(),
|
||||
):
|
||||
with safetensors.safe_open(file, framework="pt", device=str(device)) as f:
|
||||
for raw_name in f.keys():
|
||||
name = rename_key(raw_name, include_vision=include_vision)
|
||||
if name is None:
|
||||
continue
|
||||
|
||||
# Per-expert NVFP4 tensors go to the offload cache (expert pieces),
|
||||
# not this dense pass; fused bf16/q4_0 experts lack ".experts.<int>." so are unaffected.
|
||||
if _NVFP4_EXPERT_RE.search(raw_name):
|
||||
continue
|
||||
# Per-expert NVFP4 tensors go to the offload cache (expert pieces),
|
||||
# not this dense pass; fused bf16/q4_0 experts lack ".experts.<int>." so are unaffected.
|
||||
if _NVFP4_EXPERT_RE.search(raw_name):
|
||||
continue
|
||||
|
||||
# NVFP4 dense-MLP scales are consumed with their .weight (below), never yielded.
|
||||
if raw_name.endswith(_NVFP4_DENSE_SCALE_SUFFIXES):
|
||||
continue
|
||||
# NVFP4 dense-MLP scales are consumed with their .weight (below), never yielded.
|
||||
if raw_name.endswith(_NVFP4_DENSE_SCALE_SUFFIXES):
|
||||
continue
|
||||
|
||||
is_vision = name.startswith(("vision_tower.", "embed_vision."))
|
||||
is_expert = (
|
||||
not is_vision and _PACKED_EXPERT_PATTERN.match(name) is not None
|
||||
)
|
||||
if is_expert and not include_moe_experts:
|
||||
continue
|
||||
if not is_expert and not include_non_moe:
|
||||
continue
|
||||
|
||||
# Native W4A16 NVFP4 dense MLP: the .weight is FP4-packed and carries block +
|
||||
# per-tensor scales. The keyset guard (weight_scale_2 sibling present) is
|
||||
# defense-in-depth beyond config.dense_quant -- the sibling MoE checkpoint's
|
||||
# bf16 shared_mlp has no such sibling, so it falls through to the bf16 path.
|
||||
if (
|
||||
config.dense_quant == "nvfp4"
|
||||
and not is_vision
|
||||
and not is_expert
|
||||
and _NVFP4_DENSE_MLP_RE.search(raw_name)
|
||||
and raw_name[: -len(".weight")] + ".weight_scale_2" in keyset
|
||||
):
|
||||
yield from _emit_nvfp4_dense_mlp(
|
||||
f, name[: -len(".weight")], raw_name[: -len(".weight")], gateup_buf
|
||||
is_vision = name.startswith(("vision_tower.", "embed_vision."))
|
||||
is_expert = (
|
||||
not is_vision and _PACKED_EXPERT_PATTERN.match(name) is not None
|
||||
)
|
||||
continue
|
||||
if is_expert and not include_moe_experts:
|
||||
continue
|
||||
if not is_expert and not include_non_moe:
|
||||
continue
|
||||
|
||||
tensor = f.get_tensor(raw_name)
|
||||
if is_vision or is_expert:
|
||||
yield name, tensor
|
||||
continue
|
||||
|
||||
info = merge_info(name)
|
||||
if info is None:
|
||||
yield name, tensor
|
||||
continue
|
||||
|
||||
merged_key, rule = info
|
||||
slots = merge_buf.setdefault(merged_key, {})
|
||||
slots[rule.slot] = tensor
|
||||
if rule.slot == "k" and k_eq_v_layers:
|
||||
layer_match = _LAYER_INDEX_PATTERN.search(name)
|
||||
# Native W4A16 NVFP4 dense MLP: the .weight is FP4-packed and carries block + per-tensor scales.
|
||||
# The weight_scale_2 sibling guard is defense-in-depth beyond config.dense_quant -- the sibling MoE checkpoint's bf16 shared_mlp has no such sibling, so it falls through to the bf16 path.
|
||||
if (
|
||||
layer_match is not None
|
||||
and int(layer_match.group(1)) in k_eq_v_layers
|
||||
config.dense_quant == "nvfp4"
|
||||
and not is_vision
|
||||
and not is_expert
|
||||
and _NVFP4_DENSE_MLP_RE.search(raw_name)
|
||||
and reader.has(raw_name[: -len(".weight")] + ".weight_scale_2")
|
||||
):
|
||||
slots["v"] = tensor
|
||||
if not all(slot in slots for slot in rule.slots):
|
||||
continue
|
||||
parts = [slots[slot] for slot in rule.slots]
|
||||
del merge_buf[merged_key]
|
||||
yield merged_key, torch.cat(parts, dim=0)
|
||||
yield from _emit_nvfp4_dense_mlp(
|
||||
reader, name[: -len(".weight")], raw_name[: -len(".weight")], gateup_buf
|
||||
)
|
||||
continue
|
||||
|
||||
tensor = f.get_tensor(raw_name)
|
||||
if is_vision or is_expert:
|
||||
yield name, tensor
|
||||
continue
|
||||
|
||||
info = merge_info(name)
|
||||
if info is None:
|
||||
yield name, tensor
|
||||
continue
|
||||
|
||||
merged_key, rule = info
|
||||
slots = merge_buf.setdefault(merged_key, {})
|
||||
slots[rule.slot] = tensor
|
||||
if rule.slot == "k" and k_eq_v_layers:
|
||||
layer_match = _LAYER_INDEX_PATTERN.search(name)
|
||||
if (
|
||||
layer_match is not None
|
||||
and int(layer_match.group(1)) in k_eq_v_layers
|
||||
):
|
||||
slots["v"] = tensor
|
||||
if not all(slot in slots for slot in rule.slots):
|
||||
continue
|
||||
parts = [slots[slot] for slot in rule.slots]
|
||||
del merge_buf[merged_key]
|
||||
yield merged_key, torch.cat(parts, dim=0)
|
||||
|
||||
finally:
|
||||
reader.close()
|
||||
|
||||
assert not merge_buf, f"Incomplete merge groups in checkpoint: {list(merge_buf.keys())}"
|
||||
assert not gateup_buf, f"Incomplete NVFP4 gate/up merges: {list(gateup_buf.keys())}"
|
||||
|
||||
@@ -87,6 +87,8 @@ def _iter_nvfp4_resident(
|
||||
yield f"{dst_prefix}.weight", packed
|
||||
yield f"{dst_prefix}.weight_scale", scale
|
||||
yield f"{dst_prefix}.weight_global", g.expand(packed.shape[0]).contiguous()
|
||||
if reader.has(f"{src_prefix}.input_scale"):
|
||||
yield f"{dst_prefix}.input_scale", reader.get(f"{src_prefix}.input_scale").reshape(()).to(torch.float32)
|
||||
|
||||
|
||||
def _iter_attn_df11(
|
||||
|
||||
@@ -48,6 +48,34 @@ def _dsa_on(args, dsa_layer_ids) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _quant_accessor(hf_config: Any):
|
||||
"""A ``get(key, default=None)`` accessor over the HF ``quantization_config`` (dict or
|
||||
object), or ``None`` when the model has no quant config."""
|
||||
quant = getattr(hf_config, "quantization_config", None)
|
||||
if quant is None:
|
||||
return None
|
||||
return quant.get if isinstance(quant, dict) else (lambda k, d=None: getattr(quant, k, d))
|
||||
|
||||
|
||||
def _fp8_block_quant(hf_config: Any) -> tuple[str, tuple[int, int] | None]:
|
||||
"""Detect DeepSeek-V3-style 128x128 block-fp8 from HF ``quantization_config``.
|
||||
|
||||
Returns ``("fp8_block", (block_n, block_k))`` for a block-fp8 checkpoint (weights
|
||||
fp8-e4m3 + per-block ``weight_scale_inv``, dynamic activation), else ``("none", None)``.
|
||||
The quantization_config sits on the top-level hf_config (not ``text_config``).
|
||||
"""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
return "none", None
|
||||
method = str(get("quant_method") or get("quant_algo") or "").lower()
|
||||
block = get("weight_block_size")
|
||||
if method == "fp8" and block:
|
||||
bs = tuple(int(x) for x in block)
|
||||
assert bs == (128, 128), f"only 128x128 block-fp8 is supported, got {bs}"
|
||||
return "fp8_block", bs
|
||||
return "none", None
|
||||
|
||||
|
||||
def parse_config(hf_config: Any) -> ModelConfig:
|
||||
args = load_args(hf_config)
|
||||
text = getattr(hf_config, "text_config", hf_config)
|
||||
@@ -128,8 +156,6 @@ def parse_config(hf_config: Any) -> ModelConfig:
|
||||
t == "sparse" for t in mlp_types[first_dense:]
|
||||
), f"mlp_layer_types is not a dense-prefix layout: {mlp_types}"
|
||||
|
||||
from freetoken.models.qwen3_5_moe.config import _fp8_block_quant # shared until the legacy quant fields go
|
||||
|
||||
expert_quant, weight_block_size = _fp8_block_quant(hf_config)
|
||||
if expert_quant == "none":
|
||||
expert_quant = detect_expert_quant(hf_config)
|
||||
|
||||
@@ -4,6 +4,7 @@ import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Iterator
|
||||
|
||||
@@ -53,6 +54,23 @@ def iter_weight_files(model_path: str) -> list[str]:
|
||||
return [f for f in files if not f.endswith("consolidated.safetensors")] or files
|
||||
|
||||
|
||||
def safetensors_weight_map(folder: str) -> dict[str, str]:
|
||||
"""Tensor name -> shard basename, from the index or from each shard's header when the checkpoint ships none."""
|
||||
index = os.path.join(folder, "model.safetensors.index.json")
|
||||
if os.path.exists(index):
|
||||
with open(index, encoding="utf-8") as f:
|
||||
return json.load(f)["weight_map"]
|
||||
weight_map: dict[str, str] = {}
|
||||
for path in sorted(iter_weight_files(folder)):
|
||||
with open(path, "rb") as fh:
|
||||
n = struct.unpack("<Q", fh.read(8))[0]
|
||||
header = json.loads(fh.read(n))
|
||||
for name in header:
|
||||
if name != "__metadata__":
|
||||
weight_map[name] = os.path.basename(path)
|
||||
return weight_map
|
||||
|
||||
|
||||
def drop_page_cache(path: str) -> None:
|
||||
"""drop a file's page cache: banks + full checkpoint cache don't both fit in host RAM (OOM)."""
|
||||
try:
|
||||
@@ -135,14 +153,13 @@ def iter_merged_tensors(
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# compressed-tensors NVFP4 (llm-compressor) dense-weight helpers, shared by the
|
||||
# models that serve such checkpoints natively (qwen3_5_moe, muse_glimmer). Storage:
|
||||
# models that serve such checkpoints natively (muse_glimmer). Storage:
|
||||
# ``weight_packed`` (uint8 [O, IN//2]) + ``weight_scale`` (fp8-e4m3 block [O, IN//16])
|
||||
# + a scalar ``weight_global_scale``. The stored global is the *quant-side* scale, so
|
||||
# the dequant/native global is its reciprocal (vLLM inverts it identically).
|
||||
# ---------------------------------------------------------------------------------
|
||||
|
||||
# Quant scales consumed with their ``weight_packed`` (or unused: the input scales are
|
||||
# for W4A4 activation quant, which FreeToken does not run).
|
||||
# Quant scales consumed with their ``weight_packed``.
|
||||
CT_SCALE_SUFFIXES = (
|
||||
".weight_scale", ".weight_global_scale", ".input_global_scale", ".input_scale",
|
||||
)
|
||||
@@ -158,27 +175,16 @@ class ShardReader:
|
||||
|
||||
def __init__(self, model_path: str, device: torch.device):
|
||||
folder = download_hf_weight(model_path)
|
||||
index = os.path.join(folder, "model.safetensors.index.json")
|
||||
if os.path.exists(index):
|
||||
with open(index, encoding="utf-8") as f:
|
||||
weight_map = json.load(f)["weight_map"]
|
||||
self._map = {
|
||||
name: os.path.join(folder, shard) for name, shard in weight_map.items()
|
||||
}
|
||||
else: # single-file checkpoint
|
||||
import safetensors
|
||||
|
||||
self._map = {}
|
||||
for file in iter_weight_files(model_path):
|
||||
with safetensors.safe_open(file, framework="pt", device="cpu") as f:
|
||||
for name in f.keys():
|
||||
self._map[name] = file
|
||||
self._map = {name: os.path.join(folder, shard) for name, shard in safetensors_weight_map(folder).items()}
|
||||
self._device = str(device)
|
||||
self._handles: dict[str, object] = {}
|
||||
|
||||
def files(self) -> list[str]:
|
||||
return sorted(set(self._map.values()))
|
||||
|
||||
def has(self, name: str) -> bool:
|
||||
return name in self._map
|
||||
|
||||
def names_in(self, file: str) -> list[str]:
|
||||
return [name for name, shard in self._map.items() if shard == file]
|
||||
|
||||
@@ -201,21 +207,21 @@ class ShardReader:
|
||||
self._handles.clear()
|
||||
|
||||
|
||||
def nvfp4_parts_ct(f, raw_base: str) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""compressed-tensors NVFP4 -> ``(packed uint8 [O, IN//2], block scale fp8 [O, IN//16],
|
||||
per-output-row global fp16 [O])`` for the W4A16 kernels."""
|
||||
def nvfp4_parts_ct(f, raw_base: str) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""compressed-tensors NVFP4 -> ``(packed uint8 [O, IN//2], block scale fp8 [O, IN//16], per-output-row global fp16 [O], dequant-side input_scale fp32 scalar or None)`` for the NVFP4 linear method."""
|
||||
w = f.get_tensor(raw_base + ".weight_packed")
|
||||
s = f.get_tensor(raw_base + ".weight_scale")
|
||||
wg = f.get_tensor(raw_base + ".weight_global_scale").reshape(1).to(torch.float32)
|
||||
g = (1.0 / wg).to(torch.float16).expand(w.shape[0]).contiguous()
|
||||
return w, s, g
|
||||
a = None
|
||||
if f.has(raw_base + ".input_global_scale"):
|
||||
a = (1.0 / f.get_tensor(raw_base + ".input_global_scale").reshape(()).to(torch.float32))
|
||||
return w, s, g, a
|
||||
|
||||
|
||||
def ct_nvfp4_fuse(base: str, parts_tuple: tuple, buf: dict, groups: dict[str, tuple[str, ...]]):
|
||||
"""Buffer a native NVFP4 fusion part ``(w, s, g)``; emit the concatenated native parts
|
||||
(``.weight``/``.weight_scale``/``.weight_global``, output-dim concat with each part
|
||||
keeping its own scales, so the fused FP4 weight is exact) once complete, ``[]`` while
|
||||
incomplete, ``None`` if ``base`` is not a fusion part of any group in ``groups``."""
|
||||
"""Buffer a native NVFP4 fusion part ``(w, s, g, a)``; once complete, emit the concatenated ``.weight`` / ``.weight_scale`` / ``.weight_global`` (output-dim concat, each part keeps its own scales, so the fused FP4 weight is exact) plus the largest ``.input_scale`` when every part has one.
|
||||
``[]`` while incomplete, ``None`` if ``base`` is not a fusion part of any group in ``groups``."""
|
||||
for fused_suffix, parts in groups.items():
|
||||
for idx, part in enumerate(parts):
|
||||
if base.endswith(part):
|
||||
@@ -228,11 +234,15 @@ def ct_nvfp4_fuse(base: str, parts_tuple: tuple, buf: dict, groups: dict[str, tu
|
||||
ws = [slots[i][0] for i in range(len(parts))]
|
||||
ss = [slots[i][1] for i in range(len(parts))]
|
||||
gs = [slots[i][2] for i in range(len(parts))]
|
||||
return [
|
||||
acts = [slots[i][3] for i in range(len(parts))]
|
||||
out = [
|
||||
(key + ".weight", torch.cat(ws, dim=0)),
|
||||
(key + ".weight_scale", torch.cat(ss, dim=0)),
|
||||
(key + ".weight_global", torch.cat(gs, dim=0)),
|
||||
]
|
||||
if all(a is not None for a in acts):
|
||||
out.append((key + ".input_scale", torch.stack(acts).max()))
|
||||
return out
|
||||
return None
|
||||
|
||||
|
||||
@@ -293,6 +303,7 @@ __all__ = [
|
||||
"MergeRule",
|
||||
"iter_root_safetensor_files_from_index",
|
||||
"iter_weight_files",
|
||||
"safetensors_weight_map",
|
||||
"iter_merged_tensors",
|
||||
"iter_stacked_experts",
|
||||
"shard_tensor",
|
||||
|
||||
@@ -123,10 +123,12 @@ def _iter_weights_compressed_tensors(
|
||||
if emit is not None:
|
||||
yield from emit
|
||||
else: # standalone: o_proj, down_proj
|
||||
w, s, g = parts
|
||||
w, s, g, a = parts
|
||||
yield base + ".weight", w
|
||||
yield base + ".weight_scale", s
|
||||
yield base + ".weight_global", g
|
||||
if a is not None:
|
||||
yield base + ".input_scale", a
|
||||
continue
|
||||
yield name, reader.get_tensor(raw_name)
|
||||
finally:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
@@ -83,12 +82,12 @@ def iter_nvfp4_expert_pieces(
|
||||
way tensors of one expert may span shards, so they are grouped by (layer, expert) as they land.
|
||||
"""
|
||||
from freetoken.models.loader import drop_page_cache as _drop
|
||||
from freetoken.models.loader import safetensors_weight_map
|
||||
from freetoken.moe.expert_pieces import per_expert_pieces
|
||||
|
||||
drop = drop_page_cache or _drop
|
||||
folder = download_hf_weight(model_path)
|
||||
with open(os.path.join(folder, "model.safetensors.index.json"), encoding="utf-8") as f:
|
||||
weight_map = json.load(f)["weight_map"]
|
||||
weight_map = safetensors_weight_map(folder)
|
||||
|
||||
wanted: dict[str, tuple[int, int, str]] = {}
|
||||
for name in weight_map:
|
||||
|
||||
@@ -2,125 +2,24 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from freetoken.layers.quantization import QuantConfig, QuantKind
|
||||
from freetoken.models.config import (
|
||||
FullAttentionGroupConfig,
|
||||
LinearGatedDeltaGroupConfig,
|
||||
ModelConfig,
|
||||
RotaryConfig,
|
||||
detect_compressed_tensors_nvfp4,
|
||||
)
|
||||
|
||||
|
||||
def _quant_accessor(hf_config: Any):
|
||||
"""A ``get(key, default=None)`` accessor over the HF ``quantization_config`` (dict or
|
||||
object), or ``None`` when the model has no quant config."""
|
||||
quant = getattr(hf_config, "quantization_config", None)
|
||||
if quant is None:
|
||||
return None
|
||||
return quant.get if isinstance(quant, dict) else (lambda k, d=None: getattr(quant, k, d))
|
||||
|
||||
|
||||
def _fp8_block_quant(hf_config: Any) -> tuple[str, tuple[int, int] | None]:
|
||||
"""Detect DeepSeek-V3-style 128x128 block-fp8 from HF ``quantization_config``.
|
||||
|
||||
Returns ``("fp8_block", (block_n, block_k))`` for a block-fp8 checkpoint (weights
|
||||
fp8-e4m3 + per-block ``weight_scale_inv``, dynamic activation), else ``("none", None)``.
|
||||
The quantization_config sits on the top-level hf_config (not ``text_config``).
|
||||
"""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
def _expert_quant(hf_config: Any, text: Any) -> tuple[str, tuple[int, int] | None]:
|
||||
"""The routed experts' quant kind as the engine's format tag, with the scale block of block-fp8."""
|
||||
if not (getattr(text, "num_experts", 0) or 0):
|
||||
return "none", None
|
||||
method = str(get("quant_method") or get("quant_algo") or "").lower()
|
||||
block = get("weight_block_size")
|
||||
if method == "fp8" and block:
|
||||
bs = tuple(int(x) for x in block)
|
||||
assert bs == (128, 128), f"only 128x128 block-fp8 is supported, got {bs}"
|
||||
return "fp8_block", bs
|
||||
return "none", None
|
||||
|
||||
|
||||
def _expert_quant(hf_config: Any) -> str:
|
||||
"""Quantization format of the *routed* experts (the only weights served from the
|
||||
offload cache). The nvidia/modelopt checkpoints are either plain NVFP4 (``quant_algo``
|
||||
``NVFP4``) or ``MIXED_PRECISION`` (per-layer ``quantized_layers`` map); in the mixed
|
||||
case the routed experts carry their own ``W4A16_NVFP4``/``FP8`` algo. Dense quantized
|
||||
weights (attention / shared expert / lm_head) are served through their own schemes."""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
return "none"
|
||||
algo = str(get("quant_algo") or get("quant_method") or "").lower()
|
||||
if "fp4" in algo:
|
||||
return "nvfp4"
|
||||
if "mixed" in algo:
|
||||
layers = get("quantized_layers") or {}
|
||||
for name, spec in (layers.items() if isinstance(layers, dict) else []):
|
||||
if name.endswith(".mlp.experts") or ".mlp.experts." in name:
|
||||
expert_algo = str((spec or {}).get("quant_algo", "")).lower()
|
||||
if "fp4" in expert_algo:
|
||||
return "nvfp4"
|
||||
if "fp8" in expert_algo:
|
||||
return "fp8"
|
||||
return "none"
|
||||
|
||||
|
||||
# Detection now lives in models/config.py (shared with muse_glimmer); weight.py imports
|
||||
# it under this name.
|
||||
_compressed_tensors_nvfp4 = detect_compressed_tensors_nvfp4
|
||||
|
||||
|
||||
def _lm_head_quant(hf_config: Any) -> str:
|
||||
"""Whether the checkpoint stores ``lm_head`` as NVFP4. modelopt MIXED_PRECISION lists it in
|
||||
the per-layer ``quantized_layers`` map (``W4A16_NVFP4``); pure-NVFP4 checkpoints have no
|
||||
per-layer map and leave lm_head bf16. Returns ``"nvfp4"`` or ``"none"``."""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
return "none"
|
||||
layers = get("quantized_layers") or {}
|
||||
if not isinstance(layers, dict):
|
||||
return "none"
|
||||
for name, spec in layers.items():
|
||||
if name == "lm_head" or name.endswith(".lm_head"):
|
||||
if "fp4" in str((spec or {}).get("quant_algo", "")).lower():
|
||||
return "nvfp4"
|
||||
return "none"
|
||||
|
||||
|
||||
def _dense_mlp_quant(hf_config: Any) -> str:
|
||||
"""NVFP4 on the *dense* (non-MoE) decoder MLP. modelopt MIXED_PRECISION dense checkpoints
|
||||
(e.g. Qwen3.6-27B-NVFP4) list ``.mlp.{gate,up,down}_proj`` as ``W4A16_NVFP4`` in
|
||||
``quantized_layers``; MoE checkpoints have ``.mlp.experts.*`` / ``.mlp.shared_expert.*``
|
||||
instead (covered by ``expert_quant``). ``endswith(".mlp.gate_proj")`` matches only the bare
|
||||
dense MLP -- not ``.mlp.shared_expert.gate_proj`` nor ``.mlp.experts.N.gate_proj``."""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
return "none"
|
||||
layers = get("quantized_layers") or {}
|
||||
if not isinstance(layers, dict):
|
||||
return "none"
|
||||
for name, spec in layers.items():
|
||||
if name.endswith((".mlp.gate_proj", ".mlp.up_proj", ".mlp.down_proj")):
|
||||
if "fp4" in str((spec or {}).get("quant_algo", "")).lower():
|
||||
return "nvfp4"
|
||||
return "none"
|
||||
|
||||
|
||||
def _attn_quant(hf_config: Any) -> str:
|
||||
"""Per-tensor FP8 on the *dense* attention/GDN projections. The modelopt
|
||||
``MIXED_PRECISION`` checkpoints tag ``self_attn.{q,k,v,o}_proj`` and
|
||||
``linear_attn.{in_proj_qkv,in_proj_z,out_proj}`` with ``quant_algo`` ``FP8`` (fp8-e4m3
|
||||
weight + a scalar ``weight_scale``; W8A16). Returns ``"fp8_pertensor"`` when present,
|
||||
else ``"none"`` (NVFP4 dense weights are covered by ``dense_quant`` / ``lm_head_quant``)."""
|
||||
get = _quant_accessor(hf_config)
|
||||
if get is None:
|
||||
return "none"
|
||||
layers = get("quantized_layers") or {}
|
||||
if not isinstance(layers, dict):
|
||||
return "none"
|
||||
for name, spec in layers.items():
|
||||
algo = str((spec or {}).get("quant_algo", "")).lower()
|
||||
if algo == "fp8" and (".self_attn." in name or ".linear_attn." in name):
|
||||
return "fp8_pertensor"
|
||||
return "none"
|
||||
# the engine reads this tag for its MoE strategy decisions; every module takes its own scheme from the QuantConfig when it is built
|
||||
scheme = QuantConfig.from_hf(hf_config).scheme_for_name("model.language_model.layers.0.mlp.experts.0.gate_proj")
|
||||
if scheme is None:
|
||||
return "none", None
|
||||
return str(scheme.kind), scheme.weight.group if scheme.kind is QuantKind.FP8_BLOCK else None
|
||||
|
||||
|
||||
def _layer_types(text: Any) -> list[str]:
|
||||
@@ -164,28 +63,7 @@ def parse_config(hf_config: Any) -> ModelConfig:
|
||||
else {k: v for k, v in rope_params.items() if not isinstance(v, (list, dict))}
|
||||
)
|
||||
|
||||
expert_quant, weight_block_size = _fp8_block_quant(hf_config)
|
||||
if expert_quant == "none":
|
||||
expert_quant = _expert_quant(hf_config) # nvfp4 / mixed-precision modelopt
|
||||
# Dense attention/GDN quant is independent of the routed experts (block-fp8 already
|
||||
# quantizes both, so only probe for per-tensor FP8 when experts aren't block-fp8).
|
||||
attn_quant = "none" if expert_quant == "fp8_block" else _attn_quant(hf_config)
|
||||
# NVFP4 checkpoints store the dense MLP projections (shared_expert; dense non-MoE MLP) as
|
||||
# packed FP4 exactly like the routed experts -- independent of whether attention is FP8
|
||||
# (mixed) or bf16 (pure NVFP4). Keep them native FP4 (W4A16) whenever the experts are
|
||||
# NVFP4. The lm_head is detected separately (only the mixed checkpoint quantizes it).
|
||||
# MoE-NVFP4 keeps the shared_expert dense MLP native FP4 (expert_quant=="nvfp4"); a dense
|
||||
# (non-MoE) modelopt checkpoint instead tags the bare .mlp.{gate,up,down}_proj as NVFP4.
|
||||
dense_quant = "nvfp4" if expert_quant == "nvfp4" else _dense_mlp_quant(hf_config)
|
||||
lm_head_quant = _lm_head_quant(hf_config)
|
||||
|
||||
# compressed-tensors NVFP4 (dense Qwen3.6-27B): the attention (q/k/v/o, GDN out_proj) AND
|
||||
# the dense MLP are W4A16 NVFP4; GDN in_proj_*, lm_head, norms stay bf16. Wire the shared
|
||||
# W4A16 kernels (attn_quant=="nvfp4" routes the attention/GDN linears through them too).
|
||||
if _compressed_tensors_nvfp4(hf_config):
|
||||
attn_quant = "nvfp4"
|
||||
dense_quant = "nvfp4"
|
||||
lm_head_quant = "none"
|
||||
expert_quant, weight_block_size = _expert_quant(hf_config, text)
|
||||
|
||||
# Dense variants (e.g. Qwen3.6-27B) report num_experts==0: route the decoder MLP through
|
||||
# the dense Qwen3_5DenseMLP instead of the MoE block.
|
||||
@@ -254,9 +132,6 @@ def parse_config(hf_config: Any) -> ModelConfig:
|
||||
attention_groups=groups,
|
||||
expert_quant=expert_quant,
|
||||
weight_block_size=weight_block_size,
|
||||
attn_quant=attn_quant,
|
||||
dense_quant=dense_quant,
|
||||
lm_head_quant=lm_head_quant,
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -39,6 +39,8 @@ _QWEN3_5_PACKED = _DENSE_PACKED + (
|
||||
("in_proj_ba", ("in_proj_b", "in_proj_a")),
|
||||
("in_proj", ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a")),
|
||||
) + _EXPERTS_PACKED
|
||||
# routers the family builds without a quant config (qwen3_5_moe/moe.py), so a checkpoint that quantized them is dequantized at load
|
||||
_QWEN3_5_UNQUANTIZED = ("*.mlp.gate", "*.mlp.shared_expert_gate")
|
||||
# Qwen3.8's per-layer hyper-connections fuse the down projection with the block-inject rows.
|
||||
_QWEN4_EXP_PACKED = _QWEN3_5_PACKED + (
|
||||
("input_mix_weight_down_block_inject", ("input_mix_weight_down", "block_inject_weight")),
|
||||
@@ -114,6 +116,7 @@ _MODEL_REGISTRY: dict[str, ModelSpec] = {
|
||||
"Qwen3_5MoEForCausalLM",
|
||||
checkpoint_roots=_LANGUAGE_MODEL_ROOT,
|
||||
packed_modules_mapping=_QWEN3_5_PACKED,
|
||||
unquantized_modules=_QWEN3_5_UNQUANTIZED,
|
||||
),
|
||||
# Qwen3.8-Flash-Next (model_type qwen4_exp): multimodal wrapper config (text tower in
|
||||
# text_config, weights under model.language_model.); served text-only. 36 GDN + 12 QSA
|
||||
@@ -133,6 +136,7 @@ _MODEL_REGISTRY: dict[str, ModelSpec] = {
|
||||
"Qwen3_5MoEForCausalLM",
|
||||
checkpoint_roots=_LANGUAGE_MODEL_ROOT,
|
||||
packed_modules_mapping=_QWEN3_5_PACKED,
|
||||
unquantized_modules=_QWEN3_5_UNQUANTIZED,
|
||||
),
|
||||
# Muse-Glimmer-30B (model_type muse_glimmer): multimodal wrapper config (text tower in
|
||||
# text_config, weights under model.language_model.); served text-only. Dense gated GQA
|
||||
|
||||
@@ -87,22 +87,11 @@ def iter_expert_tensors_parallel(
|
||||
Peak host memory is ~(prefetch+1) shards + the banks the caller fills. Order is
|
||||
shard-then-header order (NOT global), so the consumer must place by ``name``.
|
||||
"""
|
||||
from freetoken.models.loader import safetensors_weight_map
|
||||
from freetoken.utils.hf import download_hf_weight
|
||||
|
||||
model_path = download_hf_weight(model_path) # resolve hub id -> local (parity w/ serial)
|
||||
index = os.path.join(model_path, "model.safetensors.index.json")
|
||||
if os.path.exists(index):
|
||||
with open(index) as f:
|
||||
weight_map = json.load(f)["weight_map"]
|
||||
else: # single-file / no-index checkpoint: map name -> shard from each shard's header
|
||||
weight_map = {}
|
||||
for shard in sorted(os.path.basename(p) for p in glob.glob(os.path.join(model_path, "*.safetensors"))):
|
||||
with open(os.path.join(model_path, shard), "rb") as fh:
|
||||
n = struct.unpack("<Q", fh.read(8))[0]
|
||||
hdr = json.loads(fh.read(n))
|
||||
for nm in hdr:
|
||||
if nm != "__metadata__":
|
||||
weight_map[nm] = shard
|
||||
weight_map = safetensors_weight_map(model_path)
|
||||
shards: dict[str, list[str]] = {}
|
||||
for name, shard in weight_map.items():
|
||||
if is_expert(name):
|
||||
|
||||
Reference in New Issue
Block a user