Files
Xiaoze Fan dacac5f5fa feat(spec): add MTP drafts for the Qwen3.5 family and Qwen3.8-Flash-Next (#844)
* feat(spec): add the MTP proposer for the qwen3_5 family

* test(models): read the qwen3_5 MTP head of bf16 and block-fp8 checkpoints

* feat(spec): verify qwen4_exp targets on qsa_sparse graphs with PLE verify handlers

* feat(spec): add the qwen4_exp MTP draft from the checkpoint or a Strata pack

* docs(cli): document the speculative decoding flags

* fix(spec): refuse MTP draft sources the draft cannot read before the target loads

* docs(qwen4_exp): describe the verify path in the PLE docstrings

* fix(spec): refuse a missing relative MTP draft path before the target loads

* fix(moe): read MTP head experts on the host and require both stacked tensors

* refactor(spec): tell the final prefill chunk from prompt_len instead of the scheduler's ChunkedReq

* refactor(spec): let each MTP draft family check its own weight source

* fix(qwen4_exp): size the disk PLE eager staging for decode and verify rows

* perf(kernel): read the KV-index gather's chunk count from the grid, not a constexpr

* refactor(moe): let each family name its MTP expert tensors

* refactor(spec): force the MTP draft's MoE resident in the proposer and check it after load

* fix(spec): refuse MTP with dummy weights

* refactor(spec): move HiddenRelay under spec/mtp, its only user

* refactor(spec): drop MTPDraft.config, fold its embed hooks into embed_tokens

* refactor(models): note FeatureSink's graph binding, drop its runtime_checkable

* fix(models): read quantized MTP fc projections under the quant config
2026-11-02 11:37:09 -08:00

173 lines
9.5 KiB
Python

"""Routed-expert banks straight from a GGUF's ``blk.N.ffn_{gate,up,down}_exps`` tensors, in their packed ggml rows: pinned host banks for the offload cache, or device banks for resident experts.
Each layer keeps its own ggml types, so each layer gets its own bank shapes: ``gate_up`` [E, 2I, row_bytes] (expert e's gate rows, then its up rows) and ``down`` [E, H, row_bytes]; a layer whose gate_up and down are both float (BF16 / F16 / F32) loads and runs bf16 ([E, 2I, H] and [E, H, I], the fused MoE's dtype), while a mixed float/quant layer keeps the float half in the file's own dtype, as main does.
A GGUF that stores ``ffn_gate_up_exps`` (gemma4) already holds the gate_up rows in that order.
When NVFP4 experts carry per-expert ``.scale`` tensors, every layer also gets ``global`` [E, 4] fp32: the (gate, up, down, 1) weight_scale_2, 1 where a tensor has none.
gpt-oss files carry per-expert gate / up / down biases; every layer then also gets ``gate_up_bias`` [E, 2I] and ``down_bias`` [E, H] bf16 rows, so the bias follows the expert through the slot cache like its weights do."""
from __future__ import annotations
import contextlib
import os
import torch
from freetoken.layers.quantization import QuantKind
from freetoken.layers.quantization.ggml_types import float_dtype, has_expert_scales, mmq_tail_bytes, pad_rows, type_name
from freetoken.utils import init_logger
from .reader import GgufTensorInfo, gguf_tensor_index
from .tensors import float_tensor, weight_scale
logger = init_logger(__name__)
def _expert_rows(info: GgufTensorInfo) -> torch.Tensor:
"""[E, rows, row_bytes] packed ggml rows, or an [E, rows, K] view in the file's float dtype; the
bank allocation that copies decides bf16 (a whole-layer float layer) or the file's dtype (a mixed one)."""
k, rows, experts = info.ne
raw = torch.from_numpy(info.data()).view(experts, rows, info.nbytes // (experts * rows))
dtype = float_dtype(info.ggml_type)
return raw if dtype is None else raw.view(dtype)
def _drop_page_cache(info: GgufTensorInfo) -> None:
try:
fd = os.open(info.path, os.O_RDONLY)
try:
os.posix_fadvise(fd, info.offset, info.nbytes, os.POSIX_FADV_DONTNEED)
finally:
os.close(fd)
except OSError:
pass
def _device_bank(shape: tuple[int, ...], ggml_type: int, k: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
"""An [E, rows, row] device bank; a zero row follows the last one when ggml's MMQ tiles read past it."""
experts, rows, row = shape
flat = torch.empty(experts * rows + pad_rows(ggml_type, k), row, dtype=dtype, device=device)
flat[experts * rows :].zero_()
return flat[: experts * rows].view(shape)
def resident_expert_bank(info: GgufTensorInfo, device: torch.device) -> torch.Tensor:
"""One stacked ``[E, rows, K]`` expert tensor as a resident device bank, in its packed ggml rows."""
rows = _expert_rows(info)
bank = _device_bank(tuple(rows.shape), info.ggml_type, info.ne[0], rows.dtype, device)
bank.copy_(rows)
return bank
def _expert_scales(gate_up: list[GgufTensorInfo], down: GgufTensorInfo, experts: int) -> torch.Tensor:
"""[E, 4] fp32 (gate, up, down, 1) weight_scale_2 of one layer's experts."""
gate, up = gate_up if len(gate_up) == 2 else (gate_up[0], gate_up[0])
out = torch.ones(experts, 4, dtype=torch.float32)
for col, info in enumerate((gate, up, down)):
s = weight_scale(info)
if s is None:
continue
if s.numel() != experts:
raise NotImplementedError(f"{info.name}: {s.numel()} scales for {experts} experts")
out[:, col] = s
return out
def load_gguf_expert_banks(model_path: str, num_layers: int, *, first_layer: int = 0, dummy: bool = False, device: torch.device | None = None):
"""``ExpertBanks`` with one bank per (layer, role): pinned host banks for the offload cache, filled from the file and pinned while later layers load, or resident banks on ``device``."""
from freetoken.moe.expert_banks import ExpertBanks
from freetoken.moe.host_banks import HostBank, PinPipeline
index = gguf_tensor_index(model_path)
scaled = has_expert_scales({name: info.ggml_type for name, info in index.items()})
# gpt-oss: a bias tensor per expert and role; other families ship none
biased = f"blk.{first_layer}.ffn_gate_exps.bias" in index
roles = ("gate_up", "down", "global") if scaled else ("gate_up", "down")
roles += ("gate_up_bias", "down_bias") if biased else ()
sources: dict[str, list[torch.Tensor]] = {role: [] for role in roles}
tails: dict[str, list[int]] = {role: [] for role in roles}
tags = []
with PinPipeline() if device is None else contextlib.nullcontext() as pins:
for layer in range(num_layers):
blk = f"blk.{first_layer + layer}"
down = index[f"{blk}.ffn_down_exps.weight"]
if f"{blk}.ffn_gate_up_exps.weight" in index:
gate = index[f"{blk}.ffn_gate_up_exps.weight"]
parts = [gate]
else:
gate, up = index[f"{blk}.ffn_gate_exps.weight"], index[f"{blk}.ffn_up_exps.weight"]
if gate.ggml_type != up.ggml_type:
raise NotImplementedError(f"{blk}: gate and up experts have different ggml types")
parts = [gate, up]
tags.append(("ggml", type_name(gate.ggml_type), type_name(down.ggml_type)))
tails["gate_up"].append(mmq_tail_bytes(gate.ggml_type, gate.ne[0]))
tails["down"].append(mmq_tail_bytes(down.ggml_type, down.ne[0]))
if scaled:
tails["global"].append(0)
if biased:
tails["gate_up_bias"].append(0)
tails["down_bias"].append(0)
# a whole-layer float layer runs the bf16 fused MoE; a mixed float/quant layer keeps the float half's own dtype
pure_float = float_dtype(gate.ggml_type) is not None and float_dtype(down.ggml_type) is not None
rows = [_expert_rows(info) for info in parts]
d = _expert_rows(down)
gate_up_shape = (rows[0].shape[0], sum(r.shape[1] for r in rows), rows[0].shape[2])
experts = rows[0].shape[0]
gu_dtype, down_dtype = (torch.bfloat16, torch.bfloat16) if pure_float else (rows[0].dtype, d.dtype)
if device is None:
host = {"gate_up": HostBank(gate_up_shape, gu_dtype), "down": HostBank(tuple(d.shape), down_dtype)}
if scaled:
host["global"] = HostBank((experts, 4), torch.float32)
banks = {role: bank.tensor for role, bank in host.items()}
else:
banks = {
"gate_up": _device_bank(gate_up_shape, gate.ggml_type, gate.ne[0], gu_dtype, device),
"down": _device_bank(tuple(d.shape), down.ggml_type, down.ne[0], down_dtype, device),
}
if scaled:
banks["global"] = torch.empty(experts, 4, dtype=torch.float32, device=device)
if scaled:
banks["global"].copy_(_expert_scales(parts, down, experts))
if biased:
missing = [f"{blk}.ffn_{p}_exps.bias" for p in ("gate", "up", "down") if f"{blk}.ffn_{p}_exps.bias" not in index]
if missing:
raise NotImplementedError(f"{model_path}: {', '.join(missing)}: the per-expert biases ship on every layer of a gpt-oss file")
# gpt-oss per-expert biases: gate|up as one [E, 2I] row block, down as [E, H]
gate_b, up_b, down_b = (
float_tensor(index[f"{blk}.ffn_{p}_exps.bias"]).to(torch.bfloat16) for p in ("gate", "up", "down")
)
gate_up_bias, down_bias = torch.cat([gate_b, up_b], dim=1), down_b
for role, rows_bias in (("gate_up_bias", gate_up_bias), ("down_bias", down_bias)):
if rows_bias.shape[0] != experts:
raise NotImplementedError(f"{blk}.{role}: {tuple(rows_bias.shape)} for {experts} experts")
if device is None:
host[role] = HostBank(tuple(rows_bias.shape), torch.bfloat16)
banks[role] = host[role].tensor
else:
banks[role] = torch.empty_like(rows_bias, device=device)
banks[role].copy_(rows_bias)
if dummy:
banks["gate_up"].zero_()
banks["down"].zero_()
if biased:
banks["gate_up_bias"].zero_()
banks["down_bias"].zero_()
else:
start = 0
for r in rows:
banks["gate_up"][:, start : start + r.shape[1]].copy_(r)
start += r.shape[1]
banks["down"].copy_(d)
for info in (*parts, down):
_drop_page_cache(info)
if device is None:
pins(layer, host)
for role, bank in banks.items():
sources[role].append(bank)
total = sum(t.numel() * t.element_size() for ts in sources.values() for t in ts)
logger.info_rank0(f"GGUF expert banks: {num_layers} layers, {total / 2**30:.1f} GiB {'on ' + str(device) if device is not None else 'in host RAM'}")
# the _bias formats are the gguf layouts plus the per-expert bias bank rows (_BANK_SCHEMAS)
return ExpertBanks(("gguf_scaled" if scaled else "gguf") + ("_bias" if biased else ""), sources, kind=QuantKind.GGUF, kernel="ggml", layout=None, layer_tags=tags, row_tail_bytes=tails)
__all__ = ["load_gguf_expert_banks", "resident_expert_bank"]