iq_pack: the qwen35moe entry: a second FORM table, native projection types refused by name, the nextn block left out, expert-profile.bin
FORM_QWEN35MOE (routers, ssm_alpha, ssm_beta and the 1-D shexp gate BF16 under the exact rule; the norms, ssm_a, ssm_dt.bias, ssm_conv1d F32) beside Flash-Next's FORM, byte-identical for qwen4exp (checked old against new on a toy with every Flash-Next tensor kind). A projection, the head or the embedding of a type the engine's native path has no kernel for is refused with the type and the list; an inexact F32 router is refused with the count of values whose low 16 bits are set and what --compat-bf16 would do. A -MTP file's draft block (blk.40 and up) is left out of index.txt and dense.bin as it already was of native_experts.txt. --expert-profile ships a ranking whose header matches the trunk (default data/qwen36-expert-profile.bin for qwen35moe). Fixtures: a toy qwen35moe with the shipped files' forms, with and without a nextn block. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017tPVMg2wGSNR1KANEiUtwr
This commit is contained in:
1 parent
ef48ea9a41
commit
27cc370939
2 files changed
+395
-22
No files matched your search
+148
-19
@@ -36,6 +36,16 @@ For ordinary quants, --compat-bf16 dequantizes the small projections that the en
|
||||
round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision
|
||||
weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE
|
||||
table stay unchanged.
|
||||
|
||||
Qwen3.6-35B-A3B (`general.architecture` qwen35moe; docs/qwen36-port/step4-pack.md) is a second FORM table, not a
|
||||
rewrite of Flash-Next's: the routers, `ssm_alpha`, `ssm_beta` and the 1-D shared-expert gate are F32 in the shipped
|
||||
files with every value exactly BF16, so they are written as BF16 under the exact rule above (no --compat-bf16); the
|
||||
norms, `ssm_a`, `ssm_dt.bias` and `ssm_conv1d` are F32 and copied; every projection (`attn_qkv`, `attn_gate`,
|
||||
`ssm_out`, `attn_q/k/v/output`, `ffn_*_shexp`, `output`, `token_embd`) is served natively from the GGUF and must
|
||||
be of a type the engine's native path has a kernel for (NATIVE_PROJECTION_TYPES below) - any other is refused by
|
||||
name. The draft block of a -MTP file (`blk.40` and up, `nextn_predict_layers`) belongs to the drafter's pack and is
|
||||
left out of index.txt, dense.bin and native_experts.txt alike. `expert-profile.bin` (the expert cache's ranking,
|
||||
tools/make_profile.py) is copied in from --expert-profile when its header matches the trunk's layers x experts.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -83,26 +93,76 @@ FORM = {
|
||||
"indexer.k_norm.weight": "F32", "ple_norm_conv.weight": "F32", "ple_norm_key.weight": "F32",
|
||||
"ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32",
|
||||
"ssm_norm.weight": "F32",
|
||||
# qwen35moe (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.5): the plain residual's norms in place of the hc_* set.
|
||||
# Stored F32 in every shipped file, so these are written as stored; its routers and ssm_alpha / ssm_beta are F32
|
||||
# with non-BF16 values, so a Qwen3.6 pack takes --compat-bf16 (step 4 decides the engine's form for them).
|
||||
"attn_norm.weight": "F32", "post_attention_norm.weight": "F32", "output_norm.weight": "F32",
|
||||
}
|
||||
# qwen35moe (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.5, 3.7; docs/qwen36-port/step4-pack.md): the plain residual
|
||||
# block's norms in place of the hc_* set, no indexer, no PLE. The engine's forms (src/core/layout.cpp `check_one`
|
||||
# and the kernels behind it): the router and the GDN gate projections BF16 (`moe_route`, `fused_gdn_ab`, the prefill
|
||||
# `bf16_proj`), the shared expert's 1-D gate BF16 (`shared_expert`), every norm, `ssm_a`, `ssm_dt.bias` and
|
||||
# `ssm_conv1d` F32 (read as `const float*`). The BF16 ones are F32 in both shipped files with every value exactly
|
||||
# BF16 (step3-gdn.md's census), so the exact rule writes them without --compat-bf16.
|
||||
FORM_QWEN35MOE = {
|
||||
"ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16",
|
||||
"ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16",
|
||||
"attn_norm.weight": "F32", "post_attention_norm.weight": "F32", "output_norm.weight": "F32",
|
||||
"attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "ssm_norm.weight": "F32",
|
||||
"ssm_a": "F32", "ssm_dt.bias": "F32", "ssm_conv1d.weight": "F32",
|
||||
}
|
||||
FORMS = {"qwen4exp": FORM, "qwen35moe": FORM_QWEN35MOE}
|
||||
# The qwen35moe tensors the engine serves natively from the GGUF (`NativeDense::load`'s eligible suffixes, the native
|
||||
# head and the native embedding), and the ggml types each path has a kernel for: `native_mmvq_supported`
|
||||
# (src/kernels/cuda/native_mmvq.cu) for the projections and the head, `embed_type_supported` (iq_kernels.cu: the
|
||||
# `is_iq` set plus BF16) for the embedding. A projection of any other type is refused by name: the engine has no
|
||||
# F32 / F16 GEMV and would refuse the pack at start-up ("this pack holds the tensor only in its GGUF form").
|
||||
NATIVE_PROJECTIONS_QWEN35MOE = (
|
||||
"attn_qkv.weight", "attn_gate.weight", "ssm_out.weight", # GDN layers
|
||||
"attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight", # attention layers
|
||||
"ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight", # the shared expert, every layer
|
||||
)
|
||||
NATIVE_PROJECTION_TYPES = {"Q4_0", "Q5_0", "Q5_1", "Q8_0", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "IQ4_NL", "IQ4_XS",
|
||||
"Q2_0", "IQ2_XXS", "IQ2_XS", "IQ3_XXS", "IQ3_S", "IQ2_S", "IQ1_M"}
|
||||
NATIVE_EMBED_TYPES = {"Q5_0", "Q5_1", "Q8_0", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "IQ4_NL", "IQ4_XS", "Q2_0",
|
||||
"IQ2_XXS", "IQ2_XS", "IQ3_XXS", "IQ3_S", "IQ2_S", "IQ1_M", "BF16"}
|
||||
# PLE key encodings left in the GGUF for the engine's native PLE key (Q2_0; Q8_0 in UD-Q4_K_XL). Other quantized
|
||||
# keys take the BF16 path (--compat-bf16), as before.
|
||||
NATIVE_PLE_KEY = {"Q2_0", "Q8_0"}
|
||||
KIND = {"BF16": "4", "F16": "5", "F32": "2"}
|
||||
|
||||
|
||||
def form_of(name: str):
|
||||
return FORM.get(re.sub(r"^blk\.\d+\.", "", name))
|
||||
def form_of(name: str, arch: str = "qwen4exp"):
|
||||
return FORMS.get(arch, FORM).get(re.sub(r"^blk\.\d+\.", "", name))
|
||||
|
||||
|
||||
def needs_bf16(name: str, type_name: str) -> bool:
|
||||
def needs_bf16(name: str, type_name: str, arch: str = "qwen4exp") -> bool:
|
||||
"""Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF)."""
|
||||
if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY:
|
||||
return False
|
||||
return form_of(name) == "BF16"
|
||||
return form_of(name, arch) == "BF16"
|
||||
|
||||
|
||||
def native_type_problem(name: str, type_name: str, arch: str):
|
||||
"""For a qwen35moe tensor the engine serves from the GGUF: None when its type has a native kernel, else the
|
||||
refusal (the tensor, its type, the path and the types that path takes)."""
|
||||
if arch != "qwen35moe":
|
||||
return None
|
||||
suffix = re.sub(r"^blk\.\d+\.", "", name)
|
||||
if name == "token_embd.weight":
|
||||
path, ok = "native embedding (iq_embed_rows)", NATIVE_EMBED_TYPES
|
||||
elif name == "output.weight":
|
||||
path, ok = "native head (native_mmvq)", NATIVE_PROJECTION_TYPES
|
||||
elif name.startswith("blk.") and suffix in NATIVE_PROJECTIONS_QWEN35MOE:
|
||||
path, ok = "native projection path (NativeDense, native_mmvq)", NATIVE_PROJECTION_TYPES
|
||||
else:
|
||||
return None
|
||||
if type_name in ok:
|
||||
return None
|
||||
return "%s is %s, which the engine's %s has no kernel for; it serves %s" % (
|
||||
name, type_name, path, ", ".join(sorted(ok)))
|
||||
|
||||
|
||||
def layer_of(name: str) -> int:
|
||||
"""The block index of a `blk.N.` tensor, -1 for any other."""
|
||||
m = re.match(r"^blk\.(\d+)\.", name)
|
||||
return int(m.group(1)) if m else -1
|
||||
|
||||
|
||||
def dequantize(raw: np.ndarray, type_name: str) -> np.ndarray:
|
||||
@@ -227,25 +287,32 @@ def is_expert(name: str) -> bool:
|
||||
return name.startswith("blk.") and name.endswith(("_exps.weight",))
|
||||
|
||||
|
||||
def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool):
|
||||
def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool, arch: str = "qwen4exp"):
|
||||
"""The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes,
|
||||
record or None), or an error string. `record` describes a conversion for conversions.json."""
|
||||
form = form_of(name)
|
||||
form = form_of(name, arch)
|
||||
if form is None or form == type_name:
|
||||
return KIND[type_name], raw.tobytes(), raw.nbytes, None
|
||||
values = dequantize(raw, type_name)
|
||||
rec = {"src_type": type_name, "dst_type": form}
|
||||
if form == "BF16":
|
||||
u = values.view(np.uint32) if type_name == "F32" else None
|
||||
if u is not None and not np.count_nonzero(u & 0xFFFF):
|
||||
inexact = int(np.count_nonzero(u & 0xFFFF)) if u is not None else 0
|
||||
if u is not None and not inexact:
|
||||
if not np.isfinite(values).all():
|
||||
return f"{name} is F32 with non-finite values; refused rather than converted"
|
||||
data = (u >> 16).astype("<u2").tobytes() # the exact BF16 values
|
||||
rec.update(method="f32->bf16: the values are BF16's (low 16 bits zero)", exact=True, max_abs_err=0.0)
|
||||
return "4", data, len(data), rec
|
||||
if not compat_bf16:
|
||||
what = "F32 with values that are not BF16" if type_name == "F32" else type_name
|
||||
return f"{name} is {what}, but the engine requires BF16; use --compat-bf16 (rounds to nearest-even)"
|
||||
if type_name == "F32":
|
||||
# the count is the finding: the shipped Qwen3.6 files have 0 of these (the checkpoint is BF16 and
|
||||
# the converter stored it as F32), so a non-zero count means another checkpoint or converter
|
||||
what = ("F32 with %d of %d values that are not BF16 (low 16 bits set)" % (inexact, u.size))
|
||||
else:
|
||||
what = type_name
|
||||
return (f"{name} is {what}, but the engine reads it as BF16; --compat-bf16 would round them to "
|
||||
"nearest-even (a lossy pack, recorded in compat-bf16.json)")
|
||||
data = bf16_bytes(raw, type_name)
|
||||
got = (np.frombuffer(data, dtype="<u2").astype(np.uint32) << 16).view(np.float32)
|
||||
rec.update(method="dequantize->bf16 round-to-nearest-even (--compat-bf16)" if type_name not in FLOAT else
|
||||
@@ -275,24 +342,42 @@ def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool):
|
||||
return "2", data, len(data), rec
|
||||
|
||||
|
||||
def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int:
|
||||
def model_arch(model: Model) -> str:
|
||||
return str(model.files[0].metadata.get("general.architecture", "qwen4exp"))
|
||||
|
||||
|
||||
def index_standalone(src, out, model: Model, compat_bf16: bool = False, n_trunk: int = -1) -> int:
|
||||
"""Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it
|
||||
reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF."""
|
||||
todo, problems = [], []
|
||||
reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF.
|
||||
`n_trunk` (a -MTP file's `block_count - nextn_predict_layers`): the draft blocks from `blk.<n_trunk>` up are
|
||||
left out, they are the drafter's pack's; -1 = every block."""
|
||||
arch = model_arch(model)
|
||||
todo, problems, draft = [], [], 0
|
||||
for name, (g, t, mm, p) in model.where.items():
|
||||
if is_expert(t.name) or t.name in NOT_IN_PACK:
|
||||
continue
|
||||
if n_trunk >= 0 and layer_of(name) >= n_trunk:
|
||||
draft += 1
|
||||
continue
|
||||
if len(t.shape) > 2:
|
||||
print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape)))
|
||||
return 1
|
||||
# quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes
|
||||
# --compat-bf16 to dequantize - except the native PLE key encodings
|
||||
form = form_of(name)
|
||||
form = form_of(name, arch)
|
||||
native = t.type_name not in FLOAT and (form is None or (
|
||||
name == "blk.1.ple_key.weight" and t.type_name in NATIVE_PLE_KEY))
|
||||
if t.type_name not in FLOAT and not native and not compat_bf16:
|
||||
problems.append(f"{name} is {t.type_name}, but the engine requires {form}; use --compat-bf16")
|
||||
# qwen35moe: a projection the engine must serve natively is refused unless its type has a kernel. A float
|
||||
# projection is refused too: the engine has no F32 / F16 GEMV, and "written as stored" would only move the
|
||||
# refusal to the engine's start-up
|
||||
why = native_type_problem(name, t.type_name, arch)
|
||||
if why is not None:
|
||||
problems.append(why)
|
||||
todo.append((name, g, t, mm, p, native))
|
||||
if draft:
|
||||
print("%d tensors of the draft (nextn) block(s) blk.%d and up are left to the drafter's pack" % (draft, n_trunk))
|
||||
# refused before anything is written: the previous pack stays as it was
|
||||
if problems:
|
||||
for m in problems[:8]:
|
||||
@@ -313,7 +398,7 @@ def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int:
|
||||
continue
|
||||
raw = tensor_bytes(mm, g, t)
|
||||
try:
|
||||
got = convert(name, t.type_name, raw, compat_bf16)
|
||||
got = convert(name, t.type_name, raw, compat_bf16, arch)
|
||||
except ValueError as e:
|
||||
got = str(e)
|
||||
if isinstance(got, str):
|
||||
@@ -506,6 +591,25 @@ def read_json(path: pathlib.Path):
|
||||
return None
|
||||
|
||||
|
||||
def profile_problem(path: pathlib.Path, n_layers: int, n_expert: int):
|
||||
"""The expert-cache profile's header (tools/make_profile.py, read by `read_expert_profile`) against this model's
|
||||
trunk: None when it fits, else why not. The engine would refuse it at start-up with the same numbers; checking
|
||||
here keeps a pack from shipping a ranking for another model."""
|
||||
import struct
|
||||
try:
|
||||
head = path.read_bytes()[:24]
|
||||
except OSError as e:
|
||||
return "%s: %s" % (path, e)
|
||||
if len(head) < 24 or head[:4] != b"STRP":
|
||||
return "%s is not a Strata expert profile (no STRP header)" % path
|
||||
_, nl, ne, slots, n = struct.unpack_from("<5I", head, 4)
|
||||
if (nl, ne) != (n_layers, n_expert):
|
||||
return "%s ranks %d x %d (layers x experts), this model's trunk is %d x %d" % (path, nl, ne, n_layers, n_expert)
|
||||
if n > slots or n > nl * ne:
|
||||
return "%s: %d ranked pairs in %d slots of %d" % (path, n, slots, nl * ne)
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--gguf", required=True, help="the model's shard 1")
|
||||
@@ -520,6 +624,10 @@ def main() -> int:
|
||||
ap.add_argument("--layout-only", action="store_true",
|
||||
help="write native_experts.txt alone (the per-layer expert formats, blob sizes and offsets) and "
|
||||
"print the census: the pack-side check of a model file, nothing else is written")
|
||||
ap.add_argument("--expert-profile", metavar="PROFILE.bin",
|
||||
help="the expert cache's ranking (tools/make_profile.py) to ship as <out>/expert-profile.bin; its "
|
||||
"header must say this model's trunk layers x experts. Default: data/qwen36-expert-profile.bin "
|
||||
"for a qwen35moe model when it exists and fits; none otherwise")
|
||||
a = ap.parse_args()
|
||||
if a.compat_bf16 and a.base:
|
||||
ap.error("--compat-bf16 cannot reuse --base dense weights")
|
||||
@@ -541,6 +649,19 @@ def main() -> int:
|
||||
print(got)
|
||||
return 1
|
||||
layout, text, n_expert, offset = got
|
||||
n_trunk = len(layout)
|
||||
arch = model_arch(model)
|
||||
# the expert cache's ranking: checked against the trunk before anything is written, copied in after the index
|
||||
profile = pathlib.Path(a.expert_profile) if a.expert_profile else None
|
||||
if profile is None and arch == "qwen35moe":
|
||||
default = HERE.parent / "data" / "qwen36-expert-profile.bin"
|
||||
if default.is_file() and profile_problem(default, n_trunk, n_expert) is None:
|
||||
profile = default
|
||||
if profile is not None:
|
||||
why = profile_problem(profile, n_trunk, n_expert)
|
||||
if why:
|
||||
print(why)
|
||||
return 1
|
||||
if a.layout_only:
|
||||
(out / "native_experts.txt").write_text(text, encoding="utf-8")
|
||||
kinds = {}
|
||||
@@ -591,12 +712,20 @@ def main() -> int:
|
||||
(out / "native_experts.txt").unlink(missing_ok=True)
|
||||
rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm)
|
||||
else:
|
||||
rc = index_standalone(src, out, model, a.compat_bf16)
|
||||
rc = index_standalone(src, out, model, a.compat_bf16, n_trunk)
|
||||
if rc:
|
||||
return rc
|
||||
if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists():
|
||||
subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)],
|
||||
check=True) # writes <out>/tokenizer/
|
||||
if profile is not None:
|
||||
tmp_prof = out / "expert-profile.bin.tmp"
|
||||
shutil.copyfile(profile, tmp_prof)
|
||||
tmp_prof.replace(out / "expert-profile.bin")
|
||||
print("expert-profile.bin: %s (%d x %d)" % (profile, n_trunk, n_expert))
|
||||
elif arch == "qwen35moe":
|
||||
print("no expert profile shipped (--expert-profile): the engine's --expert-profile needs one of %d x %d"
|
||||
% (n_trunk, n_expert))
|
||||
|
||||
# ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is
|
||||
# in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup
|
||||
|
||||
+247
-3
@@ -19,9 +19,10 @@ from gguf import GGUFWriter, GGMLQuantizationType as Q, quants
|
||||
import iq_pack
|
||||
|
||||
|
||||
def write_gguf(path, tensors, split=None, arch=True, kv=None):
|
||||
"""`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no); `kv` = extra u32 keys."""
|
||||
writer = GGUFWriter(path, "qwen4exp")
|
||||
def write_gguf(path, tensors, split=None, arch=True, kv=None, architecture="qwen4exp"):
|
||||
"""`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no); `kv` = extra u32 keys;
|
||||
`architecture` = the general.architecture string (qwen4exp, or qwen35moe for the Qwen3.6 fixtures)."""
|
||||
writer = GGUFWriter(path, architecture)
|
||||
if not arch: # a later shard of a split: no model metadata
|
||||
writer.kv_data[0].pop("general.architecture", None)
|
||||
for key, value in (kv or {}).items():
|
||||
@@ -592,5 +593,248 @@ class SplitArtifactTests(unittest.TestCase):
|
||||
self.assertEqual((pack / "experts.bin").read_bytes(), want)
|
||||
|
||||
|
||||
# ---- Qwen3.6-35B-A3B (qwen35moe) in miniature: hidden 64, 2 trunk layers (0 GDN, 1 attention), 4 experts of 32,
|
||||
# the shared expert 32 wide, plus (with nextn) a draft block blk.2 of the -MTP files' shape. The float tensors are
|
||||
# stored as the shipped files store them: the routers, ssm_alpha / ssm_beta and the 1-D shexp gate F32 holding BF16
|
||||
# values; the norms, ssm_a, ssm_dt.bias and ssm_conv1d F32; every projection quantized (Q8_0 here, Q6_K / Q8_0 in
|
||||
# the files).
|
||||
Q36_H, Q36_E, Q36_FF, Q36_HV, Q36_C, Q36_V, Q36_VOCAB = 64, 4, 32, 2, 64, 32, 32
|
||||
|
||||
|
||||
def bf16_exact(shape, seed):
|
||||
"""F32 values whose low 16 bits are zero: BF16 values held as F32, as the shipped files hold them."""
|
||||
x = np.random.default_rng(seed).standard_normal(shape).astype(np.float32)
|
||||
return (x.view(np.uint32) & np.uint32(0xFFFF0000)).view(np.float32)
|
||||
|
||||
|
||||
def q36_trunk_layer(l, gdn, router=None, proj_type=Q.Q8_0, proj_values=None):
|
||||
r = np.random.default_rng(100 + l)
|
||||
f32 = lambda *shape: r.standard_normal(shape).astype(np.float32)
|
||||
q = lambda *shape: (proj_values if proj_values is not None else f32(*shape))
|
||||
b = "blk.%d." % l
|
||||
t = [(b + "attn_norm.weight", f32(Q36_H), Q.F32), (b + "post_attention_norm.weight", f32(Q36_H), Q.F32),
|
||||
(b + "ffn_gate_inp.weight", router if router is not None else bf16_exact((Q36_E, Q36_H), l), Q.F32),
|
||||
(b + "ffn_gate_inp_shexp.weight", bf16_exact((Q36_H,), 50 + l), Q.F32),
|
||||
(b + "ffn_gate_shexp.weight", f32(Q36_FF, Q36_H), proj_type),
|
||||
(b + "ffn_up_shexp.weight", f32(Q36_FF, Q36_H), proj_type),
|
||||
(b + "ffn_down_shexp.weight", f32(Q36_H, Q36_FF), proj_type)]
|
||||
t += [(b + "ffn_%s_exps.weight" % role, f32(Q36_E, Q36_FF, Q36_H) if role != "down" else f32(Q36_E, Q36_H, Q36_FF),
|
||||
Q.Q8_0) for role in ("gate", "up", "down")]
|
||||
if gdn:
|
||||
t += [(b + "attn_qkv.weight", q(Q36_C, Q36_H), proj_type), (b + "attn_gate.weight", q(Q36_V, Q36_H), proj_type),
|
||||
(b + "ssm_out.weight", q(Q36_H, Q36_V), proj_type),
|
||||
(b + "ssm_conv1d.weight", f32(Q36_C, 4), Q.F32),
|
||||
(b + "ssm_alpha.weight", bf16_exact((Q36_HV, Q36_H), 60 + l), Q.F32),
|
||||
(b + "ssm_beta.weight", bf16_exact((Q36_HV, Q36_H), 70 + l), Q.F32),
|
||||
(b + "ssm_a", -np.abs(f32(Q36_HV)), Q.F32), (b + "ssm_dt.bias", f32(Q36_HV), Q.F32),
|
||||
(b + "ssm_norm.weight", f32(16), Q.F32)]
|
||||
else:
|
||||
t += [(b + "attn_q.weight", q(128, Q36_H), proj_type), (b + "attn_k.weight", q(32, Q36_H), proj_type),
|
||||
(b + "attn_v.weight", q(32, Q36_H), proj_type), (b + "attn_output.weight", q(Q36_H, Q36_H), proj_type),
|
||||
(b + "attn_q_norm.weight", f32(32), Q.F32), (b + "attn_k_norm.weight", f32(32), Q.F32)]
|
||||
return t
|
||||
|
||||
|
||||
def q36_model(path, nextn=False, **layer_kw):
|
||||
r = np.random.default_rng(7)
|
||||
f32 = lambda *shape: r.standard_normal(shape).astype(np.float32)
|
||||
tensors = [("token_embd.weight", f32(Q36_VOCAB, Q36_H), Q.Q8_0), ("output.weight", f32(Q36_VOCAB, Q36_H), Q.Q8_0),
|
||||
("output_norm.weight", f32(Q36_H), Q.F32)]
|
||||
tensors += q36_trunk_layer(0, True, **layer_kw) + q36_trunk_layer(1, False)
|
||||
kv = {}
|
||||
if nextn:
|
||||
# the draft block: an attention layer with MoE, its routers BF16 (as in the -MTP files), plus the nextn set
|
||||
draft = [(n, v, Q.BF16 if n.endswith(("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight")) else k)
|
||||
for n, v, k in q36_trunk_layer(2, False)]
|
||||
draft += [("blk.2.nextn.eh_proj.weight", f32(Q36_H, 2 * Q36_H), Q.Q8_0),
|
||||
("blk.2.nextn.enorm.weight", f32(Q36_H), Q.F32), ("blk.2.nextn.hnorm.weight", f32(Q36_H), Q.F32),
|
||||
("blk.2.nextn.shared_head_norm.weight", f32(Q36_H), Q.F32)]
|
||||
tensors += draft
|
||||
kv["qwen35moe.nextn_predict_layers"] = 1
|
||||
write_gguf(path, tensors, kv=kv, architecture="qwen35moe")
|
||||
return tensors
|
||||
|
||||
|
||||
def q36_pack(root, out, *extra, nextn=False, **layer_kw):
|
||||
"""Packs a toy model at root/q36.gguf into `out` through main(): (rc, log, tensors)."""
|
||||
path = root / "q36.gguf"
|
||||
tensors = q36_model(path, nextn=nextn, **layer_kw)
|
||||
(out / "tokenizer").mkdir(parents=True, exist_ok=True)
|
||||
for n in ["vocab.json", "chat_template.jinja"]:
|
||||
(out / "tokenizer" / n).touch()
|
||||
buf = io.StringIO()
|
||||
with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), *extra]):
|
||||
with contextlib.redirect_stdout(buf):
|
||||
rc = iq_pack.main()
|
||||
return rc, buf.getvalue(), tensors
|
||||
|
||||
|
||||
class Qwen36PackTests(unittest.TestCase):
|
||||
"""The qwen35moe entry (docs/qwen36-port/step4-pack.md): the forms, the BF16 rule's refusal with its count, the
|
||||
native projection types refused by name, the nextn block left out, index.txt's contents, expert-profile.bin."""
|
||||
|
||||
def test_forms_and_index_contents(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root, out = Path(tmp), Path(tmp) / "pack"
|
||||
rc, log, tensors = q36_pack(root, out)
|
||||
self.assertEqual(rc, 0, log)
|
||||
header, rows = iq_pack.read_index(out / "index.txt")
|
||||
dense = (out / "dense.bin").read_bytes()
|
||||
by_name = {n: (v, k) for n, v, k in tensors}
|
||||
# every non-expert tensor has a row, nothing else does, and the header counts them
|
||||
expect = {n for n in by_name if not n.endswith("_exps.weight")}
|
||||
self.assertEqual(set(rows), expect)
|
||||
self.assertIn("tensors %d" % len(expect), header[1])
|
||||
bf16 = {"ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight", "ssm_alpha.weight", "ssm_beta.weight"}
|
||||
f32 = {"attn_norm.weight", "post_attention_norm.weight", "output_norm.weight", "attn_q_norm.weight",
|
||||
"attn_k_norm.weight", "ssm_norm.weight", "ssm_a", "ssm_dt.bias", "ssm_conv1d.weight"}
|
||||
native = {"attn_qkv.weight", "attn_gate.weight", "ssm_out.weight", "attn_q.weight", "attn_k.weight",
|
||||
"attn_v.weight", "attn_output.weight", "ffn_gate_shexp.weight", "ffn_up_shexp.weight",
|
||||
"ffn_down_shexp.weight", "output.weight", "token_embd.weight"}
|
||||
at = 0
|
||||
for name, row in rows.items():
|
||||
suffix = iq_pack.re.sub(r"^blk\.\d+\.", "", name)
|
||||
v, k = by_name[name]
|
||||
ne0, ne1 = int(row[7]), int(row[8])
|
||||
self.assertEqual((ne0, ne1), (v.shape[-1], v.shape[0] if v.ndim == 2 else 0), name)
|
||||
if suffix in bf16:
|
||||
self.assertEqual(row[2], "4", name) # index kind 4: raw BF16
|
||||
self.assertEqual(int(row[4]), v.size * 2, name)
|
||||
np.testing.assert_array_equal(stored(rows, dense, name, "<u2"), (v.view(np.uint32) >> 16).ravel())
|
||||
elif suffix in f32:
|
||||
self.assertEqual(row[2], "2", name) # F32 as stored
|
||||
np.testing.assert_array_equal(stored(rows, dense, name, "<f4"), v.ravel())
|
||||
else:
|
||||
self.assertIn(suffix, native, name)
|
||||
self.assertEqual(row[1:5] + [row[6]], ["0"] * 5, name) # shape only: no bytes, no source
|
||||
self.assertEqual(int(row[5]), at, name) # the running arena offset, 0 B
|
||||
self.assertEqual((row[9], row[11]), ("8", "32"), name) # marked quantized: served natively
|
||||
if row[2] != "0":
|
||||
self.assertEqual(int(row[5]), at, name) # 64-aligned arena offsets
|
||||
self.assertEqual(int(row[3]) % 64, 0, name)
|
||||
at += (int(row[6]) + 63) // 64 * 64
|
||||
self.assertIn("pool %d" % at, header[1])
|
||||
# conversions.json: the four BF16 forms per GDN layer, two per attention layer, all exact, nothing lossy
|
||||
conv = json.loads((out / "conversions.json").read_text())
|
||||
self.assertEqual(sorted(r["name"] for r in conv["tensors"]),
|
||||
sorted(n for n in rows if iq_pack.re.sub(r"^blk\.\d+\.", "", n) in bf16))
|
||||
self.assertTrue(all(r["exact"] and r["max_abs_err"] == 0.0 for r in conv["tensors"]))
|
||||
self.assertFalse(conv["compat_bf16"])
|
||||
self.assertFalse((out / "compat-bf16.json").exists())
|
||||
# the expert table: two trunk layers
|
||||
lines = [l for l in (out / "native_experts.txt").read_text().splitlines() if not l.startswith("#")]
|
||||
self.assertEqual([l.split()[0] for l in lines], ["0", "1"])
|
||||
self.assertIn("no expert profile shipped", log)
|
||||
self.assertEqual(sorted(p.name for p in out.iterdir()),
|
||||
["conversions.json", "dense.bin", "index.txt", "native_experts.txt", "tokenizer"])
|
||||
|
||||
def test_inexact_router_is_refused_with_the_count(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root, out = Path(tmp), Path(tmp) / "pack"
|
||||
router = bf16_exact((Q36_E, Q36_H), 1)
|
||||
router[0, :3] += np.float32(1e-3) # three values with low bits set
|
||||
out.mkdir()
|
||||
(out / "dense.bin").write_bytes(b"previous pack")
|
||||
(out / "native_experts.txt").write_bytes(b"previous pack")
|
||||
rc, log, _ = q36_pack(root, out, router=router)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("blk.0.ffn_gate_inp.weight is F32 with 3 of %d values that are not BF16" % router.size, log)
|
||||
self.assertIn("--compat-bf16 would round them", log)
|
||||
self.assertEqual((out / "dense.bin").read_bytes(), b"previous pack")
|
||||
self.assertEqual((out / "native_experts.txt").read_bytes(), b"previous pack")
|
||||
self.assertFalse((out / "index.txt").exists())
|
||||
rc, log, _ = q36_pack(root, out, "--compat-bf16", router=router)
|
||||
self.assertEqual(rc, 0, log)
|
||||
compat = json.loads((out / "compat-bf16.json").read_text())
|
||||
self.assertEqual([t["name"] for t in compat["tensors"]], ["blk.0.ffn_gate_inp.weight"])
|
||||
conv = {r["name"]: r for r in json.loads((out / "conversions.json").read_text())["tensors"]}
|
||||
self.assertFalse(conv["blk.0.ffn_gate_inp.weight"]["exact"])
|
||||
self.assertTrue(conv["blk.1.ffn_gate_inp.weight"]["exact"])
|
||||
|
||||
def test_projection_types_are_refused_by_name(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root, out = Path(tmp), Path(tmp) / "pack"
|
||||
# an F32 GDN projection: the engine has no F32 GEMV
|
||||
rc, log, _ = q36_pack(root, out, proj_type=Q.F32)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("blk.0.attn_qkv.weight is F32, which the engine's native projection path", log)
|
||||
self.assertIn("Q6_K", log)
|
||||
self.assertIn("Q8_0", log)
|
||||
self.assertFalse((out / "index.txt").exists())
|
||||
self.assertFalse((out / "native_experts.txt").exists())
|
||||
# the head and the embedding have their own lists
|
||||
path = root / "q36.gguf"
|
||||
tensors = [(n, v, k) for n, v, k in q36_model(path)]
|
||||
tensors = [(n, v, Q.F32 if n == "output.weight" else Q.F16 if n == "token_embd.weight" else k)
|
||||
for n, v, k in tensors]
|
||||
write_gguf(path, tensors, architecture="qwen35moe")
|
||||
with contextlib.redirect_stdout(io.StringIO()) as buf:
|
||||
rc = iq_pack.index_standalone(path, out, iq_pack.Model(path), False, 2)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("output.weight is F32, which the engine's native head", buf.getvalue())
|
||||
self.assertIn("token_embd.weight is F16, which the engine's native embedding", buf.getvalue())
|
||||
self.assertIn("BF16", buf.getvalue()) # the embedding takes BF16, the head does not
|
||||
|
||||
def test_nextn_block_is_left_to_the_drafter(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root, out = Path(tmp), Path(tmp) / "pack"
|
||||
rc, log, tensors = q36_pack(root, out, nextn=True)
|
||||
self.assertEqual(rc, 0, log)
|
||||
_, rows = iq_pack.read_index(out / "index.txt")
|
||||
self.assertFalse([n for n in rows if n.startswith("blk.2.")], "the draft block is in the index")
|
||||
self.assertFalse([n for n in rows if "nextn" in n])
|
||||
self.assertEqual(len(rows), len([n for n, _, _ in tensors
|
||||
if not n.endswith("_exps.weight") and not n.startswith("blk.2.")]))
|
||||
draft_floats = sum(1 for n, _, k in tensors if n.startswith("blk.2.") and not n.endswith("_exps.weight"))
|
||||
self.assertIn("%d tensors of the draft (nextn) block(s) blk.2 and up are left to the drafter's pack"
|
||||
% draft_floats, log)
|
||||
self.assertIn("1 draft (nextn) block(s) at blk.2 and up are left to the MTP pack; 2 trunk layers", log)
|
||||
lines = [l for l in (out / "native_experts.txt").read_text().splitlines() if not l.startswith("#")]
|
||||
self.assertEqual([l.split()[0] for l in lines], ["0", "1"])
|
||||
# dense.bin holds exactly the trunk's float tensors: its size is their 64-aligned sum
|
||||
size = 0
|
||||
for n, v, k in tensors:
|
||||
if n.startswith("blk.2.") or n.endswith("_exps.weight") or k != Q.F32:
|
||||
continue
|
||||
suffix = iq_pack.re.sub(r"^blk\.\d+\.", "", n)
|
||||
nbytes = v.size * (2 if iq_pack.FORM_QWEN35MOE.get(suffix) == "BF16" else 4)
|
||||
size += (nbytes + 63) // 64 * 64
|
||||
self.assertEqual((out / "dense.bin").stat().st_size, size)
|
||||
|
||||
def test_expert_profile_is_checked_and_copied(self):
|
||||
import make_profile as MP
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root, out = Path(tmp), Path(tmp) / "pack"
|
||||
ranked = [(l, e) for l in range(2) for e in range(Q36_E)]
|
||||
MP.write_profile(root / "fits.bin", ranked, Q36_E, 2)
|
||||
MP.write_profile(root / "other.bin", [(l, e) for l in range(3) for e in range(Q36_E)], Q36_E, 3)
|
||||
out.mkdir()
|
||||
(out / "native_experts.txt").write_bytes(b"previous pack")
|
||||
rc, log, _ = q36_pack(root, out, "--expert-profile", str(root / "other.bin"))
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("ranks 3 x 4 (layers x experts), this model's trunk is 2 x 4", log)
|
||||
self.assertEqual((out / "native_experts.txt").read_bytes(), b"previous pack")
|
||||
self.assertFalse((out / "expert-profile.bin").exists())
|
||||
rc, log, _ = q36_pack(root, out, "--expert-profile", str(root / "fits.bin"))
|
||||
self.assertEqual(rc, 0, log)
|
||||
self.assertEqual((out / "expert-profile.bin").read_bytes(), (root / "fits.bin").read_bytes())
|
||||
self.assertIn("expert-profile.bin: %s (2 x 4)" % (root / "fits.bin"), log)
|
||||
self.assertEqual(MP.read_profile(out / "expert-profile.bin", Q36_E, 2), ranked)
|
||||
self.assertFalse(list(out.glob("*.tmp")))
|
||||
|
||||
def test_flash_next_forms_do_not_see_the_qwen36_table(self):
|
||||
"""The qwen4exp FORM table is the one it was: the Qwen3.6 names resolve to nothing there, so a Flash-Next
|
||||
tensor by one of those names (none exists) would be written as stored, as before."""
|
||||
for name in ("blk.0.attn_norm.weight", "blk.0.ssm_a", "blk.0.attn_q_norm.weight"):
|
||||
self.assertEqual(iq_pack.form_of(name, "qwen35moe"), "F32")
|
||||
self.assertEqual(iq_pack.form_of("blk.0.ssm_alpha.weight"), "BF16")
|
||||
self.assertEqual(iq_pack.form_of("blk.0.hc_attn_down.weight", "qwen35moe"), None)
|
||||
self.assertEqual(iq_pack.form_of("blk.0.attn_norm.weight"), None)
|
||||
self.assertTrue(iq_pack.needs_bf16("blk.0.ssm_alpha.weight", "F32", "qwen35moe"))
|
||||
self.assertIsNone(iq_pack.native_type_problem("blk.0.attn_qkv.weight", "F32", "qwen4exp"))
|
||||
self.assertIsNone(iq_pack.native_type_problem("blk.0.attn_qkv.weight", "Q6_K", "qwen35moe"))
|
||||
self.assertIsNone(iq_pack.native_type_problem("blk.0.ffn_gate_inp.weight", "F32", "qwen35moe"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user