okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fdb376f39
main
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 4python tools/qwen4_intake.py PATH [PATH ...] a folder, or one or more .gguf files (any shard of a set) 5python tools/qwen4_intake.py --hf REPO [--rev REV] [--dir D] Hugging Face: HTTP range reads of each shard's header only 6options: --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 12kCompiledGeometry; 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 16tools/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 19that 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 : 47sys .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 : 57n_embd :int = 2560 58n_layers :int = 48 59qsa_interval :int = 4 60n_vocab :int = 248320 61rms_eps :float = 1e-6 62ssm_state_size :int = 128 63ssm_k_heads :int = 16 64ssm_v_heads :int = 48 65ssm_d_conv :int = 4 66ssm_conv_channels :int = 10240 67ssm_value_dim :int = 6144 68n_head :int = 24 69n_head_kv :int = 2 70head_dim :int = 256 71n_rot :int = 64 72idx_q_heads :int = 4 73idx_key_dim :int = 128 74idx_block :int = 4 75idx_top_k :int = 2048 76hc :int = 4 77hc_lr :int = 320 78n_expert :int = 512 79n_expert_used :int = 10 80n_ff :int = 640 81n_ff_shexp :int = 640 82family :str = "qwen4exp" 83n_mtp_layers :int = 0 84 85@property 86def has_indexer (self )-> bool : 87return self .idx_q_heads > 0 88 89@property 90def has_hc (self )-> bool : 91return self .hc > 0 92 93@property 94def hc_dim (self )-> int : 95return self .hc * self .n_embd 96 97def is_qsa (self ,layer :int )-> bool : 98return layer % self .qsa_interval == self .qsa_interval - 1 99 100def kind (self ,layer :int )-> str : 101if layer >= self .n_layers : 102return "mtp" 103return "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 : 154return isinstance (v , (int ,float ))and not isinstance (v ,bool ) 155 156 157def _int_key (md :dict ,key :str ,required :bool ,default ,problems :list ): 158v = md .get (key ) 159if v is None : 160if required : 161problems .append ("missing " + key ) 162return default 163if not isinstance (v ,int )or isinstance (v ,bool ): 164problems .append (key + " is not an integer" ) 165return default 166if v <= 0 : 167problems .append ("%s = %d, it must be positive" % (key ,v )) 168return default 169return 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').""" 174g ,problems ,p = Geometry (), [],arch + "." 175for key ,field ,required in QWEN4_KEYS : 176setattr (g ,field ,_int_key (md ,p + key ,required ,getattr (g ,field ),problems )) 177vlen = _int_key (md ,p + "attention.value_length" ,False ,g .head_dim ,problems ) 178shexp = _int_key (md ,p + "expert_shared_feed_forward_length" ,False ,g .n_ff ,problems ) 179if problems : 180return g ,problems 181if vlen != g .head_dim : 182problems .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 )) 184g .n_ff_shexp = shexp 185if shexp != g .n_ff : 186problems .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 )) 188eps = md .get (p + "attention.layer_norm_rms_epsilon" ) 189if eps is not None : 190if not _num (eps )or not eps > 0 : 191problems .append (p + "attention.layer_norm_rms_epsilon must be a positive number" ) 192else : 193g .rms_eps = float (eps ) 194if ntokens : 195g .n_vocab = ntokens 196if g .n_head % g .n_head_kv : 197problems .append ("%sattention.head_count = %d is not a multiple of head_count_kv = %d" % (p ,g .n_head ,g .n_head_kv )) 198if g .ssm_value_dim != g .ssm_state_size * g .ssm_v_heads : 199problems .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 )) 201g .ssm_conv_channels = 2 * g .ssm_state_size * g .ssm_k_heads + g .ssm_value_dim 202if g .n_expert_used > g .n_expert or g .n_expert_used > 64 : 203problems .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 )) 205if g .n_rot > g .head_dim or g .n_rot > g .idx_key_dim or g .n_rot % 2 : 206problems .append ("%srope.dimension_count = %d is not an even slice of the head widths" % (p ,g .n_rot )) 207ratios = md .get (p + "attention.compress_ratios" ) 208if ratios is not None : 209if not isinstance (ratios ,list )or len (ratios )!= g .n_layers : 210problems .append ("%sattention.compress_ratios must list one entry for each of the %d layers" % (p ,g .n_layers )) 211elif any (ratios ):# an all-zero list is a converter's placeholder (#2396): treated as absent 212block = 0 213for l ,r in enumerate (ratios ): 214if (r != 0 )!= g .is_qsa (l )or r < 0 or (block and r and r != block ): 215problems .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" )) 217break 218if r : 219block = r 220if block : 221g .idx_block = block 222return 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().""" 227p ,problems = arch + "." , [] 228for k in QWEN35_REQUIRED : 229v = md .get (p + k ) 230if v is None : 231problems .append ("missing " + p + k ) 232elif not _num (v ): 233problems .append (p + k + " is not a number" ) 234g = Geometry (family = "qwen35moe" ) 235if problems : 236return g ,problems 237mtp ,nl = int (md [p + "nextn_predict_layers" ]),int (md [p + "block_count" ]) 238if mtp >= nl : 239problems .append (p + "nextn_predict_layers is not smaller than " + p + "block_count" ) 240if int (md [p + "full_attention_interval" ])< 2 : 241problems .append (p + "full_attention_interval must be at least 2 (the GDN / attention pattern)" ) 242g .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" ]) 243g .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" ]) 244g .n_ff ,g .n_ff_shexp = int (md [p + "expert_feed_forward_length" ]),int (md [p + "expert_shared_feed_forward_length" ]) 245g .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" ]) 246g .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" ]) 247g .n_mtp_layers ,g .hc ,g .hc_lr ,g .idx_q_heads ,g .idx_key_dim = mtp ,0 ,0 ,0 ,0 248g .n_layers = nl - mtp 249g .ssm_conv_channels = 2 * g .ssm_state_size * g .ssm_k_heads + g .ssm_value_dim 250if ntokens : 251g .n_vocab = ntokens 252v = md .get (p + "rope.dimension_count" ) 253if _num (v ): 254g .n_rot = int (v ) 255if (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 256g .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 257g .ssm_v_heads <= 0 or g .ssm_d_conv <= 0 or g .qsa_interval < 2 ): 258problems .append ("a geometry key is zero or out of range" ) 259return g ,problems 260if int (md [p + "attention.value_length" ])!= g .head_dim : 261problems .append ("attention.key_length != attention.value_length" ) 262if g .ssm_value_dim != g .ssm_state_size * g .ssm_v_heads : 263problems .append ("ssm.inner_size != ssm.state_size * ssm.time_step_rank" ) 264if g .ssm_v_heads % g .ssm_k_heads : 265problems .append ("ssm.time_step_rank is not a multiple of ssm.group_count" ) 266if g .n_head % g .n_head_kv : 267problems .append ("attention.head_count is not a multiple of attention.head_count_kv" ) 268if g .n_layers % g .qsa_interval : 269problems .append ("the layer count is not a multiple of full_attention_interval" ) 270return 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).""" 275out = [] 276for key ,field in PINNED : 277got ,want = getattr (g ,field ),getattr (COMPILED ,field ) 278if field == "idx_block" and not g .has_indexer : 279continue 280if got != want : 281out .append ({"key" :arch + "." + key ,"field" :field ,"got" :got ,"kernels_built_for" :want }) 282if abs (g .rms_eps - COMPILED .rms_eps )> 1e-6 * COMPILED .rms_eps : 283out .append ({"key" :arch + ".attention.layer_norm_rms_epsilon" ,"field" :"rms_eps" ,"got" :g .rms_eps , 284"kernels_built_for" :COMPILED .rms_eps }) 285return out 286 287 288def qwen35_limit_violations (g :Geometry ,arch :str )-> list [dict ]: 289out = [] 290for key ,field ,op ,want in QWEN35_LIMITS : 291got = getattr (g ,field ) 292if (op == "==" and got != want )or (op == "<=" and got > want ): 293out .append ({"key" :arch + "." + key ,"field" :field ,"got" :got ,"limit" :"%s %d" % (op ,want )}) 294return 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 ]]]: 302kind = g .kind (layer ) 303N ,NE ,FF ,FS = g .n_embd ,g .n_expert ,g .n_ff ,g .n_ff_shexp 304t = [("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 ])] 307if g .has_hc : 308H = g .hc_dim 309t += [("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 ])] 312else : 313t += [("attn_norm.weight" , [N ]), ("post_attention_norm.weight" , [N ])] 314if kind == "gdn" : 315t += [("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 ])] 319else : 320t += [("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 ])] 323if g .has_indexer and kind == "attention" : 324t += [("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 ])] 326if kind == "mtp" : 327t += [("nextn.eh_proj.weight" , [2 * N ,N ]), ("nextn.enorm.weight" , [N ]), ("nextn.hnorm.weight" , [N ]), 328 ("nextn.shared_head_norm.weight" , [N ])] 329return t 330 331 332def global_tensors (g :Geometry )-> list [tuple [str ,list [int ]]]: 333t = [("token_embd.weight" , [g .n_embd ,g .n_vocab ]), ("output.weight" , [g .n_embd ,g .n_vocab ])] 334if g .has_hc : 335t += [("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 ])] 337else : 338t .append (("output_norm.weight" , [g .n_embd ])) 339return 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 : 348wanted :dict [str ,list [int ]]= dict (global_tensors (g )) 349for l in range (g .n_layers + g .n_mtp_layers ): 350for name ,shape in layer_tensors (g ,l ): 351wanted ["blk.%d.%s" % (l ,name )]= shape 352missing = sorted (n for n in wanted if n not in tensors ) 353reshaped = [{"name" :n ,"got" :tensors [n ],"want" :s }for n ,s in wanted .items ()if n in tensors and list (tensors [n ])!= s ] 354extra ,known = [], [] 355for n in sorted (tensors ): 356if n in wanted : 357continue 358if not complete and QWEN4_UNLISTED .match (n ): 359known .append (n ) 360else : 361extra .append (n ) 362return {"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 : 401return TYPE_NAME .get (t ,"type%d" % t ) 402 403 404def block_elems (t :int )-> int : 405geom = G .BLOCK_GEOMETRY .get (type_name (t )) 406return 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).""" 411L = BACKEND_LISTS [be ] 412qg = block_elems (gu )if gu in L ["gu" ]else 0 413qd = block_elems (down )if down in L ["down" ]else 0 414return 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 415n_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 : 427for role ,pat in ROLE_PATTERNS : 428if pat .search (name ): 429return role 430if 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|" 431r"ssm_alpha\.weight|ssm_beta\.weight|ssm_conv1d\.weight|ple_conv1d\.weight|hc_(attn|ffn)_inject\.weight)$" ,name ): 432return "small" 433return "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).""" 438by_type :dict [str ,int ]= {} 439roles :dict [str ,dict [str ,int ]]= {} 440per_layer :dict [int ,dict [str ,int ]]= {} 441for name ,shape ,ty in tensors : 442tn = type_name (ty ) 443by_type [tn ]= by_type .get (tn ,0 )+ 1 444role = tensor_role (name ,shape ) 445roles .setdefault (role , {}) 446roles [role ][tn ]= roles [role ].get (tn ,0 )+ 1 447m = re .match (r"blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$" ,name ) 448if m : 449per_layer .setdefault (int (m .group (1 )), {})[m .group (2 )]= ty 450backends = ["cuda" ,"hip" ,"sycl" ,"metal" ] 451result = {"types" :dict (sorted (by_type .items (),key = lambda kv :- kv [1 ])),"roles" :roles ,"backends" : {},"unknown_types" : [], 452"expert_combinations" : []} 453combos :dict [tuple ,list [int ]]= {} 454for l ,d in sorted (per_layer .items ()): 455combos .setdefault ((d .get ("gate" ),d .get ("up" ),d .get ("down" )), []).append (l ) 456for (gt ,ut ,dt ),layers in combos .items (): 457result ["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 ]}) 460seen_unknown = {ty for _ ,_ ,ty in tensors if ty not in G .GGML_TYPES } 461anywhere = set (SMALL_OK )| {8 } 462for L in BACKEND_LISTS .values (): 463anywhere |= L ["is_iq" ]| L ["mmvq" ]| L ["embed_extra" ]| L ["gu" ]| L ["down" ] 464nk :dict [int ,dict ]= {} 465for name ,shape ,ty in tensors : 466if ty not in anywhere and ty in G .GGML_TYPES : 467e = nk .setdefault (ty , {"type" :type_name (ty ),"tensors" :0 ,"example" :name }) 468e ["tensors" ]+= 1 469result ["no_kernel_anywhere" ]= list (nk .values ()) 470result ["unknown_types" ]= sorted (seen_unknown ) 471allowed = FAMILY_BACKENDS .get (family or "" ,backends ) 472for be in backends : 473L = BACKEND_LISTS [be ] 474bad :list [dict ]= [] 475qwen35 = family == "qwen35moe" 476for name ,shape ,ty in tensors : 477role = tensor_role (name ,shape ) 478why = None 479if 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. 482if ty not in SMALL_OK and ty != 8 and (qwen35 or ty not in L ["is_iq" ]): 483why = "a small tensor must be F32, F16, BF16 or Q8_0" + ("" if qwen35 else " or a type the generic dequantizer takes" ) 484elif role == "indexer" : 485if ty not in SMALL_OK and ty not in L ["mmvq" ]: 486why = "no GEMV kernel for this type" 487elif role == "token_embedding" : 488if ty not in L ["is_iq" ]and ty not in L ["embed_extra" ]: 489why = "not an embedding type (embed_type_supported)" 490elif role == "dense" : 491ok = ty in L ["mmvq" ]or (not qwen35 and ty in SMALL_OK )# Flash-Next also runs BF16 / F16 dense (bf16_gemv) 492if not ok : 493why = "no native MMVQ kernel (native_mmvq_supported)" 494if why : 495bad .append ({"tensor" :name ,"type" :type_name (ty ),"role" :role ,"why" :why }) 496if g is not None : 497for l ,d in sorted (per_layer .items ()): 498gt ,ut ,dt = d .get ("gate" ),d .get ("up" ),d .get ("down" ) 499if None in (gt ,ut ,dt ): 500continue 501if gt != ut : 502bad .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" }) 504elif not expert_pair_ok (be ,gt ,dt ,g .n_embd ,g .n_ff ): 505bad .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 509grouped :dict [tuple ,dict ]= {} 510for b in bad : 511k = (b ["type" ],b ["role" ],b ["why" ]) 512e = grouped .setdefault (k , {"type" :b ["type" ],"role" :b ["role" ],"why" :b ["why" ],"tensors" :0 ,"example" :b ["tensor" ]}) 513e ["tensors" ]+= 1 514result ["backends" ][be ]= {"family_runs_here" :be in allowed ,"all_types_supported" :not bad , 515"unsupported" :list (grouped .values ()),"source" :BACKEND_SOURCES [be ]} 516return 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 : 539import strata_tokenizer as ST 540toks = md .get ("tokenizer.ggml.tokens" ) 541merges = md .get ("tokenizer.ggml.merges" ) 542types = md .get ("tokenizer.ggml.token_type" ) 543pre = md .get ("tokenizer.ggml.pre" ) 544r :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" )} 548if not isinstance (toks ,list ): 549r ["problems" ]= ["the file carries no tokenizer.ggml.tokens" ] 550return r 551r ["tokens_sha256" ]= hashlib .sha256 ("\n" .join (toks ).encode ()).hexdigest () 552if isinstance (merges ,list ): 553r ["merges_sha256" ]= hashlib .sha256 ("\n" .join (merges ).encode ()).hexdigest () 554special = [] 555counts :dict [int ,int ]= {} 556if isinstance (types ,list ): 557for i ,ty in enumerate (types ): 558counts [ty ]= counts .get (ty ,0 )+ 1 559if ty in (3 ,4 )and i < len (toks ): 560special .append ((i ,toks [i ],ty )) 561r ["token_type_counts" ]= {str (k ):v for k ,v in sorted (counts .items ())} 562r ["n_special" ]= len (special ) 563r ["same_vocabulary_as_flash_next" ]= (r ["tokens_sha256" ]== REF_TOKENIZER ["tokens_sha256" ]and 564r .get ("merges_sha256" )== REF_TOKENIZER ["merges_sha256" ]) 565by_text = {t :i for i ,t ,_ in special } 566diffs = [] 567for text ,want in REF_TOKENIZER ["key_tokens" ].items (): 568got = by_text .get (text ) 569if got != want : 570diffs .append ({"token" :text ,"flash_next_id" :want ,"this_file" :got }) 571r ["key_token_differences" ]= diffs 572r ["end_of_turn_id" ]= by_text .get ("<|im_end|>" ) 573problems = [] 574if r ["model" ]!= "gpt2" : 575problems .append ("tokenizer.ggml.model is %r; tools/strata_tokenizer.py builds the byte-level BPE ('gpt2') only" % (r ["model" ],)) 576if r ["pre_rule" ]is None : 577problems .append ("tokenizer.ggml.pre is %r: no splitting rule for it in tools/strata_tokenizer.py (knows qwen35, deepseek*)" % (pre ,)) 578if not isinstance (merges ,list ): 579problems .append ("the file carries no tokenizer.ggml.merges" ) 580r ["problems" ]= problems 581r ["builds" ]= None 582if build and not problems : 583t0 = time .time () 584try : 585sp = {k :int (md [k ])for k in md if k .startswith ("tokenizer.ggml." )and k .endswith ("_token_id" )} 586tk = ST .Tokenizer (list (toks ),list (merges ),list (types )if isinstance (types ,list )else None ,pre ,sp ) 587entry = {"ok" :True ,"seconds" :round (time .time ()- t0 ,2 )} 588if text_probe and all (ch in tk .ids for ch in G_BYTE_CHARS ): 589probe = "def f(x):\n\treturn x # café 你好\n" 590ids = tk .encode (probe ) 591entry ["roundtrip" ]= tk .decode (ids )== probe 592entry ["probe_tokens" ]= len (ids ) 593else : 594entry ["roundtrip" ]= "skipped (the vocabulary lacks the 256 byte-level tokens)" 595r ["builds" ]= entry 596except Exception as e :# noqa: BLE001 - the report names it 597r ["builds" ]= {"ok" :False ,"error" :"%s: %s" % (type (e ).__name__ ,e )} 598return r 599 600 601def _byte_chars (): 602import strata_tokenizer as ST 603return sorted (ST .BYTE_TO_UNICODE .values ()) 604 605 606G_BYTE_CHARS = _byte_chars () 607 608 609def template_report (md :dict )-> dict : 610from serve import toolformat 611src = md .get ("tokenizer.chat_template" ) 612if not isinstance (src ,str ): 613return {"present" :False } 614h = hashlib .sha256 (src .encode ()).hexdigest () 615known = KNOWN_TEMPLATES .get (h [:12 ]) 616r = {"present" :True ,"sha256" :h ,"chars" :len (src ),"known_as" :known ,"tool_call_format" :toolformat .tool_format (src )} 617r .update (toolformat .thinking_tags (src )) 618local = ROOT / "serve" / "chat_template.jinja" 619if local .is_file (): 620r ["same_as_serve_chat_template" ]= hashlib .sha256 (local .read_bytes ()).hexdigest ()== h 621return 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 : 630path :str # a local path, or "repo:path" for Hugging Face 631name :str 632size :int 633header :object # a gguf_reader.GGUFFile / quant_formats.Header 634sha256 :str | None = None 635sha256_source :str | None = None 636url :str | None = None 637 638@property 639def md (self )-> dict : 640return self .header .metadata 641 642@property 643def tensors (self ): 644return self .header .tensors 645 646 647def read_local (path :pathlib .Path )-> FileInfo : 648h = G .GGUFFile (path ) 649return FileInfo (str (path ),path .name ,path .stat ().st_size ,h ) 650 651 652def file_sha256 (path :str )-> str : 653d = hashlib .sha256 () 654with open (path ,"rb" )as f : 655while True : 656b = f .read (8 << 20 ) 657if not b : 658break 659d .update (b ) 660return d .hexdigest () 661 662 663def hf_list (repo :str ,rev :str ,subdir :str = "" )-> list [dict ]: 664base = os .environ .get ("HF_ENDPOINT" ,"https://huggingface.co" ).rstrip ("/" ) 665url = "%s/api/models/%s/tree/%s/%s?recursive=true" % (base ,repo ,urllib .parse .quote (rev ,safe = "" ),urllib .parse .quote (subdir .strip ("/" ))) 666out = [] 667while url : 668req = urllib .request .urlopen (url ,timeout = 60 ) 669out += json .load (req ) 670link = req .headers .get ("Link" ,"" ) 671m = re .search (r'<([^>]+)>;\s*rel="next"' ,link ) 672url = m .group (1 )if m else None 673return [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 : 677base = os .environ .get ("HF_ENDPOINT" ,"https://huggingface.co" ).rstrip ("/" ) 678url = "%s/%s/resolve/%s/%s" % (base ,repo ,rev ,urllib .parse .quote (e ["path" ])) 679h = QF .Header (e ["path" ],QF .RangeFile (url ),int (e ["size" ])) 680oid = (e .get ("lfs" )or {}).get ("oid" ) 681return 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.""" 686sets :dict [tuple ,list [FileInfo ]]= {} 687order = [] 688for f in files : 689m = SHARD_RE .match (os .path .basename (f .name )) 690key = (os .path .dirname (f .path ),m .group ("stem" ),m .group ("n" ))if m else (f .path ,) 691if key not in sets : 692sets [key ]= [] 693order .append (key ) 694sets [key ].append (f ) 695out = [] 696for key in order : 697out .append (sorted (sets [key ],key = lambda f :f .name )) 698return out 699 700 701# ====================================================================================================== the analysis 702def _arch_of (md :dict )-> str | None : 703a = md .get ("general.architecture" ) 704return a if isinstance (a ,str )else None 705 706 707def projector_report (f :FileInfo )-> dict : 708try : 709from strata_control .models import OUR_PROJECTOR_TYPES as ours 710except Exception :# noqa: BLE001 - the report must run from a bare tools/ copy 711ours = {"qwen3vl_merger" } 712md = f .md 713pt = md .get ("clip.projector_type" ) 714return {"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 : 720p = (arch or "" )+ "." 721n = md .get (p + "nextn_predict_layers" ) 722in_file = bool (n )or any (".nextn." in x for x in names ) 723sep = [s for s in siblings if re .search (r"mtp|draft" ,s ,re .I )] 724return {"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 : 729keys = ["name" ,"basename" ,"size_label" ,"quantized_by" ,"license" ,"license.link" ,"license.name" ,"repo_url" ,"url" , 730"file_type" ,"description" ,"type" ,"version" ,"finetune" ] 731out = {k :md ["general." + k ]for k in keys if ("general." + k )in md } 732bases = {k :v for k ,v in md .items ()if k .startswith ("general.base_model." )} 733if bases : 734out ["base_model" ]= bases 735return 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 740trunk layers, only the draft block (Unsloth's mtp-*.gguf: token_embd, output and blk.48 of a 49-block file).""" 741names = {t .name for f in files for t in f .tensors } 742return 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 : 746md = files [0 ].md 747names = [t .name for f in files for t in f .tensors ] 748blks = sorted ({int (m .group (1 ))for n in names for m in [re .match (r"blk\.(\d+)\." ,n )]if m }) 749types :dict [str ,int ]= {} 750for f in files : 751for t in f .tensors : 752types [t .type_name ]= types .get (t .type_name ,0 )+ 1 753return {"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 , 762projectors :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.""" 764md = files [0 ].md 765arch = _arch_of (md ) 766names :dict [str ,list [int ]]= {} 767tlist :list [tuple [str ,list [int ],int ]]= [] 768for f in files : 769for t in f .tensors : 770names [t .name ]= list (t .shape ) 771tlist .append ((t .name ,list (t .shape ),t .type_id )) 772rep :dict = {"files" : [],"architecture" :arch ,"tensor_count" :len (names ),"size_bytes" :sum (f .size for f in files )} 773for f in files : 774rep ["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 778split = {"count" :md .get ("split.count" ),"found" :len (files ),"complete" :True ,"problems" : []} 779sc = md .get ("split.count" ) 780if isinstance (sc ,int )and sc > 1 : 781nos = sorted (f .md .get ("split.no" )for f in files ) 782if nos != list (range (sc )): 783split ["complete" ]= False 784split ["problems" ].append ("shards present: %s of %d" % ([n + 1 for n in nos if isinstance (n ,int )],sc )) 785total = md .get ("split.tensors.count" ) 786if isinstance (total ,int )and total != len (names ): 787split ["complete" ]= False 788split ["problems" ].append ("split.tensors.count is %d, the shards hold %d" % (total ,len (names ))) 789elif len (files )> 1 : 790split ["problems" ].append ("several files but no split.count key" ) 791rep ["split" ]= split 792rep ["general" ]= general_report (md ) 793# ---- the tokenizer and the template are in the metadata shard 794rep ["tokenizer" ]= tokenizer_report (md ,build_tokenizer ) 795rep ["chat_template" ]= template_report (md ) 796ntok = rep ["tokenizer" ].get ("n_tokens" ) 797# ---- family, geometry, layout 798cand = []# (family, geometry, problems, layout) 799pref = (arch or "" )+ "." 800for fam in ("qwen4exp" ,"qwen35moe" ): 801if arch == fam : 802order = [fam ] 803elif arch in OTHER_ENGINES or arch is None : 804order = [] 805else : 806order = ["qwen4exp" ,"qwen35moe" ]# an unknown name: do the keys and tensors fit a known family? 807if fam not in order : 808continue 809g ,problems = (geometry_qwen4 if fam == "qwen4exp" else geometry_qwen35 )(md ,arch ,ntok ) 810layout = check_layout (names ,g ,complete = (fam == "qwen35moe" ))if not problems else None 811cand .append ((fam ,g ,problems ,layout )) 812best = None 813if cand : 814scored = [] 815for fam ,g ,problems ,layout in cand : 816score = (len (problems )> 0 ,0 if layout is None else len (layout ["missing" ])+ len (layout ["reshaped" ])+ len (layout ["unknown" ])) 817scored .append ((score ,fam ,g ,problems ,layout )) 818scored .sort (key = lambda x :x [0 ]) 819_ ,fam ,g ,problems ,layout = scored [0 ] 820best = (fam ,g ,problems ,layout ) 821rep ["family" ]= best [0 ]if best else None 822rep ["geometry" ]= None 823rep ["geometry_problems" ]= best [2 ]if best else [] 824rep ["layout" ]= best [3 ]if best else None 825rep ["shape_differences" ]= [] 826rep ["qwen35_limit_violations" ]= [] 827if best : 828fam ,g ,problems ,layout = best 829rep ["geometry" ]= dataclasses .asdict (g ) 830rep ["geometry" ]["keys" ]= {k [len (pref ):]:v for k ,v in md .items ()if k .startswith (pref )and not isinstance (v ,list )} 831if not problems : 832rep ["shape_differences" ]= shape_differences (g ,arch )if fam == "qwen4exp" else [] 833if fam == "qwen35moe" : 834rep ["qwen35_limit_violations" ]= qwen35_limit_violations (g ,arch ) 835ref = 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 , 836n_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 ) 837rep ["differs_from_qwen36_35b" ]= [f .name for f in dataclasses .fields (Geometry ) 838if f .name not in ("n_vocab" ,"rms_eps" ,"n_rot" ,"idx_block" ,"idx_top_k" ,"ssm_conv_channels" ) 839and getattr (g ,f .name )!= getattr (ref ,f .name )] 840rep ["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) 842emb = names .get ("token_embd.weight" ) 843rep ["vocab_matches_embedding" ]= None if not emb or not ntok else (emb [- 1 ]== ntok ) 844rep ["mtp" ]= mtp_report (md ,arch ,set (names ),siblings or []) 845rep ["projectors" ]= projectors or [] 846# ---- the verdict, the draft catalog entry and the setup config 847rep ["verdict" ]= verdict (rep ,arch ) 848rep ["draft_catalog_entry" ],rep ["draft_setup_config" ]= draft_entry (rep ,files ,arch ) 849return rep 850 851 852def verdict (rep :dict ,arch :str | None )-> dict : 853blockers ,warnings ,notes = [], [], [] 854fam = rep ["family" ] 855case ,path ,backends = "C" ,None , [] 856tk ,qt = rep ["tokenizer" ],rep ["quant" ] 857if arch is None : 858blockers .append ("the file has no general.architecture" ) 859elif arch in OTHER_ENGINES : 860blockers .append ("architecture '%s' is %s" % (arch ,OTHER_ENGINES [arch ])) 861# ---- the model part 862shape_fields = rep ["shape_differences" ] 863if fam is not None : 864if arch not in FAMILY_ARCH and (rep ["geometry_problems" ]or (rep ["layout" ]is not None and not rep ["layout" ]["ok" ])): 865blockers .append ("architecture '%s' is not a name Strata knows, and it does not fit %s either" % (arch ,FAMILY_TITLE [fam ])) 866if rep ["geometry_problems" ]: 867blockers += ["geometry: " + p for p in rep ["geometry_problems" ][:8 ]] 868lay = rep ["layout" ] 869if lay is not None and not lay ["ok" ]: 870if lay ["unknown" ]: 871blockers .append ("%d tensors the %s layout does not name: %s" % (len (lay ["unknown" ]),FAMILY_TITLE [fam ],", " .join (lay ["unknown" ][:6 ]))) 872if lay ["missing" ]: 873blockers .append ("%d tensors the %s layout wants are missing: %s" % (len (lay ["missing" ]),FAMILY_TITLE [fam ],", " .join (lay ["missing" ][:6 ]))) 874if lay ["reshaped" ]: 875r = lay ["reshaped" ][0 ] 876blockers .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" ])) 878elif arch is not None and arch not in OTHER_ENGINES : 879blockers .append ("architecture '%s' is not a family Strata knows and no key set fits qwen4exp or qwen35moe" % arch ) 880# ---- dense / expert-less models 881md_experts = rep ["geometry" ]["n_expert" ]if rep ["geometry" ]else None 882if rep ["quant" ]["roles" ].get ("routed_gate" )is None and rep ["tensor_count" ]and fam is not None : 883blockers .append ("no routed expert tensors: a dense model is a new engine path" ) 884# ---- quant support 885allowed = FAMILY_BACKENDS .get (fam or "" , []) 886usable = [b for b in allowed if qt ["backends" ][b ]["all_types_supported" ]] 887if fam is not None and not rep ["geometry_problems" ]and not usable : 888merged :dict [tuple ,list ]= {} 889for b in allowed : 890for u in qt ["backends" ][b ]["unsupported" ][:3 ]: 891merged .setdefault ((u ["role" ],u ["type" ],u ["tensors" ],u ["example" ],u ["why" ]), []).append (b ) 892for (role ,ty ,n ,ex ,why ),bs in merged .items (): 893blockers .append ("%s: %s %s (%d tensors, e.g. %s): %s" % ("/" .join (bs ),role ,ty ,n ,ex ,why )) 894elif fam is not None : 895for b in allowed : 896if b not in usable : 897us = qt ["backends" ][b ]["unsupported" ] 898notes .append ("%s cannot run this file: %s" % (b ,"; " .join ("%s %s (%d)" % (u ["role" ],u ["type" ],u ["tensors" ])for u in us [:4 ]))) 899for u in qt ["no_kernel_anywhere" ]: 900blockers .append ("quant type %s (%d tensors, e.g. %s) has no kernel in any backend's list" % (u ["type" ],u ["tensors" ],u ["example" ])) 901if qt ["unknown_types" ]: 902blockers .append ("ggml type ids this tools/gguf_reader.py does not know: %s" % qt ["unknown_types" ]) 903# ---- the tokenizer 904for p in tk .get ("problems" , []): 905blockers .append ("tokenizer: " + p ) 906if tk .get ("builds" )and not tk ["builds" ].get ("ok" ): 907blockers .append ("tokenizer: tools/strata_tokenizer.py cannot build it: " + tk ["builds" ].get ("error" ,"" )) 908if tk .get ("builds" )and tk ["builds" ].get ("ok" )and tk ["builds" ].get ("roundtrip" )is False : 909blockers .append ("tokenizer: encode + decode of a probe string does not return the string" ) 910if rep ["vocab_matches_embedding" ]is False : 911blockers .append ("tokenizer: %s tokens but the embedding has another number of rows" % tk .get ("n_tokens" )) 912if tk .get ("n_tokens" )and not tk .get ("same_vocabulary_as_flash_next" )and not tk .get ("problems" ): 913notes .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 916ct = rep ["chat_template" ] 917if not ct .get ("present" ): 918warnings .append ("no chat template in the file" ) 919elif ct ["tool_call_format" ]in ("other" ,): 920warnings .append ("the chat template documents tool calls in a form no parser handles (tool_call_format: other)" ) 921elif ct ["tool_call_format" ]== "json" : 922notes .append ("tool calls are the JSON form: the server's JSON parser is used (serve/frontend.py parser_for_template)" ) 923elif ct ["tool_call_format" ]== "dsml" : 924warnings .append ("DSML tool calls belong to the DeepSeek engine" ) 925# ---- split, projector 926if not rep ["split" ]["complete" ]: 927blockers .append ("split set incomplete: " + "; " .join (rep ["split" ]["problems" ])) 928for pr in rep ["projectors" ]: 929if not pr ["supported" ]: 930warnings .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 932if blockers : 933case = "C" 934else : 935if fam == "qwen4exp" : 936case = "B" if shape_fields else "A" 937elif fam == "qwen35moe" : 938case = "B" if rep ["qwen35_limit_violations" ]else "A" 939if arch not in FAMILY_ARCH and fam is not None : 940case = "B" 941notes .append ("known layer types under a new name: architecture '%s' must be added to model_family_from_arch (and its %s guard)" % (arch ,fam )) 942if fam == "qwen35moe" : 943shape_fields = rep ["qwen35_limit_violations" ] 944path = {"qwen4exp" :"the Flash-Next engine path (src/program, src/kernels)" ,"qwen35moe" :"src/qwen35 (strata-q36)" }[fam ] 945backends = usable 946if case == "B" and fam == "qwen4exp" : 947notes .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" ) 949if 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 951g = rep ["geometry" ] 952if (g ["n_expert" ],g ["n_expert_used" ])not in ((512 ,10 ), (256 ,8 )): 953notes .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" ])) 955return {"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 : 962return 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 967the headers only; the numbers marked 'estimate' are not measured; nothing here is wired into setup.py.""" 968gen = rep ["general" ] 969name = gen .get ("name" )or (arch or "model" ) 970fam = rep ["family" ] 971g = rep ["geometry" ]or {} 972shard_re = SHARD_RE .match (files [0 ].name ) 973pattern = files [0 ].name 974if shard_re : 975pattern = "%s-{i:05d}-of-%s.gguf" % (shard_re .group ("stem" ),shard_re .group ("n" )) 976size = rep ["size_bytes" ] 977sha = {f ["name" ]: [f ["size" ],f ["sha256" ]]for f in rep ["files" ]} 978hf_repo = None 979if files [0 ].url : 980m = re .match (r"https?://[^/]+/(.+?)/resolve/" ,files [0 ].url ) 981hf_repo = m .group (1 )if m else None 982entry = { 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 } 993cfg :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 } 996if fam and g : 997n_attn = g ["n_layers" ]// g ["qsa_interval" ] 998cfg ["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" )} 999if 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) 1001n_gdn = g ["n_layers" ]- n_attn 1002entry ["kv_bytes_per_token" ]= (n_attn + g ["n_mtp_layers" ])* 2 * g ["head_dim" ]* g ["n_head_kv" ]* 4 1003entry ["state_gb" ]= round ((n_gdn * g ["ssm_v_heads" ]* g ["ssm_state_size" ]** 2 * 4 + 1004n_gdn * (g ["ssm_d_conv" ]- 1 )* g ["ssm_conv_channels" ]* 4 )/ 1e9 ,2 ) 1005cfg ["kv_bytes_per_token" ],cfg ["state_gb" ]= entry ["kv_bytes_per_token" ],entry ["state_gb" ] 1006entry ["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" }} 1008cfg ["context_length_trained" ]= rep ["geometry" ]["keys" ].get ("context_length" ) 1009return entry ,cfg 1010 1011 1012# ====================================================================================================== driving it 1013def collect (args )-> tuple [list [FileInfo ],list [str ]]: 1014infos :list [FileInfo ]= [] 1015notes :list [str ]= [] 1016if args .hf : 1017rev = args .rev or "main" 1018entries = hf_list (args .hf ,rev ,args .dir or "" ) 1019if not entries : 1020raise SystemExit ("no .gguf files in %s@%s/%s" % (args .hf ,rev ,args .dir or "" )) 1021with concurrent .futures .ThreadPoolExecutor (max_workers = args .threads )as ex : 1022infos = list (ex .map (lambda e :read_hf_entry (args .hf ,rev ,e ),entries )) 1023return infos ,notes 1024paths :list [pathlib .Path ]= [] 1025for p in args .paths : 1026pp = pathlib .Path (p ) 1027if pp .is_dir (): 1028paths += sorted (x for x in pp .rglob ("*.gguf" )if len (x .relative_to (pp ).parts )<= 3 ) 1029elif pp .is_file (): 1030paths .append (pp ) 1031m = SHARD_RE .match (pp .name ) 1032if m :# any shard of a set stands for the set 1033for q in sorted (pp .parent .glob ("%s-*-of-%s.gguf" % (m .group ("stem" ),m .group ("n" )))): 1034if q not in paths : 1035paths .append (q ) 1036else : 1037raise SystemExit ("not a file or folder: %s" % p ) 1038if not paths : 1039raise SystemExit ("no .gguf files found" ) 1040seen ,uniq = set (), [] 1041for p in paths : 1042r = p .resolve () 1043if r not in seen : 1044seen .add (r ) 1045uniq .append (p ) 1046with concurrent .futures .ThreadPoolExecutor (max_workers = args .threads )as ex : 1047infos = list (ex .map (read_local ,uniq )) 1048if args .sha256 : 1049for f in infos : 1050f .sha256 ,f .sha256_source = file_sha256 (f .path ),"computed" 1051return infos ,notes 1052 1053 1054def run (infos :list [FileInfo ],build_tokenizer :bool = True )-> dict : 1055models ,projectors = [], [] 1056for f in infos : 1057 (projectors if _arch_of (f .md )== "clip" else models ).append (f ) 1058names = [f .name for f in infos ] 1059reps = [] 1060for s in group_sets (models ): 1061if is_drafter (s ): 1062reps .append (drafter_report (s )) 1063continue 1064pr = [projector_report (p )for p in projectors ] 1065reps .append (analyse_set (s ,siblings = names ,build_tokenizer = build_tokenizer ,projectors = pr )) 1066if not models : 1067reps = [{"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" : []}}] 1069return {"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 : 1074out = [] 1075for s in report ["sets" ]: 1076v = s ["verdict" ] 1077out .append ("=" * 100 ) 1078if "files" in s : 1079out .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 "" )) 1081out .append ("CASE %s: %s%s" % (v ["case" ],v ["reading" ], (" path: " + v ["path" ])if v .get ("path" )else "" )) 1082if v .get ("backends" ): 1083out .append (" runs on: " + ", " .join (v ["backends" ])) 1084for b in v .get ("blockers" , []): 1085out .append (" BLOCKER " + b ) 1086for d in v .get ("shape_fields_that_differ" , []): 1087out .append (" SHAPE %s is %s, kernels built for %s" % (d ["key" ],d ["got" ],d .get ("kernels_built_for" ,d .get ("limit" )))) 1088for w in v .get ("warnings" , []): 1089out .append (" WARNING " + w ) 1090for n in v .get ("notes" , []): 1091out .append (" note " + n ) 1092if "quant" in s : 1093q = s ["quant" ] 1094out .append (" quant types: " + ", " .join ("%s x%d" % kv for kv in q ["types" ].items ())) 1095for c in q ["expert_combinations" ]: 1096out .append (" experts %s/%s/%s: %d layers" % (c ["gate" ],c ["up" ],c ["down" ],c ["layers" ])) 1097out .append (" backends: " + "; " .join ("%s %s" % (b ,"ok" if d ["all_types_supported" ]else "NOT ALL" )for b ,d in q ["backends" ].items ())) 1098tk ,ct = s ["tokenizer" ],s ["chat_template" ] 1099out .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" ))) 1102out .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" ))) 1104out .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" )) 1107return "\n" .join (out ) 1108 1109 1110def main (argv = None )-> int : 1111ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 1112ap .add_argument ("paths" ,nargs = "*" ,help = "folders or .gguf files" ) 1113ap .add_argument ("--hf" ,metavar = "REPO" ,help = "a Hugging Face repository (headers by HTTP range reads)" ) 1114ap .add_argument ("--rev" ,help = "the revision for --hf (default main)" ) 1115ap .add_argument ("--dir" ,help = "a folder inside the repository" ) 1116ap .add_argument ("--out" ,default = "qwen4_intake.json" ,help = "the JSON report" ) 1117ap .add_argument ("--sha256" ,action = "store_true" ,help = "hash local files (slow)" ) 1118ap .add_argument ("--no-tokenizer-build" ,action = "store_true" ) 1119ap .add_argument ("--threads" ,type = int ,default = 8 ) 1120ap .add_argument ("--quiet" ,action = "store_true" ) 1121a = ap .parse_args (argv ) 1122if not a .hf and not a .paths : 1123ap .error ("give a folder, .gguf files or --hf REPO" ) 1124t0 = time .time () 1125infos ,_ = collect (a ) 1126t_read = time .time ()- t0 1127report = run (infos ,build_tokenizer =not a .no_tokenizer_build ) 1128report ["seconds" ]= {"headers" :round (t_read ,1 ),"total" :round (time .time ()- t0 ,1 )} 1129pathlib .Path (a .out ).write_text (json .dumps (report ,indent = 1 ,default = str ),encoding = "utf-8" ) 1130if not a .quiet : 1131render (report )) 1132"\nJSON: %s (%.1f s, headers %.1f s)" % (a .out ,report ["seconds" ]["total" ],t_read )) 1133return 0 1134 1135 1136if __name__ == "__main__" : 1137raise SystemExit (main ())