okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221qwen4_intake: the Metal and SYCL down-expert lists follow main's f-q4-kquant (Metal adds Q3_K/Q4_K/Q5_K/Q6_K/IQ3_S, SYCL Q5_K/Q6_K); test_metal_lists and test_sycl_lists read the sources againfdb376f39

main
61.1 KiB1137 linesraw
1#!/usr/bin/env python3
2"""Intake for a new model: read GGUF headers (never the weights) and say what Strata would have to do to run them.
3
4    python tools/qwen4_intake.py PATH [PATH ...]                 a folder, or one or more .gguf files (any shard of a set)
5    python tools/qwen4_intake.py --hf REPO [--rev REV] [--dir D]  Hugging Face: HTTP range reads of each shard's header only
6    options: --out FILE   (the JSON report; default qwen4_intake.json)   --sha256 (local files: hash them, slow)
7             --no-tokenizer-build   --quiet
8
9For each set of files (a split model is one set) it prints, and writes as JSON:
10
11  * the architecture and every geometry key, against both families Strata runs (qwen4exp = include/strata/core/geometry.hpp's
12    kCompiledGeometry; qwen35moe = the run-time shapes of src/qwen35 with its fixed limits);
13  * the tensor layout against the layout tables of include/strata/core/family_layout.hpp: missing, reshaped and unknown tensors;
14  * every quant type against what each backend (CUDA, HIP, SYCL, Metal) has kernels for, by tensor role;
15  * the tokenizer (model, pre-tokenizer, vocabulary, special tokens, BOS/EOS) against Flash-Next's, and whether
16    tools/strata_tokenizer.py can build it; the chat template's hash, tool-call form and thinking tags;
17  * the MTP block, the vision projector, split shards, sizes, sha256 where known, the general.* names and licence;
18  * a verdict: case A (runs now: which path and backends), B (known layer types at a new shape or under a new name: the fields
19    that differ) or C (each blocker), and a DRAFT catalog entry and setup config.  Nothing here is wired into setup.py.
20
21The tables below are ports of C++ and kernel-source lists.  tools/test_qwen4_intake.py reads the C++ files and fails when a table
22here no longer matches them, so they cannot drift quietly.
23"""
24from __future__ import annotations
25
26import argparse
27import concurrent.futures
28import dataclasses
29import hashlib
30import json
31import math
32import os
33import pathlib
34import re
35import sys
36import time
37import urllib.parse
38import urllib.request
39
40HERE = pathlib.Path(__file__).resolve().parent
41ROOT = HERE.parent
42sys.path.insert(0, str(HERE))
43import gguf_reader as G  # noqa: E402
44import quant_formats as QF  # noqa: E402
45
46if str(ROOT) not in sys.path:
47    sys.path.append(str(ROOT))
48
49TOOL_VERSION = 1
50
51# ====================================================================================================== geometry (port)
52# include/strata/core/geometry.hpp: ModelGeometry.  The defaults are Qwen3.8-Flash-Next's, the shape the kernels are compiled for.
53
54
55@dataclasses.dataclass
56class Geometry:
57    n_embd: int = 2560
58    n_layers: int = 48
59    qsa_interval: int = 4
60    n_vocab: int = 248320
61    rms_eps: float = 1e-6
62    ssm_state_size: int = 128
63    ssm_k_heads: int = 16
64    ssm_v_heads: int = 48
65    ssm_d_conv: int = 4
66    ssm_conv_channels: int = 10240
67    ssm_value_dim: int = 6144
68    n_head: int = 24
69    n_head_kv: int = 2
70    head_dim: int = 256
71    n_rot: int = 64
72    idx_q_heads: int = 4
73    idx_key_dim: int = 128
74    idx_block: int = 4
75    idx_top_k: int = 2048
76    hc: int = 4
77    hc_lr: int = 320
78    n_expert: int = 512
79    n_expert_used: int = 10
80    n_ff: int = 640
81    n_ff_shexp: int = 640
82    family: str = "qwen4exp"
83    n_mtp_layers: int = 0
84
85    @property
86    def has_indexer(self) -> bool:
87        return self.idx_q_heads > 0
88
89    @property
90    def has_hc(self) -> bool:
91        return self.hc > 0
92
93    @property
94    def hc_dim(self) -> int:
95        return self.hc * self.n_embd
96
97    def is_qsa(self, layer: int) -> bool:
98        return layer % self.qsa_interval == self.qsa_interval - 1
99
100    def kind(self, layer: int) -> str:
101        if layer >= self.n_layers:
102            return "mtp"
103        return "attention" if self.is_qsa(layer) else "gdn"
104
105
106COMPILED = Geometry()
107
108# include/strata/artifact/model_family.hpp
109FAMILY_ARCH = {"qwen4exp": "qwen4exp", "qwen35moe": "qwen35moe"}
110FAMILY_TITLE = {"qwen4exp": "Qwen3.8-Flash-Next", "qwen35moe": "Qwen3.6-35B-A3B"}
111# model_family_runs() is true for qwen4exp only; qwen35moe has the src/qwen35 path the CUDA and HIP builds switch to.  The SYCL
112# build refuses it (model_family_not_supported); Metal has no such path (docs: "Metal and Intel Arc have no such path").
113FAMILY_BACKENDS = {"qwen4exp": ["cuda", "hip", "sycl", "metal"], "qwen35moe": ["cuda", "hip"]}
114# Other architectures Strata runs with an engine of its own: never a Qwen4 path.
115OTHER_ENGINES = {"deepseek41": "strata-dsv41 (setup.py MULTI_FILE_FAMILIES): a separate engine, not the Qwen3.8 / Qwen3.6 paths"}
116
117# read_geometry() (gguf_reader.hpp): key -> (field, required), under "<arch>."
118QWEN4_KEYS = [
119    ("block_count", "n_layers", True), ("embedding_length", "n_embd", True), ("expert_count", "n_expert", True),
120    ("expert_used_count", "n_expert_used", True), ("attention.head_count", "n_head", True),
121    ("attention.head_count_kv", "n_head_kv", True), ("full_attention_interval", "qsa_interval", False),
122    ("ssm.state_size", "ssm_state_size", False), ("ssm.group_count", "ssm_k_heads", False),
123    ("ssm.time_step_rank", "ssm_v_heads", False), ("ssm.conv_kernel", "ssm_d_conv", False),
124    ("ssm.inner_size", "ssm_value_dim", False), ("attention.key_length", "head_dim", False),
125    ("rope.dimension_count", "n_rot", False), ("attention.indexer.head_count", "idx_q_heads", False),
126    ("attention.indexer.key_length", "idx_key_dim", False), ("attention.indexer.top_k", "idx_top_k", False),
127    ("hyper_connection.count", "hc", False), ("hyper_connection.low_rank", "hc_lr", False),
128    ("expert_feed_forward_length", "n_ff", False),
129]
130# geometry_unsupported() pins + compiled_geometry_mismatch(): the fields the kernels are compiled for, with the GGUF key they come from
131PINNED = [
132    ("block_count", "n_layers"), ("embedding_length", "n_embd"), ("full_attention_interval", "qsa_interval"),
133    ("ssm.state_size", "ssm_state_size"), ("ssm.group_count", "ssm_k_heads"), ("ssm.time_step_rank", "ssm_v_heads"),
134    ("ssm.conv_kernel", "ssm_d_conv"), ("ssm.inner_size", "ssm_value_dim"), ("attention.head_count", "n_head"),
135    ("attention.head_count_kv", "n_head_kv"), ("attention.key_length", "head_dim"), ("rope.dimension_count", "n_rot"),
136    ("attention.indexer.head_count", "idx_q_heads"), ("attention.indexer.key_length", "idx_key_dim"),
137    ("attention.compress_ratios", "idx_block"), ("attention.indexer.top_k", "idx_top_k"),
138    ("hyper_connection.count", "hc"), ("hyper_connection.low_rank", "hc_lr"), ("expert_feed_forward_length", "n_ff"),
139    ("expert_shared_feed_forward_length", "n_ff_shexp"),
140]
141QWEN35_REQUIRED = [
142    "block_count", "embedding_length", "attention.head_count", "attention.head_count_kv", "attention.key_length",
143    "attention.value_length", "expert_count", "expert_used_count", "expert_feed_forward_length",
144    "expert_shared_feed_forward_length", "ssm.conv_kernel", "ssm.state_size", "ssm.group_count", "ssm.time_step_rank",
145    "ssm.inner_size", "full_attention_interval", "nextn_predict_layers",
146]
147# src/qwen35/q36_engine.cu load(): "a geometry this driver's kernels do not take"
148QWEN35_LIMITS = [("attention.key_length", "head_dim", "==", 256), ("ssm.state_size", "ssm_state_size", "==", 128),
149                 ("ssm.conv_kernel", "ssm_d_conv", "==", 4), ("expert_count", "n_expert", "<=", 512),
150                 ("expert_used_count", "n_expert_used", "<=", 15)]
151
152
153def _num(v) -> bool:
154    return isinstance(v, (int, float)) and not isinstance(v, bool)
155
156
157def _int_key(md: dict, key: str, required: bool, default, problems: list):
158    v = md.get(key)
159    if v is None:
160        if required:
161            problems.append("missing " + key)
162        return default
163    if not isinstance(v, int) or isinstance(v, bool):
164        problems.append(key + " is not an integer")
165        return default
166    if v <= 0:
167        problems.append("%s = %d, it must be positive" % (key, v))
168        return default
169    return v
170
171
172def geometry_qwen4(md: dict, arch: str, ntokens: int | None) -> tuple[Geometry, list]:
173    """gguf_reader.hpp read_geometry(), for the keys under "<arch>." (the real qwen4exp guard when arch is 'qwen4exp')."""
174    g, problems, p = Geometry(), [], arch + "."
175    for key, field, required in QWEN4_KEYS:
176        setattr(g, field, _int_key(md, p + key, required, getattr(g, field), problems))
177    vlen = _int_key(md, p + "attention.value_length", False, g.head_dim, problems)
178    shexp = _int_key(md, p + "expert_shared_feed_forward_length", False, g.n_ff, problems)
179    if problems:
180        return g, problems
181    if vlen != g.head_dim:
182        problems.append("%sattention.value_length = %d and attention.key_length = %d: the attention kernels use one head width for both"
183                        % (p, vlen, g.head_dim))
184    g.n_ff_shexp = shexp
185    if shexp != g.n_ff:
186        problems.append("%sexpert_shared_feed_forward_length = %d and expert_feed_forward_length = %d: the shared expert is read "
187                        "with the routed experts' width" % (p, shexp, g.n_ff))
188    eps = md.get(p + "attention.layer_norm_rms_epsilon")
189    if eps is not None:
190        if not _num(eps) or not eps > 0:
191            problems.append(p + "attention.layer_norm_rms_epsilon must be a positive number")
192        else:
193            g.rms_eps = float(eps)
194    if ntokens:
195        g.n_vocab = ntokens
196    if g.n_head % g.n_head_kv:
197        problems.append("%sattention.head_count = %d is not a multiple of head_count_kv = %d" % (p, g.n_head, g.n_head_kv))
198    if g.ssm_value_dim != g.ssm_state_size * g.ssm_v_heads:
199        problems.append("%sssm.inner_size = %d, but ssm.state_size x ssm.time_step_rank = %d: the GDN kernels take square heads"
200                        % (p, g.ssm_value_dim, g.ssm_state_size * g.ssm_v_heads))
201    g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim
202    if g.n_expert_used > g.n_expert or g.n_expert_used > 64:
203        problems.append("%sexpert_used_count = %d, the router takes 1..%d of %d experts"
204                        % (p, g.n_expert_used, min(g.n_expert, 64), g.n_expert))
205    if g.n_rot > g.head_dim or g.n_rot > g.idx_key_dim or g.n_rot % 2:
206        problems.append("%srope.dimension_count = %d is not an even slice of the head widths" % (p, g.n_rot))
207    ratios = md.get(p + "attention.compress_ratios")
208    if ratios is not None:
209        if not isinstance(ratios, list) or len(ratios) != g.n_layers:
210            problems.append("%sattention.compress_ratios must list one entry for each of the %d layers" % (p, g.n_layers))
211        elif any(ratios):                       # an all-zero list is a converter's placeholder (#2396): treated as absent
212            block = 0
213            for l, r in enumerate(ratios):
214                if (r != 0) != g.is_qsa(l) or r < 0 or (block and r and r != block):
215                    problems.append("%sattention.compress_ratios[%d] = %d, but full_attention_interval = %d makes layer %d %s"
216                                    % (p, l, r, g.qsa_interval, l, "full attention" if g.is_qsa(l) else "linear attention"))
217                    break
218                if r:
219                    block = r
220            if block:
221                g.idx_block = block
222    return g, problems
223
224
225def geometry_qwen35(md: dict, arch: str, ntokens: int | None) -> tuple[Geometry, list]:
226    """family_layout.hpp geometry_from_gguf() after check_architecture_qwen35moe()."""
227    p, problems = arch + ".", []
228    for k in QWEN35_REQUIRED:
229        v = md.get(p + k)
230        if v is None:
231            problems.append("missing " + p + k)
232        elif not _num(v):
233            problems.append(p + k + " is not a number")
234    g = Geometry(family="qwen35moe")
235    if problems:
236        return g, problems
237    mtp, nl = int(md[p + "nextn_predict_layers"]), int(md[p + "block_count"])
238    if mtp >= nl:
239        problems.append(p + "nextn_predict_layers is not smaller than " + p + "block_count")
240    if int(md[p + "full_attention_interval"]) < 2:
241        problems.append(p + "full_attention_interval must be at least 2 (the GDN / attention pattern)")
242    g.n_embd, g.n_head, g.n_head_kv = int(md[p + "embedding_length"]), int(md[p + "attention.head_count"]), int(md[p + "attention.head_count_kv"])
243    g.head_dim, g.n_expert, g.n_expert_used = int(md[p + "attention.key_length"]), int(md[p + "expert_count"]), int(md[p + "expert_used_count"])
244    g.n_ff, g.n_ff_shexp = int(md[p + "expert_feed_forward_length"]), int(md[p + "expert_shared_feed_forward_length"])
245    g.ssm_d_conv, g.ssm_state_size, g.ssm_k_heads = int(md[p + "ssm.conv_kernel"]), int(md[p + "ssm.state_size"]), int(md[p + "ssm.group_count"])
246    g.ssm_v_heads, g.ssm_value_dim, g.qsa_interval = int(md[p + "ssm.time_step_rank"]), int(md[p + "ssm.inner_size"]), int(md[p + "full_attention_interval"])
247    g.n_mtp_layers, g.hc, g.hc_lr, g.idx_q_heads, g.idx_key_dim = mtp, 0, 0, 0, 0
248    g.n_layers = nl - mtp
249    g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim
250    if ntokens:
251        g.n_vocab = ntokens
252    v = md.get(p + "rope.dimension_count")
253    if _num(v):
254        g.n_rot = int(v)
255    if (g.n_layers <= 0 or g.n_embd <= 0 or g.n_head <= 0 or g.n_head_kv <= 0 or g.head_dim <= 0 or g.n_expert <= 0 or
256            g.n_expert_used <= 0 or g.n_expert_used > g.n_expert or g.n_ff <= 0 or g.ssm_state_size <= 0 or g.ssm_k_heads <= 0 or
257            g.ssm_v_heads <= 0 or g.ssm_d_conv <= 0 or g.qsa_interval < 2):
258        problems.append("a geometry key is zero or out of range")
259        return g, problems
260    if int(md[p + "attention.value_length"]) != g.head_dim:
261        problems.append("attention.key_length != attention.value_length")
262    if g.ssm_value_dim != g.ssm_state_size * g.ssm_v_heads:
263        problems.append("ssm.inner_size != ssm.state_size * ssm.time_step_rank")
264    if g.ssm_v_heads % g.ssm_k_heads:
265        problems.append("ssm.time_step_rank is not a multiple of ssm.group_count")
266    if g.n_head % g.n_head_kv:
267        problems.append("attention.head_count is not a multiple of attention.head_count_kv")
268    if g.n_layers % g.qsa_interval:
269        problems.append("the layer count is not a multiple of full_attention_interval")
270    return g, problems
271
272
273def shape_differences(g: Geometry, arch: str) -> list[dict]:
274    """Every pinned field that differs from the compiled shape (the engine's guard names only the first)."""
275    out = []
276    for key, field in PINNED:
277        got, want = getattr(g, field), getattr(COMPILED, field)
278        if field == "idx_block" and not g.has_indexer:
279            continue
280        if got != want:
281            out.append({"key": arch + "." + key, "field": field, "got": got, "kernels_built_for": want})
282    if abs(g.rms_eps - COMPILED.rms_eps) > 1e-6 * COMPILED.rms_eps:
283        out.append({"key": arch + ".attention.layer_norm_rms_epsilon", "field": "rms_eps", "got": g.rms_eps,
284                    "kernels_built_for": COMPILED.rms_eps})
285    return out
286
287
288def qwen35_limit_violations(g: Geometry, arch: str) -> list[dict]:
289    out = []
290    for key, field, op, want in QWEN35_LIMITS:
291        got = getattr(g, field)
292        if (op == "==" and got != want) or (op == "<=" and got > want):
293            out.append({"key": arch + "." + key, "field": field, "got": got, "limit": "%s %d" % (op, want)})
294    return out
295
296
297# ====================================================================================================== layout tables (port)
298# include/strata/core/family_layout.hpp layer_tensors() / global_tensors(); shapes are GGUF order (dim 0 contiguous).
299
300
301def layer_tensors(g: Geometry, layer: int) -> list[tuple[str, list[int]]]:
302    kind = g.kind(layer)
303    N, NE, FF, FS = g.n_embd, g.n_expert, g.n_ff, g.n_ff_shexp
304    t = [("ffn_gate_inp.weight", [N, NE]), ("ffn_gate_inp_shexp.weight", [N]), ("ffn_gate_shexp.weight", [N, FS]),
305         ("ffn_up_shexp.weight", [N, FS]), ("ffn_down_shexp.weight", [FS, N]), ("ffn_gate_exps.weight", [N, FF, NE]),
306         ("ffn_up_exps.weight", [N, FF, NE]), ("ffn_down_exps.weight", [FF, N, NE])]
307    if g.has_hc:
308        H = g.hc_dim
309        t += [("hc_attn_down.weight", [H, g.hc_lr]), ("hc_attn_up.weight", [g.hc_lr, H]), ("hc_attn_inject.weight", [H, g.hc]),
310              ("hc_attn_norm.weight", [H]), ("hc_ffn_down.weight", [H, g.hc_lr]), ("hc_ffn_up.weight", [g.hc_lr, H]),
311              ("hc_ffn_inject.weight", [H, g.hc]), ("hc_ffn_norm.weight", [H])]
312    else:
313        t += [("attn_norm.weight", [N]), ("post_attention_norm.weight", [N])]
314    if kind == "gdn":
315        t += [("attn_qkv.weight", [N, g.ssm_conv_channels]), ("attn_gate.weight", [N, g.ssm_value_dim]),
316              ("ssm_out.weight", [g.ssm_value_dim, N]), ("ssm_conv1d.weight", [g.ssm_d_conv, g.ssm_conv_channels]),
317              ("ssm_alpha.weight", [N, g.ssm_v_heads]), ("ssm_beta.weight", [N, g.ssm_v_heads]), ("ssm_a", [g.ssm_v_heads]),
318              ("ssm_dt.bias", [g.ssm_v_heads]), ("ssm_norm.weight", [g.ssm_state_size])]
319    else:
320        t += [("attn_q.weight", [N, 2 * g.n_head * g.head_dim]), ("attn_k.weight", [N, g.n_head_kv * g.head_dim]),
321              ("attn_v.weight", [N, g.n_head_kv * g.head_dim]), ("attn_output.weight", [g.n_head * g.head_dim, N]),
322              ("attn_q_norm.weight", [g.head_dim]), ("attn_k_norm.weight", [g.head_dim])]
323        if g.has_indexer and kind == "attention":
324            t += [("indexer.q_proj.weight", [N, g.idx_q_heads * g.idx_key_dim]), ("indexer.k_proj.weight", [N, g.idx_key_dim]),
325                  ("indexer.q_norm.weight", [g.idx_key_dim]), ("indexer.k_norm.weight", [g.idx_key_dim])]
326    if kind == "mtp":
327        t += [("nextn.eh_proj.weight", [2 * N, N]), ("nextn.enorm.weight", [N]), ("nextn.hnorm.weight", [N]),
328              ("nextn.shared_head_norm.weight", [N])]
329    return t
330
331
332def global_tensors(g: Geometry) -> list[tuple[str, list[int]]]:
333    t = [("token_embd.weight", [g.n_embd, g.n_vocab]), ("output.weight", [g.n_embd, g.n_vocab])]
334    if g.has_hc:
335        t += [("output_hc_down.weight", [g.hc_dim, g.hc_lr]), ("output_hc_up.weight", [g.hc_lr, g.hc_dim]),
336              ("output_hc_norm.weight", [g.hc_dim])]
337    else:
338        t.append(("output_norm.weight", [g.n_embd]))
339    return t
340
341
342# layout_table_complete(): only qwen35moe's table names every tensor.  Flash-Next's published files also carry these (its PLE and
343# n-gram tables, which "the loaders check"): known, not errors.  Anything else is an unknown tensor.
344QWEN4_UNLISTED = re.compile(r"^(per_layer_token_embd\.weight|blk\.\d+\.ple_(conv1d|key|value|norm_conv|norm_key|norm_query)\.weight)$")
345
346
347def check_layout(tensors: dict[str, list[int]], g: Geometry, complete: bool) -> dict:
348    wanted: dict[str, list[int]] = dict(global_tensors(g))
349    for l in range(g.n_layers + g.n_mtp_layers):
350        for name, shape in layer_tensors(g, l):
351            wanted["blk.%d.%s" % (l, name)] = shape
352    missing = sorted(n for n in wanted if n not in tensors)
353    reshaped = [{"name": n, "got": tensors[n], "want": s} for n, s in wanted.items() if n in tensors and list(tensors[n]) != s]
354    extra, known = [], []
355    for n in sorted(tensors):
356        if n in wanted:
357            continue
358        if not complete and QWEN4_UNLISTED.match(n):
359            known.append(n)
360        else:
361            extra.append(n)
362    return {"wanted": len(wanted), "found": len(wanted) - len(missing), "missing": missing, "reshaped": reshaped,
363            "unknown": extra, "known_unlisted": len(known), "ok": not (missing or reshaped or extra)}
364
365
366# ====================================================================================================== quant support (port)
367# ggml type ids -> names come from tools/gguf_reader.py.  The lists below are copied from the kernel sources named beside them;
368# tools/test_qwen4_intake.py parses those files and compares.
369
370TYPE_NAME = G.GGML_TYPES
371SMALL_OK = {0, 1, 30}            # F32, F16, BF16: norms, router, biases, the SSM vectors (q36_engine.cu f32(): F32 / BF16 / F16 / Q8_0)
372MMVQ = {2, 6, 7, 8, 11, 12, 13, 14, 20, 23, 42, 16, 17, 18, 21, 22, 29}        # native_mmvq_supported(): CUDA, SYCL and Metal host copy
373BACKEND_LISTS = {
374    # src/kernels/cuda/iq_kernels.cu: STRATA_GU_FMTS / STRATA_D_FMTS (STRATA_Q6K_EXPERTS=ON, the default) and is_iq().  The HIP
375    # build compiles this same file: AMD gfx11 / gfx12 / gfx1151 differ in kernel modes and speed, not in this list.
376    "cuda": {"gu": {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 6, 2, 3, 8, 40, 144, 145, 147, 148, 149},
377             "down": {20, 23, 42, 7, 6, 2, 3, 8, 13, 14, 40, 144, 146, 147, 148, 149},
378             "is_iq": {16, 17, 18, 20, 21, 22, 23, 29, 42, 11, 12, 13, 14, 7, 6, 2, 3, 8, 40, 144, 145, 146, 147, 148, 149},
379             "mmvq": MMVQ, "embed_extra": {30, 14}},
380    # sycl/src/kernels/cuda/iq_kernels.dp.cpp (the SYCL port; it has no NVFP4 or the Gyro-L pair-trellis types)
381    "sycl": {"gu": {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 6, 2, 3, 8, 144, 145},
382             "down": {20, 23, 42, 7, 6, 2, 3, 8, 13, 14, 144, 146},
383             "is_iq": {144, 145, 146, 16, 17, 18, 20, 21, 22, 23, 29, 42, 11, 12, 13, 14, 7, 6, 2, 3, 8},
384             "mmvq": MMVQ, "embed_extra": {30}},
385    # metal/src/engine/iq_host.cpp (host helpers; the kernels are mac-kern's, metal/src/engine/window.cpp: not audited)
386    "metal": {"gu": {16, 17, 18, 21, 22, 23, 29, 12, 13, 14, 42, 144, 145, 8},
387              "down": {23, 42, 144, 146, 20, 7, 6, 8, 11, 12, 13, 14, 21},
388              "is_iq": {16, 17, 18, 20, 21, 22, 23, 29, 42, 11, 12, 13, 14, 7, 6, 2, 3, 8, 144, 145, 146},
389              "mmvq": MMVQ, "embed_extra": {30}},
390}
391BACKEND_LISTS["hip"] = BACKEND_LISTS["cuda"]
392BACKEND_SOURCES = {
393    "cuda": "src/kernels/cuda/iq_kernels.cu (native_expert_supported), src/kernels/cuda/native_mmvq.cu (native_mmvq_supported)",
394    "hip": "the same two files as cuda (the HIP build compiles them)",
395    "sycl": "sycl/src/kernels/cuda/iq_kernels.dp.cpp, sycl/src/kernels/cuda/native_mmvq.dp.cpp",
396    "metal": "metal/src/engine/iq_host.cpp, metal/src/engine/mmvq_host.cpp (host helpers; Metal GEMV kernels not audited)",
397}
398
399
400def type_name(t: int) -> str:
401    return TYPE_NAME.get(t, "type%d" % t)
402
403
404def block_elems(t: int) -> int:
405    geom = G.BLOCK_GEOMETRY.get(type_name(t))
406    return geom[0] if geom else 0
407
408
409def expert_pair_ok(be: str, gu: int, down: int, n_embd: int, n_ff: int) -> bool:
410    """native_expert_supported(gu_type, d_type, n_embd, n_ff)."""
411    L = BACKEND_LISTS[be]
412    qg = block_elems(gu) if gu in L["gu"] else 0
413    qd = block_elems(down) if down in L["down"] else 0
414    return bool(qg > 0 and qd > 0 and gu in L["is_iq"] and down in L["is_iq"] and n_embd % qg == 0 and n_ff % qd == 0 and
415                n_embd % 256 == 0 and (n_ff * n_embd) % 256 == 0)
416
417
418ROLE_PATTERNS = [
419    ("routed_gate", re.compile(r"ffn_gate_exps\.weight$")), ("routed_up", re.compile(r"ffn_up_exps\.weight$")),
420    ("routed_down", re.compile(r"ffn_down_exps\.weight$")),
421    ("token_embedding", re.compile(r"^(token_embd|per_layer_token_embd)\.weight$")),
422    ("indexer", re.compile(r"\.indexer\.(q|k)_proj\.weight$")),
423]
424
425
426def tensor_role(name: str, shape: list[int]) -> str:
427    for role, pat in ROLE_PATTERNS:
428        if pat.search(name):
429            return role
430    if len(shape) == 1 or re.search(r"(norm\.weight|_norm\.weight|ssm_a|ssm_dt\.bias|ffn_gate_inp\.weight|ffn_gate_inp_shexp\.weight|"
431                                    r"ssm_alpha\.weight|ssm_beta\.weight|ssm_conv1d\.weight|ple_conv1d\.weight|hc_(attn|ffn)_inject\.weight)$", name):
432        return "small"
433    return "dense"
434
435
436def analyse_quants(tensors: list[tuple[str, list[int], int]], g: Geometry | None, family: str | None) -> dict:
437    """Each quant type against what each backend has kernels for, by role.  `tensors`: (name, shape, ggml type)."""
438    by_type: dict[str, int] = {}
439    roles: dict[str, dict[str, int]] = {}
440    per_layer: dict[int, dict[str, int]] = {}
441    for name, shape, ty in tensors:
442        tn = type_name(ty)
443        by_type[tn] = by_type.get(tn, 0) + 1
444        role = tensor_role(name, shape)
445        roles.setdefault(role, {})
446        roles[role][tn] = roles[role].get(tn, 0) + 1
447        m = re.match(r"blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$", name)
448        if m:
449            per_layer.setdefault(int(m.group(1)), {})[m.group(2)] = ty
450    backends = ["cuda", "hip", "sycl", "metal"]
451    result = {"types": dict(sorted(by_type.items(), key=lambda kv: -kv[1])), "roles": roles, "backends": {}, "unknown_types": [],
452              "expert_combinations": []}
453    combos: dict[tuple, list[int]] = {}
454    for l, d in sorted(per_layer.items()):
455        combos.setdefault((d.get("gate"), d.get("up"), d.get("down")), []).append(l)
456    for (gt, ut, dt), layers in combos.items():
457        result["expert_combinations"].append({"gate": type_name(gt) if gt is not None else None, "up": type_name(ut) if ut is not None else None,
458                                              "down": type_name(dt) if dt is not None else None, "layers": len(layers),
459                                              "first_layer": layers[0]})
460    seen_unknown = {ty for _, _, ty in tensors if ty not in G.GGML_TYPES}
461    anywhere = set(SMALL_OK) | {8}
462    for L in BACKEND_LISTS.values():
463        anywhere |= L["is_iq"] | L["mmvq"] | L["embed_extra"] | L["gu"] | L["down"]
464    nk: dict[int, dict] = {}
465    for name, shape, ty in tensors:
466        if ty not in anywhere and ty in G.GGML_TYPES:
467            e = nk.setdefault(ty, {"type": type_name(ty), "tensors": 0, "example": name})
468            e["tensors"] += 1
469    result["no_kernel_anywhere"] = list(nk.values())
470    result["unknown_types"] = sorted(seen_unknown)
471    allowed = FAMILY_BACKENDS.get(family or "", backends)
472    for be in backends:
473        L = BACKEND_LISTS[be]
474        bad: list[dict] = []
475        qwen35 = family == "qwen35moe"
476        for name, shape, ty in tensors:
477            role = tensor_role(name, shape)
478            why = None
479            if role == "small":
480                # qwen35moe (q36_engine.cu upload_f32): F32, BF16, F16 or Q8_0.  Flash-Next dequantizes small tensors with the generic
481                # dequantizer (dq_dispatch: the is_iq() list), which is why Gyro's Q5_K / Q6_K hyper-connection and SSM tensors run.
482                if ty not in SMALL_OK and ty != 8 and (qwen35 or ty not in L["is_iq"]):
483                    why = "a small tensor must be F32, F16, BF16 or Q8_0" + ("" if qwen35 else " or a type the generic dequantizer takes")
484            elif role == "indexer":
485                if ty not in SMALL_OK and ty not in L["mmvq"]:
486                    why = "no GEMV kernel for this type"
487            elif role == "token_embedding":
488                if ty not in L["is_iq"] and ty not in L["embed_extra"]:
489                    why = "not an embedding type (embed_type_supported)"
490            elif role == "dense":
491                ok = ty in L["mmvq"] or (not qwen35 and ty in SMALL_OK)       # Flash-Next also runs BF16 / F16 dense (bf16_gemv)
492                if not ok:
493                    why = "no native MMVQ kernel (native_mmvq_supported)"
494            if why:
495                bad.append({"tensor": name, "type": type_name(ty), "role": role, "why": why})
496        if g is not None:
497            for l, d in sorted(per_layer.items()):
498                gt, ut, dt = d.get("gate"), d.get("up"), d.get("down")
499                if None in (gt, ut, dt):
500                    continue
501                if gt != ut:
502                    bad.append({"tensor": "blk.%d.ffn_gate_exps / ffn_up_exps" % l, "type": type_name(gt) + "/" + type_name(ut),
503                                "role": "routed", "why": "gate and up differ in type"})
504                elif not expert_pair_ok(be, gt, dt, g.n_embd, g.n_ff):
505                    bad.append({"tensor": "blk.%d.ffn_*_exps" % l, "type": "%s/%s" % (type_name(gt), type_name(dt)), "role": "routed",
506                                "why": "no expert kernel for this gate+up / down pair at n_embd %d, n_ff %d (native_expert_supported)"
507                                       % (g.n_embd, g.n_ff)})
508        # group the identical complaints
509        grouped: dict[tuple, dict] = {}
510        for b in bad:
511            k = (b["type"], b["role"], b["why"])
512            e = grouped.setdefault(k, {"type": b["type"], "role": b["role"], "why": b["why"], "tensors": 0, "example": b["tensor"]})
513            e["tensors"] += 1
514        result["backends"][be] = {"family_runs_here": be in allowed, "all_types_supported": not bad,
515                                  "unsupported": list(grouped.values()), "source": BACKEND_SOURCES[be]}
516    return result
517
518
519# ====================================================================================================== tokenizer, template
520# Flash-Next's tokenizer (recorded from unsloth/Qwen3.8-Flash-Next-GGUF; Qwen3.6-35B-A3B's is the same vocabulary)
521REF_TOKENIZER = {
522    "n_vocab": 248320, "n_merges": 247587, "pre": "qwen35",
523    "tokens_sha256": "f307bf31f9c6130c016bc12538b9eea8877540d705167d1add3a2cb5605bf9a0",
524    "merges_sha256": "4ba698529766c7a2f5052083ea10cdf2485577f5237a332ee291054eb11e3332",
525    "bos": 248044, "eos": 248046, "pad_flash_next": 248044, "pad_qwen36": 248055,
526    "key_tokens": {"<|endoftext|>": 248044, "<|im_start|>": 248045, "<|im_end|>": 248046, "<|vision_start|>": 248053,
527                   "<|vision_end|>": 248054, "<|image_pad|>": 248056, "<tool_call>": 248058, "</tool_call>": 248059,
528                   "<tool_response>": 248066, "</tool_response>": 248067, "<think>": 248068, "</think>": 248069},
529}
530KNOWN_TEMPLATES = {
531    "12827f24b742": "Qwen3.8-Flash-Next (serve/chat_template.jinja; also the Unsloth, GSQ-RCO, Coder and Gyro files)",
532    "c3cf9e34abf4": "Swift 1.5",
533    "55d4931433fe": "Qwen3.6-35B-A3B (Unsloth MTP files)",
534    "06cada875e3a": "DeepSeek-V4.1-Flash (Unsloth)",
535}
536
537
538def tokenizer_report(md: dict, build: bool, text_probe: bool = True) -> dict:
539    import strata_tokenizer as ST
540    toks = md.get("tokenizer.ggml.tokens")
541    merges = md.get("tokenizer.ggml.merges")
542    types = md.get("tokenizer.ggml.token_type")
543    pre = md.get("tokenizer.ggml.pre")
544    r: dict = {"model": md.get("tokenizer.ggml.model"), "pre": pre, "pre_rule": ST.pre_tokenizer_kind(pre),
545               "n_tokens": len(toks) if isinstance(toks, list) else None, "n_merges": len(merges) if isinstance(merges, list) else None,
546               "bos": md.get("tokenizer.ggml.bos_token_id"), "eos": md.get("tokenizer.ggml.eos_token_id"),
547               "pad": md.get("tokenizer.ggml.padding_token_id"), "add_bos": md.get("tokenizer.ggml.add_bos_token")}
548    if not isinstance(toks, list):
549        r["problems"] = ["the file carries no tokenizer.ggml.tokens"]
550        return r
551    r["tokens_sha256"] = hashlib.sha256("\n".join(toks).encode()).hexdigest()
552    if isinstance(merges, list):
553        r["merges_sha256"] = hashlib.sha256("\n".join(merges).encode()).hexdigest()
554    special = []
555    counts: dict[int, int] = {}
556    if isinstance(types, list):
557        for i, ty in enumerate(types):
558            counts[ty] = counts.get(ty, 0) + 1
559            if ty in (3, 4) and i < len(toks):
560                special.append((i, toks[i], ty))
561    r["token_type_counts"] = {str(k): v for k, v in sorted(counts.items())}
562    r["n_special"] = len(special)
563    r["same_vocabulary_as_flash_next"] = (r["tokens_sha256"] == REF_TOKENIZER["tokens_sha256"] and
564                                          r.get("merges_sha256") == REF_TOKENIZER["merges_sha256"])
565    by_text = {t: i for i, t, _ in special}
566    diffs = []
567    for text, want in REF_TOKENIZER["key_tokens"].items():
568        got = by_text.get(text)
569        if got != want:
570            diffs.append({"token": text, "flash_next_id": want, "this_file": got})
571    r["key_token_differences"] = diffs
572    r["end_of_turn_id"] = by_text.get("<|im_end|>")
573    problems = []
574    if r["model"] != "gpt2":
575        problems.append("tokenizer.ggml.model is %r; tools/strata_tokenizer.py builds the byte-level BPE ('gpt2') only" % (r["model"],))
576    if r["pre_rule"] is None:
577        problems.append("tokenizer.ggml.pre is %r: no splitting rule for it in tools/strata_tokenizer.py (knows qwen35, deepseek*)" % (pre,))
578    if not isinstance(merges, list):
579        problems.append("the file carries no tokenizer.ggml.merges")
580    r["problems"] = problems
581    r["builds"] = None
582    if build and not problems:
583        t0 = time.time()
584        try:
585            sp = {k: int(md[k]) for k in md if k.startswith("tokenizer.ggml.") and k.endswith("_token_id")}
586            tk = ST.Tokenizer(list(toks), list(merges), list(types) if isinstance(types, list) else None, pre, sp)
587            entry = {"ok": True, "seconds": round(time.time() - t0, 2)}
588            if text_probe and all(ch in tk.ids for ch in G_BYTE_CHARS):
589                probe = "def f(x):\n\treturn x  # café 你好\n"
590                ids = tk.encode(probe)
591                entry["roundtrip"] = tk.decode(ids) == probe
592                entry["probe_tokens"] = len(ids)
593            else:
594                entry["roundtrip"] = "skipped (the vocabulary lacks the 256 byte-level tokens)"
595            r["builds"] = entry
596        except Exception as e:  # noqa: BLE001 - the report names it
597            r["builds"] = {"ok": False, "error": "%s: %s" % (type(e).__name__, e)}
598    return r
599
600
601def _byte_chars():
602    import strata_tokenizer as ST
603    return sorted(ST.BYTE_TO_UNICODE.values())
604
605
606G_BYTE_CHARS = _byte_chars()
607
608
609def template_report(md: dict) -> dict:
610    from serve import toolformat
611    src = md.get("tokenizer.chat_template")
612    if not isinstance(src, str):
613        return {"present": False}
614    h = hashlib.sha256(src.encode()).hexdigest()
615    known = KNOWN_TEMPLATES.get(h[:12])
616    r = {"present": True, "sha256": h, "chars": len(src), "known_as": known, "tool_call_format": toolformat.tool_format(src)}
617    r.update(toolformat.thinking_tags(src))
618    local = ROOT / "serve" / "chat_template.jinja"
619    if local.is_file():
620        r["same_as_serve_chat_template"] = hashlib.sha256(local.read_bytes()).hexdigest() == h
621    return r
622
623
624# ====================================================================================================== reading the headers
625SHARD_RE = re.compile(r"^(?P<stem>.*)-(?P<no>\d{5})-of-(?P<n>\d{5})\.gguf$", re.I)
626
627
628@dataclasses.dataclass
629class FileInfo:
630    path: str                       # a local path, or "repo:path" for Hugging Face
631    name: str
632    size: int
633    header: object                  # a gguf_reader.GGUFFile / quant_formats.Header
634    sha256: str | None = None
635    sha256_source: str | None = None
636    url: str | None = None
637
638    @property
639    def md(self) -> dict:
640        return self.header.metadata
641
642    @property
643    def tensors(self):
644        return self.header.tensors
645
646
647def read_local(path: pathlib.Path) -> FileInfo:
648    h = G.GGUFFile(path)
649    return FileInfo(str(path), path.name, path.stat().st_size, h)
650
651
652def file_sha256(path: str) -> str:
653    d = hashlib.sha256()
654    with open(path, "rb") as f:
655        while True:
656            b = f.read(8 << 20)
657            if not b:
658                break
659            d.update(b)
660    return d.hexdigest()
661
662
663def hf_list(repo: str, rev: str, subdir: str = "") -> list[dict]:
664    base = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
665    url = "%s/api/models/%s/tree/%s/%s?recursive=true" % (base, repo, urllib.parse.quote(rev, safe=""), urllib.parse.quote(subdir.strip("/")))
666    out = []
667    while url:
668        req = urllib.request.urlopen(url, timeout=60)
669        out += json.load(req)
670        link = req.headers.get("Link", "")
671        m = re.search(r'<([^>]+)>;\s*rel="next"', link)
672        url = m.group(1) if m else None
673    return [e for e in out if e.get("type") == "file" and e["path"].lower().endswith(".gguf")]
674
675
676def read_hf_entry(repo: str, rev: str, e: dict) -> FileInfo:
677    base = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
678    url = "%s/%s/resolve/%s/%s" % (base, repo, rev, urllib.parse.quote(e["path"]))
679    h = QF.Header(e["path"], QF.RangeFile(url), int(e["size"]))
680    oid = (e.get("lfs") or {}).get("oid")
681    return FileInfo("%s:%s" % (repo, e["path"]), e["path"], int(e["size"]), h, oid, "Hugging Face LFS metadata" if oid else None, url)
682
683
684def group_sets(files: list[FileInfo]) -> list[list[FileInfo]]:
685    """A split model is one set (same folder, stem and shard count); everything else is a set of one."""
686    sets: dict[tuple, list[FileInfo]] = {}
687    order = []
688    for f in files:
689        m = SHARD_RE.match(os.path.basename(f.name))
690        key = (os.path.dirname(f.path), m.group("stem"), m.group("n")) if m else (f.path,)
691        if key not in sets:
692            sets[key] = []
693            order.append(key)
694        sets[key].append(f)
695    out = []
696    for key in order:
697        out.append(sorted(sets[key], key=lambda f: f.name))
698    return out
699
700
701# ====================================================================================================== the analysis
702def _arch_of(md: dict) -> str | None:
703    a = md.get("general.architecture")
704    return a if isinstance(a, str) else None
705
706
707def projector_report(f: FileInfo) -> dict:
708    try:
709        from strata_control.models import OUR_PROJECTOR_TYPES as ours
710    except Exception:  # noqa: BLE001 - the report must run from a bare tools/ copy
711        ours = {"qwen3vl_merger"}
712    md = f.md
713    pt = md.get("clip.projector_type")
714    return {"file": f.name, "size": f.size, "projector_type": pt, "ours": sorted(ours), "supported": pt in ours,
715            "projection_dim": md.get("clip.vision.projection_dim"), "image_size": md.get("clip.vision.image_size"),
716            "block_count": md.get("clip.vision.block_count"), "tensors": len(f.tensors)}
717
718
719def mtp_report(md: dict, arch: str | None, names: set[str], siblings: list[str]) -> dict:
720    p = (arch or "") + "."
721    n = md.get(p + "nextn_predict_layers")
722    in_file = bool(n) or any(".nextn." in x for x in names)
723    sep = [s for s in siblings if re.search(r"mtp|draft", s, re.I)]
724    return {"in_file_layers": int(n) if isinstance(n, int) else 0, "nextn_tensors": sorted(x for x in names if ".nextn." in x)[:8],
725            "in_file": in_file, "separate_drafter_files": sep}
726
727
728def general_report(md: dict) -> dict:
729    keys = ["name", "basename", "size_label", "quantized_by", "license", "license.link", "license.name", "repo_url", "url",
730            "file_type", "description", "type", "version", "finetune"]
731    out = {k: md["general." + k] for k in keys if ("general." + k) in md}
732    bases = {k: v for k, v in md.items() if k.startswith("general.base_model.")}
733    if bases:
734        out["base_model"] = bases
735    return out
736
737
738def is_drafter(files: list[FileInfo]) -> bool:
739    """A separate MTP drafter file (Unsloth's MTP/ folder, Gyro's mtp-*.gguf): the same architecture name as the model, but no
740    trunk layers, only the draft block (Unsloth's mtp-*.gguf: token_embd, output and blk.48 of a 49-block file)."""
741    names = {t.name for f in files for t in f.tensors}
742    return any(n.startswith("blk.") for n in names) and not any(n.startswith("blk.0.") for n in names)
743
744
745def drafter_report(files: list[FileInfo]) -> dict:
746    md = files[0].md
747    names = [t.name for f in files for t in f.tensors]
748    blks = sorted({int(m.group(1)) for n in names for m in [re.match(r"blk\.(\d+)\.", n)] if m})
749    types: dict[str, int] = {}
750    for f in files:
751        for t in f.tensors:
752            types[t.type_name] = types.get(t.type_name, 0) + 1
753    return {"files": [{"name": f.name, "path": f.path, "size": f.size, "tensors": len(f.tensors), "sha256": f.sha256} for f in files],
754            "architecture": _arch_of(md), "drafter": True, "size_bytes": sum(f.size for f in files), "tensor_count": len(names),
755            "block_indices": blks, "types": types, "general": general_report(md),
756            "verdict": {"case": "-", "reading": "a separate MTP drafter file, not a model", "path": None, "backends": [], "blockers": [],
757                        "warnings": [], "shape_fields_that_differ": [],
758                        "notes": ["drafter blocks %s of arch '%s': the Flash-Next drafter is packed by tools/mtp_pack.py (not checked here)" % (blks, _arch_of(md))]}}
759
760
761def analyse_set(files: list[FileInfo], siblings: list[str] | None = None, build_tokenizer: bool = True,
762                projectors: list[dict] | None = None) -> dict:
763    """The report for one set of files (the shards of one model).  Reads nothing but what the headers already hold."""
764    md = files[0].md
765    arch = _arch_of(md)
766    names: dict[str, list[int]] = {}
767    tlist: list[tuple[str, list[int], int]] = []
768    for f in files:
769        for t in f.tensors:
770            names[t.name] = list(t.shape)
771            tlist.append((t.name, list(t.shape), t.type_id))
772    rep: dict = {"files": [], "architecture": arch, "tensor_count": len(names), "size_bytes": sum(f.size for f in files)}
773    for f in files:
774        rep["files"].append({"name": f.name, "path": f.path, "size": f.size, "tensors": len(f.tensors), "gguf_version": f.header.version,
775                             "sha256": f.sha256, "sha256_source": f.sha256_source,
776                             "split_no": f.md.get("split.no"), "split_count": f.md.get("split.count")})
777    # ---- split completeness
778    split = {"count": md.get("split.count"), "found": len(files), "complete": True, "problems": []}
779    sc = md.get("split.count")
780    if isinstance(sc, int) and sc > 1:
781        nos = sorted(f.md.get("split.no") for f in files)
782        if nos != list(range(sc)):
783            split["complete"] = False
784            split["problems"].append("shards present: %s of %d" % ([n + 1 for n in nos if isinstance(n, int)], sc))
785        total = md.get("split.tensors.count")
786        if isinstance(total, int) and total != len(names):
787            split["complete"] = False
788            split["problems"].append("split.tensors.count is %d, the shards hold %d" % (total, len(names)))
789    elif len(files) > 1:
790        split["problems"].append("several files but no split.count key")
791    rep["split"] = split
792    rep["general"] = general_report(md)
793    # ---- the tokenizer and the template are in the metadata shard
794    rep["tokenizer"] = tokenizer_report(md, build_tokenizer)
795    rep["chat_template"] = template_report(md)
796    ntok = rep["tokenizer"].get("n_tokens")
797    # ---- family, geometry, layout
798    cand = []                               # (family, geometry, problems, layout)
799    pref = (arch or "") + "."
800    for fam in ("qwen4exp", "qwen35moe"):
801        if arch == fam:
802            order = [fam]
803        elif arch in OTHER_ENGINES or arch is None:
804            order = []
805        else:
806            order = ["qwen4exp", "qwen35moe"]                  # an unknown name: do the keys and tensors fit a known family?
807        if fam not in order:
808            continue
809        g, problems = (geometry_qwen4 if fam == "qwen4exp" else geometry_qwen35)(md, arch, ntok)
810        layout = check_layout(names, g, complete=(fam == "qwen35moe")) if not problems else None
811        cand.append((fam, g, problems, layout))
812    best = None
813    if cand:
814        scored = []
815        for fam, g, problems, layout in cand:
816            score = (len(problems) > 0, 0 if layout is None else len(layout["missing"]) + len(layout["reshaped"]) + len(layout["unknown"]))
817            scored.append((score, fam, g, problems, layout))
818        scored.sort(key=lambda x: x[0])
819        _, fam, g, problems, layout = scored[0]
820        best = (fam, g, problems, layout)
821    rep["family"] = best[0] if best else None
822    rep["geometry"] = None
823    rep["geometry_problems"] = best[2] if best else []
824    rep["layout"] = best[3] if best else None
825    rep["shape_differences"] = []
826    rep["qwen35_limit_violations"] = []
827    if best:
828        fam, g, problems, layout = best
829        rep["geometry"] = dataclasses.asdict(g)
830        rep["geometry"]["keys"] = {k[len(pref):]: v for k, v in md.items() if k.startswith(pref) and not isinstance(v, list)}
831        if not problems:
832            rep["shape_differences"] = shape_differences(g, arch) if fam == "qwen4exp" else []
833            if fam == "qwen35moe":
834                rep["qwen35_limit_violations"] = qwen35_limit_violations(g, arch)
835                ref = Geometry(n_embd=2048, n_layers=40, ssm_v_heads=32, ssm_value_dim=4096, n_head=16, n_ff=512, n_ff_shexp=512,
836                               n_expert=256, n_expert_used=8, n_mtp_layers=1, family="qwen35moe", hc=0, hc_lr=0, idx_q_heads=0, idx_key_dim=0)
837                rep["differs_from_qwen36_35b"] = [f.name for f in dataclasses.fields(Geometry)
838                                                   if f.name not in ("n_vocab", "rms_eps", "n_rot", "idx_block", "idx_top_k", "ssm_conv_channels")
839                                                   and getattr(g, f.name) != getattr(ref, f.name)]
840    rep["quant"] = analyse_quants(tlist, best[1] if best and not best[2] else None, rep["family"])
841    # embedding rows must match the vocabulary (a file whose tokenizer and embedding disagree is not usable)
842    emb = names.get("token_embd.weight")
843    rep["vocab_matches_embedding"] = None if not emb or not ntok else (emb[-1] == ntok)
844    rep["mtp"] = mtp_report(md, arch, set(names), siblings or [])
845    rep["projectors"] = projectors or []
846    # ---- the verdict, the draft catalog entry and the setup config
847    rep["verdict"] = verdict(rep, arch)
848    rep["draft_catalog_entry"], rep["draft_setup_config"] = draft_entry(rep, files, arch)
849    return rep
850
851
852def verdict(rep: dict, arch: str | None) -> dict:
853    blockers, warnings, notes = [], [], []
854    fam = rep["family"]
855    case, path, backends = "C", None, []
856    tk, qt = rep["tokenizer"], rep["quant"]
857    if arch is None:
858        blockers.append("the file has no general.architecture")
859    elif arch in OTHER_ENGINES:
860        blockers.append("architecture '%s' is %s" % (arch, OTHER_ENGINES[arch]))
861    # ---- the model part
862    shape_fields = rep["shape_differences"]
863    if fam is not None:
864        if arch not in FAMILY_ARCH and (rep["geometry_problems"] or (rep["layout"] is not None and not rep["layout"]["ok"])):
865            blockers.append("architecture '%s' is not a name Strata knows, and it does not fit %s either" % (arch, FAMILY_TITLE[fam]))
866        if rep["geometry_problems"]:
867            blockers += ["geometry: " + p for p in rep["geometry_problems"][:8]]
868        lay = rep["layout"]
869        if lay is not None and not lay["ok"]:
870            if lay["unknown"]:
871                blockers.append("%d tensors the %s layout does not name: %s" % (len(lay["unknown"]), FAMILY_TITLE[fam], ", ".join(lay["unknown"][:6])))
872            if lay["missing"]:
873                blockers.append("%d tensors the %s layout wants are missing: %s" % (len(lay["missing"]), FAMILY_TITLE[fam], ", ".join(lay["missing"][:6])))
874            if lay["reshaped"]:
875                r = lay["reshaped"][0]
876                blockers.append("%d tensors have another shape than the %s layout (first: %s is %s, wants %s)"
877                                % (len(lay["reshaped"]), FAMILY_TITLE[fam], r["name"], r["got"], r["want"]))
878    elif arch is not None and arch not in OTHER_ENGINES:
879        blockers.append("architecture '%s' is not a family Strata knows and no key set fits qwen4exp or qwen35moe" % arch)
880    # ---- dense / expert-less models
881    md_experts = rep["geometry"]["n_expert"] if rep["geometry"] else None
882    if rep["quant"]["roles"].get("routed_gate") is None and rep["tensor_count"] and fam is not None:
883        blockers.append("no routed expert tensors: a dense model is a new engine path")
884    # ---- quant support
885    allowed = FAMILY_BACKENDS.get(fam or "", [])
886    usable = [b for b in allowed if qt["backends"][b]["all_types_supported"]]
887    if fam is not None and not rep["geometry_problems"] and not usable:
888        merged: dict[tuple, list] = {}
889        for b in allowed:
890            for u in qt["backends"][b]["unsupported"][:3]:
891                merged.setdefault((u["role"], u["type"], u["tensors"], u["example"], u["why"]), []).append(b)
892        for (role, ty, n, ex, why), bs in merged.items():
893            blockers.append("%s: %s %s (%d tensors, e.g. %s): %s" % ("/".join(bs), role, ty, n, ex, why))
894    elif fam is not None:
895        for b in allowed:
896            if b not in usable:
897                us = qt["backends"][b]["unsupported"]
898                notes.append("%s cannot run this file: %s" % (b, "; ".join("%s %s (%d)" % (u["role"], u["type"], u["tensors"]) for u in us[:4])))
899    for u in qt["no_kernel_anywhere"]:
900        blockers.append("quant type %s (%d tensors, e.g. %s) has no kernel in any backend's list" % (u["type"], u["tensors"], u["example"]))
901    if qt["unknown_types"]:
902        blockers.append("ggml type ids this tools/gguf_reader.py does not know: %s" % qt["unknown_types"])
903    # ---- the tokenizer
904    for p in tk.get("problems", []):
905        blockers.append("tokenizer: " + p)
906    if tk.get("builds") and not tk["builds"].get("ok"):
907        blockers.append("tokenizer: tools/strata_tokenizer.py cannot build it: " + tk["builds"].get("error", ""))
908    if tk.get("builds") and tk["builds"].get("ok") and tk["builds"].get("roundtrip") is False:
909        blockers.append("tokenizer: encode + decode of a probe string does not return the string")
910    if rep["vocab_matches_embedding"] is False:
911        blockers.append("tokenizer: %s tokens but the embedding has another number of rows" % tk.get("n_tokens"))
912    if tk.get("n_tokens") and not tk.get("same_vocabulary_as_flash_next") and not tk.get("problems"):
913        notes.append("the vocabulary is not Flash-Next's (%d tokens): check the special tokens and stop ids; %d key tokens differ"
914                     % (tk["n_tokens"], len(tk["key_token_differences"])))
915    # ---- the template
916    ct = rep["chat_template"]
917    if not ct.get("present"):
918        warnings.append("no chat template in the file")
919    elif ct["tool_call_format"] in ("other",):
920        warnings.append("the chat template documents tool calls in a form no parser handles (tool_call_format: other)")
921    elif ct["tool_call_format"] == "json":
922        notes.append("tool calls are the JSON form: the server's JSON parser is used (serve/frontend.py parser_for_template)")
923    elif ct["tool_call_format"] == "dsml":
924        warnings.append("DSML tool calls belong to the DeepSeek engine")
925    # ---- split, projector
926    if not rep["split"]["complete"]:
927        blockers.append("split set incomplete: " + "; ".join(rep["split"]["problems"]))
928    for pr in rep["projectors"]:
929        if not pr["supported"]:
930            warnings.append("picture reader %s has projector type %r, not %s: pictures off (a new vision tower)" % (pr["file"], pr["projector_type"], pr["ours"]))
931    # ---- the case
932    if blockers:
933        case = "C"
934    else:
935        if fam == "qwen4exp":
936            case = "B" if shape_fields else "A"
937        elif fam == "qwen35moe":
938            case = "B" if rep["qwen35_limit_violations"] else "A"
939        if arch not in FAMILY_ARCH and fam is not None:
940            case = "B"
941            notes.append("known layer types under a new name: architecture '%s' must be added to model_family_from_arch (and its %s guard)" % (arch, fam))
942        if fam == "qwen35moe":
943            shape_fields = rep["qwen35_limit_violations"]
944        path = {"qwen4exp": "the Flash-Next engine path (src/program, src/kernels)", "qwen35moe": "src/qwen35 (strata-q36)"}[fam]
945        backends = usable
946    if case == "B" and fam == "qwen4exp":
947        notes.append("kernels are compiled for the Flash-Next shape (include/strata/core/geometry.hpp): a rebuild with another geometry header, "
948                     "every platform; the engine refuses the file until then")
949    if case == "A" and fam == "qwen4exp":
950        # native router kernel: the (512 experts, top-10) or (256, top-8) fast path only; other counts take the generic router
951        g = rep["geometry"]
952        if (g["n_expert"], g["n_expert_used"]) not in ((512, 10), (256, 8)):
953            notes.append("the native router kernel covers 512/top-10 and 256/top-8; this file has %d/top-%d (native_router.cu native_router_topk_supported)"
954                         % (g["n_expert"], g["n_expert_used"]))
955    return {"case": case, "path": path, "backends": backends, "blockers": blockers if case != "A" else [],
956            "shape_fields_that_differ": shape_fields if case == "B" else [], "warnings": warnings, "notes": notes,
957            "reading": {"A": "runs now", "B": "known layer types at a new shape or name", "C": "port first"}[case]}
958
959
960# ====================================================================================================== the draft entry
961def slug(s: str) -> str:
962    return re.sub(r"[^a-z0-9.]+", "-", s.lower()).strip("-")
963
964
965def draft_entry(rep: dict, files: list[FileInfo], arch: str | None) -> tuple[dict, dict]:
966    """A catalog entry in the shape of setup.py's OWN_PATH_FAMILIES / the Unsloth tables, and the config it implies.  DRAFT: filled from
967    the headers only; the numbers marked 'estimate' are not measured; nothing here is wired into setup.py."""
968    gen = rep["general"]
969    name = gen.get("name") or (arch or "model")
970    fam = rep["family"]
971    g = rep["geometry"] or {}
972    shard_re = SHARD_RE.match(files[0].name)
973    pattern = files[0].name
974    if shard_re:
975        pattern = "%s-{i:05d}-of-%s.gguf" % (shard_re.group("stem"), shard_re.group("n"))
976    size = rep["size_bytes"]
977    sha = {f["name"]: [f["size"], f["sha256"]] for f in rep["files"]}
978    hf_repo = None
979    if files[0].url:
980        m = re.match(r"https?://[^/]+/(.+?)/resolve/", files[0].url)
981        hf_repo = m.group(1) if m else None
982    entry = {
983        "_status": "DRAFT: made from GGUF headers by tools/qwen4_intake.py; not wired into setup.py; every value to be checked by a person",
984        "family_key": "FILL-IN (a short id, e.g. 'qwen4')", "title": name, "by": gen.get("quantized_by") or "FILL-IN",
985        "about": "FILL-IN (one line; numbers only)", "arch": arch,
986        "hf": ("hf(%r)" % hf_repo) if hf_repo else "FILL-IN (the repository at a pinned revision)",
987        "file": pattern, "shards": len(files), "tag": "FILL-IN-", "name": slug(name),
988        "license": gen.get("license.link") or gen.get("license") or "FILL-IN", "sha256": sha, "size_bytes": size,
989        "vision": any(p["supported"] for p in rep["projectors"]) if rep["projectors"] else False,
990        "mmproj": rep["projectors"][0]["file"] if rep["projectors"] else None,
991        "mtp": (2 if rep["mtp"]["in_file"] else 0),
992    }
993    cfg: dict = {"_status": "DRAFT: the settings the verdict implies, not a config setup.py would write", "arch": arch, "case": rep["verdict"]["case"],
994                 "engine_path": rep["verdict"]["path"], "backends": rep["verdict"]["backends"], "model_name": slug(name),
995                 "gguf_first_shard": files[0].name}
996    if fam and g:
997        n_attn = g["n_layers"] // g["qsa_interval"]
998        cfg["geometry"] = {k: g[k] for k in ("n_embd", "n_layers", "n_expert", "n_expert_used", "n_ff", "n_head", "n_head_kv", "head_dim", "qsa_interval")}
999        if fam == "qwen35moe":
1000            # setup.py OWN_PATH_FAMILIES['qwen36']: "kv_bytes_per_token": 11 * 2 * 256 * 2 * 4 and "state_gb" (the GDN recurrent state)
1001            n_gdn = g["n_layers"] - n_attn
1002            entry["kv_bytes_per_token"] = (n_attn + g["n_mtp_layers"]) * 2 * g["head_dim"] * g["n_head_kv"] * 4
1003            entry["state_gb"] = round((n_gdn * g["ssm_v_heads"] * g["ssm_state_size"] ** 2 * 4 +
1004                                       n_gdn * (g["ssm_d_conv"] - 1) * g["ssm_conv_channels"] * 4) / 1e9, 2)
1005            cfg["kv_bytes_per_token"], cfg["state_gb"] = entry["kv_bytes_per_token"], entry["state_gb"]
1006        entry["models"] = {"FILL-IN-QUANT": {"about": "FILL-IN", "ram_gb": math.ceil(size / 1e9 * 1.4),
1007                                              "_ram_gb": "estimate: file size x 1.4, rounded up; measure before use"}}
1008        cfg["context_length_trained"] = rep["geometry"]["keys"].get("context_length")
1009    return entry, cfg
1010
1011
1012# ====================================================================================================== driving it
1013def collect(args) -> tuple[list[FileInfo], list[str]]:
1014    infos: list[FileInfo] = []
1015    notes: list[str] = []
1016    if args.hf:
1017        rev = args.rev or "main"
1018        entries = hf_list(args.hf, rev, args.dir or "")
1019        if not entries:
1020            raise SystemExit("no .gguf files in %s@%s/%s" % (args.hf, rev, args.dir or ""))
1021        with concurrent.futures.ThreadPoolExecutor(max_workers=args.threads) as ex:
1022            infos = list(ex.map(lambda e: read_hf_entry(args.hf, rev, e), entries))
1023        return infos, notes
1024    paths: list[pathlib.Path] = []
1025    for p in args.paths:
1026        pp = pathlib.Path(p)
1027        if pp.is_dir():
1028            paths += sorted(x for x in pp.rglob("*.gguf") if len(x.relative_to(pp).parts) <= 3)
1029        elif pp.is_file():
1030            paths.append(pp)
1031            m = SHARD_RE.match(pp.name)
1032            if m:                                   # any shard of a set stands for the set
1033                for q in sorted(pp.parent.glob("%s-*-of-%s.gguf" % (m.group("stem"), m.group("n")))):
1034                    if q not in paths:
1035                        paths.append(q)
1036        else:
1037            raise SystemExit("not a file or folder: %s" % p)
1038    if not paths:
1039        raise SystemExit("no .gguf files found")
1040    seen, uniq = set(), []
1041    for p in paths:
1042        r = p.resolve()
1043        if r not in seen:
1044            seen.add(r)
1045            uniq.append(p)
1046    with concurrent.futures.ThreadPoolExecutor(max_workers=args.threads) as ex:
1047        infos = list(ex.map(read_local, uniq))
1048    if args.sha256:
1049        for f in infos:
1050            f.sha256, f.sha256_source = file_sha256(f.path), "computed"
1051    return infos, notes
1052
1053
1054def run(infos: list[FileInfo], build_tokenizer: bool = True) -> dict:
1055    models, projectors = [], []
1056    for f in infos:
1057        (projectors if _arch_of(f.md) == "clip" else models).append(f)
1058    names = [f.name for f in infos]
1059    reps = []
1060    for s in group_sets(models):
1061        if is_drafter(s):
1062            reps.append(drafter_report(s))
1063            continue
1064        pr = [projector_report(p) for p in projectors]
1065        reps.append(analyse_set(s, siblings=names, build_tokenizer=build_tokenizer, projectors=pr))
1066    if not models:
1067        reps = [{"architecture": "clip", "projectors": [projector_report(p) for p in projectors],
1068                 "verdict": {"case": "-", "reading": "picture readers only: no model in this input", "blockers": [], "warnings": [], "notes": []}}]
1069    return {"tool": "tools/qwen4_intake.py", "tool_version": TOOL_VERSION, "generated": time.strftime("%Y-%m-%d %H:%M:%S"),
1070            "sets": reps, "picture_readers": [projector_report(p) for p in projectors]}
1071
1072
1073def render(report: dict) -> str:
1074    out = []
1075    for s in report["sets"]:
1076        v = s["verdict"]
1077        out.append("=" * 100)
1078        if "files" in s:
1079            out.append("%s   %d file(s)   %.1f GB   arch %s%s" % (s["files"][0]["name"], len(s["files"]), s["size_bytes"] / 1e9, s["architecture"],
1080                                                              "   (drafter)" if s.get("drafter") else ""))
1081        out.append("CASE %s: %s%s" % (v["case"], v["reading"], ("   path: " + v["path"]) if v.get("path") else ""))
1082        if v.get("backends"):
1083            out.append("  runs on: " + ", ".join(v["backends"]))
1084        for b in v.get("blockers", []):
1085            out.append("  BLOCKER  " + b)
1086        for d in v.get("shape_fields_that_differ", []):
1087            out.append("  SHAPE    %s is %s, kernels built for %s" % (d["key"], d["got"], d.get("kernels_built_for", d.get("limit"))))
1088        for w in v.get("warnings", []):
1089            out.append("  WARNING  " + w)
1090        for n in v.get("notes", []):
1091            out.append("  note     " + n)
1092        if "quant" in s:
1093            q = s["quant"]
1094            out.append("  quant types: " + ", ".join("%s x%d" % kv for kv in q["types"].items()))
1095            for c in q["expert_combinations"]:
1096                out.append("    experts %s/%s/%s: %d layers" % (c["gate"], c["up"], c["down"], c["layers"]))
1097            out.append("  backends: " + "; ".join("%s %s" % (b, "ok" if d["all_types_supported"] else "NOT ALL") for b, d in q["backends"].items()))
1098            tk, ct = s["tokenizer"], s["chat_template"]
1099            out.append("  tokenizer: %s / pre %s, %s tokens, %s merges, same as Flash-Next: %s, builds: %s"
1100                       % (tk["model"], tk["pre"], tk["n_tokens"], tk["n_merges"], tk.get("same_vocabulary_as_flash_next"),
1101                          (tk.get("builds") or {}).get("ok", "not tried")))
1102            out.append("  chat template: %s, tool calls: %s, thinking tags: %s"
1103                       % (ct.get("known_as") or ct.get("sha256", "none")[:12], ct.get("tool_call_format"), ct.get("has_think_tags")))
1104            out.append("  MTP: in file %s, drafter files %s; picture readers: %s"
1105                       % (s["mtp"]["in_file"], s["mtp"]["separate_drafter_files"] or "none",
1106                          [(p["file"], p["projector_type"], "ours" if p["supported"] else "NOT ours") for p in s["projectors"]] or "none"))
1107    return "\n".join(out)
1108
1109
1110def main(argv=None) -> int:
1111    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1112    ap.add_argument("paths", nargs="*", help="folders or .gguf files")
1113    ap.add_argument("--hf", metavar="REPO", help="a Hugging Face repository (headers by HTTP range reads)")
1114    ap.add_argument("--rev", help="the revision for --hf (default main)")
1115    ap.add_argument("--dir", help="a folder inside the repository")
1116    ap.add_argument("--out", default="qwen4_intake.json", help="the JSON report")
1117    ap.add_argument("--sha256", action="store_true", help="hash local files (slow)")
1118    ap.add_argument("--no-tokenizer-build", action="store_true")
1119    ap.add_argument("--threads", type=int, default=8)
1120    ap.add_argument("--quiet", action="store_true")
1121    a = ap.parse_args(argv)
1122    if not a.hf and not a.paths:
1123        ap.error("give a folder, .gguf files or --hf REPO")
1124    t0 = time.time()
1125    infos, _ = collect(a)
1126    t_read = time.time() - t0
1127    report = run(infos, build_tokenizer=not a.no_tokenizer_build)
1128    report["seconds"] = {"headers": round(t_read, 1), "total": round(time.time() - t0, 1)}
1129    pathlib.Path(a.out).write_text(json.dumps(report, indent=1, default=str), encoding="utf-8")
1130    if not a.quiet:
1131        print(render(report))
1132        print("\nJSON: %s   (%.1f s, headers %.1f s)" % (a.out, report["seconds"]["total"], t_read))
1133    return 0
1134
1135
1136if __name__ == "__main__":
1137    raise SystemExit(main())