diff --git a/README.md b/README.md index be911149..e340ce60 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ prefix-cache tiers: |---|---| | Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | +| Qwen3.8-Flash-Next, three ranks (the checkpoint padded first, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | | Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | @@ -155,6 +156,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out of tr | [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files | | [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card | | [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry | +| [`docs/TP3.md`](docs/TP3.md) | padding a checkpoint, exactly, to a world its head counts do not divide; three ranks | | [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured | | [`spec.md`](spec.md) | the design | diff --git a/docs/TP3.md b/docs/TP3.md new file mode 100644 index 00000000..cc4a8729 --- /dev/null +++ b/docs/TP3.md @@ -0,0 +1,124 @@ +# Three ranks: padding a checkpoint to a world its geometry does not divide + +Radiance shards by dividing: `n_head`, `n_head_kv`, the GDN head counts and the vocabulary each +split evenly across the world, and a count that does not divide is **refused at declare, by name** +(`share.cpp`, `rad_arch.h`). Four ranks got through for Qwen3.8-Flash-Next by replicating the two +KV heads in rank pairs (1.0.7). Three ranks cannot: 24 query heads, 2 KV heads, 16 GDN K heads and +48 GDN V heads have no even share in 3, and replication needs a world that is a multiple of the +head count. The engine is right to refuse. What this document describes is how to **change the +checkpoint** so there is nothing to refuse, exactly, and what the engine gained so that the padded +checkpoint then serves at three ranks. + +The regime is tcclaviger's `vllm/config/tp_padding.py`, which pads the same model to the same +shape at load time inside vLLM. Radiance has no load-time pad -- a container is served as it was +converted -- so the pad is done once, offline, before `rad-convert`. + +## 1. What is padded, and why it is exact + +Every padded weight gains **zeros**, placed where a zero contributes nothing to the forward pass: + +| block | tensor | gains | exact because | +|---|---|---|---| +| attention | `k_proj`, `v_proj` | zero **rows** (new KV heads) | a zero KV head stores zeros and is read only by zero query heads | +| attention | `q_proj` (fused q+gate on Flash-Next: 512-row head blocks) | zero rows so every KV group has the new ratio | a zero query head attends uniformly, and its `o_proj` column is zero, so its output is 0 | +| attention | `o_proj` | zero **columns** in the same head order | the zero heads' outputs are multiplied by zero | +| GDN | `in_proj_qkvz`, `in_proj_ba` | zero rows per the fused layout (new K and V heads) | a zero head carries a zero state | +| GDN | `conv1d` | zero channels | zero input, zero output | +| GDN | `A_log`, `dt_bias` | zero heads | a zero head decays nothing | +| GDN | `out_proj` | zero columns | the zero heads are multiplied by zero | + +Norms, embeddings, the lm_head, the router and the experts are untouched: their only width is +`n_embd`. The experts stay at the model's own 640 and the plugin slices them by parity across the +ranks (1.0.8: at three ranks the five 128-wide blocks go 2, 2, 1), so the +20 % expert bytes of a +640 → 768 pad are not paid. + +For Qwen3.8-Flash-Next the pad is **24 → 36 query heads, 2 → 3 KV heads, GDN 16 → 18 K heads and +48 → 54 V heads** -- head_dim 256 for attention and 128 for GDN are unchanged, so every rank at +three declares 12 query heads, 1 KV head and gqa 12: **the same per-rank attention geometry the +two-rank serve declares**, and the same kernels resolve. Dummies go **last**, as the vLLM pad does, +so rank 2 carries them. + +The cost is the dummies' arithmetic: 12 of 36 query heads and 2 of 18 GDN heads are zeros on the +last rank, so three ranks do 1.5× the attention work of two for 1.5× the cards. + +## 2. The tool + +`tools/pad_tp.py` (Python, numpy only; no torch) rewrites a Hugging Face safetensors checkpoint: + +```sh +tools/pad_tp.py SRC DST --heads 36 --kv-heads 3 --gdn-k 18 --gdn-v 54 --sparse +tools/pad_verify.py SRC DST +``` + +It streams one tensor at a time (a 336 GiB checkpoint pads in a few GB of RAM), reads bf16 as raw +u16 (no arithmetic happens), rewrites `config.json` with the new counts and an explicit `head_dim`, +and handles the fused layouts: the Flash-Next `q_proj` that carries the attention gate beside each +query head, and the GDN `in_proj_qkvz` / `in_proj_ba` row order. + +`--sparse` is for checkpoints larger than the free disk. Instead of copying, it **reflinks** every +original shard (btrfs, XFS; `cp --reflink`) and writes only the padded tensors into new shards named +`model-00000-of-NNNNN-tp3pad-*.safetensors`. Radiance's reader lists the index's shards sorted by +name and keeps the **first** tensor of a name (`checkpoint.cpp`, `emplace`), so the new shards +shadow the originals by sorting first. Flash-Next: 340 tensors, 6.6 GB of new bytes, the 131 +original shards shared. + +`tools/pad_verify.py` reads both checkpoints back and checks every tensor: an untouched tensor is +byte-identical, a padded one is the source in its place and zeros everywhere else. Run it before +`rad-convert`; a pad that passes it cannot change what the model computes. + +Padding proved on Llama-3.2-3B (24/8 heads, gqa 3 → 36/9, gqa 4): a 28-layer numpy forward on the +padded weights gives the same argmax as the original with max |Δlogit| 2.1e-5 (fp32 summation +order), and on the engine TP1 on the padded checkpoint produces the same text as TP1 on the +original at temperature 0. + +## 3. What the engine gained for three ranks + +- **libr4d: `all_reduce` and `all_gather` at world 3.** `ar_oneshot_3rank_exact` is the wide + one-shot family's template at 3; `ar_gather_3rank` the same for the gather the vocab-parallel + sampler declares. Both share the wide family's instance (scratch, `[block][source]` flags, seq + counters). There is no two-shot at 3: it shards the message `world` ways and a residual width + such as 2560 does not divide by 3. `wht6` is a two-rank wire; three ranks take the exact one, as + four do. Selftest: `--case ar_oneshot_3rank_exact` and `--case ar_gather_3rank`, bit-exact against + the host sum / concatenation on three gfx1201 cards, with the two-rank controls unchanged. +- **The vocabulary at a world that does not divide it.** 248 320 rows do not divide by 3 and + `share.cpp` refuses a row shard without a declared span. `qwen4exp` now declares the rank's span + for `token_embd` and `output`, and the split rule (`rad_arch.h` `shard_extent` / `shard_begin`, + restated in `core/engine.cpp`) keeps the even share whenever the world divides the vocabulary and + otherwise rounds the per-rank count up to a **128-row block** -- a block-scaled fp8 head refuses a + cut inside a tile. At three the ranks take 82 816, 82 816 and 82 688; two and four ranks divide + 248 320 evenly and are untouched. +- Everything else three ranks need was already there by 1.0.8: the width split of the experts at + any world up to the block count, the uneven tile share of the plain bf16 (protected) experts, the + N-rank gather's placement. + +## 4. Serving + +```sh +tools/pad_tp.py ~/models/Qwen3.8-Flash-Next ~/models/Qwen3.8-Flash-Next-tp3pad \ + --heads 36 --kv-heads 3 --gdn-k 18 --gdn-v 54 --sparse +tools/pad_verify.py ~/models/Qwen3.8-Flash-Next ~/models/Qwen3.8-Flash-Next-tp3pad +build/bin/rad-convert ~/models/Qwen3.8-Flash-Next-tp3pad -o qfn-tp3pad.rad \ + --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe +radiance --model qfn-tp3pad.rad --tp 3 --tp-wire exact --max-num-seqs 8 --max-model-len 200000 \ + --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 \ + --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 \ + --max-num-batched-tokens 2048 +``` + +Measured on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16, Threadripper PRO 9955WX), the +uncensored Flash-Next fine-tune padded as above and converted with the shipped recipe +(`qwen4exp-w4nl64-i8-hc8m`, here without Hessians: nearest into the codebook), this branch over +1.0.8; the two-rank column is the shipped `qwen3.8-next-flash-fp8-iq4r-moe.rad` on the same box: + +| | three ranks, padded | two ranks, shipped container | +|---|---|---| +| READY from cold | 45 s | 35 s | +| 1 / 4 / 8 streams, aggregate t/s | 173.5 / 332.2 / 410.9 | 156 / 320 / 404 | +| 4 streams at 100 K context, per stream | 41.8 | 41.2 | +| warm-prefix TTFT, 60 K prompt, second time | 0.3 s (cold 8.2 s) | — | +| HumanEval / GSM8K | 0.854 / 0.915 | 0.854 / 0.940 | + +The GSM8K gap is the Hessians the shipped container was quantised against and this one was not; +the GPTQ'd conversion of the same padded checkpoint is the comparison that closes it. Hi-vocab +tokens (CJK, Cyrillic -- rank 2's lm_head shard, the three-rank gather) decode correctly; no engine +warnings; every band the run issued resolved to a device kernel. diff --git a/tools/pad_tp.py b/tools/pad_tp.py new file mode 100755 index 00000000..02e176a8 --- /dev/null +++ b/tools/pad_tp.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""pad_tp.py — pad a Llama/Qwen-style HF safetensors checkpoint to a geometry that divides by a +tensor-parallel world size, with ZERO weights, so the padded model computes exactly what the +original does. + + pad_tp.py SRC DST --heads 36 --kv-heads 9 [--ff 8448] [--gdn-k 18 --gdn-v 54] + +What is padded and why it is exact (fp32-accumulated, zero terms add nothing): + attention k_proj / v_proj gain zero ROWS (new kv heads); q_proj gains zero rows so every kv + group has the new ratio gqa' = heads'/kv_heads' -- a group that existed keeps its real + q heads first, then zero q heads; a new group is all zero. o_proj gains zero COLUMNS + in the same head order. A zero q head attends uniformly, but its o_proj column is + zero, so it contributes 0; a zero kv head stores zeros, read only by zero q heads. + mlp gate_proj / up_proj gain zero rows, down_proj zero columns: silu(0)*0 = 0. + gdn (Qwen3-Next, --gdn-k/--gdn-v) in_proj_qkvz / in_proj_ba gain zero rows per the + fused layout, conv1d zero channels, A_log / dt_bias zero heads, out_proj zero columns. +Everything with n_embd as its only width (norms, embeddings, lm_head) is untouched. config.json is +rewritten with the new counts and an explicit head_dim. Dummies go LAST, as Rob's vLLM tp_padding +does, so rank w-1 carries them. + +bf16 is handled as raw u16 (no arithmetic happens here), so numpy alone suffices. +""" +import argparse, json, os, re, shutil, struct, sys +import numpy as np + +DT = {"BF16": (np.uint16, 2), "F16": (np.float16, 2), "F32": (np.float32, 4), "I64": (np.int64, 8), + "I32": (np.int32, 4), "U8": (np.uint8, 1), "BOOL": (np.bool_, 1), "F8_E4M3": (np.uint8, 1)} + +def st_read(path): + """-> (header dict with tensor meta, raw bytes mmap). Tiny safetensors reader.""" + with open(path, "rb") as f: + n = struct.unpack("= n_kv is all zero.""" + gqa, gqa2 = n_head // n_kv, n_head2 // n_kv2 + assert n_head % n_kv == 0 and n_head2 % n_kv2 == 0 and gqa2 >= gqa and n_kv2 >= n_kv, "ratio/kv must not shrink" + out = [] + for g in range(n_kv2): + for j in range(gqa2): + out.append(g * gqa + j if (g < n_kv and j < gqa) else -1) + return out + +def take_rows(w, idx, hd): + """rows of w grouped by hd per head: new row block i = old block idx[i], or zeros.""" + out = np.zeros((len(idx) * hd,) + w.shape[1:], dtype=w.dtype) + for i, o in enumerate(idx): + if o >= 0: out[i * hd:(i + 1) * hd] = w[o * hd:(o + 1) * hd] + return out + +def take_cols(w, idx, hd): + out = np.zeros(w.shape[:1] + (len(idx) * hd,) + w.shape[2:], dtype=w.dtype) + for i, o in enumerate(idx): + if o >= 0: out[:, i * hd:(i + 1) * hd] = w[:, o * hd:(o + 1) * hd] + return out + +def pad_rows(w, n2): + out = np.zeros((n2,) + w.shape[1:], dtype=w.dtype); out[:w.shape[0]] = w; return out + +def pad_cols(w, n2): + out = np.zeros(w.shape[:1] + (n2,) + w.shape[2:], dtype=w.dtype); out[:, :w.shape[1]] = w; return out + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src"); ap.add_argument("dst") + ap.add_argument("--heads", type=int, required=True); ap.add_argument("--kv-heads", type=int, required=True) + ap.add_argument("--ff", type=int, default=0, help="new intermediate_size for DENSE mlp (0 = unchanged; MoE experts are never padded)") + ap.add_argument("--gdn-k", type=int, default=0); ap.add_argument("--gdn-v", type=int, default=0) + ap.add_argument("--sparse", action="store_true", + help="write ONLY the padded tensors, into new shards named to sort first; reflink every original " + "shard into dst unchanged. Radiance lists shards from the index, sorted by name, and keeps the " + "first tensor of a name (core/format/checkpoint.cpp emplace), so the padded copy shadows the " + "original. Costs the padded bytes only -- the 336 GB QFN source is not copied.") + a = ap.parse_args() + cfg_all = json.load(open(os.path.join(a.src, "config.json"))) + cfg = cfg_all["text_config"] if "text_config" in cfg_all else cfg_all # Qwen3.8-Flash-Next nests it + n_head, n_kv = cfg["num_attention_heads"], cfg.get("num_key_value_heads", cfg["num_attention_heads"]) + n_embd = cfg["hidden_size"]; hd = cfg.get("head_dim") or n_embd // n_head + n_ff = cfg.get("intermediate_size", 0); n_ff2 = a.ff or n_ff # MoE-only models (QFN) have none + qmap = head_map(n_head, n_kv, a.heads, a.kv_heads) + kmap = list(range(n_kv)) + [-1] * (a.kv_heads - n_kv) + gk, gv = cfg.get("linear_num_key_heads"), cfg.get("linear_num_value_heads") + gkd, gvd = cfg.get("linear_key_head_dim"), cfg.get("linear_value_head_dim") + gk2, gv2 = a.gdn_k or gk, a.gdn_v or gv + print(f"attention {n_head}/{n_kv} (gqa {n_head//n_kv}) @ {hd} -> {a.heads}/{a.kv_heads} (gqa {a.heads//a.kv_heads}); " + f"dense ff {n_ff} -> {n_ff2}" + (f"; gdn K {gk}->{gk2} V {gv}->{gv2}" if gk else ""), flush=True) + os.makedirs(a.dst, exist_ok=True) + idx_path = os.path.join(a.src, "model.safetensors.index.json") + files = sorted(set(json.load(open(idx_path))["weight_map"].values())) if os.path.exists(idx_path) else ["model.safetensors"] + + def parts(w_, sizes, news, axis=0): + """pad each consecutive segment of `sizes` along `axis` to `news` (zeros after the real rows).""" + o = 0; outs = [] + for sz, s2 in zip(sizes, news): + seg = np.take(w_, range(o, o + sz), axis=axis); o += sz + pad = [(0, 0)] * w_.ndim; pad[axis] = (0, s2 - sz); outs.append(np.pad(seg, pad)) + assert o == w_.shape[axis], f"segments {sizes} do not cover axis {axis} of shape {w_.shape}" + return np.concatenate(outs, axis=axis) + + def plan(name, shape): + """-> (kind, transform) for a tensor, by name and SOURCE shape. None = untouched.""" + if re.search(r"self_attn\.q_proj\.(weight|bias)$", name): + # Qwen3-Next gated attention fuses q and its gate: rows = n_head * 2 * hd, per head [q | gate]. + # A plain q_proj has n_head * hd rows. Either way one head is one block of rows. + blk = shape[0] // n_head + assert blk in (hd, 2 * hd), f"{name}: {shape[0]} rows is neither {n_head}*{hd} nor {n_head}*{2*hd}" + return "q", lambda w: take_rows(w, qmap, blk) + if re.search(r"self_attn\.[kv]_proj\.(weight|bias)$", name): return "kv", lambda w: take_rows(w, kmap, hd) + if re.search(r"self_attn\.o_proj\.weight$", name): return "o", lambda w: take_cols(w, qmap, hd) + if n_ff2 != n_ff and re.search(r"mlp\.(gate|up)_proj\.weight$", name): return "ff", lambda w: pad_rows(w, n_ff2) + if n_ff2 != n_ff and re.search(r"mlp\.down_proj\.weight$", name): return "ff", lambda w: pad_cols(w, n_ff2) + if gk and re.search(r"linear_attn\.", name) and (gk2 != gk or gv2 != gv): + # Qwen3-Next GDN, both spellings. Fused: in_proj_qkvz rows [q gk*gkd][k gk*gkd][v gv*gvd][z gv*gvd], + # in_proj_ba [b gv][a gv]. Separate (Qwen3.8-Flash-Next): in_proj_qkv [q][k][v], in_proj_z [z], + # in_proj_a / in_proj_b [gv] each. conv1d channels = q,k,v. A_log / dt_bias per v head. + # out_proj columns = gv*gvd. norm is per gvd and untouched. + qkv_s, qkv_n = [gk*gkd, gk*gkd, gv*gvd], [gk2*gkd, gk2*gkd, gv2*gvd] + if re.search(r"in_proj_qkvz\.weight$", name): return "gdn", lambda w: parts(w, qkv_s + [gv*gvd], qkv_n + [gv2*gvd]) + if re.search(r"in_proj_qkv\.weight$", name): return "gdn", lambda w: parts(w, qkv_s, qkv_n) + if re.search(r"in_proj_z\.weight$", name): return "gdn", lambda w: pad_rows(w, gv2 * gvd) + if re.search(r"in_proj_ba\.weight$", name): return "gdn", lambda w: parts(w, [gv, gv], [gv2, gv2]) + if re.search(r"in_proj_[ab]\.weight$", name): return "gdn", lambda w: pad_rows(w, gv2) + if re.search(r"conv1d\.(weight|bias)$", name): return "gdn", lambda w: parts(w, qkv_s, qkv_n) + if re.search(r"(A_log|dt_bias)$", name): return "gdn", lambda w: pad_rows(w, gv2) + if re.search(r"out_proj\.weight$", name): return "gdn", lambda w: pad_cols(w, gv2 * gvd) + return None, None + + weight_map = {}; total = 0; touched = {}; sparse_items = []; sparse_bytes = 0 + for fn in files: + hdr, data = st_read(os.path.join(a.src, fn)); meta = hdr.pop("__metadata__", None); items = [] + for name in hdr: + dts = hdr[name]["dtype"]; esz = DT[dts][1]; src_shape = tuple(hdr[name]["shape"]) + kind, tf = plan(name, src_shape) + if kind: + shape = tf(np.zeros(src_shape, dtype=np.uint8)).shape # from the source shape alone; cheap + touched[kind] = touched.get(kind, 0) + 1 + else: + shape = src_shape + nbytes = int(np.prod(shape)) * esz; total += nbytes + item = (name, dts, shape, nbytes, (lambda h=hdr, d=data, n=name, t=tf: t(st_tensor(h, d, n)) if t else st_tensor(h, d, n))) + if a.sparse: + if kind: sparse_items.append(item); sparse_bytes += nbytes + weight_map[name] = fn # overridden below for padded names + else: + items.append(item); weight_map[name] = fn + if a.sparse: + dstf = os.path.join(a.dst, fn) + if not os.path.exists(dstf): + r = os.system(f"cp --reflink=always '{os.path.join(a.src, fn)}' '{dstf}' 2>/dev/null") or 0 + if r: os.link(os.path.join(a.src, fn), dstf) # not btrfs/xfs: hard link, still no copy + else: + st_write_stream(os.path.join(a.dst, fn), meta, items); print(f" wrote {fn} ({len(items)} tensors)", flush=True) + if a.sparse: + # new shards, ~2 GB each, named to sort BEFORE every original ("model-00000-…" < "model-00001-…") + CH = 2 << 30; chunks = [[]]; acc = 0 + for it in sparse_items: + if acc + it[3] > CH and chunks[-1]: chunks.append([]); acc = 0 + chunks[-1].append(it); acc += it[3] + for k, ch in enumerate(chunks): + fn = f"model-00000-of-{len(files):05d}-tp3pad-{k:03d}.safetensors" + st_write_stream(os.path.join(a.dst, fn), {"tp3pad": "zero-padded heads; shadows the originals by name order"}, ch) + for it in ch: weight_map[it[0]] = fn + print(f" wrote {fn} ({len(ch)} tensors, {sum(i[3] for i in ch)/1e9:.2f} GB)", flush=True) + print(f"sparse: {len(sparse_items)} padded tensors, {sparse_bytes/1e9:.2f} GB new; {len(files)} shards reflinked", flush=True) + if len(files) > 1 or a.sparse: + json.dump({"metadata": {"total_size": total}, "weight_map": weight_map}, + open(os.path.join(a.dst, "model.safetensors.index.json"), "w"), indent=2) + cfg["num_attention_heads"], cfg["num_key_value_heads"], cfg["head_dim"] = a.heads, a.kv_heads, hd + if n_ff: cfg["intermediate_size"] = n_ff2 + if gk: cfg["linear_num_key_heads"], cfg["linear_num_value_heads"] = gk2, gv2 + cfg_all["_tp_padding"] = {"from": {"heads": n_head, "kv_heads": n_kv, "ff": n_ff, "gdn_k": gk, "gdn_v": gv}, + "to": {"heads": a.heads, "kv_heads": a.kv_heads, "ff": n_ff2, "gdn_k": gk2, "gdn_v": gv2}, + "zero_weights": True, "dummies": "last", "sparse": bool(a.sparse)} + json.dump(cfg_all, open(os.path.join(a.dst, "config.json"), "w"), indent=2) + for f in os.listdir(a.src): + if (f.endswith(".json") and f not in ("config.json", "model.safetensors.index.json")) or f.endswith((".txt", ".model", ".jinja", ".md")): + shutil.copy2(os.path.join(a.src, f), os.path.join(a.dst, f)) + print(f"padded tensors by kind: {touched}; total {total/1e9:.2f} GB -> {a.dst}", flush=True) + +if __name__ == "__main__": + main() diff --git a/tools/pad_verify.py b/tools/pad_verify.py new file mode 100755 index 00000000..219031a0 --- /dev/null +++ b/tools/pad_verify.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""pad_verify.py — prove a pad_tp.py output is exactly the source plus zeros. + + pad_verify.py SRC PADDED + +Re-derives the head/row maps from PADDED/config.json `_tp_padding`, then for EVERY tensor in the +padded index checks, streaming one tensor at a time: + untouched tensors byte-identical to the source + padded tensors every real row/column block equals the source block it came from, and every + other element is exactly zero +Exit 0 only if all of it holds. This is the correctness gate for checkpoints no reference forward +exists for (Qwen3.8-Flash-Next). +""" +import json, os, re, struct, sys +import numpy as np +import importlib.util +spec = importlib.util.spec_from_file_location("padtp", os.path.join(os.path.dirname(os.path.abspath(__file__)), "pad_tp.py")) +padtp = importlib.util.module_from_spec(spec); spec.loader.exec_module(padtp) + +def load(d): + cfg_all = json.load(open(os.path.join(d, "config.json"))) + ip = os.path.join(d, "model.safetensors.index.json") + wm = json.load(open(ip))["weight_map"] if os.path.exists(ip) else None + files = sorted(set(wm.values())) if wm else ["model.safetensors"] + hdrs = {} + for fn in files: + h, data = padtp.st_read(os.path.join(d, fn)); h.pop("__metadata__", None) + for k in h: hdrs.setdefault(k, (h, data, fn)) # first by name order = what the engine reads + return cfg_all, hdrs, wm + +def main(): + src, dst = sys.argv[1], sys.argv[2] + cfg_all, S, _ = load(src); cfgp_all, P, wmp = load(dst) + tp = cfgp_all["_tp_padding"]; f, t = tp["from"], tp["to"] + cfg = cfg_all.get("text_config", cfg_all) + n_head, n_kv, hd = f["heads"], f["kv_heads"], cfg.get("head_dim") or cfg["hidden_size"] // f["heads"] + qmap = padtp.head_map(n_head, n_kv, t["heads"], t["kv_heads"]); kmap = list(range(n_kv)) + [-1] * (t["kv_heads"] - n_kv) + gk, gv, gk2, gv2 = f["gdn_k"], f["gdn_v"], t["gdn_k"], t["gdn_v"] + gkd, gvd = cfg.get("linear_key_head_dim"), cfg.get("linear_value_head_dim") + bad = 0; n_pad = 0; n_same = 0; zero_bytes = 0 + + def blocks_rows(new, old, idx, blk): + """new rows in blocks of blk follow idx into old; -1 blocks must be zero.""" + ok = new.shape[0] == len(idx) * blk + for i, o in enumerate(idx): + seg = new[i*blk:(i+1)*blk] + ok &= bool(np.array_equal(seg, old[o*blk:(o+1)*blk])) if o >= 0 else not seg.any() + return ok + def blocks_cols(new, old, idx, blk): + ok = new.shape[1] == len(idx) * blk + for i, o in enumerate(idx): + seg = new[:, i*blk:(i+1)*blk] + ok &= bool(np.array_equal(seg, old[:, o*blk:(o+1)*blk])) if o >= 0 else not seg.any() + return ok + def segs_rows(new, old, sizes, news): + o = n = 0; ok = new.shape[0] == sum(news) + for sz, s2 in zip(sizes, news): + ok &= bool(np.array_equal(new[n:n+sz], old[o:o+sz])) and not new[n+sz:n+s2].any(); o += sz; n += s2 + return ok and o == old.shape[0] + def pad_rows_ok(new, old, n2): return new.shape[0] == n2 and np.array_equal(new[:old.shape[0]], old) and not new[old.shape[0]:].any() + def pad_cols_ok(new, old, n2): return new.shape[1] == n2 and np.array_equal(new[:, :old.shape[1]], old) and not new[:, old.shape[1]:].any() + + for name in sorted(S): + if name not in P: print("MISSING in padded:", name); bad += 1; continue + hs, ds, _ = S[name]; hp, dp, fnp = P[name] + a = padtp.st_tensor(hs, ds, name); b = padtp.st_tensor(hp, dp, name) + if wmp and wmp.get(name) != fnp: print("INDEX/ORDER mismatch:", name, wmp.get(name), fnp); bad += 1 + ok = None + if re.search(r"self_attn\.q_proj\.(weight|bias)$", name): ok = blocks_rows(b, a, qmap, a.shape[0] // n_head) + elif re.search(r"self_attn\.[kv]_proj\.(weight|bias)$", name): ok = blocks_rows(b, a, kmap, hd) + elif re.search(r"self_attn\.o_proj\.weight$", name): ok = blocks_cols(b, a, qmap, hd) + elif f["ff"] and f["ff"] != t["ff"] and re.search(r"mlp\.(gate|up)_proj\.weight$", name): ok = pad_rows_ok(b, a, t["ff"]) + elif f["ff"] and f["ff"] != t["ff"] and re.search(r"mlp\.down_proj\.weight$", name): ok = pad_cols_ok(b, a, t["ff"]) + elif gk and (gk2 != gk or gv2 != gv) and re.search(r"linear_attn\.", name): + qs, qn = [gk*gkd, gk*gkd, gv*gvd], [gk2*gkd, gk2*gkd, gv2*gvd] + if re.search(r"in_proj_qkvz\.weight$", name): ok = segs_rows(b, a, qs + [gv*gvd], qn + [gv2*gvd]) + elif re.search(r"in_proj_qkv\.weight$", name): ok = segs_rows(b, a, qs, qn) + elif re.search(r"in_proj_z\.weight$", name): ok = pad_rows_ok(b, a, gv2 * gvd) + elif re.search(r"in_proj_ba\.weight$", name): ok = segs_rows(b, a, [gv, gv], [gv2, gv2]) + elif re.search(r"in_proj_[ab]\.weight$", name): ok = pad_rows_ok(b, a, gv2) + elif re.search(r"conv1d\.(weight|bias)$", name): ok = segs_rows(b, a, qs, qn) + elif re.search(r"(A_log|dt_bias)$", name): ok = pad_rows_ok(b, a, gv2) + elif re.search(r"out_proj\.weight$", name): ok = pad_cols_ok(b, a, gv2 * gvd) + if ok is None: + same = a.shape == b.shape and np.array_equal(a, b); n_same += 1 + if not same: print("CHANGED but should be untouched:", name, a.shape, b.shape); bad += 1 + else: + n_pad += 1; zero_bytes += b.nbytes - a.nbytes + if not ok: print("PAD MISMATCH:", name, a.shape, "->", b.shape); bad += 1 + extra = set(P) - set(S) + if extra: print("EXTRA tensors in padded:", sorted(extra)[:5]); bad += 1 + print(f"verified: {n_same} untouched identical, {n_pad} padded exact (+{zero_bytes/1e9:.2f} GB of zeros), {bad} problems") + sys.exit(1 if bad else 0) + +if __name__ == "__main__": + main()