interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / tests / flash_expert / reference.py

129 lines · 6817 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Reads ONE routed expert of ONE layer of the Qwen3.8-Flash-Next FP8 checkpoint from disk and writes the raw bytes plus an independent
4reference computation. Host only; an outside reference instrument (Python float64), not part of CUDA++.
5
6 reference.py MODEL_DIR OUT_DIR [LAYER EXPERT]
7
8Writes to OUT_DIR: gate_w.bin up_w.bin down_w.bin (E4M3 bytes), gate_s.bin up_s.bin down_s.bin (BF16 weight_scale_inv, 128 x 128 blocks),
9x.f32 (the input row, 2560 floats), gu_ref.f64 and gu_mag.f64 (y = [gate; up] x and sum |terms|, 1280 values each), a.f32 (silu(gate) * up
10rounded to float32, 640 values: the down projection's input), dn_ref.f64 and dn_mag.f64 (2560 values), and manifest.txt (shard file, tensor
11name, dtype, shape, byte range and SHA-256 of every byte read). Only shard files that have no .aria2 file beside them are read.
12"""
13import hashlib
14import json
15import struct
16import sys
17from pathlib import Path
18
19import numpy as np
20
21model, out = Path(sys.argv[1]), Path(sys.argv[2])
22layer = int(sys.argv[3]) if len(sys.argv) > 3 else 0
23expert = int(sys.argv[4]) if len(sys.argv) > 4 else 3
24out.mkdir(parents=True, exist_ok=True)
25prefix = f"model.language_model.layers.{layer}.mlp.experts.{expert}."
26want = {name: prefix + name for name in (
27 "gate_proj.weight", "gate_proj.weight_scale_inv", "up_proj.weight", "up_proj.weight_scale_inv",
28 "down_proj.weight", "down_proj.weight_scale_inv")}
29
30found = {}
31for shard in sorted(model.glob("model-*.safetensors")):
32 if (shard.parent / (shard.name + ".aria2")).exists():
33 continue # a shard still downloading is never read
34 with open(shard, "rb") as f:
35 n = struct.unpack("<Q", f.read(8))[0]
36 header = json.loads(f.read(n))
37 base = 8 + n
38 for short, full in want.items():
39 if full in header and short not in found:
40 meta = header[full]
41 lo, hi = meta["data_offsets"]
42 f.seek(base + lo)
43 data = f.read(hi - lo)
44 assert len(data) == hi - lo
45 found[short] = (shard.name, full, meta["dtype"], meta["shape"], base + lo, hi - lo, data)
46missing = [k for k in want if k not in found]
47if missing:
48 print(f"NOT_RUN: tensors not in a complete shard: {missing}", file=sys.stderr)
49 sys.exit(3)
50
51expect = {"gate_proj.weight": ("F8_E4M3", [640, 2560]), "up_proj.weight": ("F8_E4M3", [640, 2560]), "down_proj.weight": ("F8_E4M3", [2560, 640]),
52 "gate_proj.weight_scale_inv": ("BF16", [5, 20]), "up_proj.weight_scale_inv": ("BF16", [5, 20]), "down_proj.weight_scale_inv": ("BF16", [20, 5])}
53for short, (dtype, shape) in expect.items():
54 assert found[short][2] == dtype and found[short][3] == shape, (short, found[short][2:4])
55
56lines = []
57files = {"gate_proj.weight": "gate_w.bin", "up_proj.weight": "up_w.bin", "down_proj.weight": "down_w.bin",
58 "gate_proj.weight_scale_inv": "gate_s.bin", "up_proj.weight_scale_inv": "up_s.bin", "down_proj.weight_scale_inv": "down_s.bin"}
59for short, name in files.items():
60 shard, full, dtype, shape, offset, size, data = found[short]
61 (out / name).write_bytes(data)
62 lines.append(f"{name} shard={shard} tensor={full} dtype={dtype} shape={shape} file_offset={offset} bytes={size} sha256={hashlib.sha256(data).hexdigest()}")
63
64# e4m3fn decode: sign, 4 exponent bits (bias 7), 3 mantissa bits; exponent 0 is subnormal (m/8 * 2^-6); 0x7f / 0xff are NaN
65lut = np.zeros(256, dtype=np.float64)
66for b in range(256):
67 s, e, m = b >> 7, (b >> 3) & 15, b & 7
68 v = np.nan if (e == 15 and m == 7) else (m / 8.0) * 2.0 ** -6 if e == 0 else (1 + m / 8.0) * 2.0 ** (e - 7)
69 lut[b] = -v if s else v
70
71
72def weights(name, rows, cols):
73 return lut[np.frombuffer(found[name][6], dtype=np.uint8).reshape(rows, cols)]
74
75
76def scales(name, rows, cols):
77 bits = np.frombuffer(found[name][6], dtype="<u2").astype(np.uint32) << 16
78 return bits.view(np.float32).astype(np.float64).reshape(rows, cols)
79
80
81def gemv(w, s, x):
82 n, k = w.shape
83 y = np.zeros(n)
84 mag = np.zeros(n)
85 for jb in range(k // 128):
86 sb = np.repeat(s[:, jb], 128) # block scale of rows 128*i .. 128*i+127
87 term = w[:, jb * 128:(jb + 1) * 128] * x[jb * 128:(jb + 1) * 128][None, :]
88 y += term.sum(axis=1) * sb
89 mag += np.abs(term).sum(axis=1) * np.abs(sb)
90 return y, mag
91
92
93x32 = (((np.arange(2560, dtype=np.int64) * 37 + 11) % 251 - 125) / 64.0).astype(np.float32) # exact in float32
94x = x32.astype(np.float64)
95g, gm = gemv(weights("gate_proj.weight", 640, 2560), scales("gate_proj.weight_scale_inv", 5, 20), x)
96u, um = gemv(weights("up_proj.weight", 640, 2560), scales("up_proj.weight_scale_inv", 5, 20), x)
97a32 = (g / (1.0 + np.exp(-g)) * u).astype(np.float32)
98d, dm = gemv(weights("down_proj.weight", 2560, 640), scales("down_proj.weight_scale_inv", 20, 5), a32.astype(np.float64))
99assert not np.isnan(g).any() and not np.isnan(u).any() and not np.isnan(d).any(), "NaN code in the bytes read"
100# Pick two detectable changes at the same weight in the final 128-column block.
101# Prefer the original measured location. Other experts have different weights and activations.
102raw = np.frombuffer(found["down_proj.weight"][6], dtype=np.uint8).reshape(2560, 640)[:128, 512:]
103gain = scales("down_proj.weight_scale_inv", 20, 5)[0, 4] * a32[512:].astype(np.float64) / dm[:128, None]
104small = np.abs((lut[raw ^ 8] - lut[raw]) * gain)
105large = np.abs((lut[0x7e] - lut[raw]) * gain)
106eligible = (small > 1.1e-6) & (small < 2.99e-5) & (large > 3.1e-5)
107if eligible[100, 88]:
108 row, col = 100, 600
109else:
110 matches = np.argwhere(eligible)
111 if not len(matches):
112 raise ValueError("no tail weight meets both sensitivity controls")
113 row, offset = matches[0]
114 col = 512 + offset
115(out / "control.u32").write_bytes(struct.pack("<II", row, col))
116lines.append(f"tail control row={row} col={col}")
117
118(out / "x.f32").write_bytes(x32.tobytes())
119(out / "gu_ref.f64").write_bytes(np.concatenate([g, u]).astype("<f8").tobytes())
120(out / "gu_mag.f64").write_bytes(np.concatenate([gm, um]).astype("<f8").tobytes())
121(out / "a.f32").write_bytes(a32.tobytes())
122(out / "dn_ref.f64").write_bytes(d.astype("<f8").tobytes())
123(out / "dn_mag.f64").write_bytes(dm.astype("<f8").tobytes())
124for name in ("x.f32", "gu_ref.f64", "gu_mag.f64", "a.f32", "dn_ref.f64", "dn_mag.f64"):
125 lines.append(f"{name} sha256={hashlib.sha256((out / name).read_bytes()).hexdigest()}")
126lines.append(f"layer={layer} expert={expert} numpy={np.__version__}")
127lines.append(f"gate_y_range=[{g.min():.6g},{g.max():.6g}] up_y_range=[{u.min():.6g},{u.max():.6g}] down_y_range=[{d.min():.6g},{d.max():.6g}]")
128(out / "manifest.txt").write_text("\n".join(lines) + "\n")
129print("\n".join(lines))