diff --git a/.gitleaksignore b/.gitleaksignore index 0bccecc491b..f86b1e2bb41 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -2,3 +2,4 @@ 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:33 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:34 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:35 +913847b4d4a06c1cb380ba63c2156b0f621be34b:zig/tests/cuda/stored_experts_check.zig:generic-api-key:73 diff --git a/CHANGELOG.md b/CHANGELOG.md index b4462e74767..80acc4eee19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -482,6 +482,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. - Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. +- Inkling 2 Mini (`inkling2_loop`) now serves natively on one CUDA rank and on Metal. CUDA runs the 48-visit text loop's cross-pass messages, rank-64 gates and separate sliding Q/K/V inputs with per-visit KV and convolution state, prompt snapshots and exact rollback; routed experts decode stored NVFP4 and MXFP8 weights to bf16 with the reference's rounding and ascending-expert FP32 accumulation, without activation quantization. Metal's default serving path stays unchanged, while opt-in DSpark drafting preserves target tokens and rolls back exactly. CUDA TP, vision and DSpark loading remain refused by name. + +- Inkling 2 on CUDA: the family's grouped-expert launches match main's `tf_exl3_grouped_2` bit for bit under the kernel contract, and the vision tower's kernels pass gates 1 to 4 (refs #3476). Thanks to @ajensenwaud. + - Tests: the served-evidence concurrency test pairs its two generated streams in the fake server, so a busy runner can no longer decode them one after the other and turn it red; other conformance fixtures keep their pacing. - GLM-5.3-Flash on CUDA at tensor-parallel widths where a rank's fused KDA input is not a multiple of eight columns (TP=3, 5, 6 or 7): the stack is padded at load to its own width rounded up to eight columns and stays row-major bf16, so prompt windows take the staged B16 tiles with every byte as before; `TF_GLM_KDA_PAD=1` still tiles the stack for glm_mm (#3697, for #3516). Thanks to @ultradaoto. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e78c64b2b7e..589ecc68454 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -579,8 +579,8 @@ extracted headers, with the same revision annotation. No revision was derived fr `release_chat_template.jinja` and `release_tokenizer_config.json` in the same folder are byte-identical copies of that revision's `chat_template.jinja` and `tokenizer_config.json`, under the same license. -The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, -`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, the CUDA and Metal loop kernels +and the stored-expert implementations in `modelopt.zig` and `zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary diff --git a/build.zig b/build.zig index 5e638d3c0c5..16926433bfb 100644 --- a/build.zig +++ b/build.zig @@ -139,6 +139,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/h3_image_contract.zig").steps(b, target, optimize); @import("zig/build/h3_image_vision.zig").steps(b, target, optimize, test_step); @import("zig/build/ling_host.zig").tests(b, target, test_step); + @import("zig/build/visit_plan_host.zig").tests(b, target, test_step); @import("zig/build/inkling2_host.zig").tests(b, target, test_step); @import("zig/build/gpt_oss_host.zig").tests(b, test_step); @import("zig/build/digest.zig").steps(b, test_step, draft_ids, build_options); diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md new file mode 100644 index 00000000000..73da616c6de --- /dev/null +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -0,0 +1,24 @@ +# Inkling 2 Mini on CUDA: jschmied's #4441 engine registered, with #4387's checks and a whole-model run on TOP + +- Merges Ash's #4387 and jschmied's C1 (#4364), C3 (#4365) and H2 + C4 (#4441) with their commits. `inkling2_loop` + is now served by #4441's engine (graphs, fused input projections, every stream's rows in one forward); #4387's + separate loop engine, which the merge of `main` brought back, stays removed, so CUDA no longer advertises structured + output it refused. +- #4387's serving checks (device draws against host selection, fresh against resumed prompts, a prompt resumed after + another prompt resumed its prefix, two streams in shared rounds against each alone) run against #4441's engine. + Copy drafting is not checked: that engine has no draft path yet. +- The merge of `main` keeps its Metal Mini fixes: a window's grammar masks step by the padded vocabulary's words; a + snapshot copies each key head's live rows, so it restores into a cache of another capacity; norm binds where `sp_norm` + reads; a later stream of a shared forward reads its relative rows where prep wrote them; and the real-checkpoint + serving test draws the first token before its row. +- `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: the serving checks, + the float64 reference and its planted control, then first-token time, prompt speed, decode speed, memory + (`/proc/meminfo`) and the bandwidth limit at 1 and 4 streams; 4 streams must give 1.5 times one stream's total. + After the build, every check and both levels run inside `timeout 600`. + The recipe's README notes what RTX Spark (native Windows and WSL2) needs. +- `tf-cuda-test kernel-contract "inkling2 loop"` checks the served `loop.cu` message mix and three gate launches + against FP64 references, with planted controls (an aliased block, a gate reading the wrong role plane). +- Metal Mini admission budgets a target state for every stream, so concurrent full-window requests no longer run out + of state; the Metal checkpoint check reads the first logprob row after the first token, and an expired token + handle (more than 4,096 draws old) is refused instead of reading a newer token. +- A forward with token id `vocab` is refused before any launch (host test). diff --git a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md new file mode 100644 index 00000000000..4d9d93b752a --- /dev/null +++ b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md @@ -0,0 +1,10 @@ +# Inkling 2 Mini against llama.cpp on TOP's GB10 + +- `docs/recipes/inkling-2-mini-cuda/compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged + sources and serves Unsloth's UD-Q4_K_M GGUF at the CUDA receipt's settings, with each engine's file bytes, + `peak-memory.py`'s server peak, and greedy and teacher-forced agreement with the float64 reference. +- The recipe README sets it beside TensorFold's receipt from 188 (jobs `top-b77911768550`, `top-c0075bd36227` + against `top-0b05213c9f06`): 38.8 against 32.9 tok/s at one stream, 85.9 against 117.9 at four, 15.47 against + 18.78 GiB of weights, and 106.4 against 199.4 tok/s uncached at one-stream prompt processing. llama.cpp's + free-running text matches the reference continuation when re-tokenized, but its teacher-forced picks match 31 of 32 + reference tokens; TensorFold matches 32 of 32. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md new file mode 100644 index 00000000000..c473df7e183 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -0,0 +1,92 @@ +# Inkling 2 Mini on TOP's GB10 + +`run-script.sh` runs thinkingmachines/Inkling-2-Mini (revision `ed40e7da62`) whole on TOP's Spark through the Desk's +GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as `Inkling-2-Mini` (or +`models/Inkling-2-Mini`); the script refuses and lists the Inkling configs under `/assets` when it does not. + +The server is jschmied's #4441 engine (`inkling2.native`, model type `inkling2_loop`, on his #4364 and #4365): graphs, +fused input projections and one batched forward for every stream's rows in a round. #4387's checks run against it. +Upstream, jschmied closed #4441 on 23 Nov as superseded: Mini on CUDA goes through #4387's engine there (#4640, then +#4697, #4718, #4728 and #4729 for speed). This branch is local; an upstream claim must move to that stack first. +The script fails on any of: `tf-cuda-test kernel-contract "inkling2 loop"` (the served message and gate kernels +against FP64 references, with their planted controls), `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 +greedy tokens equal to the float64 host reference), that reference's planted control staying green, a failed stream +in `tools/bench_concurrent.py` at 1 and 4 streams, or 4 streams giving under 1.5 times one stream's total tok/s. The +receipt also sets one stream's decode against GB10's bandwidth limit: the weight bytes a token reads (from the +checkpoint's headers) over 273 GB/s. + +## Receipt: TOP's GB10, one capped run + +Job `top-a96a7d63bedf` at `22fb3250e`, `--context 8192`, greedy, 256 tokens, 3 reps, medians; the build ran first, then +every check and both levels inside `timeout 600`. This is one run with these settings, not a benchmark. + +| Streams | First token (code / chat) | Prompt (code) | Decode a stream (code / chat) | Total decode (code / chat) | Failed | +|---|---|---|---|---|---| +| 1 | 0.076 s / 0.097 s | 197.4 tok/s | 32.9 / 33.1 tok/s | 32.9 / 33.1 tok/s | 0 | +| 4 | 0.187 s / 0.207 s | 83.4 tok/s | 29.9 / 30.3 tok/s | 117.7 / 121.1 tok/s | 0 | + +The 4-stream gate takes each level's better prompt: 121.1 over 33.1 tok/s, 3.66x. Every stream sends the same prompt, +so the four streams route to the same experts; mixed traffic may give a lower 4-stream rate. + +Checks in the same job: the CUDA engine matched the host reference token for token, fresh and resumed prompts gave +identical logits and tokens, a prompt resumed after another prompt resumed its prefix equalled the fresh one, and two +lanes in shared rounds kept their tokens; 0 of 32 greedy tokens differed from the float64 reference (smallest reference +margin 0.11), and its planted control (no messages) differed at 6. The kernel contract passed gates 1-4 on all 5 loop +kernels with both planted controls red. + +Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 12.3 GiB before the server, +33.5 GiB with Mini loaded for 4 streams and 33.4 GiB after both levels; the server held 20.0 GiB of GPU memory +(`nvidia-smi`). + +Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the +whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.9 tok/s is 67% of it. #4387's own engine, removed +here, gave 5.7 tok/s at one stream and 9.4 at four on the same GB10 (job `top-0759755a0515`). + +## Against llama.cpp: Unsloth's UD-Q4_K_M GGUF on the same GB10 + +`compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged sources, checks the GGUF's sha256 +(`78fcedcf…34ae`), the gcc archive and the b12611 source tree, and serves it at the receipt's settings (4 slots of +8,192 positions, all layers on the GPU, greedy, 256 tokens, 3 reps, medians). Job `top-b77911768550` at `b65744605`; +the uncached one-stream prompt and source pin were checked by job `top-c0075bd36227` at `941dbada`. TensorFold's column +is the receipt above. + +| | TensorFold (bf16 safetensors) | llama.cpp (UD-Q4_K_M) | +|---|---|---| +| Weights on disk | 20,161,820,584 bytes (18.78 GiB, with the 635,801,416-byte draft head `mtp.safetensors`) | 16,610,544,608 bytes (15.47 GiB) | +| Decode, 1 stream (code / chat) | 32.9 / 33.1 tok/s | 38.8 / 39.1 tok/s | +| Decode total, 4 streams (code / chat) | 117.7 / 121.1 tok/s | 85.9 / 87.6 tok/s | +| 4 streams over 1 | 3.66x | 2.24x | +| First token, 1 stream (code / chat) | 0.076 s / 0.097 s | 0.067 s (slot cache hit) / 0.130 s | +| Prompt, 1 stream (code, uncached) | 197.4 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | +| Prompt, 4 streams (code) | 83.4 tok/s | 43.0 tok/s (cold requests only) | +| Memory, server loaded | 20.0 GiB GPU (`nvidia-smi`) | 18.1 GiB GPU (`nvidia-smi`); peak 20.57 GiB: 18.18 GPU + 2.38 resident | +| Continuation text / teacher-forced tokens vs float64 reference | 32 of 32 token picks | Same free-running text when re-tokenized / 31 of 32 token picks (differs at 5) | + +`bench_concurrent.py` warms up with the same code prompt before measuring: llama.cpp's slot cache answers every +one-stream request, so its code first token is a cache hit and `prompt_ttft_tps` is null (only cold requests +qualify). The separate uncached `/completion` measurement above supplies the missing one-stream comparison; it times +the full one-token response (0.14 s) rather than first streamed token, so its client latency includes that token's +transfer. At 4 streams the prompt figure is likewise the median of cold requests only; later rounds likely reuse the +slots the first filled, so it is about one round's requests rather than a median of 3. llama.cpp decodes one stream +18% faster from 18% fewer weight bytes on disk (15% fewer without the draft head, which `serve` does not load); at 4 +streams TensorFold's total is 37% higher. TensorFold's memory is a sample after loading, not +`peak-memory.py`'s process peak. Quality: llama.cpp's free-running text matches the 32-token reference continuation +when re-tokenized, but its teacher-forced token picks agree at 31 of 32 positions (different at position 5); +TensorFold's token picks agree at all 32 positions. + +## RTX Spark (N1X): what differs and what must change + +I see the same chip and memory model as the GB10: sm_121 and one unified pool, so the `-Dsm=121` kernel images are +the same. What differs is the host. RTX Spark runs Windows on Arm, with WSL2 as the +Linux route. From #1010 (`5b1f10812`) and #2107: + +- Native Windows builds as `aarch64-windows` with VS 2022 Build Tools' ARM64 C++ tools (`vcvarsall arm64`) as nvcc's + host compiler and the CUDA 13.4 `windows-arm64` redistributables (winget has no arm64 installer). Admission reads the + WDDM pool through `cuMemGetInfo_v2`, and `nvidia-smi`'s NPU row is filtered out. +- Under WSL2 `/proc/meminfo` is WSL's RAM (about 30 GiB of 128 GB), not the GPU's 96 GB WDDM pool; with + `WSL_DISTRO_NAME` set, admission reads the CUDA pool instead (`TENSORFOLD_UNIFIED_HOST_COUNTS` overrides it). +- For Mini on native Windows, I need the Inkling CUDA kernels compiled with MSVC as nvcc's host front end (only gcc 14 + has built them so far) and one load of the 18.2 GiB text shard (`model-00001-of-00001.safetensors`) through Windows' + threaded reads. +- For Mini under WSL2, I need neither: it is the Linux build with gcc 14. Only the pool reading above differs. +- Either way, the GB10's exactness checks must be repeated on the N1X. No N1X run of Mini exists yet. diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh new file mode 100755 index 00000000000..0ddcf933869 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Inkling 2 Mini on TOP's GB10, llama.cpp's side of the README's comparison: +# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/compare.sh +# Prints each engine's weight files on disk (TensorFold's include the draft head mtp.safetensors, which serve does not +# load), builds llama-server, then measures it under peak-memory.py with the measured part capped at 10 minutes. +# TensorFold's side is run-script.sh's own job (its float64 reference alone takes over 4 minutes); the README sets the +# two side by side. +set -eu +here=docs/recipes/inkling-2-mini-cuda +pilot=/assets/drama3-pilot +bytes() { stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {printf "%.0f bytes (%.3f GiB)", s, s / 2^30}'; } +echo "RESULT tensorfold bf16 checkpoint: $(bytes "$pilot"/Inkling-2-Mini/*.safetensors "$pilot"/models/Inkling-2-Mini/*.safetensors)" +echo "RESULT llama.cpp UD-Q4_K_M GGUF: $(bytes "$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf")" +start=$(date +%s) +sh "$here/llama-cpp-build.sh" +echo "build: $(($(date +%s) - start)) s" +start=$(date +%s) +# llama-server runs as the toolchain's loader (llama-cpp-build.sh), so that is the program peak-memory.py watches +timeout 600 python3 "$here/peak-memory.py" ld-linux-aarch64.so.1 sh "$here/llama-cpp-baseline.sh" +echo "measure: $(($(date +%s) - start)) s" diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh new file mode 100755 index 00000000000..cc4406a8da3 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10, served by the +# llama-server llama-cpp-build.sh left in /work/llama-build, on the staged toolchain's loader. compare.sh runs both. +set -eu +pilot=/assets/drama3-pilot +gguf=$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf +out=/work/out/inkling2-llama +rm -rf "$out" +mkdir -p "$out" +mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } +mem "before the server" +# run-script.sh's settings: 4 streams of 8,192 positions each +sh /work/llama-build/llama-server.sh -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ + --no-webui >"$out/server.log" 2>&1 & +server=$! +trap 'status=$?; kill $server 2>/dev/null || :; [ $status = 0 ] || { echo "llama-server log, last 60 lines:"; tail -n 60 "$out/server.log"; }' EXIT +until python3 -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5)' 2>/dev/null; do + if ! kill -0 "$server" 2>/dev/null; then + wait "$server" && code=0 || code=$? + echo "llama-server exited with status $code before answering /health" >&2 + exit 1 + fi + sleep 1 +done +mem "server loaded" +# the receipt names what the server did with -c and -ngl +grep -m 2 -E 'n_ctx_slot|offloaded' "$out/server.log" || : +# The bench warm-up fills llama.cpp's slot cache; measure the code prompt cold before it. +python3 - <<'EOF' +import json, statistics, sys, time, urllib.request +sys.path.insert(0, "tools") +from bench_concurrent import PROMPTS +prompt = next(p["prompt"] for p in PROMPTS if p["name"] == "code") +rates = [] +for _ in range(3): + body = json.dumps({"prompt": prompt, "n_predict": 1, "temperature": 0, "cache_prompt": False}).encode() + request = urllib.request.Request("http://127.0.0.1:8189/completion", body, {"Content-Type": "application/json"}) + start = time.perf_counter() + with urllib.request.urlopen(request, timeout=300) as response: + tokens = json.load(response)["timings"]["prompt_n"] + rates.append(tokens / (time.perf_counter() - start)) +print(f"RESULT llama.cpp q4_k_m gb10 1 stream code prompt, uncached: {tokens} tokens, median {statistics.median(rates):.1f} tok/s (prompt tokens over the one-token reply's time)") +EOF +for level in 1 4; do + python3 tools/bench_concurrent.py http://127.0.0.1:8189 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ + --temperatures 0 --label "llama-$level" --output "$out/streams-$level.json" + mem "after $level streams" +done +python3 - "$out" <<'EOF' +import json, sys, urllib.request +out = sys.argv[1] +def post(path, body): + req = urllib.request.Request(f"http://127.0.0.1:8189{path}", json.dumps(body).encode(), {"Content-Type": "application/json"}) + return json.load(urllib.request.urlopen(req, timeout=300)) +agg = {} +for level in (1, 4): + cells = json.load(open(f"{out}/streams-{level}.json"))["cells"] + if any(c.get("failed") for c in cells): + raise SystemExit(f"{level} streams: a request failed") + agg[level] = max(c["aggregate_tps"] for c in cells) + for c in cells: + r = c["request"] + print(f"RESULT llama.cpp q4_k_m gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") +print(f"RESULT llama.cpp q4_k_m gb10 aggregate decode: 1 stream {agg[1]:.1f} tok/s, 4 streams {agg[4]:.1f} tok/s ({agg[4] / agg[1]:.2f}x)") +# run-script.sh's float64 reference continuation of this prompt (job top-16bffb6ca094: TensorFold equals it on all 32) +prompt = "The three laws of thermodynamics, explained for a curious student:" +want = "\n\n 1. Energy cannot be created or destroyed, only transformed.\n 2. Entropy (disorder) in a closed system always increases." +got = post("/completion", {"prompt": prompt, "n_predict": 32, "temperature": 0, "cache_prompt": False})["content"] +ids = lambda s: post("/tokenize", {"content": s})["tokens"] +w, g = ids(want), ids(got) +same = next((i for i, (a, b) in enumerate(zip(w, g)) if a != b), min(len(w), len(g))) +print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference, as text (re-tokenized): first {same} of {len(w)} tokens equal: {got!r}") +# teacher-forced, as tf-cuda-test inkling2-mini-ref scores TensorFold: after the reference's own prefix, is llama.cpp's +# next pick the reference's token? A free run says nothing past its first difference. +start = post("/tokenize", {"content": prompt, "add_special": True})["tokens"] +piece = lambda t: post("/detokenize", {"tokens": [t]})["content"] +pick = lambda i: post("/completion", {"prompt": start + w[:i], "n_predict": 1, "temperature": 0, "cache_prompt": False})["content"] +misses = [i for i in range(len(w)) if pick(i) != piece(w[i])] +print(f"RESULT llama.cpp q4_k_m teacher-forced on the float64 reference: {len(w) - len(misses)} of {len(w)} picks equal, differing at {misses}") +EOF diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh new file mode 100755 index 00000000000..8e26397946d --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Builds llama.cpp b12611's CUDA llama-server into /work/llama-build for llama-cpp-baseline.sh. The job has no network: +# the Desk staged Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file (renamed .gguf) in the pilot folder's +# inkling-gguf, and llama.cpp b12611 (690b87d88, ggml-org #32704's merge) with CMake 3.31.6's linux-aarch64 archive in +# inkling-llamacpp. +set -eu +pilot=/assets/drama3-pilot +llama=$pilot/inkling-llamacpp +staged=$pilot/cuda-build-toolchain +gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu +cmake=cmake-3.31.6-linux-aarch64 +sha256sum -c --quiet <&2 + exit 1 +} +tar -C /work -xJf "$staged/$gcc.tar.xz" +tar -C /work -xzf "$llama/$cmake.tar.gz" +cc=/work/$gcc/bin/aarch64-none-linux-gnu +cuda_lib=/usr/local/cuda/targets/sbsa-linux/lib +# the staged gcc's ld searches only its own sysroot: point it at the toolkit and the host driver for libggml-cuda's needs +/work/$cmake/bin/cmake -S "$llama/llama.cpp-b12611" -B /work/llama-build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121 \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER="$cc-gcc" -DCMAKE_CXX_COMPILER="$cc-g++" \ + -DCMAKE_CUDA_COMPILER=/usr/local/cuda/bin/nvcc -DCMAKE_CUDA_HOST_COMPILER="$cc-g++" -DLLAMA_OPENSSL=OFF \ + -DCMAKE_EXE_LINKER_FLAGS="-Wl,-rpath-link,$cuda_lib:$cuda_lib/stubs:/usr/lib/aarch64-linux-gnu" \ + -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF >/dev/null +/work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null +# The staged gcc links against its own glibc 2.40 and libstdc++, newer than the job image's (GLIBC_2.38 and +# GLIBCXX_3.4.32 missing), so the server runs on the toolchain's loader. --library-path, unlike LD_LIBRARY_PATH, reaches +# only this process and wins over the driver libraries' RUNPATH, so librt (GLIBC_PRIVATE) matches its libc; the image's +# directory comes last, for libcuda and what else only the driver ships. +rt=/work/$gcc/aarch64-none-linux-gnu/libc +loader="$rt/lib/ld-linux-aarch64.so.1 --library-path $rt/lib64:$rt/usr/lib64:/work/llama-build/bin:$cuda_lib:/usr/lib/aarch64-linux-gnu" +echo "exec $loader /work/llama-build/bin/llama-server \"\$@\"" >/work/llama-build/llama-server.sh +# a loader error, or a glibc or libstdc++ library resolved from the image, shows here, before the measured part +if $loader --list /work/llama-build/bin/llama-server | grep -E '^\s*lib(c|m|rt|dl|pthread|stdc\+\+|gcc_s|gomp)\.so' | grep -v "$rt/"; then + echo "the libraries above resolved outside the toolchain's $rt" >&2 + exit 1 +fi +sh /work/llama-build/llama-server.sh --version diff --git a/docs/recipes/inkling-2-mini-cuda/peak-memory.py b/docs/recipes/inkling-2-mini-cuda/peak-memory.py new file mode 100755 index 00000000000..3b6796a8a42 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/peak-memory.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""peak-memory.py NAME COMMAND...: runs COMMAND and prints the peak memory of the server whose program is NAME. + +It samples twice a second while COMMAND runs and exits with COMMAND's status. GB10 has one memory pool, so the peak +is the largest sum in one sample of the GPU memory nvidia-smi gives the job's compute processes and the server's +RssAnon + RssShmem. RssFile stays out: a mapped weight file's pages are page cache the kernel can drop, and VmHWM +(printed beside the peak) counts them. The fall in MemAvailable since the last sample before the server counts every +byte once, with whatever else the job held meanwhile. +""" +import glob, os, signal, subprocess, sys, time + +name, command = sys.argv[1], sys.argv[2:] + + +def server() -> str | None: + for path in glob.glob("/proc/[0-9]*/cmdline"): + try: + program = open(path, "rb").read().split(b"\0")[0].decode() + except OSError: + continue + if os.path.basename(program) == name: + return path.split("/")[2] + return None + + +def kib(path: str) -> dict[str, int]: + """The kB fields of a /proc status or meminfo file.""" + fields = (line.split(":", 1) for line in open(path)) + return {k: int(v.split()[0]) for k, v in fields if v.endswith("kB\n")} + + +def gpu_kib() -> int: + rows = subprocess.run(["nvidia-smi", "--query-compute-apps=used_memory", "--format=csv,noheader,nounits"], + capture_output=True, text=True, check=True).stdout.split() + return 1024 * sum(int(mib) for mib in rows) + + +job = subprocess.Popen(command, start_new_session=True) + + +def stop(_signum, _frame): + os.killpg(job.pid, signal.SIGTERM) + job.wait() + sys.exit(124) + + +signal.signal(signal.SIGTERM, stop) +before = kib("/proc/meminfo")["MemAvailable"] +peak, hwm, fall, seen = (0, 0, 0), 0, 0, False +while job.poll() is None: + pid = server() + try: + status = kib(f"/proc/{pid}/status") if pid else None + except OSError: + status = None + available = kib("/proc/meminfo")["MemAvailable"] + if status: + seen = True + gpu, resident = gpu_kib(), status.get("RssAnon", 0) + status.get("RssShmem", 0) + peak = max(peak, (gpu + resident, gpu, resident)) + hwm, fall = max(hwm, status.get("VmHWM", 0)), max(fall, before - available) + elif not seen: + before = available + time.sleep(0.5) +gib = lambda k: f"{k / 2**20:.2f} GiB" +if seen: + print(f"RESULT {name} peak memory: {gib(peak[0])} (GPU {gib(peak[1])} + resident anon and shmem {gib(peak[2])}), " + f"VmHWM {gib(hwm)}, MemAvailable fell {gib(fall)}", flush=True) +elif job.returncode == 0: + sys.exit(f"{name} never ran under {' '.join(command)}: no peak memory to report") +sys.exit(job.returncode) diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh new file mode 100755 index 00000000000..ce07595f5c4 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -0,0 +1,113 @@ +#!/bin/sh +# Inkling 2 Mini (thinkingmachines/Inkling-2-Mini, revision ed40e7da62) whole on TOP's GB10: +# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/run-script.sh +# The job has no network: the Desk put the checkpoint in the pilot folder as Inkling-2-Mini, and the toolchain +# archives of ../minimax-h3-cuda/toolchain-stage.sh beside it. Logs and the 1/4-stream receipt land in /work/out/inkling2. +set -eu +pilot=/assets/drama3-pilot +staged=$pilot/cuda-build-toolchain +zig=zig-aarch64-linux-0.17.0 +gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu +out=/work/out/inkling2 +model= +for dir in "$pilot/Inkling-2-Mini" "$pilot/models/Inkling-2-Mini"; do + [ -f "$dir/config.json" ] && model=$dir && break +done +if [ -z "$model" ]; then + echo "no Inkling-2-Mini/config.json in $pilot or $pilot/models; Inkling configs under /assets:" >&2 + find /assets -maxdepth 5 -name config.json -exec grep -l '"inkling2' {} + >&2 || true + exit 1 +fi +# TOP's GPU slot is 10 minutes of measurement: the build runs first, then the script again under timeout, with its status +if [ -z "${INKLING2_TIMED:-}" ]; then + [ -d "$staged" ] || { echo "missing $staged: run ../minimax-h3-cuda/toolchain-stage.sh" >&2; exit 1; } + (cd "$staged" && sha256sum -c --quiet) <"$out/ids.txt" +"$bin/tf-cuda-test" inkling2-serving "$model" "$out/ids.txt" +text="The three laws of thermodynamics, explained for a curious student:" +# the float64 reference runs on one host core: its planted control runs beside it, and each must exit 0 +INKLING2_REF_PLANT=1 "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" >"$out/planted.log" 2>&1 & +planted=$! +trap 'kill $planted 2>/dev/null || :' EXIT +"$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" +wait $planted || { cat "$out/planted.log"; exit 1; } +cat "$out/planted.log" +mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } +mem "before the server" +/work/sm121/native/bin/tensorfold-native serve "$model" --backend cuda --host 127.0.0.1 --port 8188 \ + --name inkling-2-mini --parallel 4 --context 8192 --no-update-check >"$out/server.log" 2>&1 & +server=$! +trap 'kill $server 2>/dev/null || :' EXIT +python3 - <<'EOF' +import time, urllib.request +for _ in range(180): + try: + urllib.request.urlopen("http://127.0.0.1:8188/v1/models", timeout=5) + raise SystemExit(0) + except OSError: + time.sleep(1) +raise SystemExit("server did not answer /v1/models in 3 min") +EOF +mem "server loaded" +for level in 1 4; do + python3 tools/bench_concurrent.py http://127.0.0.1:8188 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ + --temperatures 0 --label "gb10-$level" --output "$out/streams-$level.json" + mem "after $level streams" +done +python3 - "$out" "$model" <<'EOF' +import glob, json, re, struct, sys +out, model = sys.argv[1:] +agg = {} +for level in (1, 4): + cells = json.load(open(f"{out}/streams-{level}.json"))["cells"] + if any(c.get("failed") for c in cells): + raise SystemExit(f"{level} streams: a request failed") + agg[level] = max(c["aggregate_tps"] for c in cells) + for c in cells: + r = c["request"] + print(f"RESULT inkling2 mini gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") +# weight bytes one decoded token reads: the core layers (loop_config) run num_passes times, each visit reads +# num_experts_per_tok of n_routed_experts experts, the unembedding is read whole and the embedding one row +text = json.load(open(f"{model}/config.json")) +text = text.get("text_config", text) +loop = text["loop_config"] +per_token = 0.0 +for path in glob.glob(f"{model}/*.safetensors"): + with open(path, "rb") as f: + header = json.loads(f.read(struct.unpack("= 0.f ? 1.f / (1.f + e) : e / (1.f + e); + return gc * tanhf(g / gc) * sg * (uc * tanhf(u / uc)); +} + // a < 0 ? 0 : a, not fmaxf, which would make a NaN sum 0. __device__ __forceinline__ float relu2(float a) { const float b = bf(a), u = b < 0.f ? 0.f : b; @@ -61,7 +68,7 @@ __device__ __forceinline__ float relu2(float a) { template __device__ __forceinline__ void epilogue(const float (&acc)[M][RT][NTW][4], int r, void* out, int N, int col0, int pr0, - int pr1, bool v0, bool v1, float limit) { + int pr1, bool v0, bool v1, float limit, float limit2 = 0.f) { #pragma unroll for (int h = 0; h < 2; ++h) { if (!(h ? v1 : v0)) continue; @@ -80,6 +87,14 @@ __device__ __forceinline__ void epilogue(const float (&acc)[M][RT][NTW][4], int } else if constexpr (EPI == 2) { o0 = swiglu(a0, acc[M - 1][r][j][2 * h], limit); o1 = swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit); + } else if constexpr (EPI == 4) { // limit and limit2: the gate's and the up's caps + if (limit2 < 0.f) { // an A/B switch (round_caps): gate and up rounded to bf16 before the caps + o0 = softcap_swiglu(bf(a0), bf(acc[M - 1][r][j][2 * h]), limit, -limit2); + o1 = softcap_swiglu(bf(a1), bf(acc[M - 1][r][j][2 * h + 1]), limit, -limit2); + } else { + o0 = softcap_swiglu(a0, acc[M - 1][r][j][2 * h], limit, limit2); + o1 = softcap_swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit, limit2); + } } else { o0 = a0; o1 = a1; diff --git a/zig/kernels/cuda/fp8_experts.cu b/zig/kernels/cuda/fp8_experts.cu index 10c2492ba2e..21e02a6a427 100644 --- a/zig/kernels/cuda/fp8_experts.cu +++ b/zig/kernels/cuda/fp8_experts.cu @@ -268,3 +268,223 @@ template __global__ void fp8_expert_prompt_kernel<2, 2, 2, 2>(const __nv_bfloat1 template __global__ void fp8_expert_prompt_kernel<1, 0, 4, 4>(const __nv_bfloat16* __restrict__, int, int, const uint4* __restrict__, const float* __restrict__, int, int, const int* __restrict__, const int* __restrict__, const int* __restrict__, void* __restrict__, int, float, int); template __global__ void fp8_expert_prompt_kernel<1, 3, 4, 4>(const __nv_bfloat16* __restrict__, int, int, const uint4* __restrict__, const float* __restrict__, int, int, const int* __restrict__, const int* __restrict__, const int* __restrict__, void* __restrict__, int, float, int); } + +// MXFP8 experts (Inkling 2 Mini's layers 20-23): e4m3 codes, one E8M0 scale per output row per 32 inputs. Each code +// times its scale is exact in bf16 (a power of two), so the weights enter the mma decoded and the sums stay fp32. +namespace tf_mxfp8_experts { + +using tf_common::fp8pair; +using tf_common::mul2; + +constexpr int MXB = 66; // uint4 a (32 columns, 32 inputs) block: fp8g's 64 of codes, then 32 E8M0 bytes +constexpr int PWARPS = 4, PSTAGES = 4; + +// 2^(e - 127) in both bf16 halves: code 0 is 2^-127 (a bf16 subnormal), 255 is NaN. +__device__ __forceinline__ uint32_t e8m0x2(uint32_t e) { + const uint32_t b = e == 0u ? 0x0040u : e == 255u ? 0x7FC0u : e << 7; + return b | (b << 16); +} + +// Column j * 8 + gq's decoded pair (inputs 4t, 4t + 1) and (4t + 2, 4t + 3) of a lane's word. +__device__ __forceinline__ void pairs(uint32_t word, uint32_t sv, uint32_t& b0, uint32_t& b1) { + b0 = mul2(fp8pair(word), sv); + b1 = mul2(fp8pair(word >> 16), sv); +} + +template +struct Stage { + uint4 w[M][2]; + uint32_t s[M]; // byte j: column j * 8 + gq's scale + uint2 xa[2], xb[2]; +}; + +template +__device__ __forceinline__ void load(Stage& st, const uint4* blk, int g, int lane, int gq, int t, + const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { + const uint4* b = blk + (size_t)g * (M * MXB); +#pragma unroll + for (int m = 0; m < M; ++m) { + st.w[m][0] = tf_common::ld_nc(b + m * MXB + 2 * lane); + st.w[m][1] = tf_common::ld_nc(b + m * MXB + 2 * lane + 1); + st.s[m] = __ldg(reinterpret_cast(b + m * MXB + 64) + gq); + } + const uint2 zero = make_uint2(0u, 0u); + const int k0 = g * 32 + 4 * t; +#pragma unroll + for (int h = 0; h < 2; ++h) { + st.xa[h] = v0 ? __ldg(reinterpret_cast(x0 + k0 + 16 * h)) : zero; + st.xb[h] = v1 ? __ldg(reinterpret_cast(x1 + k0 + 16 * h)) : zero; + } +} + +template +__device__ __forceinline__ void sum(float (&acc)[M][1][NTW][4], const Stage& st) { +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) { + const uint32_t sv = e8m0x2((st.s[m] >> (8 * j)) & 0xFFu); +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint32_t b0, b1; + pairs(comp(st.w[m][h], j), sv, b0, b1); + mma(acc[m][0][j], st.xa[h].x, st.xb[h].x, st.xa[h].y, st.xb[h].y, b0, b1); + } + } +} + +// Decode rows: a warp's 32 columns of an item over all K, 16 pairs at a time, two k32 stages in registers. +template +__device__ __forceinline__ void decode_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, + const uint4* __restrict__ W, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, + void* __restrict__ out, int N, float cap0, float cap1, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(counts) * NB; + for (int unit = blockIdx.x * 4 + (threadIdx.x >> 5); unit < units; unit += gridDim.x * 4) { + const int it = unit / NB, cb = unit - it * NB; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + const uint4* blk = W + ((size_t)e * NB + cb) * (size_t)KG * (M * MXB); + for (int r0 = 0; r0 < cnt; r0 += 16) { + const bool v0 = r0 + gq < cnt, v1 = r0 + gq + 8 < cnt; + const int pr0 = v0 ? __ldg(members + first + r0 + gq) : 0; + const int pr1 = v1 ? __ldg(members + first + r0 + gq + 8) : 0; + const __nv_bfloat16* x0 = X + (size_t)(slots ? pr0 / slots : pr0) * x_stride; + const __nv_bfloat16* x1 = X + (size_t)(slots ? pr1 / slots : pr1) * x_stride; + float acc[M][1][NTW][4]; +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][0][j][0] = acc[m][0][j][1] = acc[m][0][j][2] = acc[m][0][j][3] = 0.f; + Stage st[2]; +#pragma unroll + for (int d = 0; d < 2; ++d) + if (d < KG) load(st[d], blk, d, lane, gq, t, x0, x1, v0, v1); + for (int g0 = 0; g0 < KG; g0 += 2) { +#pragma unroll + for (int d = 0; d < 2; ++d) { + if (g0 + d >= KG) break; + sum(acc, st[d]); + if (g0 + d + 2 < KG) load(st[d], blk, g0 + d + 2, lane, gq, t, x0, x1, v0, v1); + } + } + epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, cap0, cap1); + } + } +} + +// Prompt rows: items of 64 pairs, CW warps of columns by 4 / CW warps of rows, k32 groups staged in shared memory. +template +__device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, + const uint4* __restrict__ W, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, + void* __restrict__ out, int N, float cap0, float cap1, int skip) { + static_assert((PWARPS / CW) * RT * 16 == 64, "a prompt item holds 64 pairs"); + __shared__ uint4 sw[PSTAGES][CW][M * MXB]; + __shared__ uint4 sx[PSTAGES][64][4]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int cw = warp % CW, rw = warp / CW; + const int groups = NB / CW, units = __ldg(counts) * groups; + for (int unit = blockIdx.x; unit < units; unit += gridDim.x) { + const int it = unit / groups, cg = unit - it * groups; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + const int cb = cg * CW + cw; + int pr0[RT], pr1[RT]; + bool v0[RT], v1[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int r0 = (rw * RT + r) * 16; + v0[r] = r0 + gq < cnt; + v1[r] = r0 + gq + 8 < cnt; + pr0[r] = v0[r] ? __ldg(members + first + r0 + gq) : 0; + pr1[r] = v1[r] ? __ldg(members + first + r0 + gq + 8) : 0; + } + const __nv_bfloat16* xrow[2]; +#pragma unroll + for (int c = 0; c < 2; ++c) { + const int i = threadIdx.x + c * PWARPS * 32, pr = __ldg(members + first + min(i / 4, cnt - 1)); + xrow[c] = X + (size_t)(slots ? pr / slots : pr) * x_stride + (i % 4) * 8; + } + const uint4* base = W + ((size_t)e * NB + cg * CW) * (size_t)KG * (M * MXB); + auto stage = [&](int g) { +#pragma unroll + for (int c = 0; c < 2; ++c) { + const int i = threadIdx.x + c * PWARPS * 32; + cp16(&sx[g % PSTAGES][i / 4][i % 4], xrow[c] + g * 32); + } + for (int i = threadIdx.x; i < CW * M * MXB; i += PWARPS * 32) { + const int c = i / (M * MXB), j = i % (M * MXB); + cp16(&sw[g % PSTAGES][c][j], base + ((size_t)c * KG + g) * (M * MXB) + j); + } + }; + __syncthreads(); +#pragma unroll + for (int g = 0; g < PSTAGES - 1; ++g) { + if (g < KG) stage(g); + cp_commit(); + } + float acc[M][RT][NTW][4]; +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][r][j][0] = acc[m][r][j][1] = acc[m][r][j][2] = acc[m][r][j][3] = 0.f; + const bool live = rw * RT * 16 < cnt; + for (int g = 0; g < KG; ++g) { + cp_wait(); + __syncthreads(); + if (g + PSTAGES - 1 < KG) stage(g + PSTAGES - 1); + cp_commit(); + if (!live) continue; + const int sg = g % PSTAGES; +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint2 xa[RT], xb[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int r0 = (rw * RT + r) * 16 + gq; + xa[r] = reinterpret_cast(&sx[sg][r0][0])[4 * h + t]; + xb[r] = reinterpret_cast(&sx[sg][r0 + 8][0])[4 * h + t]; + } +#pragma unroll + for (int m = 0; m < M; ++m) { + const uint4 wv = sw[sg][cw][m * MXB + 2 * lane + h]; + const uint32_t s4 = reinterpret_cast(&sw[sg][cw][m * MXB + 64])[gq]; +#pragma unroll + for (int j = 0; j < NTW; ++j) { + uint32_t b0, b1; + pairs(comp(wv, j), e8m0x2((s4 >> (8 * j)) & 0xFFu), b0, b1); +#pragma unroll + for (int r = 0; r < RT; ++r) mma(acc[m][r][j], xa[r].x, xb[r].x, xa[r].y, xb[r].y, b0, b1); + } + } + } + } + cp_wait<0>(); + if (live) { +#pragma unroll + for (int r = 0; r < RT; ++r) + epilogue(acc, r, out, N, cb * COLS + 2 * t, pr0[r], pr1[r], v0[r], v1[r], cap0, cap1); + } + } +} + +} // namespace tf_mxfp8_experts + +// The MXFP8 entries (cap0, cap1: the gate's and the up's caps; the downs ignore them), 128 threads each. +#define TF_MX_ENTRY(NAME, BODY) \ + extern "C" __global__ void __launch_bounds__(128) \ + NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, int KG, \ + int NB, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, \ + void* __restrict__ out, int N, float cap0, float cap1, int skip) { \ + tf_mxfp8_experts::BODY(X, x_stride, slots, W, KG, NB, items, counts, members, out, N, cap0, cap1, skip); \ + } +#define TF_MX_ARGS(...) __VA_ARGS__ +TF_MX_ENTRY(tf_mxfp8_softcap, decode_body) +TF_MX_ENTRY(tf_mxfp8_down_f32, decode_body) +TF_MX_ENTRY(tf_mxfp8_down_bf16, decode_body) +TF_MX_ENTRY(tf_mxfp8_prompt_softcap, prompt_body) +TF_MX_ENTRY(tf_mxfp8_prompt_down, prompt_body) diff --git a/zig/kernels/cuda/inkling2/loop.cu b/zig/kernels/cuda/inkling2/loop.cu new file mode 100644 index 00000000000..09cdb8ddbfa --- /dev/null +++ b/zig/kernels/cuda/inkling2/loop.cu @@ -0,0 +1,182 @@ +// Inkling 2 Mini's loop (inkling2_loop): the cross-pass message mixes and the rank-r gates on the core's inputs. +// C2 stand-in: the arithmetic #4337's Metal loop.metal runs (H3/C2 are other slices); fp32 sums, fixed orders. +#include +#include + +namespace ink2l { + +constexpr int kMaxBlocks = 8; // finished blocks a mix reads beside the partial state +constexpr int kMaxQueries = 4; // queries of one mix: a message's q, k, v and mlp, or an input's 1 or 3 +constexpr int kMaxGates = 3; // gates one launch runs: the attention's q, k and v inputs +constexpr int kMaxRank = 128; // gate rank (config.max_gate_rank) +constexpr int kThreads = 256; +constexpr int kWarps = kThreads / 32; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// The block's sum of v in one order: warp shuffles, then the warps' partials in warp order; every thread gets it. +__device__ __forceinline__ float blockSum(float v, float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warpSum(v); + __syncthreads(); + if (lane == 0) sh[w] = v; + __syncthreads(); + float t = 0.0f; + for (int i = 0; i < kWarps; ++i) t += sh[i]; + return t; +} + +} // namespace ink2l + +using namespace ink2l; + +// An attention-residual mix without the norm: sources are the blocks then the partial; queries attend over them. +struct LoopMixArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, H] each + const void* partial; // [rows, H]: fp32 when partial_f32, else bf16 + const float* query[kMaxQueries]; // fp32 [H] each + float* out; // fp32 [nq][rows, H], planes out_stride elements apart + long long out_stride; + int n_blocks, partial_f32, nq, rows, H; + float eps, scale; // eps: the sources' rms; scale: H^-0.5 on the scores +}; + +// Per row: each source's 1/rms, each query's softmax over (q . source) / rms * scale, then the fp32 mixes. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_mix(const LoopMixArgs a) { + __shared__ float sh[kWarps]; + __shared__ float inv[kMaxBlocks + 1]; + __shared__ float coef[kMaxQueries][kMaxBlocks + 1]; + const size_t row = blockIdx.x; + const int H = a.H, S = a.n_blocks + 1; + auto src = [&](int s, int i) -> float { + if (s < a.n_blocks) return bf(a.blocks[s][row * H + i]); + if (a.partial_f32) return static_cast(a.partial)[row * H + i]; + return bf(static_cast(a.partial)[row * H + i]); + }; + for (int s = 0; s < S; ++s) { + float acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) { + const float v = src(s, i); + acc = fmaf(v, v, acc); + } + const float t = blockSum(acc, sh); + if (threadIdx.x == 0) inv[s] = rsqrtf(t / static_cast(H) + a.eps); + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float score[kMaxBlocks + 1]; + for (int s = 0; s < S; ++s) { + float acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) acc = fmaf(a.query[q][i], src(s, i), acc); + score[s] = blockSum(acc, sh) * inv[s] * a.scale; + } + if (threadIdx.x == 0) { + float m = -INFINITY, l = 0.0f; + for (int s = 0; s < S; ++s) m = fmaxf(m, score[s]); + for (int s = 0; s < S; ++s) { + score[s] = expf(score[s] - m); + l += score[s]; + } + for (int s = 0; s < S; ++s) coef[q][s] = (score[s] / l) * inv[s]; + } + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float* dst = a.out + q * a.out_stride + row * H; + for (int i = threadIdx.x; i < H; i += kThreads) { + float u = 0.0f; + for (int s = 0; s < S; ++s) u = fmaf(coef[q][s], src(s, i), u); + dst[i] = u; + } + } +} + +// The gates of one launch: gate g reads state h[g] (fp32 [rows, H]) and message plane slot[g] of msg. +struct LoopGateArgs { + const float* h[kMaxGates]; + const float* msg; // fp32 [planes][rows, H] + long long msg_stride; // elements between the message planes + int slot[kMaxGates]; + const uint16_t* down_w[kMaxGates]; // bf16 [rank][2 H]: [state, message] + const uint16_t* forget[kMaxGates]; // bf16 [H][rank] + const uint16_t* gain[kMaxGates]; // bf16 [H][rank] + const uint16_t* norm[kMaxGates]; // bf16 [H] + uint16_t* down; // bf16 [gates][rows][rank] + uint16_t* out; // bf16 [gates][rows, H], planes out_stride elements apart + long long out_stride; + int rows, H, rank; + float eps_unit, eps; // eps_unit: the unweighted norms of state and message; eps: the gated output's norm + float* ys; // fp32 [gates][rows, H]: the gated rows before their norm +}; + +// down[g][row] = bf16(W_down [unit(h) bf16, unit(m) bf16]) for gate blockIdx.y of row blockIdx.x; block z takes +// rank rows [8 z, 8 z + 8), one a warp. Every block forms the same norms in the same order. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_down(const LoopGateArgs a) { + extern __shared__ float xs[]; // [2 H]: the normed state, then the normed message, each rounded to bf16 + __shared__ float sh[kWarps]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H; + const float* h = a.h[g] + row * H; + const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; + float sh_acc = 0.0f, sm_acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) { + sh_acc = fmaf(h[i], h[i], sh_acc); + sm_acc = fmaf(m[i], m[i], sm_acc); + } + const float ih = rsqrtf(blockSum(sh_acc, sh) / static_cast(H) + a.eps_unit); + const float im = rsqrtf(blockSum(sm_acc, sh) / static_cast(H) + a.eps_unit); + for (int i = threadIdx.x; i < H; i += kThreads) { + xs[i] = bf(tobf(h[i] * ih)); + xs[H + i] = bf(tobf(m[i] * im)); + } + __syncthreads(); + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + const int r = blockIdx.z * kWarps + w; + if (r >= a.rank) return; + const uint16_t* wr = a.down_w[g] + static_cast(r) * 2 * H; + float acc = 0.0f; + for (int i = lane; i < 2 * H; i += 32) acc = fmaf(bf(wr[i]), xs[i], acc); + acc = warpSum(acc); + if (lane == 0) a.down[(static_cast(g) * a.rows + row) * a.rank + r] = tobf(acc); +} + +// ys[g][row][i] = (1 - tanh(Wf d)) h + tanh(Wg d) m, d the gate's bf16 down row: kLin outputs a block (z). +constexpr int kLin = 128; +extern "C" __global__ void __launch_bounds__(kLin) tf_ink2_loop_gate_lin(const LoopGateArgs a) { + __shared__ float dn[kMaxRank]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H, R = a.rank; + if (threadIdx.x < R) dn[threadIdx.x] = bf(a.down[(static_cast(g) * a.rows + row) * R + threadIdx.x]); + if (threadIdx.x + kLin < R) dn[threadIdx.x + kLin] = bf(a.down[(static_cast(g) * a.rows + row) * R + threadIdx.x + kLin]); + __syncthreads(); + const int i = blockIdx.z * kLin + threadIdx.x; + if (i >= H) return; + const uint16_t* wf = a.forget[g] + static_cast(i) * R; + const uint16_t* wg = a.gain[g] + static_cast(i) * R; + float f = 0.0f, gn = 0.0f; + for (int r = 0; r < R; ++r) { + f = fmaf(bf(wf[r]), dn[r], f); + gn = fmaf(bf(wg[r]), dn[r], gn); + } + const float* h = a.h[g] + row * H; + const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; + a.ys[(static_cast(g) * a.rows + row) * H + i] = (1.0f - tanhf(f)) * h[i] + tanhf(gn) * m[i]; +} + +// out[g][row] = norm * rms(ys[g][row]): the squares summed in the order a 256-thread block strides them. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_mix(const LoopGateArgs a) { + __shared__ float sh[kWarps]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H; + const float* ys = a.ys + (static_cast(g) * a.rows + row) * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) ss = fmaf(ys[i], ys[i], ss); + const float inv = rsqrtf(blockSum(ss, sh) / static_cast(H) + a.eps); + uint16_t* dst = a.out + g * a.out_stride + row * H; + for (int i = threadIdx.x; i < H; i += kThreads) dst[i] = tobf(bf(a.norm[g][i]) * (ys[i] * inv)); +} diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu deleted file mode 100644 index 824ec095042..00000000000 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ /dev/null @@ -1,285 +0,0 @@ -// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. -#include -#include - -namespace ink2l { - -constexpr int kRank = 64; -constexpr int kMaxBlocks = 8; -constexpr int kMaxQueries = 3; - -__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } -__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } -__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } - -__device__ __forceinline__ float warpSum(float v) { - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. -template -__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); - __syncthreads(); - if (lane == 0) - for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; - __syncthreads(); - for (int i = 0; i < N; ++i) { - const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; - v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); - } -} - -// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). -__device__ __forceinline__ float queryScale(int c) { - return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); -} - -__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { - const float m = fmaxf(l0, l1); - const float e0 = expf(l0 - m), e1 = expf(l1 - m); - const float d = __fadd_rn(e0, e1); - w[0] = __fdiv_rn(e0, d); - w[1] = __fdiv_rn(e1, d); -} - -struct ArArgs { - const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer - const void* partial; // the final source, BF16 or FP32 according to partial_bf16 - const float* query; // fp32 [nq, C] - float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded - int n_blocks, partial_bf16, nq, rows, C; - float eps; -}; - -// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. -__device__ void ar(const ArArgs a) { - __shared__ float sh[32 * (1 + kMaxQueries)]; - __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; - __shared__ float rr[kMaxBlocks + 1]; - const size_t row = blockIdx.x; - const int n = a.n_blocks + 1; - auto entry = [&](int j, int c) -> float { - if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); - return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) - : static_cast(a.partial)[row * a.C + c]; - }; - for (int j = 0; j < n; ++j) { - float ss[1] = {0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float x = entry(j, c); - ss[0] = __fmaf_rn(x, x, ss[0]); - } - blockSums<1>(ss, sh); - if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); - } - __syncthreads(); - for (int j = 0; j < n; ++j) { - float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float normalized = __fmul_rn(entry(j, c), rr[j]); - for (int q = 0; q < a.nq; ++q) - dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); - } - blockSums(dots, sh); - if (threadIdx.x == 0) - for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); - } - __syncthreads(); - if (threadIdx.x < a.nq) { - float* l = wts[threadIdx.x]; - float m = -INFINITY, d = 0.0f; - for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); - for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); - for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); - } - __syncthreads(); - for (int q = 0; q < a.nq; ++q) { - float* out = a.out + (static_cast(q) * a.rows + row) * a.C; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - float h = 0.0f; - for (int j = 0; j < n; ++j) { - const float z = __fmul_rn(entry(j, c), rr[j]); - h = __fmaf_rn(wts[q][j], z, h); - } - out[c] = h; - } - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { - ink2l::ar(a); -} - -namespace ink2l { - -// One block handles one token and role, sharing each bank's normalization across all 12 core queries. -__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, - float* __restrict__ out, int rows, int core_layers, int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv[2], w[2]; - const size_t row = blockIdx.x; - const int role = blockIdx.y; // q, k, v, mlp - const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; - const float* role_queries = role == 0 || role == 3 ? qm : qkv; - const int odd = role == 3 || role == 2; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); - ss[0] = __fmaf_rn(x0, x0, ss[0]); - ss[1] = __fmaf_rn(x1, x1, ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - for (int j = 0; j < core_layers; ++j) { - const float* query = role_queries + static_cast(2 * j + odd) * c; - float dots[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float q = query[i]; - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - dots[0] = __fmaf_rn(q, b0, dots[0]); - dots[1] = __fmaf_rn(q, b1, dots[1]); - } - blockSums<2>(dots, sh); - if (threadIdx.x == 0) - softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); - __syncthreads(); - // Plane-major [core][role][rows][c]: the gates read each role's rows as one contiguous plane. - float* dst = out + ((static_cast(j) * 4 + role) * rows + row) * static_cast(c); - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); - dst[i] = __fadd_rn(m0, m1); - } - } -} - -// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). -__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, - const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, - const uint16_t* __restrict__ gain, float* __restrict__ out, - int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv_h, inv_m; - __shared__ uint16_t zeta[kRank]; - const size_t row = blockIdx.x; - const float* hr = h + row * c; - const float* mr = m + row * c; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); - ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. - for (int r = 0; r < kRank; r += 2) { - float acc[2] = {0.0f, 0.0f}; - const uint16_t* d0 = down + static_cast(r) * (2 * c); - const uint16_t* d1 = d0 + 2 * c; - for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { - const bool message = i >= c; - const float x = message ? mr[i - c] : hr[i]; - const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); - acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); - acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); - } - blockSums<2>(acc, sh); - if (threadIdx.x == 0) { - zeta[r] = tobf(acc[0]); - zeta[r + 1] = tobf(acc[1]); - } - } - __syncthreads(); - float* dst = out + row * c; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const uint16_t* f = forget + static_cast(i) * kRank; - const uint16_t* g = gain + static_cast(i) * kRank; - float sf = 0.0f, sg = 0.0f; - for (int r = 0; r < kRank; ++r) { - const float z = bf(zeta[r]); - sf = __fmaf_rn(bf(f[r]), z, sf); - sg = __fmaf_rn(bf(g[r]), z, sg); - } - const float fg = tanhf(sf), gg = tanhf(sg); - // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. - const float keep = __fsub_rn(1.0f, fg); - const float old = __fmul_rn(keep, hr[i]); - const float added = __fmul_rn(gg, mr[i]); - dst[i] = __fadd_rn(old, added); - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, - int rows, int core_layers, int c, float eps) { - ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); -} - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, - const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, - int rows, int c, float eps) { - (void)rows; - ink2l::gate(h, m, down, forget, gain, out, c, eps); -} - -// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, - const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, - const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, - uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, - uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { - constexpr int kRows = 16, kOutputs = 16, kSlice = 32; - __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; - const int role = blockIdx.z; // q=0, k=1, v=2 - const int width = role == 0 ? q_width : kv_width; - const int row0 = static_cast(blockIdx.x) * kRows; - const int j0 = static_cast(blockIdx.y) * kOutputs; - if (j0 >= width) return; - const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; - const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; - const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; - const int row = row0 + tr, j = j0 + tj; - float sum = 0.0f; - // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. - for (int k0 = 0; k0 < c; k0 += kSlice) { - for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { - const int r = e / kSlice, k = k0 + e % kSlice; - sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; - sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; - } - __syncthreads(); - for (int k = 0; k < kSlice && k0 + k < c; ++k) - sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); - __syncthreads(); - } - uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; - if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); -} - -// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { - const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; - if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); -} diff --git a/zig/kernels/cuda/nvfp4_experts.cu b/zig/kernels/cuda/nvfp4_experts.cu index 02ab967aab9..46210b6dd16 100644 --- a/zig/kernels/cuda/nvfp4_experts.cu +++ b/zig/kernels/cuda/nvfp4_experts.cu @@ -165,7 +165,8 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, int const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ members, - void* __restrict__ out, int N, float limit, int skip) { + void* __restrict__ out, int N, float limit, int skip, + float limit2 = 0.f) { TF_RING_STORAGE Ring ring; const int it = unit / NB, cb = unit - it * NB; const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); @@ -192,7 +193,7 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, int #pragma unroll for (int q = 0; q < 4; ++q) acc[m][0][j][q] *= g; } - epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, limit); + epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, limit, limit2); } } @@ -363,7 +364,8 @@ __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ members, void* __restrict__ out, int N, float limit, int cbt, int e, int first, int cnt, - const __nv_bfloat16* __restrict__ X_b, void* __restrict__ out_b, int split) { + const __nv_bfloat16* __restrict__ X_b, void* __restrict__ out_b, int split, + float limit2 = 0.f) { using P = Prompt4; constexpr int STAGES = P::STAGES; extern __shared__ uint4 sm[]; @@ -504,10 +506,10 @@ __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X void* o1 = out; if (v0 && q0 >= split) { q0 -= split; o0 = out_b; } if (v1 && q1 >= split) { q1 -= split; o1 = out_b; } - epilogue(acc, r, o0, N, cb * COLS + 2 * t, q0, q1, v0, false, limit); - epilogue(acc, r, o1, N, cb * COLS + 2 * t, q0, q1, false, v1, limit); + epilogue(acc, r, o0, N, cb * COLS + 2 * t, q0, q1, v0, false, limit, limit2); + epilogue(acc, r, o1, N, cb * COLS + 2 * t, q0, q1, false, v1, limit, limit2); } else { - epilogue(acc, r, out, N, cb * COLS + 2 * t, p0, p1, v0, v1, limit); + epilogue(acc, r, out, N, cb * COLS + 2 * t, p0, p1, v0, v1, limit, limit2); } } } @@ -519,7 +521,7 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, int NB, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, int N, float limit, int skip, const __nv_bfloat16* __restrict__ X_b, - void* __restrict__ out_b, int split) { + void* __restrict__ out_b, int split, float limit2 = 0.f) { static_assert(RT == 4, "the dispatch below spells out 0 .. 4 row tiles"); const int nbt = (NB + WN - 1) / WN, it = blockIdx.x / nbt, cbt = blockIdx.x - it * nbt; if (it >= __ldg(counts)) return; @@ -527,7 +529,7 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, if (e == skip) return; // an expert the family computes itself, left alone as the decode form does const int nt = max(0, min(RT, (cnt - 16 * RT * ((threadIdx.x >> 5) / WN) + 15) >> 4)); #define TF_TILES(NT) \ - prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, first, cnt, X_b, out_b, split) + prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, first, cnt, X_b, out_b, split, limit2) switch (nt) { case 4: TF_TILES(4); break; case 3: TF_TILES(3); break; @@ -596,3 +598,26 @@ TF_NVFP4_PAIR_PROMPT(tf_nvfp4_pair_prompt_down, 1, 3, 8) } TF_NVFP4_FACT(tf_nvfp4_fact_swiglu, 2, 2, 4) TF_NVFP4_FACT(tf_nvfp4_fact_down_f32, 1, 0, 8) + +// Soft-capped SwiGLU gate-up (Inkling 2 Mini): the decode units of nvfp4_expert_kernel<2, 2, 4> and the prompt tiles of +// tf_nvfp4_prompt_swiglu, with experts.cuh's epilogue 4 over the gate's and the up's caps. +extern "C" __global__ void __launch_bounds__(128) + tf_nvfp4_softcap(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, + const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, int N, + float gate_cap, float up_cap, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(counts) * NB; + for (int unit = blockIdx.x * 4 + (threadIdx.x >> 5); unit < units; unit += gridDim.x * 4) + tf_nvfp4_experts::unit_full<2, 4, 4>(unit, lane, gq, t, threadIdx.x >> 5, X, x_stride, slots, W, scale, KG, NB, + items, members, out, N, gate_cap, skip, up_cap); +} + +extern "C" __global__ void __launch_bounds__(128) + tf_nvfp4_prompt_softcap(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, + const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, + int N, float gate_cap, float up_cap, int skip) { + tf_nvfp4_experts::prompt_body<2, 4, 4, 1, 4>(X, x_stride, slots, W, scale, KG, NB, items, counts, members, out, N, + gate_cap, skip, nullptr, nullptr, 0, up_cap); +} diff --git a/zig/metal_runtime_inventory.zig b/zig/metal_runtime_inventory.zig index bb45f0fe19c..376206c94e6 100644 --- a/zig/metal_runtime_inventory.zig +++ b/zig/metal_runtime_inventory.zig @@ -1,6 +1,6 @@ //! Source assembly shares one module owner with the engine's family and core files. pub const metal_runtime_sources = @import("runtime_sources/root.zig"); -const engine = @import("src/tensorfold.zig"); +const engine = @import("core"); pub const gpu_profile = engine.gpu_profile; pub const sys = @import("sys"); pub const rope_freq = engine.rope_freq; diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index d0c8ab7ec66..ddc0ce60a52 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -2,9 +2,9 @@ pub const checkpoint = @import("src/core/checkpoint.zig"); pub const gguf = @import("src/core/gguf.zig"); pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); -pub const safetensors = @import("src/core/safetensors.zig"); -/// The shard file cache checkpoint_metal.zig reaches through `core`, as the engine's own core exports it. pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig"); +pub const safetensors = @import("src/core/safetensors.zig"); + pub const Checkpoint = checkpoint.Checkpoint; pub const npy = @import("src/core/npy.zig"); pub const tokenizer = @import("tokenizer"); diff --git a/zig/src/core/contract/inkling2_attn_ref.zig b/zig/src/core/contract/inkling2_attn_ref.zig index e69b48464ad..81320f42c8c 100644 --- a/zig/src/core/contract/inkling2_attn_ref.zig +++ b/zig/src/core/contract/inkling2_attn_ref.zig @@ -59,6 +59,7 @@ pub fn tau(pos: usize) f64 { return tauAt(pos, floor_pos); } + /// The log-scaling factor at `pos` for a model's n_floor: 1 + alpha ln(max((pos + 1) / floor, 1)). pub fn tauAt(pos: usize, floor: f64) f64 { return 1 + alpha * @log(@max(@as(f64, @floatFromInt(pos + 1)) / floor, 1)); @@ -96,6 +97,11 @@ pub const Call = struct { fn groupSize(call: *const Call) usize { return call.heads / call.kv; } + /// heads / kv: the query heads one key head serves. + pub fn perKv(call: *const Call) usize { + return call.groupSize(); + } + /// The fp32 sums' longest chain at a row: a 64-key tile's adds and its rescale (`chain.tile`), then the folds. fn depth(call: *const Call, pos: usize) f64 { diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index b24f4ea1efe..27835f558bc 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -4,5 +4,6 @@ const ops = @import("inkling2_ops_records.zig"); const experts = @import("inkling2_experts_records.zig"); pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; +pub const pending = experts.pending; pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 20b0945515a..89bb1ba5820 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -10,16 +10,18 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, +}; +/// ModelOpt measured on sm_121 alone (GB10, #4387); loop is unmeasured. Missing receipts refuse there (cuda_pending). +pub const pending = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_mix", .symbol = "tf_ink2_loop_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop", .threads = 256, .dynamic = 18432, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_lin", .symbol = "tf_ink2_loop_gate_lin", .image = "inkling2_loop", .threads = 128, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_mix", .symbol = "tf_ink2_loop_gate_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, }; /// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. pub const cuda_132 = [_]registry.Override{}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 2789e452181..85a9e2e49fd 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -13,6 +13,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("modelopt_lane_records.zig").cuda ++ @import("nvfp4_fact_records.zig").cuda ++ @import("nvfp4_experts32_records.zig").cuda ++ + @import("stored_experts_records.zig").cuda ++ @import("experts_bf16_records.zig").cuda ++ @import("lane_half_records.zig").cuda ++ @import("lane_fused_records.zig").cuda ++ @@ -36,6 +37,7 @@ pub const nvcc_132_after = @import("registry_learning.zig").cuda_132 ++ @import("qwen_served_records.zig").cuda_132 ++ @import("flashnext_tile_records.zig").cuda_132 ++ @import("nvfp4_fact_records.zig").cuda_132 ++ + @import("stored_experts_records.zig").cuda_132 ++ @import("experts_bf16_records.zig").cuda_132 ++ @import("pocket_records.zig").cuda_132 ++ @import("minimax_cuda_records.zig").cuda_132 ++ @@ -64,7 +66,8 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("ricursive_attn_records.zig").cuda ++ @import("registry_media.zig").cuda_pending ++ @import("registry_media.zig").cuda_tma_pending ++ - @import("h3_image_cuda_records.zig").records; + @import("h3_image_cuda_records.zig").records ++ + @import("inkling2_cuda_records.zig").pending; pub const metal_before = @import("fsr_records.zig").metal ++ @import("scale_index_records.zig").metal ++ @import("lfm3_records.zig").metal; diff --git a/zig/src/core/contract/stored_experts_records.zig b/zig/src/core/contract/stored_experts_records.zig new file mode 100644 index 00000000000..baec49f15c5 --- /dev/null +++ b/zig/src/core/contract/stored_experts_records.zig @@ -0,0 +1,20 @@ +//! Inkling 2 Mini's stored experts (soft-capped NVFP4, MXFP8): nvcc 13.0.88, sm_80/86/89/120/121. +const CudaRecord = @import("registry.zig").CudaRecord; + +pub const cuda = [_]CudaRecord{ + .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_softcap", .symbol = "tf_nvfp4_softcap", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 100, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 129, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_prompt_softcap", .symbol = "tf_nvfp4_prompt_softcap", .image = "nvfp4_experts", .threads = 128, .dynamic = 34816 }, .usage = .{ .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 209, .static = 0, .bound = 128 }, .{ .regs = 209, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_softcap", .symbol = "tf_mxfp8_softcap", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_down_f32", .symbol = "tf_mxfp8_down_f32", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_down_bf16", .symbol = "tf_mxfp8_down_bf16", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_prompt_softcap", .symbol = "tf_mxfp8_prompt_softcap", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 160, .static = 33280, .bound = 128 }, .{ .regs = 160, .static = 33280, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_prompt_down", .symbol = "tf_mxfp8_prompt_down", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 140, .static = 33280, .bound = 128 }, .{ .regs = 142, .static = 33280, .bound = 128 }, .{ .regs = 142, .static = 33280, .bound = 128 }, .{ .regs = 154, .static = 33280, .bound = 128 }, .{ .regs = 154, .static = 33280, .bound = 128 } } }, +}; + +/// What nvcc 13.2.78 compiles differently. +pub const cuda_132 = [_]@import("registry.zig").Override{ + .{ .name = "nvfp4_experts tf_nvfp4_softcap", .usage = .{ .{ .regs = 100, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts tf_nvfp4_prompt_softcap", .usage = .{ .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, + .{ .name = "fp8_experts tf_mxfp8_down_f32", .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 } } }, + .{ .name = "fp8_experts tf_mxfp8_down_bf16", .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 } } }, +}; diff --git a/zig/src/core/expert_decode.zig b/zig/src/core/expert_decode.zig new file mode 100644 index 00000000000..7d46bd0cff6 --- /dev/null +++ b/zig/src/core/expert_decode.zig @@ -0,0 +1,74 @@ +//! Stored routed-expert weights decoded on the host (Inkling 2 Mini): NVFP4 and MXFP8 as stored, no requantizing. +const std = @import("std"); + +/// An E2M1 code (low 4 bits; bit 3 the sign): 0, 0.5, 1, 1.5, 2, 3, 4, 6. +pub fn e2m1(code: u8) f64 { + const magnitude = [8]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = magnitude[code & 7]; + return if (code & 8 != 0) -v else v; +} + +/// An E4M3 (fn) code; 0x7F and 0xFF are NaN. +pub fn e4m3(code: u8) f64 { + const e: i32 = (code >> 3) & 15; + const m: f64 = @floatFromInt(code & 7); + const v: f64 = if (e == 15 and code & 7 == 7) std.math.nan(f64) else if (e == 0) m * 0x1p-9 else (8 + m) * std.math.ldexp(@as(f64, 1), e - 10); + return if (code & 0x80 != 0) -v else v; +} + +/// An E8M0 scale: 2^(code - 127); 255 is NaN. +pub fn e8m0(code: u8) f64 { + if (code == 255) return std.math.nan(f64); + return std.math.ldexp(@as(f64, 1), @as(i32, code) - 127); +} + +/// Input i's E2M1 code of a row of packed bytes, low nibble first (the order the CUDA packers assume). +pub fn nibble(row: []const u8, i: usize) u8 { + const b = row[i / 2]; + return if (i % 2 == 0) b & 15 else b >> 4; +} + +/// NVFP4 weight (row, i) of one expert's [n, k/2] codes and [n, k/16] E4M3 scales, times its factor: exact in f64. +pub fn nvfp4(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize, factor: f64) f64 { + return e2m1(nibble(codes[row * (k / 2) ..][0 .. k / 2], i)) * e4m3(scales[row * (k / 16) + i / 16]) * factor; +} + +/// The same weight as the decode kernels form it in fp32: code x block scale (exact), then one rounding by the factor. +pub fn nvfp4F32(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize, factor: f32) f32 { + const cs: f32 = @floatCast(e2m1(nibble(codes[row * (k / 2) ..][0 .. k / 2], i)) * e4m3(scales[row * (k / 16) + i / 16])); + return cs * factor; +} + +/// MXFP8 weight (row, i) of one expert's [n, k] E4M3 codes and [n, k/32] E8M0 scales: exact in f64 and in f32. +pub fn mxfp8(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize) f64 { + return e4m3(codes[row * k + i]) * e8m0(scales[row * (k / 32) + i / 32]); +} + +test "E2M1, E4M3 and E8M0 decode their extremes, signs and NaN codes" { + const t = std.testing; + try t.expectEqual(@as(f64, 6), e2m1(7)); + try t.expectEqual(@as(f64, -0.5), e2m1(9)); + try t.expect(std.math.signbit(e2m1(8))); + try t.expectEqual(@as(f64, 448), e4m3(0x7E)); + try t.expectEqual(@as(f64, -0x1p-9), e4m3(0x81)); // the least subnormal + try t.expectEqual(@as(f64, 1), e4m3(0x38)); + try t.expect(std.math.isNan(e4m3(0x7F)) and std.math.isNan(e4m3(0xFF))); + try t.expectEqual(@as(f64, 1), e8m0(127)); + try t.expectEqual(@as(f64, 0x1p-127), e8m0(0)); + try t.expect(std.math.isNan(e8m0(255))); +} + +test "NVFP4 and MXFP8 weights take input i's nibble, its 16- or 32-input scale and the factor" { + const t = std.testing; + const codes = [_]u8{ 0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16 }; + const scales = [_]u8{ 0x40, 0x38 }; // 2, then 1 + try t.expectEqual(@as(f64, -1 * 2 * 0.25), nvfp4(&codes, &scales, 32, 0, 0, 0.25)); // low nibble 0xA = -1 + try t.expectEqual(@as(f64, 6 * 2 * 0.25), nvfp4(&codes, &scales, 32, 0, 1, 0.25)); + try t.expectEqual(@as(f64, 4 * 1 * 0.25), nvfp4(&codes, &scales, 32, 0, 30, 0.25)); // byte 15 low: 6 = 4 + try t.expectEqual(@as(f32, 4 * 0.1), nvfp4F32(&codes, &scales, 32, 0, 30, 0.1)); + var mx: [64]u8 = @splat(0x38); + mx[33] = 0xC0; // -2 + const ms = [_]u8{ 127, 120 }; + try t.expectEqual(@as(f64, 1), mxfp8(&mx, &ms, 64, 0, 31)); + try t.expectEqual(@as(f64, -2 * 0x1p-7), mxfp8(&mx, &ms, 64, 0, 33)); +} diff --git a/zig/src/core/modelopt.zig b/zig/src/core/modelopt.zig index 8a3951df906..cac64a57157 100644 --- a/zig/src/core/modelopt.zig +++ b/zig/src/core/modelopt.zig @@ -1,12 +1,23 @@ //! ModelOpt config checks: NVFP4 (groups of 16; tensors, not ignore, say which linears) and MIXED_PRECISION recipes. const std = @import("std"); +const config = @import("modelopt_config.zig"); + +/// The config checks (std only, so host-only family tests can import them without the checkpoint reader). +pub const Why = config.Why; +pub const admit = config.admit; +pub const admitByTensors = config.admitByTensors; +pub const object = config.object; +pub const text = config.text; +pub const int = config.int; +const nvfp4 = config.nvfp4; +const block = config.block; /// One projection's tensors read and checked (weight, block scales, weight_scale_2, input_scale). pub const part = @import("modelopt_part.zig"); /// The NVFP4 group size ModelOpt writes for this format. -pub const nvfp4_group = 16; +pub const nvfp4_group = config.nvfp4_group; /// The group size of csf0_v1, this engine's own: no other reader takes it. pub const csf0_group = 32; @@ -57,35 +68,6 @@ pub const Recipes = struct { } }; -/// Why the check refused the checkpoint, kept for the caller's log line (tests read it instead). -pub const Why = struct { - buf: [320]u8 = undefined, - len: usize = 0, - - /// Keep the reason, cut short if it is long. - pub fn set(self: *Why, comptime fmt: []const u8, args: anytype) void { - var w: std.Io.Writer = .fixed(&self.buf); - w.print(fmt, args) catch {}; - self.len = w.end; - } - - pub fn text(self: *const Why) []const u8 { - return self.buf[0..self.len]; - } -}; - -/// config.json's quantization_config (top level, else text_config's) checked as ModelOpt NVFP4. -pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); - const q = block(root) orelse { - why.set("config.json has no ModelOpt quantization_config", .{}); - return error.NotModelOpt; - }; - try nvfp4(q, why); -} - /// `admit`'s check, with MIXED_PRECISION read: a quantized_layers entry no `Recipe` names is refused by its module. pub fn admitRecipes(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !Recipes { var arena = std.heap.ArenaAllocator.init(gpa); @@ -160,59 +142,6 @@ fn pair(v: ?std.json.Value, rows: i64, cols: i64) bool { return int(x.array.items[0]) == rows and int(x.array.items[1]) == cols; } -/// The quantization_config's NVFP4 check: quant_algo NVFP4, every config group 4-bit floats in groups of 16. -fn nvfp4(q: std.json.ObjectMap, why: *Why) !void { - const algo = text(q.get("quant_algo")) orelse ""; - if (!std.ascii.eqlIgnoreCase(algo, "NVFP4")) { - const named = if (algo.len > 0) algo else "without quant_algo"; - why.set("ModelOpt {s}: this engine reads ModelOpt NVFP4 (nvidia/GLM-5.3-Flash-NVFP4's layout)", .{named}); - return error.UnsupportedQuant; - } - const groups = object(q.get("config_groups")) orelse { - why.set("ModelOpt NVFP4 without config_groups", .{}); - return error.UnsupportedQuant; - }; - var it = groups.iterator(); - while (it.next()) |g| { - const w = if (object(g.value_ptr.*)) |o| object(o.get("weights")) else null; - const bits = if (w) |o| int(o.get("num_bits")) else null; - const size = if (w) |o| int(o.get("group_size")) else null; - const kind = if (w) |o| text(o.get("type")) orelse "" else ""; - if (bits != 4 or size != nvfp4_group or !std.mem.eql(u8, kind, "float")) { - why.set( - "ModelOpt NVFP4 group {s}: weights {?d}-bit {s} in groups of {?d}, " ++ - "expected 4-bit float in groups of 16", - .{ g.key_ptr.*, bits, kind, size }, - ); - return error.UnsupportedQuant; - } - } -} - -fn block(root: std.json.Value) ?std.json.ObjectMap { - const top = object(root) orelse return null; - for ([_]?std.json.ObjectMap{ top, object(top.get("text_config")) }) |source| { - const q = object((source orelse continue).get("quantization_config")) orelse continue; - if (std.ascii.eqlIgnoreCase(text(q.get("quant_method")) orelse "", "modelopt")) return q; - } - return null; -} - -pub fn object(v: ?std.json.Value) ?std.json.ObjectMap { - const x = v orelse return null; - return if (x == .object) x.object else null; -} - -pub fn text(v: ?std.json.Value) ?[]const u8 { - const x = v orelse return null; - return if (x == .string) x.string else null; -} - -pub fn int(v: ?std.json.Value) ?i64 { - const x = v orelse return null; - return if (x == .integer) x.integer else null; -} - test "nvidia/GLM-5.3-Flash-NVFP4's config is admitted" { var why: Why = .{}; try admit(std.testing.allocator, @embedFile("fixtures/glm53_flash_nvfp4/config.json"), &why); @@ -253,6 +182,24 @@ test "other ModelOpt formats, and configs without ModelOpt, are refused by name" , &why); } +test "admitByTensors: NVFP4 without config_groups is admitted; other algos and bad groups are refused by name" { + var why: Why = .{}; + try admitByTensors(std.testing.allocator, "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\"}}", &why); + const fp8 = "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"FP8\"}}"; + try std.testing.expectError(error.UnsupportedQuant, admitByTensors(std.testing.allocator, fp8, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "ModelOpt FP8") != null); + const g32 = + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "config_groups": + \\ {"g": {"weights": {"num_bits": 4, "type": "float", "group_size": 32}}}}} + ; + try std.testing.expectError(error.UnsupportedQuant, admitByTensors(std.testing.allocator, g32, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "groups of 32") != null); + try std.testing.expectError(error.NotModelOpt, admitByTensors(std.testing.allocator, "{\"text_config\": {}}", &why)); + // admit itself still asks for config_groups + const bare = "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\"}}"; + try std.testing.expectError(error.UnsupportedQuant, admit(std.testing.allocator, bare, &why)); +} + test "nvidia/GLM-5.3-Flash-FP4-Local's recipes: a module's, and its tensors' under it" { var why: Why = .{}; var r = try admitRecipes(std.testing.allocator, @embedFile("fixtures/glm53_flash_fp4_local/config.json"), &why); diff --git a/zig/src/core/modelopt_config.zig b/zig/src/core/modelopt_config.zig new file mode 100644 index 00000000000..4e6b8011028 --- /dev/null +++ b/zig/src/core/modelopt_config.zig @@ -0,0 +1,101 @@ +//! ModelOpt quantization_config checks on config.json alone (std only): NVFP4 in groups of 16, read by modelopt.zig. +const std = @import("std"); + +/// The NVFP4 group size ModelOpt writes for this format. +pub const nvfp4_group = 16; + +/// Why the check refused the checkpoint, kept for the caller's log line (tests read it instead). +pub const Why = struct { + buf: [320]u8 = undefined, + len: usize = 0, + + /// Keep the reason, cut short if it is long. + pub fn set(self: *Why, comptime fmt: []const u8, args: anytype) void { + var w: std.Io.Writer = .fixed(&self.buf); + w.print(fmt, args) catch {}; + self.len = w.end; + } + + pub fn text(self: *const Why) []const u8 { + return self.buf[0..self.len]; + } +}; + +/// config.json's quantization_config (top level, else text_config's) checked as ModelOpt NVFP4. +pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); + const q = block(root) orelse { + why.set("config.json has no ModelOpt quantization_config", .{}); + return error.NotModelOpt; + }; + try nvfp4(q, why); +} + +/// `admit` for a checkpoint whose tensors name each layer's format (Inkling 2 Mini: NVFP4 and MXFP8 experts by dtype): +/// quant_algo NVFP4, and config_groups, when declared, as `admit` checks them. +pub fn admitByTensors(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); + const q = block(root) orelse { + why.set("config.json has no ModelOpt quantization_config", .{}); + return error.NotModelOpt; + }; + if (q.get("config_groups") == null and std.ascii.eqlIgnoreCase(text(q.get("quant_algo")) orelse "", "NVFP4")) return; + try nvfp4(q, why); +} + +/// The quantization_config's NVFP4 check: quant_algo NVFP4, every config group 4-bit floats in groups of 16. +pub fn nvfp4(q: std.json.ObjectMap, why: *Why) !void { + const algo = text(q.get("quant_algo")) orelse ""; + if (!std.ascii.eqlIgnoreCase(algo, "NVFP4")) { + const named = if (algo.len > 0) algo else "without quant_algo"; + why.set("ModelOpt {s}: this engine reads ModelOpt NVFP4 (nvidia/GLM-5.3-Flash-NVFP4's layout)", .{named}); + return error.UnsupportedQuant; + } + const groups = object(q.get("config_groups")) orelse { + why.set("ModelOpt NVFP4 without config_groups", .{}); + return error.UnsupportedQuant; + }; + var it = groups.iterator(); + while (it.next()) |g| { + const w = if (object(g.value_ptr.*)) |o| object(o.get("weights")) else null; + const bits = if (w) |o| int(o.get("num_bits")) else null; + const size = if (w) |o| int(o.get("group_size")) else null; + const kind = if (w) |o| text(o.get("type")) orelse "" else ""; + if (bits != 4 or size != nvfp4_group or !std.mem.eql(u8, kind, "float")) { + why.set( + "ModelOpt NVFP4 group {s}: weights {?d}-bit {s} in groups of {?d}, " ++ + "expected 4-bit float in groups of 16", + .{ g.key_ptr.*, bits, kind, size }, + ); + return error.UnsupportedQuant; + } + } +} + +pub fn block(root: std.json.Value) ?std.json.ObjectMap { + const top = object(root) orelse return null; + for ([_]?std.json.ObjectMap{ top, object(top.get("text_config")) }) |source| { + const q = object((source orelse continue).get("quantization_config")) orelse continue; + if (std.ascii.eqlIgnoreCase(text(q.get("quant_method")) orelse "", "modelopt")) return q; + } + return null; +} + +pub fn object(v: ?std.json.Value) ?std.json.ObjectMap { + const x = v orelse return null; + return if (x == .object) x.object else null; +} + +pub fn text(v: ?std.json.Value) ?[]const u8 { + const x = v orelse return null; + return if (x == .string) x.string else null; +} + +pub fn int(v: ?std.json.Value) ?i64 { + const x = v orelse return null; + return if (x == .integer) x.integer else null; +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 294bb26e702..520212864cf 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -28,6 +28,7 @@ pub const draft_depth = @import("draft_depth.zig"); pub const prompt_tail = @import("prompt_tail.zig"); pub const CopyIndex = @import("copy_index.zig").CopyIndex; pub const recurrent_workspace = @import("recurrent_workspace.zig"); +pub const visit_plan = @import("visit_plan.zig"); // a looped stack's steps and state slots (Dory, Inkling 2 Mini) pub const tokenizer = @import("tokenizer"); // a module of its own, so the native server shares it pub const proposal_rows = @import("proposal_rows.zig"); pub const torch_pth = @import("torch_pth.zig"); // torch.save archives read without Python: Drama 3's codec @@ -59,6 +60,7 @@ pub const contract = @import("contract.zig"); pub const nvfp4 = @import("nvfp4.zig"); pub const nvfp4_csf32 = @import("nvfp4_csf32.zig"); pub const modelopt = @import("modelopt.zig"); +pub const expert_decode = @import("expert_decode.zig"); /// Pictures as 0.6.6 loaded them: PNG, JPEG through the pinned libjpeg-turbo, orientation, the shared bicubic resizes. pub const picture = @import("picture/picture.zig"); /// Qwen-VL image input every Qwen3.5-VL checkpoint shares: settings, geometry, M-RoPE positions, the tower's tables. @@ -90,6 +92,7 @@ test { _ = checkpoint_weights; _ = audio; _ = safetensors; + _ = expert_decode; _ = gguf; _ = affine4_host; _ = rope_yarn; @@ -152,6 +155,7 @@ test { _ = kv_pool; _ = kv_prompts; _ = state_walk; + _ = visit_plan; } pub const frame_rounds = @import("frame_rounds.zig"); diff --git a/zig/src/core/visit_plan.zig b/zig/src/core/visit_plan.zig new file mode 100644 index 00000000000..0c1eeec5193 --- /dev/null +++ b/zig/src/core/visit_plan.zig @@ -0,0 +1,165 @@ +//! A looped stack's walk: prelude, core × passes, coda; each step's layer, pass and state slots, numbered in run order. +const std = @import("std"); + +/// Layers [start, end) run `passes` times between the prelude [0, start) and the coda [end, layers). +pub const Loop = struct { start: u32, end: u32, passes: u32 }; + +/// No loop: every layer once. +pub const straight: Loop = .{ .start = 0, .end = 0, .passes = 1 }; + +/// Where a drafter's tap reads: the hidden state entering a step, or the stack's output after the final norm. +pub const Tap = union(enum) { input: u32, output }; + +/// Steps a stack of `layers` runs under `loop`; error.Layout when the core is outside the stack or runs no pass. +pub fn stepCount(layers: u32, loop: Loop) error{Layout}!u64 { + const passes_ok = loop.passes > 0 and loop.passes <= std.math.maxInt(u8) + 1; + if (loop.start > loop.end or loop.end > layers or !passes_ok) return error.Layout; + return @as(u64, layers) + @as(u64, loop.passes - 1) * (loop.end - loop.start); +} + +/// The walk of a stack whose layers keep states of the kinds in enum `Kind`, at most `max` steps. +pub fn Plan(comptime Kind: type, comptime max: usize) type { + const kinds = @typeInfo(Kind).@"enum".field_names.len; + return struct { + const Self = @This(); + + pub const Step = struct { + layer: u16, + pass: u8 = 0, // 0 outside the core + slot: [kinds]?u16 = @splat(null), // the step's state of each kind, numbered in run order within the kind + enter: bool = false, // the core's first layer, at every pass + leave: bool = false, // the core's last layer, at every pass + + pub fn of(s: Step, k: Kind) ?u16 { + return s.slot[@backingInt(k)]; + } + }; + + steps: [max]Step = undefined, + len: u32 = 0, + counts: [kinds]u32 = @splat(0), + loop: Loop = straight, + layers: u32 = 0, // physical layers + + pub fn slice(p: *const Self) []const Step { + return p.steps[0..p.len]; + } + + /// Slots of `k`: one per step whose layer keeps that state. + pub fn count(p: *const Self, k: Kind) u32 { + return p.counts[@backingInt(k)]; + } + + /// The walk of `layers` under `loop`; `holds.keeps(layer, kind)`: the states a layer keeps at every visit. + pub fn build(layers: u32, loop: Loop, holds: anytype) error{ Layout, TooManySteps }!Self { + if (try stepCount(layers, loop) > max) return error.TooManySteps; + var p: Self = .{ .loop = loop, .layers = layers }; + for (0..loop.start) |i| p.add(holds, @intCast(i), 0); + for (0..loop.passes) |pass| { + const first = p.len; + for (loop.start..loop.end) |i| p.add(holds, @intCast(i), @intCast(pass)); + if (p.len == first) continue; + p.steps[first].enter = true; + p.steps[p.len - 1].leave = true; + } + for (loop.end..layers) |i| p.add(holds, @intCast(i), 0); + return p; + } + + fn add(p: *Self, holds: anytype, layer: u16, pass: u8) void { + var s: Step = .{ .layer = layer, .pass = pass }; + inline for (0..kinds) |k| { + if (holds.keeps(layer, @as(Kind, @fromBackingInt(@intCast(k))))) { + s.slot[k] = @intCast(p.counts[k]); + p.counts[k] += 1; + } + } + p.steps[p.len] = s; + p.len += 1; + } + + /// The step `layer` runs at `pass` (pass 0 outside the core), or null when the walk has none. + pub fn visit(p: *const Self, layer: u32, pass: u32) ?u32 { + const l = p.loop; + const core = l.end - l.start; + if (layer < l.start) return if (pass == 0) layer else null; + if (layer < l.end) return if (pass < l.passes) l.start + pass * core + (layer - l.start) else null; + return if (pass == 0 and layer < p.layers) layer + (l.passes - 1) * core else null; + } + + /// Tap t < step count reads the input to step t; t = step count, the output after the final norm. + pub fn tap(p: *const Self, t: u32) error{NoSuchStep}!Tap { + if (t < p.len) return .{ .input = t }; + if (t == p.len) return .output; + return error.NoSuchStep; + } + }; +} + +const testing = std.testing; + +const Two = enum { sliding, full }; + +/// Every third layer keeps a full cache, the others a sliding one; layer 1 keeps none. +const Thirds = struct { + fn keeps(_: Thirds, layer: u16, k: Two) bool { + if (layer == 1) return false; + return (k == .full) == (layer % 3 == 2); + } +}; + +test "a looped walk: prelude once, the core each pass with enter and leave, coda once, slots in run order" { + const P = Plan(Two, 64); + const p = try P.build(8, .{ .start = 2, .end = 5, .passes = 3 }, Thirds{}); + try testing.expectEqual(@as(u32, 8 + 2 * 3), p.len); + const layers = [_]u16{ 0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 5, 6, 7 }; + const passes = [_]u8{ 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0 }; + for (p.slice(), layers, passes, 0..) |s, l, ps, i| { + try testing.expectEqual(l, s.layer); + try testing.expectEqual(ps, s.pass); + try testing.expectEqual(l == 2, s.enter); + try testing.expectEqual(l == 4, s.leave); + try testing.expectEqual(@as(?u32, @intCast(i)), p.visit(l, ps)); + } + // full at layers 2 and 5 (each core pass, then the coda): 4 slots; sliding at the rest but layer 1: 9 + try testing.expectEqual(@as(u32, 4), p.count(.full)); + try testing.expectEqual(@as(u32, 9), p.count(.sliding)); + try testing.expectEqual(@as(?u16, null), p.steps[1].of(.sliding)); + try testing.expectEqual(@as(?u16, null), p.steps[1].of(.full)); + const full = [_]u32{ 2, 5, 8, 11 }; + for (full, 0..) |at, n| try testing.expectEqual(@as(?u16, @intCast(n)), p.steps[at].of(.full)); + var next: u16 = 0; + for (p.slice()) |s| if (s.of(.sliding)) |slot| { + try testing.expectEqual(next, slot); + try testing.expectEqual(@as(?u16, null), s.of(.full)); + next += 1; + }; + try testing.expectEqual(@as(?u32, null), p.visit(2, 3)); + try testing.expectEqual(@as(?u32, null), p.visit(0, 1)); + try testing.expectEqual(@as(?u32, null), p.visit(8, 0)); +} + +test "no loop: every layer once at pass 0, nothing enters or leaves, taps are inputs then the output" { + const P = Plan(Two, 16); + const p = try P.build(6, straight, Thirds{}); + try testing.expectEqual(@as(u32, 6), p.len); + for (p.slice(), 0..) |s, i| { + try testing.expectEqual(@as(u16, @intCast(i)), s.layer); + try testing.expect(s.pass == 0 and !s.enter and !s.leave); + try testing.expectEqual(@as(?u32, @intCast(i)), p.visit(@intCast(i), 0)); + } + try testing.expectEqual(Tap{ .input = 5 }, try p.tap(5)); + try testing.expectEqual(Tap.output, try p.tap(6)); + try testing.expectError(error.NoSuchStep, p.tap(7)); +} + +test "a core outside the stack, no pass, too many passes or too many steps is refused" { + const P = Plan(Two, 16); + try testing.expectError(error.Layout, P.build(6, .{ .start = 4, .end = 3, .passes = 2 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 7, .passes = 2 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 4, .passes = 0 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 4, .passes = 257 }, Thirds{})); + try testing.expectError(error.TooManySteps, P.build(6, .{ .start = 2, .end = 4, .passes = 7 }, Thirds{})); + _ = try P.build(6, .{ .start = 2, .end = 4, .passes = 6 }, Thirds{}); + try testing.expectEqual(@as(u64, 6 + 255 * 2), try stepCount(6, .{ .start = 2, .end = 4, .passes = 256 })); +} diff --git a/zig/src/cuda/experts.zig b/zig/src/cuda/experts.zig index 46913ed6993..642564386fb 100644 --- a/zig/src/cuda/experts.zig +++ b/zig/src/cuda/experts.zig @@ -7,6 +7,7 @@ const kernels = @import("kernels.zig"); const grouped = @import("grouped.zig"); const driver = @import("driver.zig"); const ggml = @import("ggml.zig"); +const mx = @import("experts_mx.zig"); const prompt_layout = @import("experts_prompt_layout.zig"); const Driver = driver.Driver; @@ -17,7 +18,7 @@ const Plan = grouped.Plan; const Affine3Experts = @import("experts3.zig").Affine3Experts; pub const Bf16Experts = @import("experts_bf16.zig").Bf16Experts; -pub const Format = enum { affine4, affine3, fp8g, nvfp4, nvfp4_csf0, exl3, iq2xxs, bf16 }; +pub const Format = enum { affine4, affine3, fp8g, nvfp4, nvfp4_csf0, exl3, iq2xxs, bf16, mxfp8 }; /// One layer's experts on the device as each format's make() lays them out; a family stacks its shared ones last. pub const Layer = struct { @@ -34,6 +35,8 @@ pub const Layer = struct { after: bool = false, // exl3: clamp silu's output (min(silu(g), L): Ling), not its input (silu(min(g, L))); others refuse it relu2: bool = false, // nvfp4: up is one projection under relu^2 (Nemotron), not SwiGLU's gate and up; iq2xxs: always swiglu: bool = false, // affine4: up is gate and up interleaved per group ([E][NI/32][D/64][2][288]) under SwiGLU + caps: [2]f32 = .{ 0, 0 }, // nvfp4, mxfp8: Inkling's soft-capped SwiGLU (gate cap, up cap); 0, 0 for none + round_caps: bool = false, // with caps: gate and up sums rounded to bf16 before the soft cap (an A/B switch) shared: i32 = -1, // affine3: the expert whose tables are 4-bit (a SwiGLU pair at shared_up, down at shared_down) shared_up: u64 = 0, shared_down: u64 = 0, @@ -55,10 +58,12 @@ pub const Grouped = struct { nvfp4_csf0: ?*const @import("experts32.zig").Nvfp4b32Experts = null, iq2xxs: ?*const Iq2xxsExperts = null, bf16: ?*const Bf16Experts = null, + mxfp8: ?*const mx.Mxfp8Experts = null, /// Decode rows: `items` bounds the plan, `pairs` its picks; `tile` 16 or 64 (EXL3 only); `skip` an expert or -1. pub fn decode(g: Grouped, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, pairs: usize, tile: usize, skip: i32) !void { if (l.after and l.format != .exl3) return error.OptionNotBuilt; // the clamp-after order is built for EXL3 only + try mx.capsBuilt(l); switch (l.format) { .exl3 => return (g.exl3 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, pairs, tile, skip), .affine4 => { @@ -81,12 +86,14 @@ pub const Grouped = struct { .nvfp4_csf0 => return (g.nvfp4_csf0 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, skip), .iq2xxs => return iq2Run(g.iq2xxs orelse return error.FormatNotLoaded, s, false, epi, in, l, p, out, items, skip), .bf16 => return (g.bf16 orelse return error.FormatNotLoaded).run(s, false, epi, in, l, p, out, items, skip), + .mxfp8 => return (g.mxfp8 orelse return error.FormatNotLoaded).run(s, false, epi, in, l, p, out, items, skip), } } /// Prompt rows: `items` bounds the plan, `pairs` its picks; `tile` 16 or 64 (EXL3 only); `skip` an expert or -1. pub fn prompt(g: Grouped, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, pairs: usize, tile: usize, skip: i32) !void { if (l.after and l.format != .exl3) return error.OptionNotBuilt; // the clamp-after order is built for EXL3 only + try mx.capsBuilt(l); switch (l.format) { .exl3 => return (g.exl3 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, pairs, tile, skip), .affine4 => { @@ -109,6 +116,7 @@ pub const Grouped = struct { .nvfp4_csf0 => return (g.nvfp4_csf0 orelse return error.FormatNotLoaded).runPrompt(s, epi, in, l, p, out, items, skip), .iq2xxs => return iq2Run(g.iq2xxs orelse return error.FormatNotLoaded, s, true, epi, in, l, p, out, items, skip), .bf16 => return (g.bf16 orelse return error.FormatNotLoaded).run(s, true, epi, in, l, p, out, items, skip), + .mxfp8 => return (g.mxfp8 orelse return error.FormatNotLoaded).run(s, true, epi, in, l, p, out, items, skip), } } }; @@ -116,7 +124,7 @@ pub const Grouped = struct { /// Pairs a prompt item holds, per format (the Python engines' prompt tiles). pub fn promptTile(f: Format) usize { return switch (f) { - .affine4, .affine3, .fp8g, .nvfp4, .nvfp4_csf0, .exl3, .iq2xxs, .bf16 => 64, + .affine4, .affine3, .fp8g, .nvfp4, .nvfp4_csf0, .exl3, .iq2xxs, .bf16, .mxfp8 => 64, }; } @@ -347,6 +355,7 @@ pub const Nvfp4Experts = struct { prompt_fns: [3]Function, // relu^2 up, SwiGLU gate-up, bf16 sums down pair_fns: [2]Function, // paired prompt SwiGLU gate-up and bf16 down, 128 pairs an item fact_fns: [2]Function, // the decode form's sums on prompt tiles: SwiGLU gate-up, fp32 down + softcap: mx.Softcap = .{}, // Inkling's soft-capped SwiGLU gate-up, decode and prompt (experts_mx.zig) warps: usize = 4, pub const cols = 32; // output columns a block @@ -416,6 +425,7 @@ pub const Nvfp4Experts = struct { f.* = try mod.function(name); try f.allowDynamicShared(prompt_layout.promptSmem(parts, wn)); } + e.softcap = try mx.Softcap.resolve(mod, sms); return e; } @@ -425,6 +435,7 @@ pub const Nvfp4Experts = struct { /// One call of nvfp4/experts.py's _run on a plan of at most `items` items. pub fn run(e: *const Nvfp4Experts, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + if (epi == .up and l.caps[0] != 0) return e.softcap.run(s, false, in, l, p, out, items, skip); const gate = epi == .up; const kg = (if (gate) l.dims else l.width) / 32; const nb = (if (gate) l.width else l.dims) / cols; @@ -449,6 +460,7 @@ pub const Nvfp4Experts = struct { /// Prompt rows on a plan of at most `items` items of 64 pairs: up (relu^2 or SwiGLU by the layer), bf16 sums down. pub fn runPrompt(e: *const Nvfp4Experts, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { if (epi == .down_f32) return error.EpilogueNotBuilt; + if (epi == .up and l.caps[0] != 0) return e.softcap.run(s, true, in, l, p, out, items, skip); const gate = epi == .up; const parts: usize = if (gate and !l.relu2) 2 else 1; const nb = (if (gate) l.width else l.dims) / cols; @@ -521,70 +533,6 @@ pub const Nvfp4Experts = struct { } }; -test "a packed nvfp4 block puts each nibble and scale where nvfp4/experts.py's _pack does" { - const gpa = std.testing.allocator; - const n = 64; - const k = 64; - const codes = try gpa.alloc(u8, n * k / 2); - defer gpa.free(codes); - for (codes, 0..) |*c, i| c.* = @truncate(i * 29 + 3); - var scales: [n * k / 16]u8 = undefined; - for (&scales, 0..) |*c, i| c.* = @truncate(i * 7 + 1); - var out: [n / 32 * (k / 32) * Nvfp4Experts.words]u32 = undefined; - Nvfp4Experts.packOne(&out, codes, &scales, n, k); - const words = Nvfp4Experts.words; - // block (cb 1, g 1), lane gq 3, t 2, tile j 1: row 32 + 8 + 3 = 43; input 32 + 16 + 8 + 3 (h 1, q 3) -> slot 7 - const w = out[(1 * 2 + 1) * words + (3 * 4 + 2) * 4 + 1]; - try std.testing.expectEqual(@as(u32, codes[43 * 32 + 59 / 2] >> 4), (w >> Nvfp4Experts.slot(1, 3)) & 0xF); - // its scale byte (t 2, h 1, j 1, c 0): row 32 + 8 + 4 = 44, k16 group 3 - const sc = std.mem.sliceAsBytes(out[(1 * 2 + 1) * words + 128 ..][0..16]); - try std.testing.expectEqual(scales[44 * 4 + 3], sc[((2 * 2 + 1) * 4 + 1) * 2]); -} - -test "packGateUp stacks packOne's gate and up blocks per (column block, k32 group)" { - const n = 64; - const k = 64; - const words = Nvfp4Experts.words; - var codes: [2][n * k / 2]u8 = undefined; - var scales: [2][n * k / 16]u8 = undefined; - for (0..2) |m| { - for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); - for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); - } - var one: [2][n / 32 * (k / 32) * words]u32 = undefined; - for (0..2) |m| Nvfp4Experts.packOne(&one[m], &codes[m], &scales[m], n, k); - var both: [2 * one[0].len]u32 = undefined; - Nvfp4Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); - for (0..one[0].len / words) |b| for (0..2) |m| { - try std.testing.expectEqualSlices(u32, one[m][b * words ..][0..words], both[(2 * b + m) * words ..][0..words]); - }; -} - -test "nvfp4 rows of either kind are refused when the format is not loaded" { - const g: Grouped = .{}; - const l: Layer = .{ .format = .nvfp4, .up = 0, .down = 0, .width = 64, .dims = 64, .experts = 2, .relu2 = true }; - const s: Stream = undefined; // never reached: the refusal comes first - const p: Plan = .{ .members = 0, .items = 0, .counts = 0, .rank = 0, .hist = 0 }; - try std.testing.expectError(error.FormatNotLoaded, g.prompt(s, .up, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 64, -1)); - try std.testing.expectError(error.FormatNotLoaded, g.decode(s, .down_bf16, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 16, -1)); - try std.testing.expectEqual(@as(usize, 2 * 2 * 3 * 144 * 4), Nvfp4Experts.bytes(2, 64, 96, 1)); -} - -test "a packed fp8 expert puts each word where fp8/experts.py's pack does" { - const gpa = std.testing.allocator; - const n = 128; - const k = 128; - const w = try gpa.alloc(u8, n * k); - defer gpa.free(w); - for (w, 0..) |*b, i| b.* = @truncate(i * 31 + 7); - const out = try gpa.alloc(u32, n * k / 4); - defer gpa.free(out); - Fp8Experts.packOne(out, w, n, k); - // (cb 1, g 2, gq 5, t 3, h 1, j 2): row 32 + 16 + 5 = 53, word 2 * 8 + 4 + 3 = 23 - const idx = (((((1 * 4 + 2) * 8 + 5) * 4 + 3) * 2 + 1) * 4) + 2; - const words = std.mem.bytesAsSlice(u32, @as([]align(1) const u8, w)); - try std.testing.expectEqual(words[53 * (k / 4) + 23], out[idx]); -} test { _ = @import("experts_host_test.zig"); // Grouped's refusals before any launch diff --git a/zig/src/cuda/experts_host_test.zig b/zig/src/cuda/experts_host_test.zig index 65f4a7f7952..3497f76e003 100644 --- a/zig/src/cuda/experts_host_test.zig +++ b/zig/src/cuda/experts_host_test.zig @@ -1,4 +1,4 @@ -//! Grouped's refusals before any launch: a format not loaded, an epilogue or an option it was not built with. +//! Grouped's refusals before any launch, and the NVFP4 and FP8 block packings' layouts. const std = @import("std"); const experts = @import("experts.zig"); @@ -6,6 +6,8 @@ const Grouped = experts.Grouped; const Layer = experts.Layer; const Plan = @import("grouped.zig").Plan; const Stream = @import("stream.zig").Stream; +const Nvfp4Experts = experts.Nvfp4Experts; +const Fp8Experts = experts.Fp8Experts; test "a format that is not loaded, or an option it was not built with, is refused before any launch" { const g: Grouped = .{}; @@ -53,3 +55,68 @@ test "bf16 experts refuse dims or widths off the 32-wide blocks before any launc } } } + +test "a packed nvfp4 block puts each nibble and scale where nvfp4/experts.py's _pack does" { + const gpa = std.testing.allocator; + const n = 64; + const k = 64; + const codes = try gpa.alloc(u8, n * k / 2); + defer gpa.free(codes); + for (codes, 0..) |*c, i| c.* = @truncate(i * 29 + 3); + var scales: [n * k / 16]u8 = undefined; + for (&scales, 0..) |*c, i| c.* = @truncate(i * 7 + 1); + var out: [n / 32 * (k / 32) * Nvfp4Experts.words]u32 = undefined; + Nvfp4Experts.packOne(&out, codes, &scales, n, k); + const words = Nvfp4Experts.words; + // block (cb 1, g 1), lane gq 3, t 2, tile j 1: row 32 + 8 + 3 = 43; input 32 + 16 + 8 + 3 (h 1, q 3) -> slot 7 + const w = out[(1 * 2 + 1) * words + (3 * 4 + 2) * 4 + 1]; + try std.testing.expectEqual(@as(u32, codes[43 * 32 + 59 / 2] >> 4), (w >> Nvfp4Experts.slot(1, 3)) & 0xF); + // its scale byte (t 2, h 1, j 1, c 0): row 32 + 8 + 4 = 44, k16 group 3 + const sc = std.mem.sliceAsBytes(out[(1 * 2 + 1) * words + 128 ..][0..16]); + try std.testing.expectEqual(scales[44 * 4 + 3], sc[((2 * 2 + 1) * 4 + 1) * 2]); +} + +test "packGateUp stacks packOne's gate and up blocks per (column block, k32 group)" { + const n = 64; + const k = 64; + const words = Nvfp4Experts.words; + var codes: [2][n * k / 2]u8 = undefined; + var scales: [2][n * k / 16]u8 = undefined; + for (0..2) |m| { + for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); + for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); + } + var one: [2][n / 32 * (k / 32) * words]u32 = undefined; + for (0..2) |m| Nvfp4Experts.packOne(&one[m], &codes[m], &scales[m], n, k); + var both: [2 * one[0].len]u32 = undefined; + Nvfp4Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); + for (0..one[0].len / words) |b| for (0..2) |m| { + try std.testing.expectEqualSlices(u32, one[m][b * words ..][0..words], both[(2 * b + m) * words ..][0..words]); + }; +} + +test "nvfp4 rows of either kind are refused when the format is not loaded" { + const g: Grouped = .{}; + const l: Layer = .{ .format = .nvfp4, .up = 0, .down = 0, .width = 64, .dims = 64, .experts = 2, .relu2 = true }; + const s: Stream = undefined; // never reached: the refusal comes first + const p: Plan = .{ .members = 0, .items = 0, .counts = 0, .rank = 0, .hist = 0 }; + try std.testing.expectError(error.FormatNotLoaded, g.prompt(s, .up, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 64, -1)); + try std.testing.expectError(error.FormatNotLoaded, g.decode(s, .down_bf16, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 16, -1)); + try std.testing.expectEqual(@as(usize, 2 * 2 * 3 * 144 * 4), Nvfp4Experts.bytes(2, 64, 96, 1)); +} + +test "a packed fp8 expert puts each word where fp8/experts.py's pack does" { + const gpa = std.testing.allocator; + const n = 128; + const k = 128; + const w = try gpa.alloc(u8, n * k); + defer gpa.free(w); + for (w, 0..) |*b, i| b.* = @truncate(i * 31 + 7); + const out = try gpa.alloc(u32, n * k / 4); + defer gpa.free(out); + Fp8Experts.packOne(out, w, n, k); + // (cb 1, g 2, gq 5, t 3, h 1, j 2): row 32 + 16 + 5 = 53, word 2 * 8 + 4 + 3 = 23 + const idx = (((((1 * 4 + 2) * 8 + 5) * 4 + 3) * 2 + 1) * 4) + 2; + const words = std.mem.bytesAsSlice(u32, @as([]align(1) const u8, w)); + try std.testing.expectEqual(words[53 * (k / 4) + 23], out[idx]); +} diff --git a/zig/src/cuda/experts_mx.zig b/zig/src/cuda/experts_mx.zig new file mode 100644 index 00000000000..eb25c5847fc --- /dev/null +++ b/zig/src/cuda/experts_mx.zig @@ -0,0 +1,262 @@ +//! Stored-format experts for Inkling 2 Mini: MXFP8 (fp8_experts.cu) and the soft-capped SwiGLU on NVFP4's kernels. +const std = @import("std"); +const module = @import("module.zig"); +const launch_ = @import("launch.zig"); +const stream_ = @import("stream.zig"); +const kernels = @import("kernels.zig"); +const driver = @import("driver.zig"); +const experts = @import("experts.zig"); + +const Module = module.Module; +const Function = module.Function; +const Stream = stream_.Stream; +const Plan = @import("grouped.zig").Plan; +const Layer = experts.Layer; +const Epi = experts.Epi; +const Rows = experts.Rows; + +/// NVFP4's per-expert factor: amax / denominator, each rounded to bf16 as the reference loads it (open question F1). +pub fn nvfp4Factor(amax: f32, denominator: f32) f32 { + return bf16(amax) / bf16(denominator); +} + +/// x rounded to bf16 (nearest, ties to even), as an f32; the checkpoint's amax values are finite. +fn bf16(x: f32) f32 { + const b: u32 = @bitCast(x); + return @bitCast((b +% 0x7FFF +% ((b >> 16) & 1)) & 0xFFFF0000); +} + +/// A layer's caps: both 0 (plain), or both positive and finite (soft-capped SwiGLU); refused where no kernel has them. +pub fn capsBuilt(l: Layer) !void { + if (l.caps[0] == 0 and l.caps[1] == 0) { + if (l.format == .mxfp8) return error.OptionNotBuilt; // MXFP8's gate-up is built soft-capped only + return; + } + for (l.caps) |c| if (!(c > 0 and c < std.math.inf(f32))) return error.BadSoftcap; + if (l.format != .nvfp4 and l.format != .mxfp8) return error.OptionNotBuilt; + if (l.relu2 or l.limit != 0 or l.swiglu or l.after) return error.OptionNotBuilt; + if (l.width % 32 != 0 or l.dims % 32 != 0) return error.UnexpectedShape; // whole blocks of 32 both ways +} + +/// Inkling's w13 interleaves rows (2j gate j, 2j + 1 up j): one expert's rows of `row_bytes` split into gate, up. +pub fn splitGateUp(rows: []const u8, row_bytes: usize, gate: []u8, up: []u8) void { + const pairs = rows.len / (2 * row_bytes); + std.debug.assert(rows.len == 2 * pairs * row_bytes and gate.len == pairs * row_bytes and up.len == gate.len); + for (0..pairs) |j| { + @memcpy(gate[j * row_bytes ..][0..row_bytes], rows[2 * j * row_bytes ..][0..row_bytes]); + @memcpy(up[j * row_bytes ..][0..row_bytes], rows[(2 * j + 1) * row_bytes ..][0..row_bytes]); + } +} + +/// The caps as the kernels take them: a negative up cap asks for gate and up rounded to bf16 first (round_caps). +pub fn kernelCaps(l: Layer) [2]f32 { + return .{ l.caps[0], if (l.round_caps) -l.caps[1] else l.caps[1] }; +} + +/// An expert call's arguments as the soft-capped and MXFP8 entries take them; `scale` null for MXFP8 (in its blocks). +pub fn argsOf(in: Rows, gate: bool, w: u64, scale: ?u64, kg: usize, nb: usize, p: Plan, out: u64, n: usize, caps: [2]f32, skip: i32) launch_.Args { + var a: launch_.Args = .{}; + a.add(in.x); + a.add(@as(i32, @intCast(in.stride))); + a.add(@as(i32, @intCast(if (gate) in.slots else 0))); + a.add(w); + if (scale) |v| a.add(v); + a.add(@as(i32, @intCast(kg))); + a.add(@as(i32, @intCast(nb))); + for ([_]u64{ p.items, p.counts, p.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(caps[0]); + a.add(caps[1]); + a.add(skip); + return a; +} + +/// nvfp4_experts.cu's soft-capped SwiGLU gate-up: decode units of 4 warps, and the prompt tiles of 4 warps. +pub const Softcap = struct { + fns: [2]Function = undefined, // decode, prompt + resident: usize = 0, + + pub const symbols = [2][:0]const u8{ "tf_nvfp4_softcap", "tf_nvfp4_prompt_softcap" }; + pub const prompt_wn = 4; + + pub fn resolve(mod: Module, sms: usize) !Softcap { + var c: Softcap = .{}; + for (symbols, &c.fns) |name, *f| f.* = try mod.function(name); + try c.fns[1].allowDynamicShared(experts.Nvfp4Experts.promptSmem(2, prompt_wn)); + c.resident = @max(1, try c.fns[0].occupancy(128, 0)) * sms; + return c; + } + + /// Gate-up on a plan of at most `items` items (16 pairs decode, 64 prompt); capsBuilt checked the layer. + pub fn run(c: Softcap, s: Stream, prompt: bool, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + const nb = l.width / 32; + var a = argsOf(in, true, l.up, l.up_scale, l.dims / 32, nb, p, out, l.width, kernelCaps(l), skip); + const grid = if (prompt) items * ((nb + prompt_wn - 1) / prompt_wn) else @min((items * nb + 3) / 4, c.resident); + if (grid < 1) return; + const smem: u32 = if (prompt) experts.Nvfp4Experts.promptSmem(2, prompt_wn) else 0; + const cfg: launch_.Config = .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 }, .shared = smem }; + try launch_.launch(c.fns[@intFromBool(prompt)], cfg, s, &a); + } +}; + +/// MXFP8 experts: e4m3 codes with one E8M0 scale per output row per 32 inputs, blocks of 32 columns by 32 inputs. +pub const Mxfp8Experts = struct { + mod: Module, + fns: [5]Function, // decode: soft-capped gate-up, fp32 down, bf16 down; prompt: soft-capped gate-up, bf16 down + resident: [3]usize, // the decode entries' blocks a grid may hold + + pub const words = 264; // int32 a block: fp8g's 256 code words ([32 lanes][2][4]), then 32 E8M0 bytes + pub const prompt_cw = [2]usize{ 2, 4 }; // column warps a prompt CTA: gate-up, down (64 pairs an item) + pub const symbols = [5][:0]const u8{ "tf_mxfp8_softcap", "tf_mxfp8_down_f32", "tf_mxfp8_down_bf16", "tf_mxfp8_prompt_softcap", "tf_mxfp8_prompt_down" }; + + pub fn load(d: *const driver.Driver, sms: usize) !Mxfp8Experts { + if (!kernels.available) return error.BuiltWithoutKernels; + var mod = try Module.load(d, kernels.fp8_experts); + errdefer mod.unload(); + var e: Mxfp8Experts = .{ .mod = mod, .fns = undefined, .resident = undefined }; + for (symbols, &e.fns) |name, *f| f.* = try mod.function(name); + for (&e.resident, 0..) |*r, i| r.* = @max(1, try e.fns[i].occupancy(128, 0)) * sms; + return e; + } + + pub fn unload(e: *Mxfp8Experts) void { + e.mod.unload(); + } + + /// The entry a call takes, or the refusal: prompt rows have no fp32 down. + pub fn entry(prompt: bool, epi: Epi) !usize { + return switch (epi) { + .up => if (prompt) 3 else 0, + .down_f32 => if (prompt) error.EpilogueNotBuilt else 1, + .down_bf16 => if (prompt) 4 else 2, + }; + } + + /// One call on a plan of at most `items` items (16 pairs decode, 64 prompt); the layer's caps already checked. + pub fn run(e: *const Mxfp8Experts, s: Stream, prompt: bool, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + const fi = try entry(prompt, epi); + const gate = epi == .up; + const n = if (gate) l.width else l.dims; + const k = if (gate) l.dims else l.width; + if (n % 32 != 0 or k % 32 != 0) return error.UnexpectedShape; + const nb = n / 32; + const cw = prompt_cw[@intFromBool(!gate)]; + if (prompt and nb % cw != 0) return error.UnexpectedShape; + const grid = if (prompt) items * (nb / cw) else @min((items * nb + 3) / 4, e.resident[fi]); + if (grid < 1) return; + var a = argsOf(in, gate, if (gate) l.up else l.down, null, k / 32, nb, p, out, n, kernelCaps(l), skip); + try launch_.launch(e.fns[fi], .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); + } + + /// Bytes of `count` experts' blocks for n outputs from k inputs: [E][n/32][k/32][parts][264] int32. + pub fn bytes(count: usize, n: usize, k: usize, parts: usize) usize { + return count * (n / 32) * (k / 32) * parts * words * 4; + } + + /// One expert's e4m3 codes [n, k] and E8M0 scales [n, k/32] (row-major, as stored) as blocks [n/32][k/32][264]. + pub fn packOne(out: []u32, codes: []const u8, scales: []const u8, n: usize, k: usize) void { + packPart(out, 1, 0, codes, scales, n, k); + } + + /// Gate and up interleaved per (column block, k32 group): [n/32][k/32][2][264], each [codes, scales] as stored. + pub fn packGateUp(out: []u32, gate: [2][]const u8, up: [2][]const u8, n: usize, k: usize) void { + packPart(out, 2, 0, gate[0], gate[1], n, k); + packPart(out, 2, 1, up[0], up[1], n, k); + } + + /// Lane (gq, t)'s words [h][j]: row j * 8 + gq, inputs 16h + 4t .. + 3 (fp8g's order); scale byte 4 gq + j. + fn packPart(out: []u32, parts: usize, part: usize, codes: []const u8, scales: []const u8, n: usize, k: usize) void { + const kg = k / 32; + std.debug.assert(n % 32 == 0 and k % 32 == 0 and out.len == n / 32 * kg * parts * words and part < parts); + std.debug.assert(codes.len == n * k and scales.len == n * kg); + for (0..n / 32) |cb| for (0..kg) |g| { + const block = out[((cb * kg + g) * parts + part) * words ..][0..words]; + for (0..8) |gq| for (0..4) |t| for (0..2) |h| for (0..4) |j| { + const row = cb * 32 + j * 8 + gq; + const at = row * k + g * 32 + h * 16 + t * 4; + block[((gq * 4 + t) * 2 + h) * 4 + j] = std.mem.readInt(u32, codes[at..][0..4], .little); + }; + const sc = std.mem.sliceAsBytes(block[256..]); + for (0..8) |gq| for (0..4) |j| { + sc[gq * 4 + j] = scales[(cb * 32 + j * 8 + gq) * kg + g]; + }; + }; + } +}; + +test "the NVFP4 factor rounds amax and the denominator to bf16 before it divides" { + const amax: f32 = 0.3310546875 + 0x1p-12; // not a bf16 + const want = @as(f32, 0.33203125) / 2688.0; // bf16(amax) is 0.33203125; 2688 = 6 x 448 is a bf16 + try std.testing.expectEqual(want, nvfp4Factor(amax, 2688)); + try std.testing.expect(nvfp4Factor(amax, 2688) != amax / 2688); +} + +test "w13's row 1 is up row 0 and row 2 gate row 1: a code planted in row 1 lands in the up part, never the gate" { + const n = 32; // gate and up rows each + const k = 32; + var rows: [2 * n * k]u8 = @splat(0x00); + var sc: [2 * n]u8 = @splat(127); + rows[1 * k + 5] = 0x38; // stored row 1 (up row 0), input 5 + rows[2 * k + 7] = 0x40; // stored row 2 (gate row 1), input 7 + var g: [n * k]u8 = undefined; + var u: [n * k]u8 = undefined; + var gs: [n]u8 = undefined; + var us: [n]u8 = undefined; + splitGateUp(&rows, k, &g, &u); + splitGateUp(&sc, 1, &gs, &us); + try std.testing.expectEqual(@as(u8, 0x38), u[5]); + try std.testing.expectEqual(@as(u8, 0x40), g[k + 7]); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, &u, &.{0x38}) + std.mem.count(u8, &u, &.{0x40})); + var out: [2 * Mxfp8Experts.words]u32 = undefined; + Mxfp8Experts.packGateUp(&out, .{ &g, &gs }, .{ &u, &us }, n, k); + // row 0, input 5 = lane (gq 0, t 1), half 0, tile j 0, byte 1 of the word; part 1 (up) holds it, part 0 not + const at = ((0 * 4 + 1) * 2 + 0) * 4 + 0; + try std.testing.expectEqual(@as(u32, 0x38), (out[Mxfp8Experts.words + at] >> 8) & 0xFF); + try std.testing.expectEqual(@as(u32, 0), (out[at] >> 8) & 0xFF); +} + +test "a packed MXFP8 block holds fp8g's code words and each row's scale at byte 4 gq + j" { + const gpa = std.testing.allocator; + const n = 64; + const k = 96; + const codes = try gpa.alloc(u8, n * k); + defer gpa.free(codes); + for (codes, 0..) |*c, i| c.* = @truncate(i * 31 + 7); + var scales: [n * k / 32]u8 = undefined; + for (&scales, 0..) |*c, i| c.* = @truncate(i * 13 + 5); + const out = try gpa.alloc(u32, Mxfp8Experts.bytes(1, n, k, 1) / 4); + defer gpa.free(out); + Mxfp8Experts.packOne(out, codes, &scales, n, k); + // the code words of every block are Fp8Experts.packOne's order (fp8_experts.cu's lane loads) + for (0..n / 32) |cb| for (0..k / 32) |g| for (0..8) |gq| for (0..4) |t| for (0..2) |h| for (0..4) |j| { + const row = cb * 32 + j * 8 + gq; + const w = std.mem.readInt(u32, codes[row * k + g * 32 + h * 16 + t * 4 ..][0..4], .little); + try std.testing.expectEqual(w, out[(cb * (k / 32) + g) * Mxfp8Experts.words + ((gq * 4 + t) * 2 + h) * 4 + j]); + }; + // block (cb 1, g 2): row 32 + 8 j + gq's scale for group 2 at byte 4 gq + j of the block's last 32 + const sc = std.mem.sliceAsBytes(out[(1 * 3 + 2) * Mxfp8Experts.words + 256 ..][0..8]); + for (0..8) |gq| for (0..4) |j| try std.testing.expectEqual(scales[(32 + 8 * j + gq) * 3 + 2], sc[gq * 4 + j]); +} + +test "packGateUp stacks gate then up per (column block, k32 group)" { + const n = 32; + const k = 64; + var codes: [2][n * k]u8 = undefined; + var scales: [2][n * k / 32]u8 = undefined; + for (0..2) |m| { + for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); + for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); + } + var one: [2][Mxfp8Experts.bytes(1, n, k, 1) / 4]u32 = undefined; + for (0..2) |m| Mxfp8Experts.packOne(&one[m], &codes[m], &scales[m], n, k); + var both: [2 * one[0].len]u32 = undefined; + Mxfp8Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); + const w = Mxfp8Experts.words; + for (0..one[0].len / w) |b| for (0..2) |m| { + try std.testing.expectEqualSlices(u32, one[m][b * w ..][0..w], both[(2 * b + m) * w ..][0..w]); + }; +} + +test { + _ = @import("experts_mx_test.zig"); // dispatch, arguments and refusals on a mock launcher +} diff --git a/zig/src/cuda/experts_mx_test.zig b/zig/src/cuda/experts_mx_test.zig new file mode 100644 index 00000000000..d8460b35c5f --- /dev/null +++ b/zig/src/cuda/experts_mx_test.zig @@ -0,0 +1,133 @@ +//! Stored-format experts on a mock launcher: the entry each call takes, its arguments, refusals that launch none. +const std = @import("std"); +const abi = @import("abi.zig"); +const experts = @import("experts.zig"); +const mx = @import("experts_mx.zig"); +const Driver = @import("driver.zig").Driver; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; +const Plan = @import("grouped.zig").Plan; + +const Mock = struct { + var launches: usize = 0; + var selected: usize = 0; + var grid: u32 = 0; + var shared: u32 = 0; + var words: [16]u64 = undefined; + fn launch(f: abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, sm: c_uint, _: abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result { + launches += 1; + selected = @intFromPtr(f.?); + grid = gx; + shared = sm; + // the soft-capped NVFP4 entry has 15 arguments, the MXFP8 ones 14 (no scale pointer) + const wide = [_]usize{ 0, 3, 4, 7, 8, 9, 10 }; + const n: usize = if (selected < 40) 15 else 14; + for (0..n) |i| { + const big = if (selected < 40) std.mem.indexOfScalar(usize, &wide, i) != null else std.mem.indexOfScalar(usize, &[_]usize{ 0, 3, 6, 7, 8, 9 }, i) != null; + words[i] = if (big) @as(*const u64, @ptrCast(@alignCast(params.?[i].?))).* else @as(*const u32, @ptrCast(@alignCast(params.?[i].?))).*; + } + return 0; + } +}; + +const plan: Plan = .{ .items = 60, .counts = 70, .members = 80, .rank = 90, .hist = 100 }; +const in_up: experts.Rows = .{ .x = 10, .stride = 2304, .slots = 8 }; +const mini: experts.Layer = .{ .format = .nvfp4, .up = 20, .down = 30, .up_scale = 40, .down_scale = 50, .width = 1152, .dims = 2304, .experts = 128, .caps = .{ 4, 25 } }; + +fn kernelsOn(d: *Driver) struct { k4: experts.Nvfp4Experts, k8: mx.Mxfp8Experts } { + d.api.cuLaunchKernel = Mock.launch; + var k4: experts.Nvfp4Experts = undefined; // only the soft-capped entries are reachable from the calls below + k4.softcap = .{ .fns = .{ .{ .d = d, .handle = @ptrFromInt(31) }, .{ .d = d, .handle = @ptrFromInt(32) } }, .resident = 96 }; + var k8: mx.Mxfp8Experts = .{ .mod = undefined, .fns = undefined, .resident = @splat(96) }; + for (&k8.fns, 0..) |*f, i| f.* = .{ .d = d, .handle = @ptrFromInt(41 + i) }; + return .{ .k4 = k4, .k8 = k8 }; +} + +test "soft-capped NVFP4 gate-up takes tf_nvfp4_softcap with both caps; prompt rows the prompt entry and its shared" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const g: experts.Grouped = .{ .nvfp4 = &k.k4 }; + const s: Stream = .{ .d = &d, .handle = null }; + try g.decode(s, .up, in_up, mini, plan, 110, 5, 32, 16, -1); + try std.testing.expectEqual(@as(usize, 31), Mock.selected); + try std.testing.expectEqual(@as(u32, (5 * 36 + 3) / 4), Mock.grid); + try std.testing.expectEqual(@as(u64, 8), Mock.words[2]); // slots + try std.testing.expectEqual(@as(u64, 40), Mock.words[4]); // the per-expert factors + try std.testing.expectEqual(@as(u64, 2304 / 32), Mock.words[5]); + try std.testing.expectEqual(@as(u64, 1152 / 32), Mock.words[6]); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 4))), @as(u32, @truncate(Mock.words[12]))); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 25))), @as(u32, @truncate(Mock.words[13]))); + try std.testing.expectEqual(@as(u64, @as(u32, @bitCast(@as(i32, -1)))), Mock.words[14]); + try g.prompt(s, .up, in_up, mini, plan, 110, 3, 192, 64, 7); + try std.testing.expectEqual(@as(usize, 32), Mock.selected); + try std.testing.expectEqual(@as(u32, 3 * 9), Mock.grid); + try std.testing.expectEqual(experts.Nvfp4Experts.promptSmem(2, 4), Mock.shared); + try std.testing.expectEqual(@as(u64, 7), Mock.words[14]); +} + +test "MXFP8 calls take their entry by form and epilogue, with no scale pointer and the layer's caps" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const g: experts.Grouped = .{ .mxfp8 = &k.k8 }; + const s: Stream = .{ .d = &d, .handle = null }; + var l = mini; + l.format = .mxfp8; + const in_down: experts.Rows = .{ .x = 11, .stride = 1152 }; + const cases = [_]struct { prompt: bool, epi: experts.Epi, want: usize, grid: u32, kg: u64, nb: u64 }{ + .{ .prompt = false, .epi = .up, .want = 41, .grid = (5 * 36 + 3) / 4, .kg = 72, .nb = 36 }, + .{ .prompt = false, .epi = .down_f32, .want = 42, .grid = (5 * 72 + 3) / 4, .kg = 36, .nb = 72 }, + .{ .prompt = false, .epi = .down_bf16, .want = 43, .grid = (5 * 72 + 3) / 4, .kg = 36, .nb = 72 }, + .{ .prompt = true, .epi = .up, .want = 44, .grid = 5 * 18, .kg = 72, .nb = 36 }, + .{ .prompt = true, .epi = .down_bf16, .want = 45, .grid = 5 * 18, .kg = 36, .nb = 72 }, + }; + for (cases) |c| { + const in = if (c.epi == .up) in_up else in_down; + if (c.prompt) try g.prompt(s, c.epi, in, l, plan, 110, 5, 40, 64, -1) else try g.decode(s, c.epi, in, l, plan, 110, 5, 40, 16, -1); + try std.testing.expectEqual(c.want, Mock.selected); + try std.testing.expectEqual(c.grid, Mock.grid); + try std.testing.expectEqual(@as(u64, if (c.epi == .up) 8 else 0), Mock.words[2]); + try std.testing.expectEqual(@as(u64, if (c.epi == .up) 20 else 30), Mock.words[3]); + try std.testing.expectEqual(c.kg, Mock.words[4]); + try std.testing.expectEqual(c.nb, Mock.words[5]); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 25))), @as(u32, @truncate(Mock.words[12]))); + } +} + +test "refusals by name launch nothing: MXFP8 not loaded, caps unbuilt or malformed, shapes, prompt fp32 down" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const s: Stream = .{ .d = &d, .handle = null }; + const none: experts.Grouped = .{}; + const both: experts.Grouped = .{ .nvfp4 = &k.k4, .mxfp8 = &k.k8 }; + Mock.launches = 0; + var l = mini; + l.format = .mxfp8; + try std.testing.expectError(error.FormatNotLoaded, none.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + try std.testing.expectError(error.FormatNotLoaded, none.prompt(s, .down_bf16, in_up, l, plan, 0, 1, 8, 64, -1)); + try std.testing.expectError(error.EpilogueNotBuilt, both.prompt(s, .down_f32, in_up, l, plan, 0, 1, 8, 64, -1)); + l.caps = .{ 0, 0 }; // MXFP8's gate-up is built soft-capped only + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + for ([_][2]f32{ .{ 4, 0 }, .{ -4, 25 }, .{ 4, std.math.inf(f32) }, .{ std.math.nan(f32), 25 } }) |cp| { + l.caps = cp; + try std.testing.expectError(error.BadSoftcap, both.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + } + for (std.enums.values(experts.Format)) |f| if (f != .nvfp4 and f != .mxfp8) { + var o = mini; + o.format = f; + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, o, plan, 0, 1, 8, 16, -1)); + try std.testing.expectError(error.OptionNotBuilt, both.prompt(s, .up, in_up, o, plan, 0, 1, 8, 64, -1)); + }; + var r = mini; + r.relu2 = true; + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, r, plan, 0, 1, 8, 16, -1)); + r = mini; + r.limit = 7; + try std.testing.expectError(error.OptionNotBuilt, both.prompt(s, .up, in_up, r, plan, 0, 1, 8, 64, -1)); + r = mini; + r.width = 1144; + try std.testing.expectError(error.UnexpectedShape, both.decode(s, .up, in_up, r, plan, 0, 1, 8, 16, -1)); + r.format = .mxfp8; + r.width = 1152 + 32; // 37 column blocks: the prompt gate-up takes 2 a CTA + try std.testing.expectError(error.UnexpectedShape, both.prompt(s, .up, in_up, r, plan, 0, 1, 8, 64, -1)); + try std.testing.expectEqual(@as(usize, 0), Mock.launches); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index bf53d71117e..9e48cafa58e 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -120,8 +120,8 @@ pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").bytes else &.{}; pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; -pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; +pub const inkling2_loop: []const u8 = if (available) &Blob("fatbin_inkling2_loop").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index a00354ee677..38468bfce1c 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -58,6 +58,7 @@ pub const kda = @import("kda.zig"); pub const gdn_prep = @import("gdn_prep.zig"); pub const qk_rows = @import("qk_rows.zig"); pub const experts = @import("experts.zig"); +pub const experts_mx = @import("experts_mx.zig"); pub const pair_experts = @import("experts_pair.zig"); pub const affine_experts = @import("affine_experts.zig"); pub const experts32 = @import("experts32.zig"); @@ -121,6 +122,7 @@ test { _ = @import("experts.zig"); _ = @import("experts32.zig"); _ = @import("experts_waves.zig"); + _ = @import("experts_mx.zig"); _ = @import("sample.zig"); _ = @import("roce.zig"); _ = @import("roce_nap.zig"); diff --git a/zig/src/families/dory/schedule.zig b/zig/src/families/dory/schedule.zig index 935745c9ae7..fb8e7f65796 100644 --- a/zig/src/families/dory/schedule.zig +++ b/zig/src/families/dory/schedule.zig @@ -1,6 +1,7 @@ //! Dory's sublayer order: input, the recurrent block `loops` times, output; per_loop KV caches, one an attention step. const std = @import("std"); const config = @import("config.zig"); +const visit_plan = @import("core").visit_plan; const Config = config.Config; const Kind = config.Kind; @@ -42,28 +43,38 @@ pub const Schedule = struct { } }; +/// Dory's one state kind: an attention sublayer's KV cache (sliding or full by its sublayer's kind). +const State = enum { cache }; +const Walk = visit_plan.Plan(State, max_steps); + +const Holds = struct { + c: *const Config, + pub fn keeps(h: Holds, sub: u16, _: State) bool { + return h.c.kinds[sub] != .mlp; + } +}; + /// The steps of `c` at `c.loops` loops: I + R * loops + O, caches numbered in the order the steps run. pub fn build(c: Config) Schedule { + const core_end: u32 = @intCast(c.input + c.recurrent); + const loop: visit_plan.Loop = .{ .start = @intCast(c.input), .end = core_end, .passes = @intCast(c.loops) }; + // config.parse and withLoops bound sublayers by max_sublayers and loops to 1..max_loops + const w = Walk.build(@intCast(c.sublayers), loop, Holds{ .c = &c }) catch unreachable; var s: Schedule = .{}; - const add = struct { - fn one(sch: *Schedule, cc: Config, sub: usize, loop: usize) void { - var st: Step = .{ .sub = @intCast(sub), .kind = cc.kinds[sub], .loop = @intCast(loop) }; - if (st.kind != .mlp) { - st.cache = @intCast(sch.caches); - sch.cache_kind[sch.caches] = st.kind; - sch.caches += 1; - } - sch.steps[sch.len] = st; - sch.len += 1; - } - }.one; - for (0..c.input) |i| add(&s, c, i, 0); - for (0..c.loops) |l| { - for (c.input..c.input + c.recurrent) |i| add(&s, c, i, l); - s.steps[s.len - c.recurrent].enter = true; - s.steps[s.len - 1].leave = true; + for (w.slice()) |v| { + const st: Step = .{ + .sub = v.layer, + .kind = c.kinds[v.layer], + .loop = v.pass, + .cache = v.of(.cache), + .enter = v.enter, + .leave = v.leave, + }; + if (st.cache) |i| s.cache_kind[i] = st.kind; + s.steps[s.len] = st; + s.len += 1; } - for (c.input + c.recurrent..c.sublayers) |i| add(&s, c, i, 0); + s.caches = w.count(.cache); return s; } diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index 9d30527e4d8..594efb83ab2 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -1,11 +1,22 @@ -//! Inkling 2 Small and Mini shapes from config.json, refusing every layout the engine does not run. +//! Inkling 2's shape from config.json: Small (inkling2) and the looped Mini (inkling2_loop); other layouts refused. const std = @import("std"); +const modelopt = @import("modelopt"); -/// The most backbone layers the plan tables hold (Inkling 2 Small has 48). +/// The most backbone layers the plan tables hold (Inkling 2 Small has 48, Mini 24). pub const max_layers = 128; -/// The most scheduled layer visits the visit-plan table holds. -pub const max_visits = max_layers * 8; +/// The most layer visits a token makes (Mini: 24 layers, layers 6..17 three times, so 48). +pub const max_visits = 256; + +/// The widest gate rank the loop kernels hold (loop.cu kMaxRank; Mini's gate_rank is 64). +pub const max_gate_rank = 128; + +/// The attention kernels' fixed widths (attention.cu and the Metal attention shaders). +pub const head_dim = 128; +pub const d_rel = 16; + +/// The most finished attention-residual blocks a residual mix reads (ops.cu and loop.cu; Small makes 8, Mini 4). +pub const max_blocks = 8; /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -40,13 +51,9 @@ pub const Why = struct { /// One attention geometry: sliding layers read the `swa_*` keys, global layers the plain ones. pub const Heads = struct { q: u32, kv: u32, dim: u32 }; -/// The fixed loop schedule: all layers once, then only the core on each later pass. -pub const Loop = struct { - core_start: u32, // inclusive physical layer id - core_end: u32, // exclusive physical layer id - passes: u32, - gate_rank: u32, -}; +/// loop_config: layers [start, end) run `passes` times; passes after the first restart from the core's entry state +/// and take gated messages (rank `rank`) from the pass before. +pub const Loop = struct { start: u32, end: u32, passes: u32, rank: u32 }; pub const Text = struct { hidden: u32, @@ -72,12 +79,12 @@ pub const Text = struct { up_cap: f32, logit_cap: f32, max_context: u32, - loop: ?Loop, + loop: ?Loop = null, // inkling2_loop only - /// The number of scheduled layer visits; a drafter target equal to this is the final norm. - pub fn visitCount(c: *const Text) u32 { + /// Layer visits a token makes: every layer once, the core's layers once a pass. + pub fn visits(c: *const Text) u32 { const l = c.loop orelse return c.layers; - return c.layers + (l.passes - 1) * (l.core_end - l.core_start); + return c.layers + (l.passes - 1) * (l.end - l.start); } pub fn heads(c: *const Text, i: u32) Heads { @@ -90,7 +97,7 @@ pub const Text = struct { } }; -/// The draft head's shape (mtp_config); target taps are visit ids, with `visitCount` meaning the final norm. +/// The draft head's shape (mtp_config); taps are layer visits (`Text.visits()`: the output after the final norm). pub const Mtp = struct { layers: u32, q_heads: u32, @@ -196,6 +203,10 @@ fn heads(o: std.json.ObjectMap, prefix: []const u8, why: *Why) !Heads { why.set("{d} query heads do not split over {d} key/value heads", .{ q, kv }); return error.Layout; } + if (dim != head_dim) { + why.set("{s}head_dim {d} is not {d}, the attention kernels' width", .{ prefix, dim, head_dim }); + return error.Unsupported; + } return .{ .q = q, .kv = kv, .dim = dim }; } @@ -219,31 +230,7 @@ fn layerTypes(o: std.json.ObjectMap, layers: u32, why: *Why) !void { } } -fn parseLoop(o: std.json.ObjectMap, layers: u32, block: u32, why: *Why) !Loop { - const l: Loop = .{ - .core_start = try index(o, "core_start", why), - .core_end = try int(o, "core_end", why), - .passes = try int(o, "num_passes", why), - .gate_rank = try int(o, "gate_rank", why), - }; - try fixed(o, "is_varloop", false, why); - if (l.core_start == 0 or l.core_start >= l.core_end or l.core_end > layers) { - why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers", .{ l.core_start, l.core_end, layers }); - return error.Layout; - } - if (l.core_start % block != 0 or l.core_end % block != 0 or l.core_start != block or l.core_end + block != layers) { - why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, leaving its first and last blocks outside the loop", .{block}); - return error.Layout; - } - const visits = @as(u64, layers) + @as(u64, l.passes - 1) * @as(u64, l.core_end - l.core_start); - if (visits > max_visits) { - why.set("loop_config makes {d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); - return error.Layout; - } - return l; -} - -fn parseText(o: std.json.ObjectMap, why: *Why) !Text { +fn parseText(o: std.json.ObjectMap, looped: bool, why: *Why) !Text { var t: Text = undefined; t.loop = null; t.hidden = try int(o, "hidden_size", why); @@ -277,6 +264,14 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { why.set("n_layers_per_attn_res_block {d} is past num_hidden_layers {d}", .{ t.block, t.layers }); return error.Layout; } + if (std.math.divCeil(u32, t.layers, t.block) catch unreachable > max_blocks) { + why.set("n_layers_per_attn_res_block {d} splits {d} layers into more than the residual mixes' {d} blocks", .{ t.block, t.layers, max_blocks }); + return error.Layout; + } + if (t.d_rel != d_rel) { + why.set("d_rel {d} is not {d}, the attention kernels' width", .{ t.d_rel, d_rel }); + return error.Unsupported; + } if (try int(o, "sconv_kernel_size", why) != conv_taps) { why.set("sconv_kernel_size must be {d}: the checkpoint's published short convolutions", .{conv_taps}); return error.Unsupported; @@ -313,10 +308,49 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { return error.Unsupported; }; try layerTypes(o, t.layers, why); - if (o.get("loop_config")) |_| t.loop = try parseLoop(try object(o, "loop_config", why), t.layers, t.block, why); + t.loop = null; + if (looped) { + try fixed(o, "attn_res_normalize_values", true, why); + t.loop = try parseLoop(try object(o, "loop_config", why), &t, why); + } else if (o.get("loop_config") != null) { + why.set("loop_config needs model_type inkling2_loop", .{}); + return error.Unsupported; + } return t; } +/// loop_config: a fixed pass count (is_varloop refused) over a core of whole attention-residual blocks. +fn parseLoop(o: std.json.ObjectMap, t: *const Text, why: *Why) !Loop { + if (o.get("is_varloop")) |v| if (v != .bool or v.bool) { + why.set("loop_config.is_varloop must be false: the engine runs a fixed number of passes", .{}); + return error.Unsupported; + }; + const l: Loop = .{ + .start = try index(o, "core_start", why), + .end = try index(o, "core_end", why), + .passes = try int(o, "num_passes", why), + .rank = try int(o, "gate_rank", why), + }; + if (l.start == 0 or l.start >= l.end or l.end > t.layers) { + why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers; bounds outside the backbone's first and last blocks are not whole blocks of {d}", .{ l.start, l.end, t.layers, t.block }); + return error.Layout; + } + if (l.start % t.block != 0 or l.end % t.block != 0 or l.start != t.block or l.end + t.block != t.layers) { + why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, not whole blocks of {d} outside its first and last blocks", .{ t.block, t.block }); + return error.Layout; + } + if (l.passes < 2 or l.rank > max_gate_rank) { + why.set("loop_config: num_passes {d} must be at least 2 and gate_rank {d} at most {d}", .{ l.passes, l.rank, max_gate_rank }); + return error.Layout; + } + const visits = @as(u64, t.layers) + @as(u64, l.passes - 1) * (l.end - l.start); + if (visits > max_visits) { + why.set("{d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); + return error.Layout; + } + return l; +} + fn parseVision(o: std.json.ObjectMap, text_hidden: u32, why: *Why) !Vision { var v: Vision = undefined; v.hidden = try int(o, "hidden_size", why); @@ -364,29 +398,35 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { m.local[@intCast(e.integer)] = true; } for (taps.array.items) |e| { - if (e != .integer or e.integer < 0 or e.integer > t.visitCount()) { + if (e != .integer or e.integer < 0 or e.integer > t.visits()) { why.set("mtp_config's target_layer_ids names a layer the backbone does not have", .{}); return error.Layout; } + if (t.loop != null and m.taps_n > 0 and e.integer <= m.taps[m.taps_n - 1]) { + why.set("mtp_config's target_layer_ids must rise: they name visits in run order", .{}); + return error.Layout; + } m.taps[m.taps_n] = @intCast(e.integer); m.taps_n += 1; } return m; } -/// A quantization_config in config.json must be ModelOpt NVFP4, which the experts' header dtype refines per layer. -fn quantization(o: std.json.ObjectMap, why: *Why) !void { +/// A quantization_config must be ModelOpt NVFP4 (core.modelopt); each layer's expert format is its tensors' dtype. +fn quantization(gpa: std.mem.Allocator, o: std.json.ObjectMap, json: []const u8, why: *Why) !void { const v = o.get("quantization_config") orelse return; - const q = if (v == .object) v.object else { + if (v != .object) { why.set("quantization_config is not an object", .{}); return error.Quant; - }; - const ok = std.ascii.eqlIgnoreCase(text(q, "quant_method") orelse "", "modelopt") and - std.ascii.eqlIgnoreCase(text(q, "quant_algo") orelse "", "NVFP4"); - if (!ok) { - why.set("quantization_config: the loader reads ModelOpt NVFP4 experts (MXFP8 layers follow from their tensors)", .{}); - return error.Quant; } + var core_why: modelopt.Why = .{}; + modelopt.admitByTensors(gpa, json, &core_why) catch |e| switch (e) { + error.NotModelOpt, error.UnsupportedQuant => { + why.set("quantization_config: the loader reads ModelOpt NVFP4 experts (MXFP8 layers follow from their tensors): {s}", .{core_why.text()}); + return error.Quant; + }, + else => return e, + }; } /// config.json as the reference (configuration_inkling2.py) and the checkpoint read it; a refusal is in `why`. @@ -402,26 +442,18 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { } const o = parsed.value.object; const arch = o.get("architectures"); - const arch_ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; - const arch_name: []const u8 = if (arch_ok) arch.?.array.items[0].string else ""; - const model_name = text(o, "model_type") orelse ""; - const small = std.mem.eql(u8, arch_name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2"); - const looped = std.mem.eql(u8, arch_name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2_loop"); + const one = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; + const name = if (one) arch.?.array.items[0].string else ""; + const kind = text(o, "model_type") orelse ""; + const small = std.mem.eql(u8, name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2"); + const looped = std.mem.eql(u8, name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2_loop"); if (!small and !looped) { - why.set("not an Inkling 2 checkpoint: Small or Mini model_type and architectures must match", .{}); + why.set("not an Inkling 2 checkpoint: model_type and architectures must match Inkling2ForConditionalGeneration (inkling2) or Inkling2LoopForConditionalGeneration (inkling2_loop)", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); - try quantization(o, why); - const t = try parseText(try object(o, "text_config", why), why); - if (looped and t.loop == null) { - why.set("inkling2_loop requires text_config.loop_config", .{}); - return error.BadConfig; - } - if (small and t.loop != null) { - why.set("loop_config requires the inkling2_loop model and architecture", .{}); - return error.Unsupported; - } + try quantization(gpa, o, json, why); + const t = try parseText(try object(o, "text_config", why), looped, why); const eos = try int(o, "eos_token_id", why); if (eos >= t.vocab) { why.set("eos_token_id is not a token of the {d}-token vocabulary", .{t.vocab}); diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index a8ad85ab3c7..c7159fca2ae 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -52,17 +52,17 @@ test "Inkling 2 Mini's config.json parses: 24 weight layers, 48 visits and four const c = try config.parse(t.allocator, mini, &why); try t.expectEqual(@as(u32, 2304), c.text.hidden); try t.expectEqual(@as(u32, 24), c.text.layers); - try t.expectEqual(@as(u32, 48), c.text.visitCount()); + try t.expectEqual(@as(u32, 48), c.text.visits()); try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); try t.expectEqual(@as(u32, 8192), c.text.log_floor); try t.expectEqual(@as(u32, 128), c.text.experts); try t.expectEqual(@as(u32, 1152), c.text.expert_inter); try t.expectEqual(@as(f32, 8), c.text.route_scale); const loop = c.text.loop.?; - try t.expectEqual(@as(u32, 6), loop.core_start); - try t.expectEqual(@as(u32, 18), loop.core_end); + try t.expectEqual(@as(u32, 6), loop.start); + try t.expectEqual(@as(u32, 18), loop.end); try t.expectEqual(@as(u32, 3), loop.passes); - try t.expectEqual(@as(u32, 64), loop.gate_rank); + try t.expectEqual(@as(u32, 64), loop.rank); try t.expectEqual(@as(u32, 2304), c.vision.text_hidden); const m = c.mtp.?; try t.expectEqual(@as(u32, 3), m.layers); @@ -146,6 +146,16 @@ test "an mlp_ratio past 1024 is refused instead of overflowing, as is a block lo try refused(tiny, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 4294967295", error.Layout, "is past num_hidden_layers"); } +test "attention-residual blocks past the mixes' eight and widths the attention kernels do not run are refused" { + var why: config.Why = .{}; + try t.expectEqual(@as(u32, config.max_blocks), (try config.parse(t.allocator, real, &why)).text.layers / 6); + try refused(real, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 5", error.Layout, "into more than the residual mixes' 8 blocks"); + try refused(tiny, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 1", error.Layout, "splits 12 layers into more than"); + try refused(tiny, "\"head_dim\": 128,\n \"d_rel\"", "\"head_dim\": 64,\n \"d_rel\"", error.Unsupported, "head_dim 64 is not 128"); + try refused(tiny, "\"swa_head_dim\": 128", "\"swa_head_dim\": 256", error.Unsupported, "swa_head_dim 256 is not 128"); + try refused(tiny, "\"d_rel\": 16", "\"d_rel\": 32", error.Unsupported, "d_rel 32 is not 16"); +} + test "a scoring function, a layer count, a quantization_config and a root that the engine cannot read are refused" { try refused(tiny, "\"use_gate_bias\": true,\n \"tie_word_embeddings\"", "\"use_gate_bias\": true,\n \"scoring_func\": \"softmax\",\n \"tie_word_embeddings\"", error.Unsupported, "scoring_func must be"); try refused(tiny, "\"hidden_size\": 128,\n \"num_hidden_layers\": 12", "\"hidden_size\": 128,\n \"num_hidden_layers\": 129", error.Layout, "129 layers: the plan tables hold 128"); diff --git a/zig/src/families/inkling2/core_parts.zig b/zig/src/families/inkling2/core_parts.zig new file mode 100644 index 00000000000..589419cb361 --- /dev/null +++ b/zig/src/families/inkling2/core_parts.zig @@ -0,0 +1,15 @@ +//! The core parts the family's host files import by name (safetensors, visit_plan, modelopt), as the CUDA family +//! module reaches them through core; the host-only tests import the core files themselves (build/inkling2_host.zig). +const core = @import("core"); + +pub const DType = core.safetensors.DType; +pub const Header = core.safetensors.Header; +pub const Entry = core.safetensors.Entry; + +pub const Plan = core.visit_plan.Plan; +pub const Loop = core.visit_plan.Loop; +pub const Tap = core.visit_plan.Tap; +pub const straight = core.visit_plan.straight; + +pub const Why = core.modelopt.Why; +pub const admitByTensors = core.modelopt.admitByTensors; diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig deleted file mode 100644 index 6bb3b8d7fe0..00000000000 --- a/zig/src/families/inkling2/cuda_native.zig +++ /dev/null @@ -1,220 +0,0 @@ -//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const loop = @import("loop.zig"); -const engine = @import("loop_engine.zig"); -const backend = @import("loop_backend.zig"); - -pub const model_type = "inkling2_loop"; -pub const formats: []const []const u8 = &.{"modelopt-mixed"}; -pub const default_context: i64 = 1_048_576; -pub const max_segments: u32 = 1; -pub const prompt_rows: u32 = engine.prompt_rows; -pub const window_rows: u32 = engine.window_rows; -pub const explains_open = true; - -pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; -pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -pub const Options = struct { - context: usize, - drafts: bool, - segments: usize = 1, - slide: bool = false, - vision: ?VisionOptions = null, - precision: ?enum { full } = null, - room: ?Room = null, - drafter: ?[]const u8 = null, - tp: usize = 1, - rank: usize = 0, - master: ?[]const u8 = null, - master_port: u16 = 29551, -}; - -pub const Owned = struct { - gpa: std.mem.Allocator, - admission: loop.Admission, - kernels: engine.Kernels, - stream: cuda.Stream, - weights: @import("loop_weights.zig").Weights, - model: engine.Model, - backend: backend.Backend, -}; - -pub const Loaded = struct { - backend: lanes.backend.Backend, - facts: lanes.Model, - rows: u32, - stream_bytes: usize, - free_streams: u32 = 1, - ctx: *anyopaque, - deinit: *const fn (*anyopaque) void, - reserve: *const fn (*anyopaque, u32) anyerror!void = reserve, - target: *Owned, -}; - -fn own(ptr: *anyopaque) *Owned { - return @ptrCast(@alignCast(ptr)); -} - -fn release(p: *anyopaque) void { - const o = own(p); - o.stream.synchronize() catch {}; - o.backend.deinit(); - o.stream.deinit(); - o.model.deinit(); - o.kernels.deinit(); - o.weights.deinit(); - const gpa = o.gpa; - gpa.destroy(o); -} - -/// The server's stream count: a cache slot each, past the one allocated at load. -fn reserve(p: *anyopaque, streams: u32) anyerror!void { - return own(p).backend.reserve(streams); -} - -pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { - const o: *const Owned = @ptrCast(@alignCast(p)); - return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); -} - -pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { - if (kernels != null) return error.Inkling2CapturedKernels; - if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; - if (o.vision != null) return error.Inkling2LoopTextOnly; - if (o.drafter != null) return error.Inkling2DSparkPending; - const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); - defer gpa.free(path); - const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); - defer gpa.free(bytes); - var why: config.Why = .{}; - const c = config.parse(gpa, bytes, &why) catch |err| { - std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); - return err; - }; - try loop.validateLoad(&c, 1, false); - if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; - var ck = try core.Checkpoint.openModel(gpa, io, dir); - defer ck.close(); - try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. - var precisions: [config.max_layers]plan_.Precision = undefined; - @memset(&precisions, .nvfp4); - var header_arena = std.heap.ArenaAllocator.init(gpa); - defer header_arena.deinit(); - var merged: core.safetensors.Header = .empty; - for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); - try @import("names.zig").precisions(merged, c.text.layers, &precisions); - const p = try plan_.build(&c.text, precisions[0..c.text.layers]); - var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); - errdefer w.deinit(); - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - ck.release(); - var k = try engine.Kernels.load(ctx); - errdefer k.deinit(); - var stream = try cuda.Stream.init(ctx.d, true); - errdefer stream.deinit(); - var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); - errdefer m.deinit(); - var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); - errdefer be.deinit(); - const out = try gpa.create(Owned); - errdefer gpa.destroy(out); - out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; - // The value copies above own pointers to their old stack homes; retarget the live model/backend now. - out.model.w = &out.weights; - out.backend.m = &out.model; - out.backend.k = &out.kernels; - return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = backend.streamBytes(&out.model), .ctx = out, .deinit = release, .target = out }; -} - -pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { - return own(ptr).model.snapshotBytes(at); -} - -pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { - return @ptrCast(try own(ptr).backend.saveState(owner, at)); -} - -pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { - return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); -} - -pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { - own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); -} - -pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { - return switch (err) { - error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", - error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", - error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", - error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", - error.Inkling2TooManyStreams => "Inkling 2 Mini on CUDA holds at most 16 streams: lower --parallel", - error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", - else => null, - }; -} - -test "Mini native registration and refusal wording are explicit" { - try std.testing.expectEqualStrings("inkling2_loop", model_type); - try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); - try std.testing.expectEqual(16, engine.max_slots); // the stream cap explain() names - for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { - try std.testing.expect(explain(null, err) != null); - } -} - -test "the complete prompt snapshot hooks match the store vtable" { - const pc: struct { - bytes: *const fn (*anyopaque, u32) u64, - save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, - restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, - drop: *const fn (*anyopaque, *anyopaque) void, - } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; - try std.testing.expect(@intFromPtr(pc.save) != 0); -} - -test "stream_bytes is what an extra stream's slot and lane buffers allocate, 806,408 bytes past the cache on Mini" { - const Record = struct { // a DeviceBuffer hook that hands out addresses and sums what is asked - bytes: usize = 0, - next: u64 = 1 << 32, - fn alloc(ctx: *anyopaque, len: usize) ?u64 { - const r: *@This() = @ptrCast(@alignCast(ctx)); - r.bytes += len; - r.next += std.mem.alignForward(u64, len, 512); - return r.next; - } - fn free(_: *anyopaque, _: u64) bool { - return true; - } - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - var w: @import("loop_weights.zig").Weights = undefined; - w.c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var precisions: [24]plan_.Precision = @splat(.nvfp4); - w.p = try plan_.build(&w.c.text, &precisions); - var m: engine.Model = undefined; - m.d = @ptrFromInt(0x1000); // never called: the hook answers every allocation - m.w = &w; - m.layout = try loop.CacheLayout.init(&w.c.text, &w.p, 8192); - var b: backend.Backend = undefined; - b.d = m.d; - b.m = &m; - b.held = 1; - var rec: Record = .{}; - const before = cuda.memory.currentHook(); - cuda.memory.setHook(.{ .ctx = &rec, .alloc = Record.alloc, .free = Record.free }); - defer cuda.memory.setHook(before); - var slot = try m.newSlot(); - defer for ([2]*cuda.DeviceBuffer{ &slot.cache, &slot.sites }) |x| x.free(); - try b.slotBuffers(2); // the second stream's lane buffers; the first already holds its own - defer for (&b.slot[1]) |*x| x.free(); - try std.testing.expectEqual(@as(u64, rec.bytes), backend.streamBytes(&m)); - try std.testing.expectEqual(@as(u64, 48 * 4 * 32 + 200_058 * 4 + 32), backend.streamBytes(&m) - m.layout.bytes); -} diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 5caed096fef..05c88f6e672 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -4,10 +4,9 @@ test { _ = @import("config_test.zig"); _ = @import("names.zig"); _ = @import("names_test.zig"); + _ = @import("mini_host_test.zig"); _ = @import("plan.zig"); _ = @import("loop.zig"); - _ = @import("loop_model.zig"); - _ = @import("loop_model_test.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index f311dc17d35..0eecf58de99 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,4 +1,5 @@ -//! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. +//! Inkling 2 on CUDA: Small's kernels (attention, glue) and Mini (inkling2_loop) at one rank: config, plan, weights, +//! the loop's gates and messages, the forward over 48 visit slots a stream. pub const image = @import("image.zig"); pub const vision = @import("vision.zig"); @@ -6,10 +7,18 @@ pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); pub const experts = @import("experts.zig"); pub const modelopt = @import("modelopt.zig"); +pub const config = @import("config.zig"); +pub const plan = @import("plan.zig"); +pub const names = @import("names.zig"); pub const loop = @import("loop.zig"); -pub const loop_model = @import("loop_model.zig"); -pub const loop_math_cuda = @import("loop_math_cuda.zig"); -pub const native = @import("cuda_native.zig"); +pub const mini_weights = @import("mini_weights.zig"); +pub const mini_model = @import("mini_model.zig"); +pub const mini_backend = @import("mini_backend.zig"); +pub const mini_snap = @import("mini_snap.zig"); +/// The float64 reference the CUDA forward's greedy tokens are checked against. +pub const mini_ref = @import("mini_ref.zig"); +/// The native CUDA registry's entry for inkling2_loop (native/cuda_families.zig). +pub const native = @import("mini_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -23,6 +32,12 @@ test { _ = modelopt; _ = native; _ = loop; - _ = loop_model; - _ = loop_math_cuda; + _ = config; + _ = plan; + _ = mini_model; + _ = @import("mini_visit.zig"); + _ = mini_weights; + _ = mini_backend; + _ = mini_snap; + _ = mini_ref; } diff --git a/zig/src/families/inkling2/kernels.zig b/zig/src/families/inkling2/kernels.zig index 42545e7715c..5cb8f24f5af 100644 --- a/zig/src/families/inkling2/kernels.zig +++ b/zig/src/families/inkling2/kernels.zig @@ -1,9 +1,10 @@ //! Inkling 2's attention kernels (inkling2/attention.cu): the launch plan's geometry and the four launches. const std = @import("std"); const cuda = @import("cuda"); +const config = @import("config.zig"); -pub const head_dim = 128; -pub const d_rel = 16; +pub const head_dim = config.head_dim; +pub const d_rel = config.d_rel; pub const extent = 1024; /// Keys a tile of tf_ink2_attn reads at once, and (row, head) pairs a block holds. pub const tile_keys = 64; @@ -153,8 +154,14 @@ fn goShared(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, sha try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = shared }, s, a); } +/// Whether heads split into whole groups (query head h reads key head h / (heads / kv_heads)): Small 24/4, Mini 24/8. +pub fn headsFit(r: Rows) error{Inkling2Heads}!void { + if (r.heads == 0 or r.kv_heads == 0 or r.heads % r.kv_heads != 0) return error.Inkling2Heads; +} + /// q, rel (per head) and k, v (per key head, written to the caches at pos % ring) from the projections' rows. pub fn prep(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, c: Prep, raw: [4]u64, scales: [2]u64, q: u64, rel: u64, kv: Cache) !void { + try headsFit(r); var a: cuda.Args = .{}; for (raw) |v| a.add(v); for (scales) |v| a.add(v); @@ -176,6 +183,7 @@ pub fn relTable(k: *const Kernels, s: cuda.Stream, r: Rows, rel: u64, proj: u64, /// Attention into chunk partials (`stride` a row and head; a split call's sub-chunks), then the ordered merge. pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, slots: usize, q: u64, kv: Cache, tab: u64, part_o: u64, part_ml: u64, sink: u64, gate: u64, out: u64) !void { + try headsFit(r); if (slotsFor(l, r.last_pos + 1) > stride) return error.Inkling2Partials; const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); var a: cuda.Args = .{}; diff --git a/zig/src/families/inkling2/kernels_test.zig b/zig/src/families/inkling2/kernels_test.zig index 210ac545eaa..71a96c95385 100644 --- a/zig/src/families/inkling2/kernels_test.zig +++ b/zig/src/families/inkling2/kernels_test.zig @@ -108,8 +108,7 @@ test "inkling2 kernels: sliding partials are a row's window at any depth, a tile } /// A call's sliding stores as tf_ink2_attn makes them: each slot the merge reads once; returns the old strays. -fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize) !usize { - const group = 6; +fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize, group: u32) !usize { const l = k.Layer.sliding(1024, 2048); const stride: usize = k.slotsFor(l, 1); // 5 below 81,920: a stray store lands on a neighbour (row, head)'s slots const count = try a.alloc(u8, n * group * stride); @@ -147,12 +146,46 @@ fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize) !usize { test "inkling2 kernels: sliding stores stay in their own slots for windows that straddle a chunk edge" { const a = t.allocator; // the drafted check's long text: 8-row windows at 2,296..2,302 (a window's first keys cross chunk 5's edge) - try t.expectEqual(@as(usize, 0), try slidingStores(a, 2295, 8)); - try t.expect(try slidingStores(a, 2300, 8) > 0); - try t.expect(try slidingStores(a, 2296, 8) > 0); - var p0: usize = 0; - while (p0 < 4400) : (p0 += 1) for (1..9) |n| { - _ = try slidingStores(a, p0, n); + try t.expectEqual(@as(usize, 0), try slidingStores(a, 2295, 8, 6)); + try t.expect(try slidingStores(a, 2300, 8, 6) > 0); + try t.expect(try slidingStores(a, 2296, 8, 6) > 0); + // Small's 6 query heads a key head at TP=2, Mini's 3 (24 over 8 key heads) + for ([_]u32{ 6, 3 }) |group| { + var p0: usize = 0; + while (p0 < 4400) : (p0 += 1) for (1..9) |n| { + _ = try slidingStores(a, p0, n, group); + }; + for ([_]usize{ 0, 2048, 4096 }) |at| _ = try slidingStores(a, at, 2048, group); + } +} + +test "inkling2 kernels: Mini's 8 key heads launch a group of 3; heads that do not split are refused, nothing launched" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const fun = struct { + fn of(drv: *const cuda.Driver, i: usize) cuda.Function { + return .{ .d = drv, .handle = @ptrFromInt(i) }; + } }; - for ([_]usize{ 0, 2048, 4096 }) |at| _ = try slidingStores(a, at, 2048); + const kern: k.Kernels = .{ .mod = .{ .d = &d, .handle = null }, .prep = fun.of(&d, 1), .rel_table = fun.of(&d, 2), .attn = fun.of(&d, 3), .merge = fun.of(&d, 4), .attn_fold = fun.of(&d, 3), .pmod = .{ .d = &d, .handle = null }, .attn_prompt = fun.of(&d, 3) }; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + const cfg: k.Prep = .{ .qk_clip = 22.6, .rel_clip = 8, .floor = 8192, .alpha = 0.1, .eps = 1e-6 }; + const l = k.Layer.global(1048576); + var r: k.Rows = .{ .rows = 2048, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 1048575 }; + Fake.count = 0; + try k.prep(&kern, s, r, l, cfg, .{ 0, 0, 0, 0 }, .{ 0, 0 }, 0, 0, .{ .k = 0, .v = 0 }); + try t.expectEqual([3]u32{ 2048, 40, 1 }, Fake.grids[0]); // 24 q heads, 8 k and 8 v heads a row + // a 2,048-row prompt call: 2,048 x 3 pairs a key head in blocks of 128 + try k.attend(&kern, s, r, l, 64, 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual([3]u32{ 48, 8, 64 }, Fake.grids[2]); + try t.expectEqual(@as(u32, 6), k.tileChunks(3, k.Layer.sliding(1024, 1))); // a tile's 21 rows and their windows + try t.expectEqual(@as(usize, 96), k.tileCount(2048, 3)); + const counted = Fake.count; + for ([_][2]u32{ .{ 24, 5 }, .{ 24, 0 }, .{ 0, 8 } }) |h| { + r.heads = h[0]; + r.kv_heads = h[1]; + try t.expectError(error.Inkling2Heads, k.prep(&kern, s, r, l, cfg, .{ 0, 0, 0, 0 }, .{ 0, 0 }, 0, 0, .{ .k = 0, .v = 0 })); + try t.expectError(error.Inkling2Heads, k.attend(&kern, s, r, l, 64, 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + } + try t.expectEqual(counted, Fake.count); } diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig index a7a12d62c4d..a7c7ebed03b 100644 --- a/zig/src/families/inkling2/loop.zig +++ b/zig/src/families/inkling2/loop.zig @@ -1,168 +1,131 @@ -//! Inkling 2 Mini's loop host layout: 48 private visit caches, whole-state snapshots and one-rank admission. +//! Inkling 2 Mini's loop launches (inkling2/loop.cu): cross-pass message mixes and the core inputs' rank-r gates. +//! C2 stand-in: the arithmetic #4337's Metal implementation runs; the kernel contract for these is C2's slice. const std = @import("std"); +const cuda = @import("cuda"); const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -pub fn validateLoad(c: *const config.Config, rank: usize, images: bool) !void { - if (rank != 1) return error.Inkling2LoopOneRankOnly; - if (images) return error.Inkling2LoopTextOnly; - const lp = c.text.loop orelse return error.Inkling2LoopRequired; - if (lp.gate_rank != 64) return error.UnsupportedLoopGateRank; -} - -pub const SnapshotSlot = struct { - kv_offset: u64, - kv_bytes: u64, - conv_offset: u64, - conv_bytes: u64, +pub const max_blocks = config.max_blocks; +pub const max_queries = 4; +pub const max_gates = 3; +pub const max_rank = 128; +const threads = 256; +const lin_threads = 128; // loop.cu kLin + +/// loop.cu's LoopMixArgs, field for field. +pub const MixArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), + partial: u64, + query: [max_queries]u64 = @splat(0), + out: u64, + out_stride: i64, + n_blocks: i32, + partial_f32: i32, + nq: i32, + rows: i32, + h: i32, + eps: f32, + scale: f32, }; -/// A stream or a saved prompt owns the same complete layout: no visit shares KV or convolution state with another. -pub const CacheLayout = struct { - slots: [config.max_visits]SnapshotSlot, - n: u32, - bytes: u64, - - pub fn init(c: *const config.Text, p: *const plan_.Plan, context: u32) !CacheLayout { - if (context == 0 or context > c.max_context or p.n_visits != c.visitCount()) return error.BadLoopCache; - var out: CacheLayout = undefined; - out.n = p.n_visits; - out.bytes = 0; - const conv_values = 3 * (2 * @as(u64, c.local.kv * c.local.dim) + 2 * @as(u64, c.hidden)); - for (p.visits[0..p.n_visits], 0..) |visit, i| { - const layer = p.layers[visit.layer]; - const rows: u32 = @intCast(@min(2048, context)); - const tokens = if (layer.kind == .global) - std.mem.alignForward(u32, context, 64) - else - std.mem.alignForward(u32, c.window + rows - 1, 64); - const kv = try std.math.mul(u64, tokens, 2 * @as(u64, layer.heads.kv * layer.heads.dim * 2)); - // The recurrence rounds each site then widens its complete state to FP32 before the FMAs. - const conv = try std.math.mul(u64, conv_values, 4); - out.slots[i] = .{ .kv_offset = out.bytes, .kv_bytes = kv, .conv_offset = 0, .conv_bytes = conv }; - out.bytes = try std.math.add(u64, out.bytes, kv); - } - var conv_offset = out.bytes; - for (out.slots[0..out.n]) |*slot| { - slot.conv_offset = conv_offset; - conv_offset = try std.math.add(u64, conv_offset, slot.conv_bytes); - } - out.bytes = conv_offset; - return out; - } - - pub fn at(l: *const CacheLayout, visit: u32) SnapshotSlot { - return l.slots[visit]; - } +/// loop.cu's LoopGateArgs, field for field. +pub const GateArgs = extern struct { + h: [max_gates]u64 = @splat(0), + msg: u64, + msg_stride: i64, + slot: [max_gates]i32 = @splat(0), + down_w: [max_gates]u64 = @splat(0), + forget: [max_gates]u64 = @splat(0), + gain: [max_gates]u64 = @splat(0), + norm: [max_gates]u64 = @splat(0), + down: u64, + out: u64, + out_stride: i64, + rows: i32, + h_dim: i32, + rank: i32, + eps_unit: f32, + eps: f32, + ys: u64 = 0, // fp32 [gates][rows, H] scratch: the gated rows before their norm }; -/// The serial lane adapter's admission rule. One request occupies one complete 48-visit stream. -pub const Admission = struct { - context: u32, +pub const Kernels = struct { + mod: cuda.Module, + mix: cuda.Function, + gate_down: cuda.Function, + gate_lin: cuda.Function, + gate_mix: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop); + errdefer mod.unload(); + return .{ + .mod = mod, + .mix = try mod.function("tf_ink2_loop_mix"), + .gate_down = try mod.function("tf_ink2_loop_gate_down"), + .gate_lin = try mod.function("tf_ink2_loop_gate_lin"), + .gate_mix = try mod.function("tf_ink2_loop_gate_mix"), + }; + } - pub fn fits(a: Admission, prompt: u32, max_tokens: u32) bool { - return prompt <= a.context and max_tokens <= a.context - prompt; + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; } }; -/// A prompt-cache save or restore copies every byte of this layout, including all four convolution recurrences. -pub fn snapshotBytes(l: *const CacheLayout) u64 { - return l.bytes; +/// The shapes the kernels hold: blocks, queries, gates and rank in their arrays; a refusal names the bound. +pub fn mixFits(a: MixArgs) error{Inkling2LoopShape}!void { + if (a.rows <= 0 or a.h <= 0 or a.nq <= 0 or a.nq > max_queries or a.n_blocks < 0 or a.n_blocks > max_blocks) + return error.Inkling2LoopShape; } -pub const Snapshot = struct { - bytes: []u8, - - pub fn save(gpa: std.mem.Allocator, state: []const u8, l: *const CacheLayout) !Snapshot { - if (state.len != l.bytes) return error.BadLoopSnapshot; - return .{ .bytes = try gpa.dupe(u8, state) }; - } - - pub fn restore(s: *const Snapshot, state: []u8, l: *const CacheLayout) !void { - if (s.bytes.len != l.bytes or state.len != l.bytes) return error.BadLoopSnapshot; - @memcpy(state, s.bytes); - } - - pub fn deinit(s: *Snapshot, gpa: std.mem.Allocator) void { - gpa.free(s.bytes); - s.* = undefined; - } -}; - -test "a saved prompt restores every visit byte and owns its copy" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const layout = try CacheLayout.init(&c.text, &p, 1); - const state = try std.testing.allocator.alloc(u8, @intCast(layout.bytes)); - defer std.testing.allocator.free(state); - for (state, 0..) |*v, i| v.* = @truncate(i * 29 + 7); - var saved = try Snapshot.save(std.testing.allocator, state, &layout); - defer saved.deinit(std.testing.allocator); - @memset(state, 0xa5); - try saved.restore(state, &layout); - try std.testing.expectEqualSlices(u8, saved.bytes, state); - try std.testing.expectError(error.BadLoopSnapshot, Snapshot.save(std.testing.allocator, state[0 .. state.len - 1], &layout)); +pub fn gateFits(a: GateArgs, count: usize) error{Inkling2LoopShape}!void { + if (a.rows <= 0 or a.h_dim <= 0 or a.rank <= 0 or a.rank > max_rank or count == 0 or count > max_gates or a.ys == 0) + return error.Inkling2LoopShape; } -test "Mini has 48 independent KV and convolution slots and a whole-state snapshot" { - const config_test = @import("config_test.zig"); - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var why: config.Why = .{}; - const c = try config.parse(a, config_test.mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const layout = try CacheLayout.init(&c.text, &p, 1_048_576); - try std.testing.expectEqual(@as(u32, 48), layout.n); - try std.testing.expectEqual(@as(u64, 3072 * 2 * 8 * 128 * 2), layout.at(0).kv_bytes); - try std.testing.expectEqual(@as(u64, 1_048_576 * 2 * 8 * 128 * 2), layout.at(5).kv_bytes); - try std.testing.expectEqual(@as(u64, 34_866_888_704), layout.bytes); - try std.testing.expectEqual(layout.bytes, snapshotBytes(&layout)); - try std.testing.expect((Admission{ .context = 8192 }).fits(8000, 192)); - try std.testing.expectEqual(@as(u64, 79_872), layout.at(0).conv_bytes); +/// fp32 mixes of `nq` queries over a row's blocks and partial (no norm): a block a row. +pub fn mix(k: *const Kernels, s: cuda.Stream, a: MixArgs) !void { + try mixFits(a); + var args: cuda.Args = .{}; + args.add(a); + try cuda.launch.launch(k.mix, .{ .grid = .{ .x = @intCast(a.rows) }, .block = .{ .x = threads } }, s, &args); } -test "Mini loop load is one-rank text-only with rank-64 gated controllers" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - try validateLoad(&c, 1, false); - try std.testing.expectError(error.Inkling2LoopOneRankOnly, validateLoad(&c, 2, false)); - try std.testing.expectError(error.Inkling2LoopTextOnly, validateLoad(&c, 1, true)); +/// The gates' rank-r down rows, then the gated, normed inputs: a block a (row, gate) each. +pub fn gates(k: *const Kernels, s: cuda.Stream, a: GateArgs, n: usize) !void { + try gateFits(a, n); + var args: cuda.Args = .{}; + args.add(a); + const grid: cuda.Dim3 = .{ .x = @intCast(a.rows), .y = @intCast(n) }; + const h: u32 = @intCast(a.h_dim); + // spread over the GPU: rank rows 8 a block, outputs 128 a block; the norm a block a row and gate + const down: cuda.Dim3 = .{ .x = grid.x, .y = grid.y, .z = @intCast(std.math.divCeil(i32, a.rank, threads / 32) catch unreachable) }; + try cuda.launch.launch(k.gate_down, .{ .grid = down, .block = .{ .x = threads }, .shared = 2 * h * 4 }, s, &args); + const lin: cuda.Dim3 = .{ .x = grid.x, .y = grid.y, .z = std.math.divCeil(u32, h, lin_threads) catch unreachable }; + try cuda.launch.launch(k.gate_lin, .{ .grid = lin, .block = .{ .x = lin_threads } }, s, &args); + try cuda.launch.launch(k.gate_mix, .{ .grid = grid, .block = .{ .x = threads } }, s, &args); } -test "pass two resets and only completed passes with a successor capture message banks" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const lp = c.text.loop.?; - var banks: u32 = 0; - for (p.visits[0..p.n_visits]) |visit| { - if (visit.pass == 2 and visit.layer == lp.core_start) try std.testing.expect(visit.hasMessages()); - if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) banks += 1; - } - try std.testing.expectEqual(lp.passes - 1, banks); +test "loop: the argument structs keep loop.cu's layouts" { + try std.testing.expectEqual(@as(usize, 8 * 8 + 8 + 4 * 8 + 8 + 8 + 5 * 4 + 2 * 4 + 4), @sizeOf(MixArgs)); + try std.testing.expectEqual(@as(usize, 3 * 8 + 8 + 8 + 3 * 4 + 4 + 4 * 3 * 8 + 3 * 8 + 3 * 4 + 2 * 4 + 4 + 8), @sizeOf(GateArgs)); } -test "pass snapshots and rollback layout cover every visit" { - const config_test = @import("config_test.zig"); - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), config_test.mini, &why); - var precisions: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &precisions); - const layout = try CacheLayout.init(&c.text, &p, 4096); - try std.testing.expectEqual(@as(u32, 48), layout.n); - try std.testing.expect(layout.at(17).kv_offset != layout.at(29).kv_offset); - try std.testing.expectEqual(@as(u64, layout.at(46).conv_offset + layout.at(46).conv_bytes), layout.at(47).conv_offset); +test "loop: shapes past the kernels' arrays are refused by name" { + const ok: MixArgs = .{ .partial = 1, .out = 1, .out_stride = 0, .n_blocks = 1, .partial_f32 = 0, .nq = 4, .rows = 1, .h = 2304, .eps = 1e-6, .scale = 1 }; + try mixFits(ok); + var bad = ok; + bad.nq = 5; + try std.testing.expectError(error.Inkling2LoopShape, mixFits(bad)); + bad = ok; + bad.n_blocks = 9; + try std.testing.expectError(error.Inkling2LoopShape, mixFits(bad)); + const g: GateArgs = .{ .ys = 1, .msg = 1, .msg_stride = 0, .down = 1, .out = 1, .out_stride = 0, .rows = 1, .h_dim = 2304, .rank = 64, .eps_unit = 1e-6, .eps = 1e-6 }; + try gateFits(g, 3); + try std.testing.expectError(error.Inkling2LoopShape, gateFits(g, 4)); + var wide = g; + wide.rank = 129; + try std.testing.expectError(error.Inkling2LoopShape, gateFits(wide, 1)); } diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig deleted file mode 100644 index 4834266e850..00000000000 --- a/zig/src/families/inkling2/loop_backend.zig +++ /dev/null @@ -1,346 +0,0 @@ -//! Inkling 2 Mini lane execution and snapshot adapter. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const engine = @import("loop_engine.zig"); -const ops = @import("ops.zig"); - -const Model = engine.Model; -const Kernels = engine.Kernels; -const prompt_rows = engine.prompt_rows; -const window_rows = engine.window_rows; -const token_ring = 1024; - -const Lane = struct { - len: usize = 0, - fill: ?usize = null, - base: usize = 0, - rows: std.ArrayList(u32) = .empty, - last: u64, - rule: u64, - sampled: bool = false, -}; - -/// The bytes a slot's lane buffers ask for: a vocabulary row of last logits and a sampling rule. -pub fn laneAllocs(vocab: u32) [2]usize { - return .{ @as(usize, vocab) * 4, @sizeOf(cuda.sample.Rule) }; -} - -/// The device bytes each served stream holds: its model slot (engine.slotAllocs) and its lane buffers. -pub fn streamBytes(m: *const Model) u64 { - const slot = engine.slotAllocs(&m.layout, m.w.p.n_visits); - const lane = laneAllocs(m.w.c.text.unpadded_vocab); - return slot[0] + slot[1] + lane[0] + lane[1]; -} - -pub const Backend = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - m: *Model, - k: *const Kernels, - s: cuda.Stream, - lanes_: [engine.max_slots]?Lane = @splat(null), - streams: [engine.max_slots]?*lanes.Stream = @splat(null), // the stream each model slot holds - tokens: cuda.DeviceBuffer, - logits16: cuda.DeviceBuffer, - meta: cuda.DeviceBuffer, - slot: [engine.max_slots][2]cuda.DeviceBuffer = undefined, // each slot's last prompt logits and sampling rule - next: u64 = 0, - held: usize = 0, // slots with buffers - - const be = lanes.backend; - - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { - const v = m.w.c.text.unpadded_vocab; - var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); - errdefer tokens.free(); - var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); - errdefer logits16.free(); - var meta = try cuda.DeviceBuffer.alloc(d, 16); - errdefer meta.free(); - var b: Backend = .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta }; - try b.slotBuffers(m.n_slots); - return b; - } - - /// Each model slot's own last-logits and rule buffers, up to `n`. - pub fn slotBuffers(b: *Backend, n: usize) !void { - const sizes = laneAllocs(b.m.w.c.text.unpadded_vocab); - for (0..n) |i| { - if (i < b.held) continue; - var last = try cuda.DeviceBuffer.alloc(b.d, sizes[0]); - errdefer last.free(); - b.slot[i] = .{ last, try cuda.DeviceBuffer.alloc(b.d, sizes[1]) }; - b.held = i + 1; - } - } - - /// The server's stream count: one model slot and its buffers per stream. - pub fn reserve(b: *Backend, streams: u32) !void { - if (streams > engine.max_slots) return error.Inkling2TooManyStreams; - try b.m.addSlots(b.s, streams); - try b.slotBuffers(streams); - } - - pub fn deinit(b: *Backend) void { - for (&b.lanes_) |*x| if (x.*) |*l| l.rows.deinit(b.gpa); - for (b.slot[0..b.held]) |*pair| for (pair) |*x| x.free(); - b.meta.free(); - b.logits16.free(); - b.tokens.free(); - b.* = undefined; - } - - pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &vtable }; - } - - pub fn facts(_: *const Backend) lanes.Model { - return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; - } - - pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { - return b.freeSlot() != null and prompt <= b.m.context and max_new <= b.m.context - prompt; - } - - fn freeSlot(b: *const Backend) ?usize { - for (b.streams[0..@min(b.m.n_slots, b.held)], 0..) |x, i| if (x == null) return i; - return null; - } - - fn slotOf(b: *const Backend, s: *const lanes.Stream) ?usize { - for (b.streams, 0..) |x, i| if (x == s) return i; - return null; - } - - /// The device buffer holding `s`'s last prompt logits. - pub fn lastOf(b: *const Backend, s: *const lanes.Stream) !u64 { - const i = b.slotOf(s) orelse return error.UnknownStream; - return b.lanes_[i].?.last; - } - - fn self(ptr: *anyopaque) *Backend { - return @ptrCast(@alignCast(ptr)); - } - - fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); - } - - /// `s`'s lane, its model slot selected for the calls that follow. - fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { - const i = b.slotOf(s) orelse return error.UnknownStream; - if (i >= b.m.n_slots) return error.UnknownStream; - b.m.slot = i; - return if (b.lanes_[i]) |*l| l else error.UnknownStream; - } - - fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { - const saved = s.reuse.saved orelse return 0; - const k: *const Model.Saved = @ptrCast(@alignCast(saved)); - if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { - s.reuse_failed = true; - return 0; - } - b.m.restore(b.s, k) catch { - s.reuse_failed = true; - return 0; - }; - s.cached = k.at; - return k.at; - } - - fn opening(b: *Backend, s: *lanes.Stream) !*Lane { - const prompt = s.prompt(); - if (prompt.len == 0) return error.EmptyPrompt; - if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; - if (b.slotOf(s) == null) { - const i = b.freeSlot() orelse return error.NoFreeSlot; - b.lanes_[i] = .{ .last = b.slot[i][0].ptr, .rule = b.slot[i][1].ptr }; - b.streams[i] = s; - } - const l = try b.laneOf(s); - l.sampled = false; - if (cuda.sample.ruleFor(s.sampling)) |r| { - try b.upload(l.rule, std.mem.asBytes(&r)); - l.sampled = true; - } - l.len = 0; - try b.m.reset(b.s); - const at = b.resumeSaved(s); - l.len = at; - l.fill = at; - s.fill_at.store(@intCast(at), .monotonic); - return l; - } - - fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { - const prompt = s.prompt(); - const at = l.fill.?; - if (s.isCancelled()) return error.Cancelled; - var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); - for (s.reuse.marks) |mark| { - if (mark > at and mark < end) end = mark; - } - const done = end == prompt.len; - try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); - if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); - l.len = end; - l.fill = if (done) null else end; - s.fill_at.store(@intCast(end), .monotonic); - if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) - hook.at(hook.ptr, s, @intCast(end)); - return done; - } - - fn handle(b: *Backend) usize { - const h = b.next; - b.next += 1; - return @intCast(h % token_ring); - } - - fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { - const v = b.m.w.c.text.unpadded_vocab; - if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); - try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); - const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; - try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); - try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); - } - - fn read(ptr: *anyopaque, h: u64) anyerror!u32 { - const b = self(ptr); - if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; - var out: [1]u32 = undefined; - try b.s.synchronize(); - try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); - return out[0]; - } - - const vtable: be.Backend.VTable = .{ - .prefill = prefill, - .prefill_step = prefillStep, - .first = first, - .first_masked = firstMasked, - .queue = queue, - .read = read, - .verify = verify, - .keep = keep, - .draft = draft, - .release = release, - .reports_fill = true, - }; - - fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { - const b = self(ptr); - const l = try b.opening(s); - errdefer release(ptr, s); - while (!try b.chunk(s, l)) {} - } - - fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { - const b = self(ptr); - const going = if (b.slotOf(s)) |i| b.lanes_[i].?.fill != null else false; - const l = if (going) try b.laneOf(s) else try b.opening(s); - errdefer release(ptr, s); - return b.chunk(s, l); - } - - fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - if (position != l.len or l.fill != null) return error.PositionMismatch; - const h = b.next; - try b.drawRows(l, l.last, 1, position, b.handle()); - return h; - } - - fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { - return error.StructuresUnsupported; - } - - fn feed(b: *Backend, value: be.Feed) !u32 { - return switch (value) { - .value => |v| v, - .handle => |h| read(b, h), - }; - } - - fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - const token = try b.feed(value); - if (position != l.len + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); - l.len += 1; - const h = b.next; - try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); - return h; - } - - fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { - const b = self(ptr); - if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; - const w = windows[0]; - if (w.held != 0) return error.NoHeldDrafts; - if (w.parents != null) return error.ChainsOnly; - if (w.masks.len != 0) return error.StructuresUnsupported; - const l = try b.laneOf(w.stream); - const n = w.rows(); - if (n == 0 or n > window_rows) return error.WindowTooWide; - l.base = l.len; - l.rows.clearRetainingCapacity(); - try l.rows.append(b.gpa, w.pending); - try l.rows.appendSlice(b.gpa, w.tokens); - for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); - try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); - var got: [window_rows]u32 = undefined; - try b.s.synchronize(); - try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); - @memcpy(out[0].sampled[0..n], got[0..n]); - @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); - l.len = l.base + n; - } - - fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { - const b = self(ptr); - if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; - const l = try b.laneOf(windows[0].stream); - const path = paths[0]; - if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; - for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; - try b.m.rewind(b.k, b.s, path.len); - l.len = l.base + path.len; - } - - fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { - for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; - } - - pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - if ((l.fill orelse l.len) != at) return error.NotAtMark; - return b.m.save(b.s, at); - } - - pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - try b.m.restore(b.s, saved); - l.len = saved.at; - } - - pub fn dropState(b: *Backend, saved: *Model.Saved) void { - b.m.drop(b.s, saved); - } - - fn release(ptr: *anyopaque, s: *lanes.Stream) void { - const b = self(ptr); - const i = b.slotOf(s) orelse return; - if (b.lanes_[i]) |*l| l.rows.deinit(b.gpa); - b.lanes_[i] = null; - b.streams[i] = null; - } -}; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig deleted file mode 100644 index c04446872e6..00000000000 --- a/zig/src/families/inkling2/loop_engine.zig +++ /dev/null @@ -1,591 +0,0 @@ -//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. -const std = @import("std"); -const cuda = @import("cuda"); -const config = @import("config.zig"); -const loop = @import("loop.zig"); -const weights_ = @import("loop_weights.zig"); -const ops = @import("ops.zig"); -const attention = @import("kernels.zig"); -const modelopt = @import("modelopt.zig"); -const loop_math = @import("loop_math_cuda.zig"); - -pub const prompt_rows: usize = 2048; -pub const window_rows: usize = 16; - -pub const Kernels = struct { - glue: ops.Kernels, - attn: attention.Kernels, - moe: modelopt.Kernels, - loop: loop_math.Kernels, - sample_mod: cuda.Module, - draws: cuda.sample.Draws, - - pub fn load(ctx: *const cuda.Context) !Kernels { - const d = ctx.d; - var glue = try ops.Kernels.load(d); - errdefer glue.unload(); - var attn = try attention.Kernels.load(d); - errdefer attn.unload(); - const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); - var moe = try modelopt.Kernels.load(d, sms); - errdefer moe.unload(); - var lm = try loop_math.Kernels.load(d); - errdefer lm.unload(); - var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); - errdefer sample_mod.unload(); - return .{ - .glue = glue, - .attn = attn, - .moe = moe, - .loop = lm, - .sample_mod = sample_mod, - .draws = try cuda.sample.Draws.resolve(sample_mod), - }; - } - - pub fn deinit(k: *Kernels) void { - k.sample_mod.unload(); - k.loop.unload(); - k.moe.unload(); - k.attn.unload(); - k.glue.unload(); - k.* = undefined; - } -}; - -const Scratch = struct { - ids: u64, - pos: u64, - seg_of: u64, - segs: u64, - tiles: u64, - blocks: [ops.max_blocks]u64 = @splat(0), - partial_a: u64, - partial_b: u64, - prelude: u64, - bank0: u64, - bank1: u64, - raw: u64, // three FP32 AR/gate rows per token - messages: u64, // four FP32 message rows per token - normalized: u64, // three BF16 rows per token - t: u64, - q_raw: u64, - rel_raw: u64, - sink: u64, - gate: u64, - k_raw: u64, - v_raw: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64, - v_dynamic: u64, - q_prepared: u64, - rel_prepared: u64, - rel_table: u64, - part_o: u64, - part_ml: u64, - attn_heads: u64, - attn_out: u64, - route_scores: u64, - route_pick: u64, - route_weights: u64, - moe_out: u64, - moe_scratch: u64, - hidden: u64, - logits: u64, - backup: u64, - hist: u64, -}; - -/// A stream's state (every visit's K/V rows and conv states, its rewind sites); at most `max_slots`, one in use. -const Slot = struct { cache: cuda.DeviceBuffer, sites: cuda.DeviceBuffer }; -pub const max_slots = 16; - -/// The bytes a slot's allocations ask for: the cache layout and four rewind sites a visit. -pub fn slotAllocs(layout: *const loop.CacheLayout, n_visits: u32) [2]usize { - return .{ @intCast(layout.bytes), @as(usize, n_visits) * 4 * @sizeOf(ops.RewindSite) }; -} - -pub const Model = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - w: *const weights_.Weights, - context: usize, - layout: loop.CacheLayout, - slots: [max_slots]Slot = undefined, - n_slots: usize = 0, - slot: usize = 0, // the slot forwards, snapshots and rewinds use; forwards share the scratch - recorded: ?usize = null, // the slot whose window `backup` and `hist` hold - s: Scratch = undefined, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - - fn slotBase(m: *const Model) u64 { - return m.slots[m.slot].cache.ptr; - } - - /// Allocates slots until `n` exist, each with zeroed conv states and its own rewind sites. - pub fn addSlots(m: *Model, s: cuda.Stream, n: usize) !void { - if (n > max_slots) return error.TooManySlots; - const keep = m.slot; - defer m.slot = keep; - const kv: usize = @as(usize, m.w.c.text.local.kv) * m.w.c.text.local.dim; - var sites: [config.max_visits * 4]ops.RewindSite = undefined; - while (m.n_slots < n) { - var slot = try m.newSlot(); - errdefer for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); - m.slots[m.n_slots] = slot; - m.slot = m.n_slots; - for (0..m.w.p.n_visits) |v| for (0..4) |site| { - const c = if (site < 2) kv else m.w.c.text.hidden; - const hist = m.histOf(@intCast(v), site) - m.s.hist; - sites[v * 4 + site] = .{ .state = m.convOf(@intCast(v), site), .hist = @intCast(hist), .backup = @intCast(m.backupOf(@intCast(v), site)), .c = @intCast(c) }; - }; - try m.upload(s, slot.sites.ptr, std.mem.sliceAsBytes(sites[0 .. m.w.p.n_visits * 4])); - try m.reset(s); - try s.synchronize(); - m.n_slots += 1; - } - } - - /// A slot's two allocations, sized by slotAllocs: its cache and its rewind-site table. - pub fn newSlot(m: *const Model) !Slot { - const sizes = slotAllocs(&m.layout, m.w.p.n_visits); - var cache = try cuda.DeviceBuffer.alloc(m.d, sizes[0]); - errdefer cache.free(); - return .{ .cache = cache, .sites = try cuda.DeviceBuffer.alloc(m.d, sizes[1]) }; - } - - fn alloc(m: *Model, bytes: usize) !u64 { - var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); - errdefer b.free(); - try m.buffers.append(m.gpa, b); - return b.ptr; - } - - fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(m.d, dst, bytes, s); - } - - fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); - } - - fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); - } - - fn layerGeometry(m: *const Model, layer: u32) attention.Layer { - return if (config.isGlobal(layer)) - attention.Layer.global(@intCast(m.context)) - else - attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); - } - - fn cacheOf(m: *const Model, visit: u32) attention.Cache { - const slot = m.layout.at(visit); - const base = m.slotBase() + slot.kv_offset; - return .{ .k = base, .v = base + slot.kv_bytes / 2 }; - } - - fn convOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.slotBase() + m.layout.at(visit).conv_offset; - for (0..site) |i| at += 3 * widths[i] * 4; - return at; - } - - fn histOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; - for (0..site) |i| at += window_rows * widths[i] * 4; - return at; - } - - fn backupOf(m: *const Model, visit: u32, site: usize) usize { - return m.convOf(visit, site) - (m.slotBase() + m.layout.at(0).conv_offset); - } - - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { - const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); - var m: Model = .{ - .gpa = gpa, - .d = d, - .w = w, - .context = context, - .layout = layout, - }; - errdefer m.deinitBuffers(); - const c = w.c.text; - const h: usize = c.hidden; - const q: usize = @as(usize, c.global.q) * c.global.dim; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const rows = prompt_rows; - const rel_rows = rows * c.global.q * attention.extent; - const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); - const global = attention.Layer.global(@intCast(context)); - const local_slots = attention.slotsFor(local, context); - const global_slots = attention.slotsFor(global, context); - const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); - const hist_values = @as(usize, w.p.n_visits) * (2 * kv + 2 * h) * window_rows; - m.s = .{ - .ids = try m.alloc(rows * 4), - .pos = try m.alloc(rows * 4), - .seg_of = try m.alloc(rows * 4), - .segs = try m.alloc(@sizeOf(attention.Seg)), - .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), - .partial_a = try m.alloc(rows * h * 2), - .partial_b = try m.alloc(rows * h * 2), - .prelude = try m.alloc(rows * h * 2), - .bank0 = try m.alloc(rows * h * 2), - .bank1 = try m.alloc(rows * h * 2), - .raw = try m.alloc(3 * rows * h * 4), - .messages = try m.alloc(4 * rows * h * 4), - .normalized = try m.alloc(3 * rows * h * 2), - .t = try m.alloc(rows * h * 4), - .q_raw = try m.alloc(rows * q * 2), - .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), - .sink = try m.alloc(rows * c.global.q * 2), - .gate = try m.alloc(rows * q * 2), - .k_raw = try m.alloc(rows * kv * 2), - .v_raw = try m.alloc(rows * kv * 2), - .k_conv = try m.alloc(rows * kv * 2), - .v_conv = try m.alloc(rows * kv * 2), - .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .q_prepared = try m.alloc(rows * q * 2), - .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), - .rel_table = try m.alloc(rel_rows * 2), - .part_o = try m.alloc(part_slots * attention.head_dim * 4), - .part_ml = try m.alloc(part_slots * 8), - .attn_heads = try m.alloc(rows * q * 2), - .attn_out = try m.alloc(rows * h * 2), - .route_scores = try m.alloc(rows * c.experts * 4), - .route_pick = try m.alloc(rows * c.experts * 4), - .route_weights = try m.alloc(rows * c.experts * 4), - .moe_out = try m.alloc(rows * h * 2), - .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), - .hidden = try m.alloc(rows * h * 2), - .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), - .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), - .hist = try m.alloc(hist_values * 4), - }; - for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); - try m.addSlots(s, 1); - return m; - } - - fn deinitBuffers(m: *Model) void { - for (m.buffers.items) |*b| b.free(); - m.buffers.deinit(m.gpa); - } - - pub fn deinit(m: *Model) void { - m.deinitBuffers(); - for (m.slots[0..m.n_slots]) |*slot| for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); - m.* = undefined; - } - - pub fn reset(m: *const Model, s: cuda.Stream) !void { - try m.zeros(s, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - } - - pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { - if (kept > window_rows) return error.WindowTooWide; - if (m.recorded != m.slot) return error.RewindOfAnotherSlot; - try ops.rewind(&k.glue, s, m.slots[m.slot].sites.ptr, m.w.p.n_visits * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); - } - - fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { - var a: loop_math.ArArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - return a; - } - - fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { - var a: ops.MixArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - a.norm = norms; - return a; - } - - /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. - pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { - const c = m.w.c.text; - const rows = tokens.len; - const h: usize = c.hidden; - if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) - return error.BadLoopRows; - if (record and rows > window_rows) return error.WindowTooWide; - var ids: [prompt_rows]i32 = undefined; - var pos: [prompt_rows]i32 = undefined; - var seg_of: [prompt_rows]i32 = @splat(0); - for (tokens, 0..) |token, i| { - ids[i] = @intCast(token); - pos[i] = @intCast(p0 + i); - } - try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); - try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); - try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); - const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; - try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); - m.recorded = if (record) m.slot else null; - if (record) try m.copy(s, m.s.backup, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - - try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); - var partial = m.s.partial_a; - var next = m.s.partial_b; - var n_blocks: usize = 0; - const lp = c.loop.?; - - for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { - const layer = m.w.p.at(visit.layer); - const lw = &m.w.layers[visit.layer]; - if (visit.pass >= 2 and visit.layer == lp.core_start) { - try m.copy(s, partial, m.s.prelude, rows * h * 2); - n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks - } - const messages = visit.hasMessages(); - if (messages) { - const core_j = visit.layer - lp.core_start; - try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); - } - const nq: usize = if (layer.kind == .global) 3 else 1; - const query = m.w.attn_queries[visit.layer]; - const blocks = m.s.blocks[0..n_blocks]; - const raw_stride = rows * h * 4; - const norm_stride = rows * h * 2; - if (messages) { - if (nq == 3) { - try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); - } else { - // A sliding layer stores one query; each gated role gets its own AR result from that query. - for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); - } - for (0..3) |role| { - const ctl = lw.controllers[role]; - try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); - const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); - } - } else { - try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); - } - const u_q = m.s.normalized; - const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; - const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; - const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; - const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; - try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); - try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); - - const geometry = m.layerGeometry(visit.layer); - const cache = m.cacheOf(visit.cache_slot); - const dynamic = layer.kind == .global; - for (0..2) |kind| { - const input = if (kind == 0) u_k else u_v; - const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; - if (dynamic) { - try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); - try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); - } - try ops.conv(&k.glue, s, .{ - .x = if (kind == 0) m.s.k_raw else m.s.v_raw, - .state = m.convOf(visit.cache_slot, kind), - .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, - .dyn = if (dynamic) dyn_out else 0, - .out = if (kind == 0) m.s.k_conv else m.s.v_conv, - .hist = if (record) m.histOf(visit.cache_slot, kind) else 0, - .x_bf16 = 1, - .heads = @intCast(layer.heads.kv), - .c = @intCast(kv_width), - .rows = @intCast(rows), - .mode = 0, - }, 1); - } - var tiles: [128]attention.Tile = undefined; - const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); - try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); - const stride = attention.slotsFor(geometry, m.context); - const part_capacity = prompt_rows * layer.heads.q * stride; - const r: attention.Rows = .{ - .rows = @intCast(rows), - .heads = layer.heads.q, - .kv_heads = layer.heads.kv, - .pos = m.s.pos, - .seg_of = m.s.seg_of, - .segs = m.s.segs, - .tiles = m.s.tiles, - .n_tiles = @intCast(n_tiles), - .last_pos = @intCast(p0 + rows - 1), - }; - const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; - try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); - try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); - try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); - try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); - - if (layer.boundary) { - try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); - n_blocks += 1; - } - try ops.conv(&k.glue, s, .{ - .x = m.s.attn_out, - .state = m.convOf(visit.cache_slot, 2), - .w = lw.attn_conv, - .base = if (layer.boundary) 0 else partial, - .resid = m.s.t, - .hist = if (record) m.histOf(visit.cache_slot, 2) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 1, - }, 1); - - const mlp_query = m.w.mlp_queries[visit.layer]; - const mlp_blocks = m.s.blocks[0..n_blocks]; - if (messages) { - try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); - const ctl = lw.controllers[3]; - try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } else { - try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } - try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); - try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); - try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); - try ops.conv(&k.glue, s, .{ - .x = m.s.moe_out, - .state = m.convOf(visit.cache_slot, 3), - .w = lw.mlp_conv, - .resid = m.s.t, - .out = next, - .hist = if (record) m.histOf(visit.cache_slot, 3) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 2, - }, 1); - std.mem.swap(u64, &partial, &next); - - if (visit.layer + 1 == lp.core_start) try m.copy(s, m.s.prelude, partial, rows * h * 2); - if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) { - try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); - try m.copy(s, m.s.bank1, partial, rows * h * 2); - } - } - - if (heads == 0) return; - try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); - try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); - try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); - try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); - } - - pub const Saved = struct { - at: u32, - visits: u32, - passes: u32, - hidden: u32, - buf: cuda.DeviceBuffer, - }; - - /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. - pub fn snapshotBytes(m: *const Model, at: usize) u64 { - var bytes = m.layout.bytes - m.layout.at(0).conv_offset; - for (0..m.w.p.n_visits) |v| { - const layer = m.w.p.at(m.w.p.visits[v].layer); - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const row = @as(u64, layer.heads.kv) * layer.heads.dim * 2; - bytes += 2 * count * row; - } - return bytes; - } - - fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { - const at: usize = saved.at; - var off: usize = 0; - for (0..m.w.p.n_visits) |v| { - const visit = m.w.p.visits[v]; - const layer = m.w.p.at(visit.layer); - const geometry = m.layerGeometry(visit.layer); - const rb = @as(usize, layer.heads.dim) * 2; // the caches are head-major: [kv head][ring][dim] - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const first = at - count; - const cache = m.cacheOf(visit.cache_slot); - for ([2]u64{ cache.k, cache.v }) |k_or_v| for (0..layer.heads.kv) |head| { - const base = k_or_v + head * geometry.ring * rb; - var pos = first; - while (pos < at) { - const row = pos % geometry.ring; - const n = @min(at - pos, geometry.ring - row); - const dev = base + row * rb; - const src = if (out) dev else saved.buf.ptr + off; - const dst = if (out) saved.buf.ptr + off else dev; - try m.copy(s, dst, src, n * rb); - off += n * rb; - pos += n; - } - }; - } - const conv = m.slotBase() + m.layout.at(0).conv_offset; - const bytes = m.layout.bytes - m.layout.at(0).conv_offset; - try m.copy(s, if (out) saved.buf.ptr + off else conv, if (out) conv else saved.buf.ptr + off, bytes); - } - - pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { - if (at == 0 or at > m.context) return error.NotAtMark; - const gpa = m.gpa; - const saved = try gpa.create(Saved); - errdefer gpa.destroy(saved); - const lp = m.w.c.text.loop.?; - saved.* = .{ .at = at, .visits = m.w.p.n_visits, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; - errdefer saved.buf.free(); - try m.copyState(s, saved, true); - return saved; - } - - pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { - const lp = m.w.c.text.loop.?; - if (saved.visits != m.w.p.n_visits or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) - return error.StateOfAnotherModel; - if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; - try m.copyState(s, saved, false); - } - - pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { - s.synchronize() catch {}; - saved.buf.free(); - m.gpa.destroy(saved); - } -}; diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig deleted file mode 100644 index 9a0d4cc4b63..00000000000 --- a/zig/src/families/inkling2/loop_math_cuda.zig +++ /dev/null @@ -1,158 +0,0 @@ -//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. -const std = @import("std"); -const cuda = @import("cuda"); - -pub const rank = 64; -pub const max_blocks = 8; -pub const max_queries = 3; - -/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. -pub const ArArgs = extern struct { - blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state - partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source - query: u64, // FP32 [nq][c] - out: u64, // FP32 [nq][rows][c] - n_blocks: i32, - partial_bf16: i32, - nq: i32, - rows: i32, - c: i32, - eps: f32, -}; - -pub const Kernels = struct { - mod: cuda.Module, - ar_fn: cuda.Function, - messages_fn: cuda.Function, - gate_fn: cuda.Function, - project_qkv_fn: cuda.Function, - round_bf16_fn: cuda.Function, - - pub fn load(d: *const cuda.Driver) !Kernels { - if (!cuda.kernels.available) return error.BuiltWithoutKernels; - var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); - errdefer mod.unload(); - return .{ - .mod = mod, - .ar_fn = try mod.function("tf_ink2_loop_ar"), - .messages_fn = try mod.function("tf_ink2_loop_messages"), - .gate_fn = try mod.function("tf_ink2_loop_gate"), - .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), - .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), - }; - } - - pub fn unload(k: *Kernels) void { - k.mod.unload(); - k.* = undefined; - } -}; - -fn int(x: anytype) i32 { - return @intCast(x); -} - -fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { - try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); -} - -/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. -pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { - if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) - return error.Inkling2LoopArShape; - var args: cuda.Args = .{}; - args.add(a); - try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); -} - -/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. -pub fn messages( - k: *const Kernels, - s: cuda.Stream, - bank0_bf16: u64, - bank1_bf16: u64, - queries_qm_f32: u64, - queries_kv_f32: u64, - out_f32: u64, - rows: usize, - core_layers: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; - var a: cuda.Args = .{}; - for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); -} - -/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. -pub fn gate( - k: *const Kernels, - s: cuda.Stream, - state_f32: u64, - message_f32: u64, - down_bf16: u64, - forget_bf16: u64, - gain_bf16: u64, - out_f32: u64, - rows: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; - var a: cuda.Args = .{}; - for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); -} - -/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. -pub fn projectQkv( - k: *const Kernels, - s: cuda.Stream, - u_q: u64, - u_k: u64, - u_v: u64, - wq: u64, - wk: u64, - wv: u64, - raw_q: u64, - raw_k: u64, - raw_v: u64, - rows: usize, - c: usize, - q_width: usize, - kv_width: usize, -) !void { - if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; - var a: cuda.Args = .{}; - for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); - for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); - try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); -} - -/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. -pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { - if (n == 0) return; - var a: cuda.Args = .{}; - for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); - a.add(@as(i64, @intCast(n))); - try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); -} - -test "loop math argument ABI and message role offsets" { - try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); - const c = 2304; - const j = 7; - const row = 3; - const core_layers = 12; - const base = ((row * core_layers + j) * 4) * c; - for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { - const at = base + role * c; - const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; - try std.testing.expect(at >= base and queries < 24 * c); - } -} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig deleted file mode 100644 index c56b1ce7a2e..00000000000 --- a/zig/src/families/inkling2/loop_model.zig +++ /dev/null @@ -1,464 +0,0 @@ -//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. -const std = @import("std"); -const bf = @import("bf16_round"); - -pub const hidden_size = 2304; -pub const gate_rank = 64; -pub const physical_layers = 24; -pub const core_start = 6; -pub const core_end = 18; -pub const core_layers = core_end - core_start; -pub const num_passes = 3; -pub const visit_count = 48; -pub const message_roles = 4; -pub const rms_eps = 1e-6; - -pub const ShapeError = error{BadShape}; -pub const VisitError = error{BadVisit}; -pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; - -fn narrow32(v: f64) f32 { - return @floatCast(v); -} - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. -pub fn bf16(v: f64) f64 { - return bf.bf16(v); -} - -/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. -pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { - if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; - var squares: f32 = 0; - for (x) |v| { - const a = narrow32(v); - squares += a * a; - } - const mean = squares / @as(f32, @floatFromInt(x.len)); - const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); - for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); -} - -/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. -pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { - if (weight.len != x.len or scratch.len != x.len) return error.BadShape; - try rms(x, eps, scratch); - for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); -} - -/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. -pub fn residualScale(hidden: usize) ShapeError!f32 { - if (hidden == 0) return error.BadShape; - return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); -} - -fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { - if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - const count = states.len / h + 1; - if (normalized.len != count * h) return error.BadShape; - for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); - try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); - return count; -} - -fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { - if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; - const h = query.len; - const count = normalized.len / h; - if (count == 0 or weights.len != count) return error.BadShape; - const scale = try residualScale(h); - var top: f32 = -std.math.inf(f32); - for (0..count) |i| { - var dot: f32 = 0; - for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); - const logit = dot * scale; - weights[i] = widen32(logit); - top = @max(top, logit); - } - var denominator: f32 = 0; - for (weights) |*w| { - const d = narrow32(w.* - widen32(top)); - const e = @exp(d); - w.* = widen32(e); - denominator += e; - } - @memset(out, 0); - for (0..count) |i| { - const weight = narrow32(weights[i]) / denominator; - for (out, normalized[i * h ..][0..h]) |*o, v| { - const a = narrow32(o.*); - o.* = widen32(a + weight * narrow32(v)); - } - } -} - -/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. -pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { - if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; - const count = states.len / h + 1; - const normalized = try gpa.alloc(f64, count * h); - defer gpa.free(normalized); - const weights = try gpa.alloc(f64, count); - defer gpa.free(weights); - _ = try normalizeSources(states, partial, eps, normalized); - for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); -} - -pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; - -/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. -pub const MessageBank = struct { - block: []const f64, - partial: []const f64, -}; - -/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. -pub const MessageQueries = struct { - q_mlp: []const f64, - kv: []const f64, - - /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. - pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { - if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; - const odd: usize = @intFromBool(role == .mlp or role == .v); - const row_index = 2 * core + odd; - const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; - return source[row_index * hidden ..][0..hidden]; - } -}; - -fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { - if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; - const normalized = try gpa.alloc(f64, 2 * bank.block.len); - errdefer gpa.free(normalized); - try rms(bank.block, eps, normalized[0..bank.block.len]); - try rms(bank.partial, eps, normalized[bank.block.len..]); - return normalized; -} - -/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. -pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { - if (query.len != bank.block.len or out.len != query.len) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - try retrieve(normalized, query, out, &weights); -} - -/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. -pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { - const h = bank.block.len; - if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - const roles = [_]MessageRole{ .q, .k, .v, .mlp }; - for (0..core_layers) |j| for (roles, 0..) |role, r| { - const query = try queries.row(j, role, h); - const at = (j * message_roles + r) * h; - try retrieve(normalized, query, out[at..][0..h], &weights); - }; -} - -/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. -pub const GateWeights = struct { - down: []const f64, // [rank][2H], with the h half before the message half - forget: []const f64, // [H][rank] - gain: []const f64, // [H][rank] - rank: usize, -}; - -fn gateDot(row: []const f64, values: []const f64) f32 { - var sum: f32 = 0; - for (row, values) |w, v| sum += narrow32(w) * narrow32(v); - return sum; -} - -/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). -pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { - const width = h.len; - if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; - if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; - const joined = try gpa.alloc(f64, 2 * width); - defer gpa.free(joined); - const zeta = try gpa.alloc(f64, w.rank); - defer gpa.free(zeta); - try rms(h, eps, joined[0..width]); - try rms(m, eps, joined[width..]); - for (joined) |*v| v.* = bf16(v.*); - for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); - for (0..width) |i| { - const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); - const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); - const keep: f32 = 1 - forget; - const left = keep * narrow32(h[i]); - const right = gain * narrow32(m[i]); - out[i] = widen32(left + right); - } -} - -pub const AttentionKind = enum { sliding, global }; - -/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. -pub const Visit = struct { - index: u8, - layer: u8, - pass: u8, // zero outside the core, one-based inside it - cache_slot: u8, - reference_slot: u8, - kind: AttentionKind, - boundary: bool, - has_messages: bool, - ar_queries: u8, - attention_sources: u8, - mlp_sources: u8, -}; - -pub fn visit(index: usize) VisitError!Visit { - if (index >= visit_count) return error.BadVisit; - const layer: u8 = if (index < core_start) - @intCast(index) - else if (index < 42) - @intCast(core_start + (index - core_start) % core_layers) - else - @intCast(index - 24); - const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; - const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; - const global = (@as(usize, layer) + 1) % 6 == 0; - const boundary = layer % 6 == 0; - const blocks: u8 = (layer + 5) / 6; - return .{ - .index = @intCast(index), - .layer = layer, - .pass = pass, - .cache_slot = @intCast(index), - .reference_slot = reference, - .kind = if (global) .global else .sliding, - .boundary = boundary, - .has_messages = pass >= 2, - .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, - .attention_sources = if (layer == 0) 0 else blocks + 1, - .mlp_sources = blocks + 1 + @intFromBool(boundary), - }; -} - -pub const Sources = struct { - blocks: []const f64, // [completed block][H] - partial: []const f64, // p before attention, or unrounded t before the MLP -}; - -/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. -pub const Driver = struct { - gpa: std.mem.Allocator, - hidden: usize, - storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] - block_count: usize, - next: usize, - phase: enum { ready, attention, mlp }, - active: Visit, - have_snapshot: bool, - - pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { - if (embedding.len == 0) return error.BadShape; - const h = embedding.len; - const storage = try gpa.alloc(f64, 10 * h); - @memset(storage, 0); - for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); - return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; - } - - pub fn deinit(d: *Driver) void { - d.gpa.free(d.storage); - d.* = undefined; - } - - fn blocks(d: *Driver) []f64 { - return d.storage[0 .. d.block_count * d.hidden]; - } - - fn partial(d: *Driver) []f64 { - return d.storage[8 * d.hidden .. 9 * d.hidden]; - } - - fn work(d: *Driver) []f64 { - return d.storage[9 * d.hidden .. 10 * d.hidden]; - } - - /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. - pub fn begin(d: *Driver, index: usize) DriverError!Visit { - if (index >= visit_count) return error.BadVisit; - if (d.phase != .ready or d.next != index) return error.BadSequence; - if (index == core_start) { - if (d.block_count != 1) return error.BadDriverState; - @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); - @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); - d.have_snapshot = true; - } - if (index == 18 or index == 30) { - if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; - @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); - @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); - @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); - @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); - d.block_count = 1; - } - d.active = visit(index) catch return error.BadVisit; - d.phase = .attention; - return d.active; - } - - pub fn attentionSources(d: *Driver) DriverError!Sources { - if (d.phase != .attention) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } - - /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. - pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { - if (d.phase != .attention) return error.BadSequence; - if (attention.len != d.hidden) return error.BadShape; - if (d.active.boundary) { - if (d.block_count == 4) return error.BadDriverState; - @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); - d.block_count += 1; - for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); - } else { - for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); - } - d.phase = .mlp; - } - - /// AR's second call sees the extended block list and t, not bf16(t). - pub fn mlpSources(d: *Driver) DriverError!Sources { - if (d.phase != .mlp) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.work() }; - } - - /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. - pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { - if (d.phase != .mlp) return error.BadSequence; - if (mlp.len != d.hidden) return error.BadShape; - for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); - d.phase = .ready; - d.next += 1; - } - - /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. - pub fn messageBank(d: *Driver) DriverError!MessageBank { - if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; - return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; - } - - /// The five final AR sources after visit 47: four completed blocks and P_24. - pub fn finalSources(d: *Driver) DriverError!Sources { - if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } -}; - -pub fn e2m1(code: u8) f64 { - const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; - const magnitude = table[code & 7]; - return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); -} - -/// OCP E4M3FN, including its subnormals and sole NaN encodings. -pub fn e4m3(code: u8) f64 { - const negative = code & 0x80 != 0; - const exponent: u8 = (code >> 3) & 0xf; - const mantissa: u8 = code & 7; - if (exponent == 15 and mantissa == 7) return std.math.nan(f64); - const magnitude = if (exponent == 0) - std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) - else - std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); - return if (negative) -magnitude else magnitude; -} - -/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. -pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { - const a = narrow32(bf16(amax)); - const d = narrow32(bf16(denominator)); - return widen32(a / d); -} - -fn nvWeight(code: u8, scale: u8, factor: f32) f64 { - const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact - return bf16(widen32(inner * factor)); -} - -pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { - return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); -} - -/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. -pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; - const factor = narrow32(nvfp4OuterFactor(amax, denominator)); - for (out, 0..) |*v, c| { - const packed_byte = codes[c / 2]; - const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; - v.* = nvWeight(code, scales[c / 16], factor); - } -} - -pub fn mxfp8Scale(scale: u8) f64 { - return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); -} - -pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { - return bf16(e4m3(code) * mxfp8Scale(scale)); -} - -/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). -pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; - for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); -} - -/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. -pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { - if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; - for (0..rows) |r| { - var sum: f32 = 0; - for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); - out[r] = bf16(widen32(sum)); - } -} - -fn softcap32(x: f32, cap: f32) f32 { - return cap * std.math.tanh(x / cap); -} - -/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. -pub fn expertActivation(gate: f64, up: f64) f64 { - const g = narrow32(gate); - const sigmoid: f32 = 1 / (1 + @exp(-g)); - const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); - return bf16(widen32(act)); -} - -/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. -pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { - if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; - @memset(out, 0); - for (0..expert_count) |e| { - var found = false; - for (ids, 0..) |id, r| if (id == e) { - if (found) return error.BadShape; - found = true; - const weight = narrow32(route_weights[r]); - for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { - const term = weight * narrow32(value); - sum.* = widen32(narrow32(sum.*) + term); - } - } else if (id >= expert_count) return error.BadShape; - } - for (out) |*v| v.* = bf16(v.*); -} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig deleted file mode 100644 index ee0bcf64dab..00000000000 --- a/zig/src/families/inkling2/loop_model_test.zig +++ /dev/null @@ -1,214 +0,0 @@ -const std = @import("std"); -const model = @import("loop_model.zig"); - -const Driver = model.Driver; -const GateWeights = model.GateWeights; -const MessageBank = model.MessageBank; -const MessageQueries = model.MessageQueries; -const attentionResidual = model.attentionResidual; -const bf16 = model.bf16; -const combineExperts = model.combineExperts; -const crossPassMessage = model.crossPassMessage; -const crossPassMessages = model.crossPassMessages; -const e2m1 = model.e2m1; -const e4m3 = model.e4m3; -const expertActivation = model.expertActivation; -const expertProjection = model.expertProjection; -const hidden_size = model.hidden_size; -const messageGate = model.messageGate; -const mxfp8ReferenceRow = model.mxfp8ReferenceRow; -const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; -const mxfp8Scale = model.mxfp8Scale; -const nvfp4OuterFactor = model.nvfp4OuterFactor; -const nvfp4ReferenceRow = model.nvfp4ReferenceRow; -const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; -const residualScale = model.residualScale; -const rms = model.rms; -const visit = model.visit; -const visit_count = model.visit_count; -const weightedRms = model.weightedRms; - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { - try std.testing.expectApproxEqAbs(expected, actual, tolerance); -} - -test "norm scale and weighted RMS's sole final bf16 rounding" { - const x = [_]f64{ 3, 4, 0, 0 }; - var out: [4]f64 = undefined; - var scratch: [4]f64 = undefined; - try rms(&x, 0, &out); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); - try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); - // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. - try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); -} - -test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { - const state = [_]f64{ 3, 4, 0, 0 }; - const partial = [_]f64{ 0, 10, 0, 0 }; - const query = [_]f64{ 1, 0, 0, 0 }; - var out: [4]f64 = undefined; - try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); - // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); -} - -test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { - const a = [_]f64{ 3, 4, 0, 0 }; - const p = [_]f64{ 0, 10, 0, 0 }; - var out: [4]f64 = undefined; - try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - - var q_rows: [24]f64 = undefined; - var kv_rows: [24]f64 = undefined; - for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); - for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); - const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; - try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); - try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); - try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); - try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); - - var messages: [visit_count]f64 = undefined; - const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; - try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); - for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); -} - -test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { - const h = [_]f64{ 3, 4, 0, 0 }; - const m = [_]f64{ 0, 10, 0, 0 }; - const weights: GateWeights = .{ - .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, - .forget = &.{ 1, 0, 0, 0 }, - .gain = &.{ 0, 1, 0, 0 }, - .rank = 1, - }; - var out: [4]f64 = undefined; - try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); - // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). - const z: f32 = 5.03125; - const a: f32 = std.math.tanh(z); - const expected0: f32 = (1 - a) * 3; - const expected1: f32 = 4 + a * 10; - try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); - try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); - try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); -} - -test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { - var driver = try Driver.init(std.testing.allocator, &.{7}); - defer driver.deinit(); - const zero = [_]f64{0}; - for (0..visit_count) |v| { - _ = try driver.begin(v); - if (v == 6 or v == 18 or v == 30) { - const src = try driver.attentionSources(); - try std.testing.expectEqual(@as(usize, 1), src.blocks.len); - try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); - try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 - } - if (v == 18) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 - try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 - } else if (v == 30) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 - try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 - } - const delta = [_]f64{@floatFromInt(v + 1)}; - try driver.afterAttention(&delta); - try driver.finish(&zero); - } - const final = try driver.finalSources(); - // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. - try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); - try std.testing.expectEqual(@as(f64, 272), final.partial[0]); -} - -test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { - const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ - .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, - .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, - .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, - .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, - }; - for (expected) |e| { - const v = try visit(e.index); - try std.testing.expectEqual(e.layer, v.layer); - try std.testing.expectEqual(e.pass, v.pass); - try std.testing.expectEqual(e.reference, v.reference_slot); - try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); - try std.testing.expectEqual(e.messages, v.has_messages); - try std.testing.expectEqual(e.ar, v.ar_queries); - try std.testing.expectEqual(e.attn, v.attention_sources); - try std.testing.expectEqual(e.mlp, v.mlp_sources); - } - try std.testing.expectError(error.BadVisit, visit(48)); -} - -test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { - // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. - try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); - try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); - var row: [16]f64 = undefined; - var codes: [8]u8 = @splat(0); - codes[0] = 0xb3; - const scales = [_]u8{0x38}; - try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); - try std.testing.expectEqual(@as(f64, 1.5), row[0]); - try std.testing.expectEqual(@as(f64, -1.5), row[1]); - try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); - try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); -} - -test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { - try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); - try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 - var codes: [64]u8 = @splat(0); - codes[0] = 0x38; // one - codes[31] = 0x3c; // 1.5, still group zero - codes[32] = 0x3c; // group one - var out: [64]f64 = undefined; - try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); - try std.testing.expectEqual(@as(f64, 8), out[0]); - try std.testing.expectEqual(@as(f64, 12), out[31]); - try std.testing.expectEqual(@as(f64, 6), out[32]); -} - -test "expert projection and softcapped SwiGLU have no activation quantization" { - var projected: [2]f64 = undefined; - try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); - try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); - const g: f32 = 1; - const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); - try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); -} - -test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { - const ids = [_]u32{ 2, 1, 0 }; - const weights = [_]f64{ 1, 1, 1 }; - // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. - const outputs = [_]f64{ -1, 0x1p-24, 1 }; - var out: [1]f64 = undefined; - try combineExperts(3, &ids, &weights, &outputs, 1, &out); - try std.testing.expectEqual(@as(f64, 0), out[0]); -} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig deleted file mode 100644 index 7bc6263c0fa..00000000000 --- a/zig/src/families/inkling2/loop_weights.zig +++ /dev/null @@ -1,228 +0,0 @@ -//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const modelopt = @import("modelopt.zig"); - -pub const Controller = struct { - down: u64, - forget: u64, - gain: u64, -}; - -pub const Attention = struct { - wq: u64, - wk: u64, - wv: u64, - wr: u64, - wo: u64, - gate: u64, - sink: u64, - q_scale: u64, - rel_scale: u64, - rel_proj: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64 = 0, - v_dynamic: u64 = 0, - /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. - norms: [3]u64, -}; - -/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. -pub const Layer = struct { - attn: Attention, - attn_conv: u64, - mlp_norm: u64, - mlp_conv: u64, - router: u64, - router_bias: u64, - experts: modelopt.Layer, - controllers: [4]Controller, -}; - -pub const Weights = struct { - gpa: std.mem.Allocator, - c: config.Config, - p: plan_.Plan, - embed: u64 = 0, - embed_norm: u64 = 0, - norm: u64 = 0, - unembed: u64 = 0, - output_query: u64 = 0, - attn_queries: []u64 = &.{}, - mlp_queries: []u64 = &.{}, - cross_qm: u64 = 0, - cross_kv: u64 = 0, - layers: []Layer = &.{}, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - bytes: usize = 0, - - pub fn deinit(w: *Weights) void { - for (w.buffers.items) |*b| b.free(); - w.buffers.deinit(w.gpa); - w.gpa.free(w.layers); - w.gpa.free(w.attn_queries); - w.gpa.free(w.mlp_queries); - w.* = undefined; - } -}; - -/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. -const Loader = struct { - w: *Weights, - arena: cuda.DeviceBuffer, - used: usize = 0, - - pub fn alloc(l: *Loader, len: usize) !u64 { - const at = std.mem.alignForward(usize, l.used, 256); - const end = try std.math.add(usize, at, len); - if (end > l.arena.len) return error.LoopWeightsOverflow; - l.used = end; - l.w.bytes += len; - return l.arena.ptr + at; - } - - fn put(l: *Loader, bytes: []const u8) !u64 { - const p = try l.alloc(bytes.len); - try l.arena.upload(p - l.arena.ptr, bytes); - return p; - } - - fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { - var buf: [256]u8 = undefined; - const name = try std.fmt.bufPrint(&buf, fmt, args); - return l.put((try ck.expect(name, dtype, dims)).bytes); - } -}; - -fn checkpointBytes(ck: *const core.Checkpoint) !usize { - var total: usize = 0; - for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { - if (!std.mem.startsWith(u8, name, "model.llm.")) continue; - const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); - total = try std.math.add(usize, total, padded); - }; - return total; -} - -fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { - const h: usize = c.hidden; - const names = [4][]const u8{ "attn", "k", "v", "mlp" }; - for (names, out) |role, *g| { - var prefix: [160]u8 = undefined; - const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); - var down: [224]u8 = undefined; - var forget: [224]u8 = undefined; - var gain: [224]u8 = undefined; - g.* = .{ - .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), - .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), - .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), - }; - } -} - -/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. -pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { - if (c.text.loop == null) return error.Inkling2LoopRequired; - var formats: [config.max_layers]modelopt.Format = undefined; - for (p.layers[0..c.text.layers], 0..) |layer, k| { - formats[k] = switch (layer.precision) { - .nvfp4 => .nvfp4, - .mxfp8 => .mxfp8, - }; - } - const total = try checkpointBytes(ck); - var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); - var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; - errdefer w.deinit(); - w.buffers.append(gpa, arena) catch |err| { - arena.free(); - return err; - }; - w.layers = try gpa.alloc(Layer, c.text.layers); - w.attn_queries = try gpa.alloc(u64, c.text.layers); - w.mlp_queries = try gpa.alloc(u64, c.text.layers); - var l: Loader = .{ .w = &w, .arena = arena }; - const h: usize = c.text.hidden; - w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); - w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); - w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); - w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); - w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); - - for (w.layers, 0..) |*layer, k| { - const i: u32 = @intCast(k); - const L = .{i}; - const hd = c.text.heads(i); - const q: usize = @as(usize, hd.q) * hd.dim; - const kv: usize = @as(usize, hd.kv) * hd.dim; - w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); - if (i == 0) { - w.attn_queries[k] = 0; - } else if (config.isGlobal(i)) { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); - } else { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); - } - const A = struct { - fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { - return loader.tensor(checkpoint, fmt, args, .bf16, dims); - } - }; - layer.attn = .{ - .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), - .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), - .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), - .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), - .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), - .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), - .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), - .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), - .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), - .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), - .k_conv = undefined, - .v_conv = undefined, - .norms = undefined, - }; - inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { - const conv = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) - else - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); - if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; - if (config.isGlobal(i)) { - const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); - if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; - } - const norm = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) - else if (j == 0) - try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}) - else - layer.attn.norms[1]; // a sliding layer's k and v share one attn_norm upload - layer.attn.norms[j + 1] = norm; - } - layer.attn.norms[0] = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) - else - layer.attn.norms[1]; - layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); - layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); - layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); - var prefix: [96]u8 = undefined; - layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); - @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); - const lp = c.text.loop.?; - if (i >= lp.core_start and i < lp.core_end) try controllers(&l, ck, &c.text, i, lp.gate_rank, &layer.controllers); - } - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - return w; -} diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 6688dc8d7a0..49095e4facc 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -1,8 +1,9 @@ //! Pure host geometry and ABI declarations for Inkling 2 Mini Metal attention. const std = @import("std"); +const config = @import("../config.zig"); -pub const head_dim = 128; -pub const d_rel = 16; +pub const head_dim = config.head_dim; +pub const d_rel = config.d_rel; pub const extent = 1024; pub const tile_keys = 64; pub const sliding_chunk = 256; diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index b7faf6dab82..268b02d7da9 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -284,8 +284,7 @@ pub const Metal = struct { } fn read(self: *Metal, handle: u64) !u32 { - if (handle >= self.next) return error.InvalidInklingTokenHandle; - const token = self.tokens[handle % ring]; + const token = try ringToken(self.tokens, self.next, handle); if (token >= self.vocab()) return error.InvalidInklingToken; return token; } @@ -427,6 +426,12 @@ fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } +/// The token behind `handle`: only the last `ring` handles drawn are still held. +fn ringToken(tokens: []const u32, next: u64, handle: u64) !u32 { + if (handle >= next or next - handle > ring) return error.InvalidInklingTokenHandle; + return tokens[handle % ring]; +} + fn firstLogprobRow(l: []const f32, tokens: []const u32, next: usize, count: u8) lanes.LogprobRow { std.debug.assert(tokens.len == ring and next > 0); return logprobRow(l, tokens[(next - 1) % ring], count); @@ -466,3 +471,12 @@ test "sampled first-token logprob uses the last written handle, not argmax" { const lse = @log(@as(f64, 1) + @exp(-@as(f64, 1)) + @exp(-@as(f64, 2)) + @exp(-@as(f64, 3))); try std.testing.expectApproxEqAbs(@as(f32, -3) - @as(f32, @floatCast(lse)), row.logprob, 1e-6); } + +test "a token handle expires once the ring has wrapped past it" { + var tokens: [ring]u32 = @splat(0); + tokens[0] = 7; + try std.testing.expectEqual(@as(u32, 7), try ringToken(&tokens, ring, 0)); + try std.testing.expectError(error.InvalidInklingTokenHandle, ringToken(&tokens, ring + 1, 0)); + try std.testing.expectEqual(@as(u32, 7), try ringToken(&tokens, ring + 1, ring)); + try std.testing.expectError(error.InvalidInklingTokenHandle, ringToken(&tokens, ring, ring)); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index afb7382ba5f..5fe3fb18778 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -17,7 +17,6 @@ pub const Segment = struct { cache: *state.Cache, rows: usize }; pub const Options = struct { all: bool = false, ids: ?Ref = null, - flight: ?*mtl.CommandBuffer = null, taps: ?state.Ref = null, }; @@ -133,7 +132,7 @@ fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); } -fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize) void { +fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visits.Step, rows: usize) void { const lp = m.weight_plan.at(v.layer); const w = &m.weights.layers[v.layer]; if (v.layer == 0) { @@ -145,7 +144,7 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), query, arRow(s, role, rows, i, false), lp.attn_sources, 1); } } - if (v.hasMessages()) { + if (v.pass > 0) { const controllers = w.controllers.?; const core = v.layer - 6; for (0..3) |role| for (0..rows) |i| { @@ -154,7 +153,7 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra loop.gates(&m.loop, e, l(arRow(s, source_role, rows, i, false)), l(messageRow(s, core, role, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(arRow(s, role, rows, i, true)), 1); }; } - const gated = v.hasMessages(); + const gated = v.pass > 0; // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. if (!gated and lp.kind == .local) { norm(m, e, arRow(s, 0, rows, 0, false), w.attn.q_norm, at(s.q_norm, 0), rows); @@ -173,13 +172,13 @@ fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, s glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); } -fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment) !void { +fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visits.Step, segments: []const Segment) !void { var base: usize = 0; for (segments, 0..) |seg, si| { const rows = seg.rows; const cache = seg.cache; - const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); - const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + const layer0 = cache.attentionLayer(&m.weight_plan, v.of(.conv).?, rows); + const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(cache.ring(v.of(.conv).?)), .chunk = layer0.chunk, .tau = layer0.tau }; const start = cache.len; const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(start + rows - 1), .streams = 1 }; const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; @@ -188,7 +187,7 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: .seg_of = a(at(s.seg_of, base * 4)), .segs = a(at(s.segs, si * @sizeOf(ap.Seg))), }; - const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; + const kv = attention.Cache{ .k = a(cache.keys(v.of(.conv).?)), .v = a(cache.values(v.of(.conv).?)) }; try convInputForAttention(m, e, s, cache, v, base, rows, true); try convInputForAttention(m, e, s, cache, v, base, rows, false); attention.prep(&m.attention, e, rr, layer, prep, meta, .{ a(at(s.q_raw, base * state.query_width * 2)), a(at(s.k_conv, base * state.kv_width * 2)), a(at(s.v_conv, base * state.kv_width * 2)), a(at(s.rel_raw, base * state.rel_width * 2)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * state.rel_width * 2)), kv); @@ -198,15 +197,15 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: } } -fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) !void { +fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visits.Step, base: usize, rows: usize, key: bool) !void { const lp = m.weight_plan.at(v.layer); const w = &m.weights.layers[v.layer]; const raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2); const projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2); - const normalized = if (key) at(s.k_norm, 0) else if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - const taps = cache.staged(v.cache_slot, if (key) 0 else 1, 0); - copyBf16(m, e, cache.history(v.cache_slot, if (key) 0 else 1), taps, 3 * state.kv_width); - copyBf16(m, e, projected, cache.staged(v.cache_slot, if (key) 0 else 1, 3), rows * state.kv_width); + const normalized = if (key) at(s.k_norm, 0) else if (v.pass > 0 or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + const taps = cache.staged(v.of(.conv).?, if (key) 0 else 1, 0); + copyBf16(m, e, cache.history(v.of(.conv).?, if (key) 0 else 1), taps, 3 * state.kv_width); + copyBf16(m, e, projected, cache.staged(v.of(.conv).?, if (key) 0 else 1, 3), rows * state.kv_width); switch (if (key) w.attn.k_conv else w.attn.v_conv) { .static => |weight| glue.convStatic(&m.glue, e, taps, r(weight), raw, @intCast(rows), state.kv_width), .dynamic => |d| glue.convDynamic(&m.glue, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), raw, @intCast(rows), state.kv_width), @@ -233,11 +232,11 @@ fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, laye try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); } -fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, rows: usize, taps: ?state.Ref) !void { +fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visits.Step, segments: []const Segment, rows: usize, taps: ?state.Ref) !void { const lp = m.weight_plan.at(v.layer); - const gated = v.hasMessages(); + const gated = v.pass > 0; if (taps) |to| { - const channel: ?usize = switch (v.cache_slot) { + const channel: ?usize = switch (v.of(.conv).?) { 5 => 0, 23 => 1, 41 => 2, @@ -245,7 +244,7 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la }; if (channel) |ch| captureTap(m, e, at(s.p, 0), to, rows, ch); } - if (v.pass > 1 and v.layer == 6) bankAndReset(m, e, s, rows); + if (v.pass > 0 and v.layer == 6) bankAndReset(m, e, s, rows); const w = &m.weights.layers[v.layer]; // The running BF16 p is the partial AR source before attention replaces it with t. widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); @@ -262,7 +261,7 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la dense(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); var base: usize = 0; for (segments) |seg| { - staticPostConv(m, e, seg.cache, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0), base, seg.rows); + staticPostConv(m, e, seg.cache, v.of(.conv).?, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0), base, seg.rows); base += seg.rows; } runtime(m, e, .attention_partial, &.{ at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.partial, 0) }, rows * state.hidden, if (lp.boundary) lp.blocks_in + 1 else 0); @@ -277,11 +276,11 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la try routedExperts(m, e, s, v.layer, rows); base = 0; for (segments) |seg| { - staticPostConv(m, e, seg.cache, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0), base, seg.rows); + staticPostConv(m, e, seg.cache, v.of(.conv).?, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0), base, seg.rows); base += seg.rows; } runtime(m, e, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, rows * state.hidden, 0); - if (v.cache_slot == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); + if (v.of(.conv).? == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); } fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment) void { @@ -322,7 +321,7 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, const cb = m.queue.commandBuffer(); const e = cb.compute(.serial); glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); - for (m.weight_plan.visits[0..m.weight_plan.n_visits]) |*v| try visit(m, e, s, v, segments, rows, options.taps); + for (m.weight_plan.visits.slice()) |*v| try visit(m, e, s, v, segments, rows, options.taps); widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); const final = finalPlan(rows, options.all, options.taps != null); for (0..final.work_rows) |j| { @@ -336,10 +335,6 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, commitFullHistories(m, e, s, segments); e.end(); cb.commit(); - if (options.flight) |flight| { - flight.* = cb.retain(); - return; - } cb.wait(); if (cb.failure()) |msg| { std.log.err("inkling2_loop forward: {s}", .{msg}); diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig index 87c98f36fcf..bed9a8af710 100644 --- a/zig/src/families/inkling2/metal/model.zig +++ b/zig/src/families/inkling2/metal/model.zig @@ -78,7 +78,7 @@ pub const runtime_names = [_][:0]const u8{ pub fn admitConfig(c: *const cfg.Config) !void { const t = c.text; const l = t.loop orelse return error.Inkling2NotMini; - if (l.passes != 3 or l.core_start != 6 or l.core_end != 18 or l.gate_rank != 64) + if (l.passes != 3 or l.start != 6 or l.end != 18 or l.rank != 64) return error.UnsupportedInkling2Loop; if (t.hidden != 2304 or t.layers != 24 or t.vocab != 201024 or t.unpadded_vocab != 200058 or t.window != 1024 or t.d_rel != 16 or t.rel_extent != 1024 or t.log_floor != 8192 or @@ -177,7 +177,7 @@ fn loadWeights(c: *const ck.Checkpoint, config: *const cfg.Config, wp: *const la l.gu = try matrix(c, layer, "w13", p.precision, 2304, 2304); l.down = try matrix(c, layer, "w2", p.precision, 2304, 1152); l.controllers = null; - if (config.text.loop) |lp| if (layer >= lp.core_start and layer < lp.core_end) { + if (config.text.loop) |lp| if (layer >= lp.start and layer < lp.end) { var controllers: [4]Controller = undefined; inline for (.{ "attn", "k", "v", "mlp" }, 0..) |role, j| controllers[j] = .{ .down = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".down_weight", .{layer}, .bf16, &.{ 64, 4608 }), @@ -235,7 +235,7 @@ pub const Model = struct { var precisions: [24]layer_plan.Precision = undefined; for (&precisions, 0..) |*p, i| p.* = if (i < 20) .nvfp4 else .mxfp8; m.weight_plan = try layer_plan.build(&m.config.text, &precisions); - if (m.weight_plan.n_visits != 48) return error.UnsupportedInkling2Loop; + if (m.weight_plan.visits.len != 48) return error.UnsupportedInkling2Loop; for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "model.llm."); m.weights = try loadWeights(&m.checkpoint, &m.config, &m.weight_plan); diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig index f12f0fe2ad3..5b5499dcb1d 100644 --- a/zig/src/families/inkling2/metal/runtime_test.zig +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -36,7 +36,7 @@ fn mini() cfg.Config { .up_cap = 25, .logit_cap = 30, .max_context = 1048576, - .loop = .{ .core_start = 6, .core_end = 18, .passes = 3, .gate_rank = 64 }, + .loop = .{ .start = 6, .end = 18, .passes = 3, .rank = 64 }, }, .vision = undefined, .mtp = null, @@ -56,20 +56,20 @@ test "Mini admits only its fixed geometry and expands 24 weights to 48 visits" { const c = mini(); try model.admitConfig(&c); const p = schedule(); - try std.testing.expectEqual(@as(u32, 48), p.n_visits); + try std.testing.expectEqual(@as(u32, 48), p.visits.len); try std.testing.expectEqual(@as(u32, 8), p.visitCount(.global)); try std.testing.expectEqual(@as(u32, 5), p.final_sources); - for (p.visits[0..p.n_visits], 0..) |v, i| { - try std.testing.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + for (p.visits.slice(), 0..) |v, i| { + try std.testing.expectEqual(@as(u16, @intCast(i)), v.of(.conv).?); try std.testing.expect(v.layer < 24); } for ([_]usize{ 18, 30 }) |i| { - try std.testing.expect(p.visits[i].pass > 1); - try std.testing.expectEqual(@as(u32, 6), p.visits[i].layer); - try std.testing.expect(p.visits[i].hasMessages()); + try std.testing.expect(p.visits.steps[i].pass > 0); + try std.testing.expectEqual(@as(u16, 6), p.visits.steps[i].layer); + try std.testing.expect(p.messages(@intCast(i))); } - try std.testing.expect(!p.visits[0].hasMessages()); - try std.testing.expect(!(p.visits[17].pass > 1 and p.visits[17].layer == 6)); + try std.testing.expect(!p.messages(0)); + try std.testing.expect(!(p.visits.steps[17].pass > 0 and p.visits.steps[17].layer == 6)); } test "Every visit and convolution role has disjoint persistent and staged bytes" { diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 01c2085e4b7..415f3fbc087 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -100,7 +100,7 @@ pub const Cache = struct { follow: ?mtl.ResidencySet.Follow = null, pub fn init(device: mtl.Device, capacity: usize, schedule: *const plan.Plan) !Cache { - if (capacity == 0 or capacity > 1048576 or schedule.n_visits != visit_slots) return error.Inkling2CacheShape; + if (capacity == 0 or capacity > 1048576 or schedule.visits.len != visit_slots) return error.Inkling2CacheShape; var out: Cache = .{ .kv = undefined, .conv = undefined, @@ -115,7 +115,7 @@ pub const Cache = struct { }; var at: usize = 0; for (0..visit_slots) |slot| { - const global = schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global; + const global = schedule.at(schedule.visits.steps[slot].layer).kind == .global; const ring_size = if (global) globalSlots(capacity) else sliding_ring; out.globals[slot] = global; out.rings[slot] = @intCast(ring_size); @@ -187,7 +187,7 @@ pub const Cache = struct { pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { std.debug.assert(rows <= max_rows); - var layer = if (schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); + var layer = if (schedule.at(schedule.visits.steps[slot].layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); layer.ring = @intCast(c.ring(slot)); return layer; } diff --git a/zig/src/families/inkling2/mini_backend.zig b/zig/src/families/inkling2/mini_backend.zig new file mode 100644 index 00000000000..daf81aca079 --- /dev/null +++ b/zig/src/families/inkling2/mini_backend.zig @@ -0,0 +1,404 @@ +//! Inkling 2 Mini behind lanes.Backend: a cache slot a stream (48 visit slots), a prompt chunk a step, one forward +//! a round of one-row windows over every stream. No draft head yet (C5) and no copy drafts: a conv state has no +//! rollback here, so every window keeps all its rows. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const mm = @import("mini_model.zig"); +const snap = @import("mini_snap.zig"); + +const be = lanes.backend; +const Stream = lanes.Stream; + +/// Prompt rows a step takes. +pub const prompt_rows = mm.prompt_rows; +/// Window rows a round takes over every stream. +pub const round_rows = mm.round_rows; +/// Drawn tokens a handle names (a ring; read before the round loop could wrap it). +const ring = 1024; + +/// The serving launches beside the forward: argmax, bf16 logits and sample.cu's keyed draws. +pub const Draws = struct { + mods: [3]cuda.Module, + argmax_fn: cuda.Function, + to_bf16_fn: cuda.Function, + draws: cuda.sample.Draws, + + pub fn load(d: *const cuda.Driver) !Draws { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const kk = cuda.kernels; + var x: Draws = undefined; + var loaded: usize = 0; + errdefer for (x.mods[0..loaded]) |*m| m.unload(); + for ([_][]const u8{ kk.sample, kk.torch_argmax, kk.torch_pointwise }, 0..) |img, i| { + x.mods[i] = try cuda.Module.load(d, img); + loaded += 1; + } + x.draws = try cuda.sample.Draws.resolve(x.mods[0]); + x.argmax_fn = try x.mods[1].function("tf_argmax_rows_i32_kernel"); + x.to_bf16_fn = try x.mods[2].function("tf_f32_to_bf16_kernel"); + return x; + } + + pub fn deinit(x: *Draws) void { + for (&x.mods) |*m| m.unload(); + } + + /// Each row's argmax over `v` fp32 logits, the first maximum on ties, into `out` (int32 a row). + fn argmax(x: *const Draws, s: cuda.Stream, logits: u64, rows: usize, v: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, v, v }) |n| a.add(@as(i64, @intCast(n))); + a.add(@as(i32, 1)); // dtype 1: fp32 + try cuda.launch.launch(x.argmax_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 1024 } }, s, &a); + } + + fn toBf16(x: *const Draws, s: cuda.Stream, src: u64, dst: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(dst); + a.add(@as(u64, n)); + const grid: u32 = @intCast(@max(1, @min((n + 255) / 256, 65535))); + try cuda.launch.launch(x.to_bf16_fn, .{ .grid = .{ .x = grid }, .block = .{ .x = 256 } }, s, &a); + } +}; + +const Lane = struct { + slot: usize, + len: u64 = 0, // positions [0, len) hold this stream's keys and its conv states are at len + base: u64 = 0, // the length the last verify started from + rows: std.ArrayList(u32) = .empty, // the last verify's row tokens + last: u64, // the prompt's last row's fp32 logits (the first draw reads them) + rule: u64, // sample.cu's Rule, when the stream samples + sampled: bool = false, + fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts +}; + +/// The positions a slot holds for a served window, in whole 1,024s. +pub fn capacity(window: usize) !usize { + if (window == 0) return error.BadContext; + return (try std.math.add(usize, window, 1023)) / 1024 * 1024; +} + +/// A prompt and its reply fit `physical` positions. +pub fn fits(physical: usize, prompt: usize, reply: usize) bool { + return prompt <= physical and reply <= physical - prompt; +} + +pub const Mini = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *mm.Model, + k: *const mm.Kernels, + x: *const Draws, + s: cuda.Stream, + image_token: u32, + lanes: std.AutoHashMapUnmanaged(*const Stream, Lane) = .empty, + free: []bool, // slot i is free + logits16: cuda.DeviceBuffer, // a round's logits as bf16 for keyed draws + tok: cuda.DeviceBuffer, // drawn tokens: the handle ring, then a round's rows + meta: cuda.DeviceBuffer, // a draw's first position minus one, a window each + slot_bufs: []cuda.DeviceBuffer, // a slot's last-row logits, then its rule: two a slot + next: u64 = 0, + + fn vocab(x: *const Mini) usize { + return x.m.c.unpadded_vocab; + } + + /// The device bytes `init` allocates: bf16 logits, the token ring, metas, each slot's last row and rule. + pub fn openBytes(vocab_: usize, slots: usize) usize { + return round_rows * vocab_ * 2 + (ring + round_rows) * 4 + round_rows * 16 + slots * (vocab_ * 4 + @sizeOf(cuda.sample.Rule)); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *mm.Model, k: *const mm.Kernels, x: *const Draws, s: cuda.Stream, image_token: u32) !Mini { + const v = m.c.unpadded_vocab; + const free = try gpa.alloc(bool, m.slots); + errdefer gpa.free(free); + @memset(free, true); + var logits16 = try cuda.DeviceBuffer.alloc(d, round_rows * v * 2); + errdefer logits16.free(); + var tok = try cuda.DeviceBuffer.alloc(d, (ring + round_rows) * 4); + errdefer tok.free(); + var meta = try cuda.DeviceBuffer.alloc(d, round_rows * 16); + errdefer meta.free(); + const bufs = try gpa.alloc(cuda.DeviceBuffer, 2 * m.slots); + errdefer gpa.free(bufs); + var made: usize = 0; + errdefer for (bufs[0..made]) |*b| b.free(); + for (bufs, 0..) |*b, i| { + b.* = try cuda.DeviceBuffer.alloc(d, if (i % 2 == 0) v * 4 else @sizeOf(cuda.sample.Rule)); + made += 1; + } + return .{ .gpa = gpa, .d = d, .m = m, .k = k, .x = x, .s = s, .image_token = image_token, .free = free, .logits16 = logits16, .tok = tok, .meta = meta, .slot_bufs = bufs }; + } + + pub fn deinit(x: *Mini) void { + var it = x.lanes.valueIterator(); + while (it.next()) |l| l.rows.deinit(x.gpa); + x.lanes.deinit(x.gpa); + for (x.slot_bufs) |*b| b.free(); + x.gpa.free(x.slot_bufs); + x.gpa.free(x.free); + x.logits16.free(); + x.tok.free(); + x.meta.free(); + } + + pub fn backend(x: *Mini) be.Backend { + return .{ .ptr = x, .vtable = &vtable }; + } + + const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true }; + + /// The round loop's facts: no draft head and no copies; one-row windows, streams sharing a forward. + pub fn facts(x: *const Mini) lanes.Model { + return .{ .copy_drafts = false, .exact_width = 1, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .plain_share = true, .batch_rows = round_rows, .max_streams = @intCast(@min(x.m.slots, round_rows)) }; + } + + fn self(ptr: *anyopaque) *Mini { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(x: *Mini, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(x.d, dst, bytes, x.s); + } + + /// Rows [row0, row0 + rows) of fp32 `logits` drawn into tok[at..], row r at `position0 + r` (argmax when greedy). + fn drawRows(x: *Mini, l: *const Lane, logits: u64, row0: usize, rows: usize, position0: u64, at: usize, meta_at: usize) !void { + const v = x.vocab(); + const src = logits + row0 * v * 4; + if (!l.sampled) return x.x.argmax(x.s, src, rows, v, x.tok.ptr + at * 4); + try x.x.toBf16(x.s, src, x.logits16.ptr, rows * v); + const meta = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + const mp = x.meta.ptr + meta_at * 16; + try x.upload(mp, std.mem.asBytes(&meta)); + try x.x.draws.draw(x.s, x.logits16.ptr, v, l.rule, mp, 0, x.tok.ptr + at * 4, rows, null, null); + } + + fn freeSlot(x: *const Mini) ?usize { + return std.mem.indexOfScalar(bool, x.free, true); + } + + /// Whether a request could start now: a free slot; one that never fits passes (its open refuses it). + pub fn admits(x: *const Mini, prompt: usize, max_new: usize) bool { + if (!fits(x.m.context, prompt, max_new)) return true; + return x.freeSlot() != null; + } + + /// A prompt pass begins: a slot and the stream's rule; images are refused by name until the vision slice (C6). + fn opening(x: *Mini, s: *Stream) !*Lane { + const p = s.prompt(); + if (p.len == 0) return error.EmptyPrompt; + if (std.mem.indexOfScalar(u32, p, x.image_token) != null) return error.Inkling2MiniImages; + if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext; + const got = try x.lanes.getOrPut(x.gpa, s); + if (!got.found_existing) { + const slot = x.freeSlot() orelse { + x.lanes.removeByPtr(got.key_ptr); + return error.NoFreeSlot; + }; + got.value_ptr.* = .{ .slot = slot, .last = x.slot_bufs[2 * slot].ptr, .rule = x.slot_bufs[2 * slot + 1].ptr }; + x.free[slot] = false; + } + const l = got.value_ptr; + l.sampled = false; + if (cuda.sample.ruleFor(s.sampling)) |r| { + try x.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + } + s.cached = 0; + l.fill = x.resumeAt(s, l, p.len); + s.fill_at.store(@intCast(l.fill.?), .monotonic); + return l; + } + + /// The kept state's position, restored into the slot (0: none, not this prompt's, or another plan's). + fn resumeAt(x: *Mini, s: *Stream, l: *const Lane, len: usize) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const snap.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= len) { + s.reuse_failed = true; + return 0; + } + snap.restore(x.m, x.s, l.slot, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + + /// The prompt pass stands at `at` (a chunk start or a mark): copy the stream's state there. + pub fn saveState(x: *Mini, owner: ?*anyopaque, at: u32) !*snap.Saved { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if ((l.fill orelse l.len) != at) return error.NotAtMark; // a state is copied only where the pass stands + return snap.save(x.gpa, x.m, x.s, l.slot, at); + } + + pub fn restoreState(x: *Mini, owner: ?*anyopaque, k: *const snap.Saved) !void { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + try snap.restore(x.m, x.s, l.slot, k); + l.len = k.at; + } + + pub fn dropState(x: *Mini, k: *snap.Saved) void { + snap.drop(x.gpa, x.s, k); + } + + /// One chunk from `l.fill`; true once the prompt's last row is in. + fn chunk(x: *Mini, s: *Stream, l: *Lane) !bool { + const p = s.prompt(); + const at = l.fill.?; + if (s.isCancelled()) return error.Cancelled; + var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); + for (s.reuse.marks) |mk| if (mk > at and mk < end) { + end = mk; + }; + const done = end == p.len; + try x.m.forward(x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }}, true, end - at - 1, @intFromBool(done)); + if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, x.vocab() * 4, x.s.handle), "cuMemcpyDtoDAsync"); + s.fill_at.store(@intCast(end), .monotonic); + l.fill = if (done) null else end; + if (done) l.len = p.len; + if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); + return done; + } + + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + const x = self(ptr); + const l = try x.opening(s); + errdefer x.dropLane(s); + while (!try x.chunk(s, l)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *Stream, _: u32) anyerror!bool { + const x = self(ptr); + const going = if (x.lanes.getPtr(s)) |l| l.fill != null else false; + const l = if (going) x.lanes.getPtr(s).? else try x.opening(s); + errdefer x.dropLane(s); + return x.chunk(s, l); + } + + fn handle(x: *Mini) usize { + const h = x.next; + x.next += 1; + return @intCast(h % ring); + } + + fn first(ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64 { + const x = self(ptr); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = x.next; + try x.drawRows(l, l.last, 0, 1, position, x.handle(), 0); + return h; + } + + fn value(x: *Mini, feed: be.Feed) !u32 { + return switch (feed) { + .value => |v| v, + .handle => |h| read(x, h), + }; + } + + fn queue(ptr: *anyopaque, s: *Stream, feed: be.Feed, position: u64) anyerror!u64 { + const x = self(ptr); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + const t = try x.value(feed); + if (position != l.len + 1) return error.PositionMismatch; + try x.m.forward(x.k, x.s, &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{t} }}, false, 0, 1); + l.len += 1; + const h = x.next; + try x.drawRows(l, x.m.s.logits, 0, 1, position, x.handle(), 0); + return h; + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const x = self(ptr); + if (h >= x.next or x.next - h > ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try x.s.synchronize(); + try x.tok.download(@intCast((h % ring) * 4), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const x = self(ptr); + const chains = try x.gpa.alloc(mm.Chain, windows.len); + defer x.gpa.free(chains); + var total: usize = 0; + for (windows, chains) |w, *c| { + if (w.held != 0) return error.NoHeldDrafts; // no draft head + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = x.lanes.getPtr(w.stream) orelse return error.UnknownStream; + if (w.rows() > mm.window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(x.gpa, w.pending); + try l.rows.appendSlice(x.gpa, w.tokens); + for (w.positions, 0..) |pos, r| if (pos != l.base + r + 1) return error.PositionMismatch; + c.* = .{ .slot = l.slot, .p0 = l.base, .tokens = l.rows.items }; + total += l.rows.items.len; + } + if (total > round_rows) return error.RoundTooWide; + try x.m.forward(x.k, x.s, chains, false, 0, total); + var at: usize = 0; + for (windows, 0..) |w, i| { + const l = x.lanes.getPtr(w.stream).?; + try x.drawRows(l, x.m.s.logits, at, l.rows.items.len, w.positions[0], ring + at, i); + at += l.rows.items.len; + } + var got: [round_rows]u32 = undefined; + try x.s.synchronize(); + try x.tok.download(ring * 4, std.mem.sliceAsBytes(got[0..total])); + at = 0; + for (windows, out) |w, o| { + const l = x.lanes.getPtr(w.stream).?; + const n = l.rows.items.len; + @memcpy(o.sampled[0..n], got[at..][0..n]); + @memcpy(o.drafts[0 .. n - 1], l.rows.items[1..]); + l.len = l.base + n; + at += n; + } + } + + /// Every window keeps all its rows: the conv states hold no history to roll back to (no drafts are offered). + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const x = self(ptr); + for (windows, paths) |w, path| { + const l = x.lanes.getPtr(w.stream) orelse return error.UnknownStream; + if (path.len != l.rows.items.len) return error.Inkling2MiniNoRollback; + for (path, 0..) |r, i| if (r != i) return error.ChainsOnly; + } + } + + /// No draft head: absorbing is a no-op, and a request for drafts is refused by name. + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + fn dropLane(x: *Mini, s: *const Stream) void { + if (x.lanes.fetchRemove(s)) |entry| { + var l = entry.value; + x.free[l.slot] = true; + l.rows.deinit(x.gpa); + } + } + + fn release(ptr: *anyopaque, s: *Stream) void { + self(ptr).dropLane(s); + } +}; + +test "a slot holds the window in whole 1,024s; a reply past it does not fit" { + try std.testing.expectEqual(@as(usize, 32768), try capacity(32768)); + try std.testing.expectEqual(@as(usize, 1024), try capacity(1000)); + try std.testing.expectError(error.BadContext, capacity(0)); + try std.testing.expect(fits(32768, 30000, 2768)); + try std.testing.expect(!fits(32768, 30000, 2769)); + try std.testing.expect(!fits(32768, 32769, 0)); +} diff --git a/zig/src/families/inkling2/mini_host_test.zig b/zig/src/families/inkling2/mini_host_test.zig new file mode 100644 index 00000000000..d8ffcf1b147 --- /dev/null +++ b/zig/src/families/inkling2/mini_host_test.zig @@ -0,0 +1,180 @@ +//! Inkling 2 Mini (inkling2_loop) on the host: its config.json, the loop's visits and slots, the weight map against +//! the published headers (folded fixtures), each layer's expert precision and what the loop parse refuses. +const std = @import("std"); +const config = @import("config.zig"); +const names = @import("names.zig"); +const plan = @import("plan.zig"); +const st = @import("core").safetensors; +const unfold = @import("names_test.zig").unfold; + +const t = std.testing; +pub const mini = @embedFile("fixtures/mini_config.json"); +const model_fixture = @embedFile("fixtures/mini_model_header.txt"); +const mtp_fixture = @embedFile("fixtures/mini_mtp_header.txt"); + +fn parse(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + return config.parse(a, mini, &why); +} + +fn refused(from: []const u8, to: []const u8, want: anyerror, says: []const u8) !void { + if (std.mem.count(u8, mini, from) != 1) return error.EditAnchor; + const edited = try std.mem.replaceOwned(u8, t.allocator, mini, from, to); + defer t.allocator.free(edited); + var why: config.Why = .{}; + try t.expectError(want, config.parse(t.allocator, edited, &why)); + if (std.mem.indexOf(u8, why.text(), says) == null) { + std.debug.print("refusal \"{s}\" does not name \"{s}\"\n", .{ why.text(), says }); + return error.TestUnexpectedResult; + } +} + +test "Mini's config.json parses: 24 layers, a core of 6..17 three times (48 visits), rank 64, taps by visit" { + const c = try parse(t.allocator); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.local); + try t.expectEqual(@as(u32, 128), c.text.experts); + try t.expectEqual(@as(u32, 1152), c.text.expert_inter); + try t.expectEqual(@as(u32, 8192), c.text.log_floor); + try t.expectEqual(config.Loop{ .start = 6, .end = 18, .passes = 3, .rank = 64 }, c.text.loop.?); + try t.expectEqual(@as(u32, 48), c.text.visits()); + const m = c.mtp.?; + try t.expectEqual(@as(u32, 3), m.layers); + try t.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, m.taps[0..m.taps_n]); +} + +test "Mini's visits: prelude 0..5, the core three passes, coda 18..23; 40 sliding, 8 full and 48 conv slots" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + var prec: [24]plan.Precision = undefined; + try names.precisions(try unfold(a, model_fixture, "inkling2-mini-model"), 24, &prec); + const p = try plan.build(&c.text, &prec); + const v = &p.visits; + try t.expectEqual(@as(u32, 48), v.len); + try t.expectEqual(@as(u32, 40), v.count(.sliding)); + try t.expectEqual(@as(u32, 8), v.count(.full)); + try t.expectEqual(@as(u32, 48), v.count(.conv)); + try t.expectEqual(@as(u32, 1), p.pre_blocks); + try t.expectEqual(@as(u32, 1), p.bank_blocks); + for (v.slice(), 0..) |s, k| { + const want: u32 = if (k < 6) @intCast(k) else if (k < 42) 6 + @as(u32, @intCast(k - 6)) % 12 else @intCast(k - 24); + try t.expectEqual(want, s.layer); + try t.expectEqual(@as(u8, if (k < 6 or k >= 42) 0 else @intCast((k - 6) / 12)), s.pass); + try t.expectEqual(k >= 18 and k < 42, p.messages(@intCast(k))); + try t.expectEqual(k == 18 or k == 30, p.restarts(@intCast(k))); + try t.expectEqual(@as(?u16, @intCast(k)), s.of(.conv)); + } + // the taps' visits: 5 is L5 pass 0, 23 is L11 pass 1, 41 is L17 pass 2 (global slots 0, 3 and 6); 48 the output + for ([_]u32{ 5, 23, 41 }, [_]u32{ 5, 11, 17 }, [_]u16{ 0, 3, 6 }) |tap, layer, full| { + const s = v.steps[(try v.tap(tap)).input]; + try t.expectEqual(layer, s.layer); + try t.expectEqual(@as(?u16, full), s.of(.full)); + } + try t.expectEqual(@as(@TypeOf(try v.tap(48)), .output), try v.tap(48)); + try t.expectEqual(@as(u32, 5), p.coreIndex(23)); + try t.expectEqual(@as(u32, 0), p.coreIndex(3)); +} + +test "Mini's folded headers unfold to its 1244 and 54 tensors, digests equal" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + try t.expectEqual(@as(usize, 1244), (try unfold(arena.allocator(), model_fixture, "inkling2-mini-model")).count()); + try t.expectEqual(@as(usize, 54), (try unfold(arena.allocator(), mtp_fixture, "inkling2-mini-mtp")).count()); +} + +test "the map names exactly Mini's tensors: controllers, cross-pass queries, NVFP4 L0-19 and MXFP8 L20-23" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const entries = try unfold(a, model_fixture, "inkling2-mini-model"); + const r = try names.check(a, &c, entries, .model); + try t.expectEqual(@as(usize, 1244), r.expected); + try t.expect(r.clean()); + var prec: [24]plan.Precision = undefined; + try names.precisions(entries, 24, &prec); + for (prec, 0..) |p, i| try t.expectEqual(if (i < 20) plan.Precision.nvfp4 else plan.Precision.mxfp8, p); + const mtp = try names.check(a, &c, try unfold(a, mtp_fixture, "inkling2-mini-mtp"), .mtp); + try t.expectEqual(@as(usize, 54), mtp.expected); + try t.expect(mtp.clean()); +} + +test "a missing controller and a wrong cross-pass shape are reported by name" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const all = try unfold(a, model_fixture, "inkling2-mini-model"); + var kept: st.Header = .empty; + for (all.keys(), all.values()) |name, e| { + var x = e; + if (std.mem.eql(u8, name, "model.llm.layers.9.controllers.v.gain_weight")) continue; + if (std.mem.eql(u8, name, "model.llm.middle_cycle_cross_pass_kv_queries")) x.shape[0] = 12; + try kept.put(a, name, x); + } + const r = try names.check(a, &c, kept, .model); + try t.expectEqual(@as(usize, 1), r.missing.items.len); + try t.expectEqualStrings("model.llm.layers.9.controllers.v.gain_weight", r.missing.items[0]); + try t.expectEqual(@as(usize, 1), r.wrong.items.len); + try t.expectEqualStrings("model.llm.middle_cycle_cross_pass_kv_queries", r.wrong.items[0]); +} + +test "the loop parse refuses is_varloop, a core off the blocks, one pass, a wide rank and a loop on Small by name" { + try refused("\"is_varloop\": false", "\"is_varloop\": true", error.Unsupported, "is_varloop must be false"); + try refused("\"core_end\": 18", "\"core_end\": 17", error.Layout, "not whole blocks of 6"); + try refused("\"core_end\": 18", "\"core_end\": 30", error.Layout, "not whole blocks of 6"); + try refused("\"num_passes\": 3", "\"num_passes\": 1", error.Layout, "at least 2"); + try refused("\"gate_rank\": 64", "\"gate_rank\": 129", error.Layout, "gate_rank 129 at most 128"); + try refused("\"num_passes\": 3", "\"num_passes\": 40", error.Layout, "the plan tables hold 256"); + try refused("\"loop_config\"", "\"loop_cfg\"", error.BadConfig, "no loop_config"); + try refused("\"attn_res_normalize_values\": true", "\"attn_res_normalize_values\": false", error.Unsupported, "attn_res_normalize_values"); + try refused("\"model_type\": \"inkling2_loop\"", "\"model_type\": \"inkling2\"", error.NotInkling2, "inkling2_loop"); + try refused("23,\n 41,", "41,\n 23,", error.Layout, "must rise"); + try refused("23,\n 41,", "23,\n 49,", error.Layout, "a layer the backbone does not have"); +} + +test "Small with a loop_config is refused: the loop needs model_type inkling2_loop" { + const tiny = @import("config_test.zig").tiny; + const from = "\"n_layers_per_attn_res_block\": 6,"; + const to = from ++ " \"loop_config\": {\"core_start\": 6, \"core_end\": 12, \"num_passes\": 2, \"gate_rank\": 8},"; + const edited = try std.mem.replaceOwned(u8, t.allocator, tiny, from, to); + defer t.allocator.free(edited); + var why: config.Why = .{}; + try t.expectError(error.Unsupported, config.parse(t.allocator, edited, &why)); + try t.expectEqualStrings("loop_config needs model_type inkling2_loop", why.text()); +} + +test "Mini's quantization_config goes through core.modelopt: NVFP4 without config_groups, FP8 refused" { + try refused("\"quant_algo\": \"NVFP4\"", "\"quant_algo\": \"FP8\"", error.Quant, "ModelOpt FP8"); + try refused("\"quant_method\": \"modelopt\"", "\"quant_method\": \"awq\"", error.Quant, "no ModelOpt quantization_config"); +} + +/// A file's header read from disk (the shard holds data too; only the header is read). +fn headerOf(a: std.mem.Allocator, dir: []const u8, file: []const u8) !st.Header { + const path = try std.fmt.allocPrint(a, "{s}/{s}", .{ dir, file }); + const f = try std.Io.Dir.cwd().openFile(t.io, path, .{}); + defer f.close(t.io); + var prefix: [8]u8 = undefined; + if (try f.readPositionalAll(t.io, &prefix, 0) != 8) return error.BadSafetensors; + const size = std.math.cast(usize, try f.length(t.io)) orelse return error.BadSafetensors; + const json = try a.alloc(u8, try st.headerSize(std.mem.readInt(u64, &prefix, .little), size)); + if (try f.readPositionalAll(t.io, json, 8) != json.len) return error.BadSafetensors; + return st.parseHeader(a, json, std.math.maxInt(usize)); +} + +test "the released Mini's model and mtp headers and config match the map (TF_INKLING2_MINI=)" { + const dir = std.mem.span(std.c.getenv("TF_INKLING2_MINI") orelse return error.SkipZigTest); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const model = try names.check(a, &c, try headerOf(a, dir, "model-00001-of-00001.safetensors"), .model); + try t.expectEqual(@as(usize, 1244), model.expected); + try t.expect(model.clean()); + const mtp = try names.check(a, &c, try headerOf(a, dir, "mtp.safetensors"), .mtp); + try t.expect(mtp.clean()); +} diff --git a/zig/src/families/inkling2/mini_model.zig b/zig/src/families/inkling2/mini_model.zig new file mode 100644 index 00000000000..e9a88cdaae6 --- /dev/null +++ b/zig/src/families/inkling2/mini_model.zig @@ -0,0 +1,374 @@ +//! Inkling 2 Mini's forward on one GPU over cache slots: 48 visit slots a stream (40 sliding rings, 8 whole caches, +//! 48 conv states), prompt chunks of one stream and decode rows of many, embedding to soft-capped logits. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const wts = @import("mini_weights.zig"); +const attn = @import("kernels.zig"); +const ops = @import("ops.zig"); +const loop = @import("loop.zig"); +const visit = @import("mini_visit.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; + +/// Prompt rows a forward takes at most: one stream's chunk. +pub const prompt_rows = 512; +/// Decode rows a forward takes over every stream. +pub const round_rows = 64; +/// The widest window one stream verifies in a decode forward. +pub const window_rows = 16; +/// Conv sites a visit keeps state for: the key and value convs, after attention, after the MLP. +pub const Site = enum { k, v, attn, mlp }; + +/// A stream's rows in one forward: its cache slot, first position and tokens. +pub const Chain = struct { slot: usize, p0: usize, tokens: []const u32 }; + +pub const Kernels = struct { + attn: attn.Kernels, + ops: ops.Kernels, + loop: loop.Kernels, + lane: cuda.qmmf.Lane, + dense: cuda.dense_rows.DenseRows, + nv: cuda.experts.Nvfp4Experts, + mx: cuda.experts_mx.Mxfp8Experts, + glue: cuda.moe_glue.MoeGlue, + plan_mod: cuda.Module, + router: cuda.grouped.Router, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const d = ctx.d; + var k: Kernels = undefined; + k.attn = try attn.Kernels.load(d); + errdefer k.attn.unload(); + k.ops = try ops.Kernels.load(d); + errdefer k.ops.unload(); + k.loop = try loop.Kernels.load(d); + errdefer k.loop.unload(); + k.lane = try cuda.qmmf.Lane.load(d, (try ctx.capability()) / 10); + errdefer k.lane.unload(); + k.dense = try cuda.dense_rows.DenseRows.load(d); + errdefer k.dense.unload(); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + k.nv = try cuda.experts.Nvfp4Experts.load(d, sms); + errdefer k.nv.unload(); + k.mx = try cuda.experts_mx.Mxfp8Experts.load(d, sms); + errdefer k.mx.unload(); + k.glue = try cuda.moe_glue.MoeGlue.load(d); + errdefer k.glue.unload(); + k.plan_mod = try cuda.Module.load(d, cuda.kernels.experts); + errdefer k.plan_mod.unload(); + k.router = try cuda.grouped.Router.resolve(k.plan_mod); + return k; + } + + pub fn deinit(k: *Kernels) void { + k.plan_mod.unload(); + k.glue.unload(); + k.mx.unload(); + k.nv.unload(); + k.dense.unload(); + k.lane.unload(); + k.loop.unload(); + k.ops.unload(); + k.attn.unload(); + } + + pub fn experts(k: *const Kernels) cuda.experts.Grouped { + return .{ .nvfp4 = &k.nv, .mxfp8 = &k.mx }; + } +}; + +/// The forward's device scratch, sized for `prompt_rows` rows (decode rounds use the first `round_rows`). +pub const Scratch = struct { + ids: u64, // int32 [R] + pos: u64, // int32 [R] + seg_of: u64, // int32 [R]: the row's stream in the call + segs: [2]u64, // attention Seg [streams]: sliding, then full caches (offsets differ by cache length) + conv_segs: u64, // int4 [streams]: row0, rows, slot + tiles: u64, // attention Tile [max tiles] + h: [2]u64, // bf16 [R, H]: the running state in, the next visit's out + blocks: u64, // bf16 [max blocks][R, H] + bank: u64, // bf16 [bank blocks][R, H]: the previous pass's blocks past its entry + bank_h: u64, // bf16 [R, H]: the previous pass's output + msg: u64, // fp32 [4][R, H] + mixf: u64, // fp32 [3][R, H] + gdown: u64, // bf16 [3][R][rank] + xin: u64, // bf16 [3][R, H] + q: u64, + kraw: u64, + vraw: u64, + rel: u64, + gate: u64, + sink: u64, + gys: u64, // fp32 [3][rows, H]: the gates' rows before their norm + fused: u64, // a one-row forward's fused projections, Fused.all bf16 columns (q, gate, rel, sink, k, v) + dyn: [2]u64, // fp32 [R, kv * 4] + kc: u64, + vc: u64, + qp: u64, + relp: u64, + tab: u64, + part_o: u64, + part_ml: u64, + att: u64, + o: u64, + h32: u64, // fp32 [R, H] + xm: u64, + scores: u64, + pick: u64, + rw: u64, + plan: cuda.grouped.Plan, + act: u64, + y: u64, + moe: u64, + xf: u64, + logits: u64, // fp32 [round_rows, unpadded vocab] + lane_part: u64, + entries: usize, // (row, head, partial) slots part_o and part_ml hold +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *const wts.Weights, + c: *const config.Text, + context: usize, // positions a slot holds + slots: usize, + sliding: attn.Layer, + full: attn.Layer, + kv: [2][config.max_visits]u64 = undefined, // a visit's K and V: [slots][kv][len][128] bf16 + conv: [config.max_visits][4]u64 = undefined, // a visit's conv states: fp32 [slots][3][C] by Site + s: Scratch = undefined, + buffers: std.ArrayList(DeviceBuffer) = .empty, + planned: ?usize = null, // a plan: the bytes counted, nothing allocated + /// Decode forwards of n one-row windows as CUDA graphs, captured at first use ([n]); TF_INKLING2_GRAPHS=0: off. + graphs: [round_rows + 1]?cuda.graph.Exec = @splat(null), + graphed: bool = true, + + fn alloc(m: *Model, bytes: usize) !u64 { + if (m.planned) |*p| { + p.* += std.mem.alignForward(usize, @max(bytes, 256), 256); + return 0; + } + var b = try DeviceBuffer.alloc(m.d, @max(bytes, 256)); + errdefer b.free(); + try m.buffers.append(m.gpa, b); + return b.ptr; + } + + fn zeros(m: *Model, s: cuda.Stream, bytes: usize) !u64 { + const p = try m.alloc(bytes); + if (m.planned == null) try m.d.check(m.d.api.cuMemsetD8Async(p, 0, bytes, s.handle), "cuMemsetD8Async"); + return p; + } + + fn blank(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const wts.Weights, context: usize, slots: usize) Model { + return .{ + .gpa = gpa, + .d = d, + .w = w, + .c = &w.config.text, + .context = context, + .slots = slots, + .sliding = attn.Layer.sliding(w.config.text.window, prompt_rows), + .full = attn.Layer.global(@intCast(context)), + }; + } + + /// The caches and scratch of `slots` streams at `context` positions. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize) !Model { + var m = blank(gpa, d, w, context, slots); + errdefer m.deinit(); + try m.build(s, k); + try s.synchronize(); + return m; + } + + /// The device bytes init would allocate. + pub fn openBytes(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize) !usize { + var m = blank(gpa, d, w, context, slots); + m.planned = 0; + try m.build(s, k); + return m.planned.?; + } + + /// One stream's caches: 40 sliding rings, 8 whole caches and 48 conv states (Mini). + pub fn streamBytes(m: *const Model) usize { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + const v = &m.w.plan.visits; + const caches = v.count(.sliding) * m.sliding.ring + v.count(.full) * m.full.ring; + return caches * kvw * 2 * 2 + v.count(.conv) * 3 * (2 * kvw + 2 * @as(usize, t.hidden)) * 4; + } + + pub fn deinit(m: *Model) void { + for (&m.graphs) |*g| if (g.*) |*e| { + e.deinit(); + g.* = null; + }; + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + } + + fn build(m: *Model, s: cuda.Stream, k: *const Kernels) !void { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + for (m.w.plan.visits.slice(), 0..) |step, i| { + const len: usize = if (step.of(.full) != null) m.full.ring else m.sliding.ring; + for (0..2) |side| m.kv[side][i] = try m.alloc(m.slots * len * kvw * 2); + for (std.enums.values(Site)) |site| { + const width: usize = if (site == .k or site == .v) kvw else t.hidden; + m.conv[i][@intFromEnum(site)] = try m.zeros(s, m.slots * 3 * width * 4); + } + } + try m.scratch(k); + } + + fn scratch(m: *Model, k: *const Kernels) !void { + const t = m.c; + const r: usize = prompt_rows; + const h: usize = t.hidden; + const q: usize = @as(usize, t.local.q) * t.local.dim; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + const heads: usize = t.local.q; + const rank: usize = t.loop.?.rank; + const pairs = r * t.topk; + const blocks = (t.layers + t.block - 1) / t.block; + // partials: every prompt row's sliding or full chunks, or a split decode call's sub-chunks + const stride_full = attn.slotsFor(m.full, m.context); + const entries = @max(r * heads * @max(attn.slotsFor(m.sliding, m.context), stride_full), attn.split_rows * heads * stride_full * attn.subs); + var part: usize = 0; + for (m.w.layers) |l| for ([_]cuda.qmmf.Weight{ l.attn.qx, l.attn.all }) |w| { + part = @max(part, k.lane.partBytes(1, w)); + }; + for (m.w.layers) |l| for ([_]cuda.qmmf.Weight{ l.attn.wq, l.attn.wk, l.attn.wv, l.attn.wr, l.attn.gate, l.attn.sink, l.attn.wo }) |w| { + for (1..r + 1) |rows| part = @max(part, k.lane.partBytes(rows, w)); + }; + for (1..round_rows + 1) |rows| part = @max(part, k.lane.partBytes(rows, m.w.unembed)); + const items = cuda.grouped.maxItems(pairs, t.experts, 64); + m.s = .{ + .ids = try m.alloc(r * 4), + .pos = try m.alloc(r * 4), + .seg_of = try m.alloc(r * 4), + .segs = .{ try m.alloc(round_rows * @sizeOf(attn.Seg)), try m.alloc(round_rows * @sizeOf(attn.Seg)) }, + .conv_segs = try m.alloc(round_rows * 16), + .tiles = try m.alloc((attn.tileCount(r, 3) + round_rows) * @sizeOf(attn.Tile)), + .h = .{ try m.alloc(r * h * 2), try m.alloc(r * h * 2) }, + .blocks = try m.alloc(blocks * r * h * 2), + .bank = try m.alloc(@max(1, m.w.plan.bank_blocks) * r * h * 2), + .bank_h = try m.alloc(r * h * 2), + .msg = try m.alloc(4 * r * h * 4), + .mixf = try m.alloc(3 * r * h * 4), + .gdown = try m.alloc(3 * r * rank * 2), + .xin = try m.alloc(3 * r * h * 2), + .q = try m.alloc(r * q * 2), + .kraw = try m.alloc(r * kvw * 2), + .vraw = try m.alloc(r * kvw * 2), + .rel = try m.alloc(r * heads * t.d_rel * 2), + .gate = try m.alloc(r * q * 2), + .sink = try m.alloc(r * heads * 2), + .gys = try m.alloc(3 * r * h * 4), + .fused = try m.alloc(wts.Fused.of(t).all * 2), + .dyn = .{ try m.alloc(r * t.global.kv * config.conv_taps * 4), try m.alloc(r * t.global.kv * config.conv_taps * 4) }, + .kc = try m.alloc(r * kvw * 2), + .vc = try m.alloc(r * kvw * 2), + .qp = try m.alloc(r * q * 2), + .relp = try m.alloc(r * heads * t.d_rel * 2), + .tab = try m.alloc(attn.tableBytes(r, @intCast(heads))), + .part_o = try m.alloc(entries * attn.head_dim * 4), + .part_ml = try m.alloc(entries * 8), + .att = try m.alloc(r * q * 2), + .o = try m.alloc(r * h * 2), + .h32 = try m.alloc(r * h * 4), + .xm = try m.alloc(r * h * 2), + .scores = try m.alloc(r * t.experts * 4), + .pick = try m.alloc(pairs * 4), + .rw = try m.alloc(pairs * 4), + .plan = .{ + .members = try m.alloc(pairs * 4), + .items = try m.alloc(items * 12), + .counts = try m.alloc(8), + .rank = try m.alloc(pairs * 4), + .hist = try m.alloc(((pairs + 1023) / 1024) * t.experts * 4), + }, + .act = try m.alloc(pairs * t.expert_inter * 2), + .y = try m.alloc(pairs * h * 4), + .moe = try m.alloc(r * h * 2), + .xf = try m.alloc(r * h * 2), + .logits = try m.alloc(round_rows * t.unpadded_vocab * 4), + .lane_part = try m.alloc(part), + .entries = entries, + }; + } + + pub fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(m.d, dst, bytes, s); + } + + pub fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } + + /// A slot's conv states to zero: a stream starting at position 0 has no inputs before it. + pub fn clear(m: *Model, s: cuda.Stream, slot: usize) !void { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + for (0..m.w.plan.visits.len) |v| for (std.enums.values(Site)) |site| { + const width: usize = if (site == .k or site == .v) kvw else t.hidden; + const at = m.conv[v][@intFromEnum(site)] + slot * 3 * width * 4; + try m.d.check(m.d.api.cuMemsetD8Async(at, 0, 3 * width * 4, s.handle), "cuMemsetD8Async"); + }; + } + + /// Every chain's rows (one prompt chunk, or decode windows); rows [head0, head0 + heads)'s fp32 logits at s.logits. + pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, chains: []const Chain, prompt: bool, head0: usize, heads: usize) !void { + var rows: usize = 0; + for (chains, 0..) |ch, i| { + if (ch.tokens.len == 0 or ch.slot >= m.slots or ch.p0 + ch.tokens.len > m.context) return error.BadChain; + if (!prompt and ch.tokens.len > window_rows) return error.WindowTooWide; + for (chains[0..i]) |o| if (o.slot == ch.slot) return error.BadChain; + for (ch.tokens) |id| if (id >= m.c.vocab) return error.InvalidToken; + rows += ch.tokens.len; + } + if (rows == 0 or rows > @as(usize, if (prompt) prompt_rows else round_rows) or (prompt and chains.len != 1)) return error.TooManyRows; + if (chains.len > round_rows or heads > round_rows or head0 + heads > rows) return error.TooManyRows; + for (chains) |ch| if (ch.p0 == 0) try m.clear(s, ch.slot); + var r = try visit.Rows.stage(m, s, chains, rows, prompt); + // one row a stream, every row's logits: the launches depend on the row count alone (the rest is on the device) + if (prompt or !m.graphed or head0 != 0 or heads != rows or r.streams != rows or r.n_tiles != rows) + return visit.run(m, k, s, &r, head0, heads); + const g = &m.graphs[rows]; + if (g.* == null) g.* = try m.capture(k, s, &r); + try g.*.?.launchOn(s); + } + + /// A decode forward of `r.n` one-row windows, captured as a graph. + fn capture(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const visit.Rows) !cuda.graph.Exec { + try s.synchronize(); + try cuda.graph.beginCapture(s, .thread_local); + visit.run(m, k, s, r, 0, r.n) catch |e| { + if (cuda.graph.endCapture(s)) |g| { + var gg = g; + gg.deinit(); + } else |_| {} + return e; + }; + var g = try cuda.graph.endCapture(s); + defer g.deinit(); + return g.instantiate(); + } +}; + +test "the forward's launches type-check against the shared operators" { + std.testing.refAllDecls(Model); + std.testing.refAllDecls(Kernels); +} + +test "the forward refuses token id vocab before any launch" { + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, @embedFile("fixtures/mini_config.json"), &why); + // no driver, weights or caches: a launch before the check would fault + var m: Model = .{ .gpa = std.testing.allocator, .d = undefined, .w = undefined, .c = &c.text, .context = 64, .slots = 1, .sliding = undefined, .full = undefined }; + const bad = [_]u32{ 1, c.text.vocab }; + try std.testing.expectError(error.InvalidToken, m.forward(undefined, undefined, &.{.{ .slot = 0, .p0 = 0, .tokens = &bad }}, true, 0, 1)); +} diff --git a/zig/src/families/inkling2/mini_native.zig b/zig/src/families/inkling2/mini_native.zig new file mode 100644 index 00000000000..7e2b8bb04e4 --- /dev/null +++ b/zig/src/families/inkling2/mini_native.zig @@ -0,0 +1,220 @@ +//! Inkling 2 Mini (inkling2_loop) behind the native CUDA registry (native/cuda.zig): one rank, text only, plain +//! decode. Images (C6), a drafter (C5) and --loops are refused by name before any weight is read. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const wts = @import("mini_weights.zig"); +const mm = @import("mini_model.zig"); +const be = @import("mini_backend.zig"); +const snap = @import("mini_snap.zig"); + +pub const model_type = "inkling2_loop"; +pub const formats: []const []const u8 = &.{"modelopt-nvfp4"}; +pub const default_context: i64 = 32768; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = be.prompt_rows; +pub const takes_drafter = false; +pub const drafter_refusal = "--drafter: Inkling 2 Mini on CUDA serves plain decode so far; its DSpark drafter is the next slice (C5)"; +pub const explains_open = true; +/// A kept state is the caches and conv states through its position, nothing past it (no draft head reads on). +pub const snap_lookahead: u32 = 0; + +/// The server's reading of the room left after the weights; null if unreadable. +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +/// `loops` is here to refuse it by name: the pass count is the checkpoint's loop_config. +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 4, lanes_fixed: bool = false, room: ?Room = null, loops: ?u32 = null }; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + target: *be.Mini, +}; + +const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: mm.Kernels, x: be.Draws, s: cuda.Stream, m: mm.Model, b: be.Mini }; + +/// Streams to allocate in `room`: as asked, else (auto) the most that fit; a fixed count past them refuses. +fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { + const most = be.round_rows; + if (fixed and asked > most) return error.ParallelPastRound; + var n = std.math.clamp(@as(usize, asked), 1, most); + while (try plan.bytes(n) > room) : (n -= 1) { + if (fixed) return error.ParallelPastMemory; + if (n == 1) return error.NoStreamFits; + } + return n; +} + +const Plan = struct { + own: *const Owned, + d: *const cuda.Driver, + context: usize, + + fn bytes(p: Plan, n: usize) !u64 { + const o = p.own; + return try mm.Model.openBytes(o.gpa, p.d, o.s, &o.w, &o.k, p.context, n) + be.Mini.openBytes(o.w.config.text.unpadded_vocab, n); + } +}; + +/// What open refuses before any weight is read: --loops and captured kernels (--drafter: the host, drafter_refusal). +/// `drafts` is the server's default on: with no head it drafts nothing (facts: mtp and copies off). +fn refuse(kernels: ?[]const u8, o: Options) !void { + if (o.loops != null) return error.Inkling2MiniLoopsFixed; + if (kernels != null) return error.CapturedKernels; + if (o.lanes_fixed and o.lanes > be.round_rows) return error.ParallelPastRound; +} + +/// The checkpoint, the kernels and every stream's caches. +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + try refuse(kernels, o); + const context = try be.capacity(o.context); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.gpa = gpa; + own.w = try wts.load(gpa, io, ctx.d, dir); + errdefer own.w.deinit(); + if (context > own.w.config.text.max_context) return error.PastContext; + own.k = try mm.Kernels.load(ctx); + errdefer own.k.deinit(); + own.x = try be.Draws.load(ctx.d); + errdefer own.x.deinit(); + own.s = try cuda.Stream.init(ctx.d, false); + errdefer own.s.deinit(); + const plan: Plan = .{ .own = own, .d = ctx.d, .context = context }; + const room: u64 = if (o.room) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); + const n = fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { + if (e == error.ParallelPastMemory) { + const most = fit(room, o.lanes, false, plan) catch 0; + std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token window, and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ o.lanes, gib(try plan.bytes(o.lanes)), context, gib(room), most, if (most == 1) "" else "s" }); + } + return e; + }; + own.m = try mm.Model.init(gpa, ctx.d, own.s, &own.w, &own.k, context, n); + errdefer own.m.deinit(); + own.b = try be.Mini.init(gpa, ctx.d, &own.m, &own.k, &own.x, own.s, own.w.config.image_token); + std.log.info("Inkling 2 Mini: {d} visits a token ({d} sliding, {d} full, {d} conv slots a stream), {d} streams of {d} positions, {d:.2} GiB of weights", .{ own.w.plan.visits.len, own.w.plan.visits.count(.sliding), own.w.plan.visits.count(.full), own.w.plan.visits.count(.conv), n, context, gib(own.w.bytes) }); + return .{ + .backend = own.b.backend(), + .facts = own.b.facts(), + .rows = 1, + .stream_bytes = own.m.streamBytes(), + .free_streams = @intCast(n), + .ctx = own, + .deinit = release, + .target = &own.b, + }; +} + +fn mini(ptr: *anyopaque) *be.Mini { + return @ptrCast(@alignCast(ptr)); +} + +/// Bytes a state at `at` prompt tokens takes. +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return snap.bytes(mini(ptr).m, at); +} + +/// The prompt pass stands at `at` (a chunk start or a mark): copy the stream's state there. +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try mini(ptr).saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return mini(ptr).restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + mini(ptr).dropState(@ptrCast(@alignCast(saved))); +} + +/// Whether a request's caches could start now (the lane host's admission, on its engine thread). +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const own: *const Owned = @ptrCast(@alignCast(p)); + return own.b.admits(prompt, max_tokens); +} + +fn gib(b: u64) f64 { + return @as(f64, @floatFromInt(b)) / (1 << 30); +} + +/// A request or load this engine refuses, in words; null: none of its own. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2MiniLoopsFixed => "--loops: Inkling 2 Mini runs the passes its loop_config names (3 over layers 6 to 17); serve without --loops", + error.Inkling2MiniImages => "images: Inkling 2 Mini on CUDA reads text only until its vision slice (C6) lands; send text parts only", + error.Inkling2MiniNoRollback => "Inkling 2 Mini on CUDA keeps every verified row (no drafts are offered to roll back)", + error.Inkling2NotLooped => "Inkling 2 Small (model_type inkling2) has no CUDA engine yet: this one serves inkling2_loop", + error.Inkling2WeightMap => "the checkpoint's tensors differ from what its config.json implies (the log names each one)", + error.Inkling2Nvfp4Denominator => "an NVFP4 expert's outer_scale_denominator is not 2688, the one the checkpoint's factors are checked against", + error.PastContext => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", + error.NoFreeSlot => "every stream's caches are in use: retry once another request ends", + error.NoDraftHead => "Inkling 2 Mini on CUDA has no drafter yet (C5): serve without --drafter or drafts", + error.StructuresUnsupported => "structured output is not built for Inkling 2 Mini on CUDA yet", + error.CapturedKernels => "Inkling 2 Mini runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.BuiltWithoutKernels => "this build carries no CUDA kernel images: build with -Dnvcc", + error.ParallelPastRound => std.fmt.comptimePrint("--parallel: Inkling 2 Mini on CUDA holds at most {d} streams (a round's rows)", .{be.round_rows}), + error.ParallelPastMemory => "--parallel: the CUDA memory budget fits fewer Inkling 2 Mini streams than asked (each stream's 48 visit slots are allocated at load): lower --parallel or --context, or serve --parallel auto", + error.NoStreamFits => "the CUDA memory budget fits no Inkling 2 Mini stream after the weights: lower --context or free device memory", + else => null, + }; +} + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.b.deinit(); + own.m.deinit(); + own.s.deinit(); + own.x.deinit(); + own.k.deinit(); + own.w.deinit(); + own.gpa.destroy(own); +} + +test "Inkling 2 Mini open: --loops and captured kernels are refused by name before any load" { + const base: Options = .{ .context = 4096, .drafts = false }; + try refuse(null, base); + var o = base; + o.loops = 3; + try std.testing.expectError(error.Inkling2MiniLoopsFixed, refuse(null, o)); + o = base; + o.drafts = true; // the server's default: nothing to draft with, not a refusal + try refuse(null, o); + try std.testing.expectError(error.CapturedKernels, refuse("dir", base)); + // open refuses before it allocates: a failing allocator sees no request + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + var d: cuda.Driver = undefined; + const ctx: cuda.Context = .{ .d = &d, .handle = undefined, .device = 0 }; + o = base; + o.loops = 2; + try std.testing.expectError(error.Inkling2MiniLoopsFixed, open(failing.allocator(), std.testing.io, &ctx, "/nonexistent", null, o)); + try std.testing.expectEqual(@as(usize, 0), failing.allocations); +} + +test "every refusal of its own is worded, the rest left to the server" { + for ([_]anyerror{ error.Inkling2MiniLoopsFixed, error.Inkling2MiniImages, error.Inkling2MiniNoRollback, error.Inkling2NotLooped, error.Inkling2WeightMap, error.Inkling2Nvfp4Denominator, error.PastContext, error.NoFreeSlot, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.ParallelPastRound, error.ParallelPastMemory, error.NoStreamFits }) |e| { + try std.testing.expect(explain(null, e) != null); + } + try std.testing.expect(explain(null, error.OutOfMemory) == null); +} + +/// A synthetic plan: `stream` bytes a stream plus `fixed` bytes of scratch. +const Fake = struct { + stream: u64, + fixed: u64, + fn bytes(f: Fake, n: usize) !u64 { + return f.fixed + n * f.stream; + } +}; + +test "the streams allocated at open fit the room: auto takes what fits, a fixed count refuses" { + const g: u64 = 1 << 30; + const one: Fake = .{ .stream = g, .fixed = 0 }; + try std.testing.expectEqual(@as(usize, 2), try fit(2 * g, 8, false, one)); + try std.testing.expectError(error.ParallelPastMemory, fit(2 * g, 8, true, one)); + try std.testing.expectError(error.NoStreamFits, fit(g - 1, 8, false, one)); + try std.testing.expectError(error.ParallelPastRound, fit(1024 * g, 65, true, one)); +} diff --git a/zig/src/families/inkling2/mini_ref.zig b/zig/src/families/inkling2/mini_ref.zig new file mode 100644 index 00000000000..8a9038fc4e8 --- /dev/null +++ b/zig/src/families/inkling2/mini_ref.zig @@ -0,0 +1,500 @@ +//! Inkling 2 Mini's forward in float64 on the host over a whole token sequence: the reference the CUDA engine's greedy +//! tokens are checked against (teacher-forced: each position's argmax and its margin). No intermediate rounding; the +//! stored weights decoded exactly (NVFP4 factor as experts_mx.nvfp4Factor). Slow: tiny checkpoint, short runs. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const names = @import("names.zig"); + +const Tensor = core.checkpoint.Tensor; +const Checkpoint = core.checkpoint.Checkpoint; + +/// Each position's top token, its margin over the runner-up and the top logit (soft-capped). +/// Its five best ids and logits, best first (ties: the lower id), for cross-engine comparisons. +pub const Pick = struct { id: u32, margin: f64, top: f64, ids: [5]u32 = @splat(0), logits: [5]f64 = @splat(-std.math.inf(f64)) }; + +const e4m3_table = blk: { + @setEvalBranchQuota(100000); + var t: [256]f64 = undefined; + for (0..256) |i| t[i] = core.expert_decode.e4m3(@intCast(i)); + break :blk t; +}; + +fn bf(bytes: []const u8, i: usize) f64 { + const u: u32 = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + return @as(f32, @bitCast(u << 16)); +} + +fn f32At(bytes: []const u8, i: usize) f64 { + return std.mem.bytesToValue(f32, bytes[4 * i ..][0..4]); +} + +fn dotBf(w: []const u8, row: usize, k: usize, x: []const f64) f64 { + var s: f64 = 0; + const base = row * k; + for (0..k) |i| s += bf(w, base + i) * x[i]; + return s; +} + +/// y[n] = W[n, k] (bf16) x. +fn matvec(w: Tensor, x: []const f64, y: []f64) void { + const k = x.len; + for (y, 0..) |*o, j| o.* = dotBf(w.bytes, j, k, x); +} + +fn rmsInv(x: []const f64, eps: f64) f64 { + var s: f64 = 0; + for (x) |v| s += v * v; + return 1.0 / @sqrt(s / @as(f64, @floatFromInt(x.len)) + eps); +} + +fn sigmoid(x: f64) f64 { + return 1.0 / (1.0 + @exp(-x)); +} + +/// x rounded to bf16 (via f32, nearest-even), back in f64. +fn bf16Round(x: f64) f64 { + const u: u32 = @bitCast(@as(f32, @floatCast(x))); + const r = (u + 0x7fff + ((u >> 16) & 1)) & 0xffff0000; + return @as(f32, @bitCast(r)); +} + +fn mat2(a: std.mem.Allocator, n: usize, w: usize) ![][]f64 { + const x = try a.alloc([]f64, n); + for (x) |*row| row.* = try a.alloc(f64, w); + return x; +} + +/// x * scale (bf16 [.], from `at`), clipped to L2 norm `thr`, times tau. +fn clipScaled(x: []f64, scale: ?[]const u8, at: usize, thr: f64, tau: f64) void { + if (scale) |sb| for (x, 0..) |*v, i| { + v.* *= bf(sb, at + i); + }; + var s: f64 = 0; + for (x) |v| s += v * v; + const f = @min(thr / (@sqrt(s) + 1e-6), 1); + for (x) |*v| v.* *= f * tau; +} + +/// A causal short conv over positions, in place: static [C][4] taps (oldest first, the newest times x) over +/// sqrt(5), or with `dyn` ([n][heads * 4] input-dependent taps) the static_w [4][C] form over 3; a residual x each. +fn convTime(x: [][]f64, w: Tensor, dyn: ?[][]f64, heads: usize) !void { + const n = x.len; + if (n == 0) return; + const c = x[0].len; + var prev: [3][]f64 = undefined; + var buf: [3][8192]f64 = undefined; + if (c > 8192) return error.Inkling2RefWidth; + for (0..3) |k| { + prev[k] = buf[k][0..c]; + @memset(prev[k], 0); + } + for (0..n) |t| { + const cur = x[t]; + for (0..c) |ch| { + const h0 = prev[0][ch]; + const h1 = prev[1][ch]; + const h2 = prev[2][ch]; + const xi = cur[ch]; + var y: f64 = undefined; + if (dyn) |d| { + const hd = ch / (c / heads); + const dd = d[t][hd * 4 ..][0..4]; + y = (bf(w.bytes, ch) + dd[0]) * xi + (bf(w.bytes, c + ch) + dd[1]) * h2 + (bf(w.bytes, 2 * c + ch) + dd[2]) * h1 + (bf(w.bytes, 3 * c + ch) + dd[3]) * h0; + y = (y + xi) / 3.0; + } else { + y = bf(w.bytes, ch * 4) * h0 + bf(w.bytes, ch * 4 + 1) * h1 + bf(w.bytes, ch * 4 + 2) * h2 + bf(w.bytes, ch * 4 + 3) * xi; + y = (y + xi) / @sqrt(5.0); + } + prev[0][ch] = h1; + prev[1][ch] = h2; + prev[2][ch] = xi; + cur[ch] = y; + } + } +} + +/// Row `row` of one expert's stored matrix (k inputs) dotted with x: NVFP4 codes x E4M3 block scales, or MXFP8. +fn expertDot(nv: bool, codes: []const u8, scales: []const u8, k: usize, row: usize, x: []const f64) f64 { + var s: f64 = 0; + if (nv) { + const cr = codes[row * (k / 2) ..][0 .. k / 2]; + const sr = scales[row * (k / 16) ..][0 .. k / 16]; + for (0..k) |i| s += core.expert_decode.e2m1(core.expert_decode.nibble(cr, i)) * e4m3_table[sr[i / 16]] * x[i]; + } else { + const cr = codes[row * k ..][0..k]; + const sr = scales[row * (k / 32) ..][0 .. k / 32]; + for (0..k) |i| s += e4m3_table[cr[i]] * core.expert_decode.e8m0(sr[i / 32]) * x[i]; + } + return s; +} + +pub const Ref = struct { + gpa: std.mem.Allocator, + c: config.Config, + p: plan_.Plan, + ck: *Checkpoint, + round_caps: bool = false, // gate and up rounded to bf16 before the soft caps (the experts' round_caps A/B) + plant: bool = false, // a planted control: the cross-pass messages dropped (the check must then go red) + + fn get(r: *Ref, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [128]u8 = undefined; + return r.ck.get(try std.fmt.bufPrint(&buf, fmt, args)); + } + + /// The residual mix of `query` (fp32 rows) over sources (blocks then the partial) at one position, no norm. + fn mixOne(h: usize, sources: []const []const f64, query: []const u8, qrow: usize, out: []f64) void { + var w: [16]f64 = undefined; + var inv: [16]f64 = undefined; + var m: f64 = -std.math.inf(f64); + for (sources, 0..) |s, j| { + inv[j] = rmsInv(s, 1e-6); + var d: f64 = 0; + for (0..h) |i| d += f32At(query, qrow * h + i) * s[i]; + w[j] = d * inv[j] / @sqrt(@as(f64, @floatFromInt(h))); + m = @max(m, w[j]); + } + var l: f64 = 0; + for (sources, 0..) |_, j| { + w[j] = @exp(w[j] - m); + l += w[j]; + } + @memset(out, 0); + for (sources, 0..) |s, j| for (0..h) |i| { + out[i] += w[j] / l * inv[j] * s[i]; + }; + } + + fn normInto(x: []f64, gamma: Tensor, eps: f64) void { + const r = rmsInv(x, eps); + for (x, 0..) |*v, i| v.* = v.* * r * bf(gamma.bytes, i); + } + + /// A gate: (1 - tanh(Wf d)) h + tanh(Wg d) m with d = Wdown [unit(h), unit(m)], then normed by `gamma`. + fn gate(r: *Ref, h: []const f64, msg: []const f64, ctl_layer: u32, comptime name: []const u8, gamma: Tensor, out: []f64) !void { + const hd = h.len; + const rank: usize = r.c.text.loop.?.rank; + const eps: f64 = r.c.text.eps; + const down = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".down_weight", .{ctl_layer}); + const forget = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".forget_weight", .{ctl_layer}); + const gain = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".gain_weight", .{ctl_layer}); + const cat = try r.gpa.alloc(f64, 2 * hd); + defer r.gpa.free(cat); + const ih = rmsInv(h, eps); + const im = rmsInv(msg, eps); + for (0..hd) |i| { + cat[i] = h[i] * ih; + cat[hd + i] = msg[i] * im; + } + var d: [config.max_gate_rank]f64 = undefined; + for (0..rank) |j| d[j] = dotBf(down.bytes, j, 2 * hd, cat); + for (0..hd) |i| { + const f = dotBf(forget.bytes, i, rank, d[0..rank]); + const g = dotBf(gain.bytes, i, rank, d[0..rank]); + out[i] = (1 - std.math.tanh(f)) * h[i] + std.math.tanh(g) * msg[i]; + } + normInto(out, gamma, eps); + } + + /// Teacher-forced picks of every position of `ids` (`out.len == ids.len`). + pub fn run(r: *Ref, ids: []const u32, out: []Pick) !void { + var arena = std.heap.ArenaAllocator.init(r.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const t = &r.c.text; + const n = ids.len; + const h: usize = t.hidden; + const nblocks = (t.layers + t.block - 1) / t.block; + var hcur = try mat2(a, n, h); + var hnext = try mat2(a, n, h); + var blocks: [16][][]f64 = undefined; + for (0..nblocks) |b| blocks[b] = try mat2(a, n, h); + const bank = try mat2(a, n, h); + const bank_h = try mat2(a, n, h); + const embed = try r.get("model.llm.embed.weight", .{}); + const enorm = try r.get("model.llm.embed_norm.weight", .{}); + for (ids, 0..) |id, i| { + for (0..h) |c| hcur[i][c] = bf(embed.bytes, @as(usize, id) * h + c); + normInto(hcur[i], enorm, t.eps); + } + for (r.p.visits.slice(), 0..) |_, v| { + try r.visit(a, @intCast(v), ids.len, hcur, hnext, &blocks, bank, bank_h); + std.mem.swap([][]f64, &hcur, &hnext); + } + const oq = try r.get("model.llm.attn_res.output_query", .{}); + const norm = try r.get("model.llm.norm.weight", .{}); + const unembed = try r.get("model.llm.unembed.weight", .{}); + const xf = try a.alloc(f64, h); + var src: [17][]const f64 = undefined; + for (0..n) |i| { + const nb = r.p.final_sources - 1; + for (0..nb) |b| src[b] = blocks[b][i]; + src[nb] = hcur[i]; + mixOne(h, src[0 .. nb + 1], oq.bytes, 0, xf); + normInto(xf, norm, t.eps); + var best: Pick = .{ .id = 0, .margin = 0, .top = 0 }; + for (0..t.unpadded_vocab) |vid| { + const l = t.logit_cap * std.math.tanh(dotBf(unembed.bytes, vid, h, xf) / t.logit_cap); + if (l <= best.logits[4]) continue; + var at: usize = 4; + while (at > 0 and l > best.logits[at - 1]) : (at -= 1) { + best.logits[at] = best.logits[at - 1]; + best.ids[at] = best.ids[at - 1]; + } + best.logits[at] = l; + best.ids[at] = @intCast(vid); + } + best.id = best.ids[0]; + best.top = best.logits[0]; + best.margin = best.logits[0] - best.logits[1]; + out[i] = best; + } + } + + fn visit(r: *Ref, a: std.mem.Allocator, v: u32, n: usize, hin: [][]f64, hout: [][]f64, blocks: *[16][][]f64, bank: [][]f64, bank_h: [][]f64) !void { + const t = &r.c.text; + const p = &r.p; + const i = p.visits.steps[v].layer; + const spec = p.at(i); + const h: usize = t.hidden; + const global = spec.kind == .global; + const msgs = p.messages(v) and !r.plant; + const L = .{i}; + if (p.bank_blocks > 1) return error.Inkling2RefBank; // one banked block (Mini), or none (the tiny checkpoint) + if (p.restarts(v)) for (0..n) |row| { + for (0..p.bank_blocks) |b| @memcpy(bank[row], blocks[p.pre_blocks + 1 + b][row]); + @memcpy(bank_h[row], hin[row]); + @memcpy(hin[row], blocks[p.pre_blocks][row]); + }; + const xin = [3][][]f64{ try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n) }; + const msg = [4][][]f64{ try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n) }; + var norms: [3]Tensor = undefined; + if (global) { + norms = .{ try r.get("model.llm.layers.{d}.q_input_norm.weight", L), try r.get("model.llm.layers.{d}.k_input_norm.weight", L), try r.get("model.llm.layers.{d}.v_input_norm.weight", L) }; + } else { + const one = try r.get("model.llm.layers.{d}.attn_norm.weight", L); + norms = .{ one, one, one }; + } + const aq: ?Tensor = if (i > 0) try r.get("model.llm.attn_res.attn_queries.{d}", .{i - 1}) else null; + const core_j = p.coreIndex(v); + const cross = .{ try r.get("model.llm.middle_cycle_cross_pass_queries", .{}), try r.get("model.llm.middle_cycle_cross_pass_kv_queries", .{}) }; + var src: [17][]const f64 = undefined; + for (0..n) |row| { + for (0..3) |q| xin[q][row] = try a.alloc(f64, h); + if (msgs) { + for (0..4) |q| msg[q][row] = try a.alloc(f64, h); + for (0..p.bank_blocks) |b| src[b] = bank[row]; + src[p.bank_blocks] = bank_h[row]; + const sources = src[0 .. p.bank_blocks + 1]; + // the message queries: main 2j (q), kv 2j (k), kv 2j + 1 (v), main 2j + 1 (mlp) + mixOne(h, sources, cross[0].bytes, 2 * core_j, msg[0][row]); + mixOne(h, sources, cross[1].bytes, 2 * core_j, msg[1][row]); + mixOne(h, sources, cross[1].bytes, 2 * core_j + 1, msg[2][row]); + mixOne(h, sources, cross[0].bytes, 2 * core_j + 1, msg[3][row]); + } + const nq: usize = spec.attn_queries; + for (0..spec.blocks_in) |b| src[b] = blocks[b][row]; + src[spec.blocks_in] = hin[row]; + for (0..@max(nq, 1)) |q| { + if (i == 0) { + @memcpy(xin[q][row], hin[row]); + } else mixOne(h, src[0 .. spec.blocks_in + 1], aq.?.bytes, q, xin[q][row]); + } + if (msgs) { + var y: [3][]f64 = undefined; + inline for (.{ "attn", "k", "v" }, 0..) |name, g| { + y[g] = try a.alloc(f64, h); + try r.gate(xin[if (nq == 3) g else 0][row], msg[g][row], i, name, norms[g], y[g]); + } + for (0..3) |g| @memcpy(xin[g][row], y[g]); + } else for (0..@max(nq, 1)) |q| normInto(xin[q][row], norms[q], t.eps); + if (!global and !msgs) for (1..3) |q| @memcpy(xin[q][row], xin[0][row]); + } + // the attention, its conv into the residual, the block boundary, the MLP input, experts and the MLP conv + const h32 = try mat2(a, n, h); + try r.attention(a, v, n, xin, h32); + try convTime(h32, try r.get("model.llm.layers.{d}.attn_sconv.weight", L), null, 1); + for (0..n) |row| if (!spec.boundary) for (0..h) |c| { + h32[row][c] += hin[row][c]; + }; + if (spec.boundary and !p.restarts(v)) for (0..n) |row| @memcpy(blocks[i / t.block][row], hin[row]); + const nb = spec.blocks_in + @intFromBool(spec.boundary); + const mq = try r.get("model.llm.attn_res.mlp_queries.{d}", L); + const mnorm = try r.get("model.llm.layers.{d}.mlp_norm.weight", L); + const moe = try mat2(a, n, h); + const xm = try a.alloc(f64, h); + for (0..n) |row| { + for (0..nb) |b| src[b] = blocks[b][row]; + src[nb] = h32[row]; + mixOne(h, src[0 .. nb + 1], mq.bytes, 0, xm); + if (msgs) { + const y = try a.alloc(f64, h); + try r.gate(xm, msg[3][row], i, "mlp", mnorm, y); + @memcpy(xm, y); + } else normInto(xm, mnorm, t.eps); + try r.experts(a, i, xm, moe[row]); + } + try convTime(moe, try r.get("model.llm.layers.{d}.mlp_sconv.weight", L), null, 1); + for (0..n) |row| for (0..h) |c| { + hout[row][c] = h32[row][c] + moe[row][c]; + }; + } + + /// The routed experts at one position: sigmoid scores, top-k by score + bias, the soft-capped SwiGLU, weighted sum. + fn experts(r: *Ref, a: std.mem.Allocator, i: u32, x: []const f64, out: []f64) !void { + const t = &r.c.text; + const h: usize = t.hidden; + const m: usize = t.expert_inter; + const L = .{i}; + const router = try r.get("model.llm.layers.{d}.mlp.gate.weight", L); + const bias = try r.get("model.llm.layers.{d}.mlp.gate.bias", L); + var score: [512]f64 = undefined; + var sel: [512]f64 = undefined; + for (0..t.experts) |e| { + score[e] = sigmoid(dotBf(router.bytes, e, h, x)); + sel[e] = score[e] + f32At(bias.bytes, e); + } + var pick: [32]usize = undefined; + var total: f64 = 0; + for (0..t.topk) |k| { + var best: usize = 0; + var bv = -std.math.inf(f64); + for (0..t.experts) |e| if (sel[e] > bv) { + bv = sel[e]; + best = e; + }; + pick[k] = best; + sel[best] = -std.math.inf(f64); + total += score[best]; + } + const pre = "model.llm.layers.{d}.mlp.experts."; + const w13 = try r.get(pre ++ "w13_weight", L); + const s13 = try r.get(pre ++ "w13_weight_scale", L); + const w2 = try r.get(pre ++ "w2_weight", L); + const s2 = try r.get(pre ++ "w2_weight_scale", L); + const nv = w13.dtype == .u8; + var f13: f64 = 1; + var f2: f64 = 1; + const act = try a.alloc(f64, m); + @memset(out, 0); + for (pick[0..t.topk]) |e| { + if (nv) { + const den: f32 = @floatCast(f32At((try r.get(pre ++ "w13_weight_outer_scale_denominator", L)).bytes, 0)); + f13 = @import("cuda").experts_mx.nvfp4Factor(@floatCast(f32At((try r.get(pre ++ "w13_weight_amax", L)).bytes, e)), den); + f2 = @import("cuda").experts_mx.nvfp4Factor(@floatCast(f32At((try r.get(pre ++ "w2_weight_amax", L)).bytes, e)), den); + } + const c13 = w13.bytes[e * (w13.bytes.len / t.experts) ..][0 .. w13.bytes.len / t.experts]; + const sc13 = s13.bytes[e * (s13.bytes.len / t.experts) ..][0 .. s13.bytes.len / t.experts]; + for (0..m) |j| { + var gu: [2]f64 = .{ 0, 0 }; + // w13's rows interleave gate and up + for (0..2) |half| gu[half] = expertDot(nv, c13, sc13, h, 2 * j + half, x) * f13; + if (r.round_caps) for (&gu) |*g| { + g.* = bf16Round(g.*); + }; + act[j] = sigmoid(gu[0]) * t.gate_cap * std.math.tanh(gu[0] / t.gate_cap) * t.up_cap * std.math.tanh(gu[1] / t.up_cap); + } + const c2 = w2.bytes[e * (w2.bytes.len / t.experts) ..][0 .. w2.bytes.len / t.experts]; + const sc2 = s2.bytes[e * (s2.bytes.len / t.experts) ..][0 .. s2.bytes.len / t.experts]; + const w = score[e] / (total + 1e-20) * t.route_scale; + for (0..h) |row| out[row] += w * expertDot(nv, c2, sc2, m, row, act) * f2; + } + } + + /// The attention of every position at visit `v` from its inputs (q from plane 0, k from 1, v from 2) into `y`. + fn attention(r: *Ref, a: std.mem.Allocator, v: u32, n: usize, xin: [3][][]f64, y: [][]f64) !void { + const t = &r.c.text; + const p = &r.p; + const i = p.visits.steps[v].layer; + const global = p.at(i).kind == .global; + const L = .{i}; + const hd = t.local; + const qw: usize = @as(usize, hd.q) * hd.dim; + const kvw: usize = @as(usize, hd.kv) * hd.dim; + const dr: usize = t.d_rel; + const q = try mat2(a, n, qw); + const k = try mat2(a, n, kvw); + const vv = try mat2(a, n, kvw); + const rel = try mat2(a, n, hd.q * dr); + const gate_ = try mat2(a, n, qw); + const sink = try mat2(a, n, hd.q); + const w = .{ + try r.get("model.llm.layers.{d}.attn.wq_du.weight", L), try r.get("model.llm.layers.{d}.attn.wk_dv.weight", L), + try r.get("model.llm.layers.{d}.attn.wv_dv.weight", L), try r.get("model.llm.layers.{d}.attn.wr_du.weight", L), + try r.get("model.llm.layers.{d}.attn.gate_attn.weight", L), try r.get("model.llm.layers.{d}.attn.attn_sink_proj.weight", L), + }; + for (0..n) |row| { + matvec(w[0], xin[0][row], q[row]); + matvec(w[1], xin[1][row], k[row]); + matvec(w[2], xin[2][row], vv[row]); + matvec(w[3], xin[0][row], rel[row]); + matvec(w[4], xin[0][row], gate_[row]); + matvec(w[5], xin[0][row], sink[row]); + } + if (global) { + const taps = kvw / hd.dim * 4; + const dk = try mat2(a, n, taps); + const dv = try mat2(a, n, taps); + const pk = try r.get("model.llm.layers.{d}.attn.k_sconv.weight_proj", L); + const pv = try r.get("model.llm.layers.{d}.attn.v_sconv.weight_proj", L); + for (0..n) |row| { + matvec(pk, xin[1][row], dk[row]); + matvec(pv, xin[2][row], dv[row]); + } + try convTime(k, try r.get("model.llm.layers.{d}.attn.k_sconv.static_w", L), dk, hd.kv); + try convTime(vv, try r.get("model.llm.layers.{d}.attn.v_sconv.static_w", L), dv, hd.kv); + } else { + try convTime(k, try r.get("model.llm.layers.{d}.attn.k_sconv.weight", L), null, 1); + try convTime(vv, try r.get("model.llm.layers.{d}.attn.v_sconv.weight", L), null, 1); + } + const qs = try r.get("model.llm.layers.{d}.attn.q_l2_clip.scale", L); + const rs = try r.get("model.llm.layers.{d}.attn.rel_l2_clip.scale", L); + const proj = try r.get("model.llm.layers.{d}.attn.rel_logits_proj.proj", L); + const extent: usize = proj.dim(1); + for (0..n) |row| { + const tau: f64 = if (global) 1 + t.log_alpha * @log(@max(@as(f64, @floatFromInt(row + 1)) / @as(f64, @floatFromInt(t.log_floor)), 1)) else 1; + for (0..hd.q) |hh| { + clipScaled(q[row][hh * hd.dim ..][0..hd.dim], qs.bytes, hh * hd.dim, t.qk_clip, tau); + clipScaled(rel[row][hh * dr ..][0..dr], rs.bytes, hh * dr, t.rel_clip, tau); + } + for (0..hd.kv) |hh| { + clipScaled(k[row][hh * hd.dim ..][0..hd.dim], null, 0, t.qk_clip, 1); + const vr = vv[row][hh * hd.dim ..][0..hd.dim]; + const inv = rmsInv(vr, t.eps); + for (vr) |*x| x.* *= inv; + } + } + const att = try mat2(a, n, qw); + const scale = 1.0 / @sqrt(@as(f64, @floatFromInt(hd.dim))); + const group = hd.q / hd.kv; + const sc = try a.alloc(f64, n); + for (0..n) |row| for (0..hd.q) |hh| { + const kh = hh / group; + const lo = if (global) 0 else (row + 1) -| t.window; + var mx: f64 = sink[row][hh]; + for (lo..row + 1) |j| { + var s: f64 = 0; + for (0..hd.dim) |d| s += q[row][hh * hd.dim + d] * k[j][kh * hd.dim + d]; + const dist = row - j; + var bias: f64 = 0; + if (dist < extent) for (0..dr) |d| { + bias += rel[row][hh * dr + d] * bf(proj.bytes, d * extent + dist); + }; + sc[j] = s * scale + bias; + mx = @max(mx, sc[j]); + } + var l: f64 = @exp(sink[row][hh] - mx); + const o = att[row][hh * hd.dim ..][0..hd.dim]; + @memset(o, 0); + for (lo..row + 1) |j| { + const e = @exp(sc[j] - mx); + l += e; + for (0..hd.dim) |d| o[d] += e * vv[j][kh * hd.dim + d]; + } + for (o, 0..) |*x, d| x.* = x.* / l * sigmoid(gate_[row][hh * hd.dim + d]); + }; + const wo = try r.get("model.llm.layers.{d}.attn.wo_ud.weight", L); + for (0..n) |row| matvec(wo, att[row], y[row]); + } +}; diff --git a/zig/src/families/inkling2/mini_snap.zig b/zig/src/families/inkling2/mini_snap.zig new file mode 100644 index 00000000000..35688a86a5a --- /dev/null +++ b/zig/src/families/inkling2/mini_snap.zig @@ -0,0 +1,112 @@ +//! A stream's state at a prompt position (the prompt cache's copy): the 48 visits' K and V, the full ones through +//! `at` and the sliding rings' last 1,023 positions, and every visit's four conv states. Nothing else carries over +//! between forwards: blocks, bank and messages are each forward's own. +const std = @import("std"); +const cuda = @import("cuda"); +const mm = @import("mini_model.zig"); + +/// A kept state: the copied rows and conv states in `buf`, in `each`'s order. +pub const Saved = struct { + at: u32, + visits: u32, // the plan's visit count it was made under (a state never crosses plans) + buf: cuda.DeviceBuffer, +}; + +/// Positions a sliding ring keeps at `at`: a later row reads keys from its position - window + 1 on. +pub fn tail(window: usize, at: usize) usize { + return @min(at, window - 1); +} + +fn rowBytes(m: *const mm.Model) usize { + return @as(usize, m.c.local.dim) * 2; +} + +fn convWidth(m: *const mm.Model, site: mm.Site) usize { + return if (site == .k or site == .v) @as(usize, m.c.local.kv) * m.c.local.dim else m.c.hidden; +} + +/// Each copy of `slot`'s state at `at`, in order: per visit K then V, each head's kept positions in runs of +/// consecutive ring rows; then the visit's four conv states ([3][C] fp32). +pub fn each(m: *const mm.Model, slot: usize, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { + const rb = rowBytes(m); + const kvh: usize = m.c.local.kv; + var off: usize = 0; + for (m.w.plan.visits.slice(), 0..) |step, v| { + const full = step.of(.full) != null; + const len: usize = if (full) m.full.ring else m.sliding.ring; + const from = if (full) 0 else at - tail(m.c.window, at); + for (0..2) |side| for (0..kvh) |h| { + const base = m.kv[side][v] + ((slot * kvh + h) * len) * rb; + var p = from; + while (p < at) { + const row = p % len; + const run = @min(at - p, len - row); + try f(ctx, base + row * rb, off, run * rb); + off += run * rb; + p += run; + } + }; + for (std.enums.values(mm.Site)) |site| { + const n = 3 * convWidth(m, site) * 4; + try f(ctx, m.conv[v][@intFromEnum(site)] + slot * n, off, n); + off += n; + } + } +} + +const Count = struct { + n: *usize, + fn add(c: Count, _: u64, _: usize, len: usize) anyerror!void { + c.n.* += len; + } +}; + +/// Bytes a state at `at` takes. +pub fn bytes(m: *const mm.Model, at: usize) u64 { + var n: usize = 0; + each(m, 0, at, Count{ .n = &n }, Count.add) catch unreachable; + return n; +} + +const Copy = struct { + m: *const mm.Model, + s: cuda.Stream, + buf: u64, + out: bool, // slot -> buf (save), else buf -> slot (restore) + fn copy(c: Copy, dev: u64, off: usize, len: usize) anyerror!void { + const src = if (c.out) dev else c.buf + off; + const dst = if (c.out) c.buf + off else dev; + try c.m.d.check(c.m.d.api.cuMemcpyDtoDAsync_v2(dst, src, len, c.s.handle), "cuMemcpyDtoDAsync"); + } +}; + +/// Copy `slot`'s state at `at` into new storage, queued on `s` behind the chunk that ends there. +pub fn save(gpa: std.mem.Allocator, m: *const mm.Model, s: cuda.Stream, slot: usize, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .visits = @intCast(m.w.plan.visits.len), .buf = try cuda.DeviceBuffer.alloc(m.d, @max(bytes(m, at), 256)) }; + errdefer k.buf.free(); + try each(m, slot, at, Copy{ .m = m, .s = s, .buf = k.buf.ptr, .out = true }, Copy.copy); + return k; +} + +/// Make `slot` hold `k`'s state, queued on `s` before the next chunk; a state of another plan is refused. +pub fn restore(m: *const mm.Model, s: cuda.Stream, slot: usize, k: *const Saved) !void { + if (k.visits != m.w.plan.visits.len) return error.Inkling2StateOfAnotherPlan; + if (k.at > m.context) return error.PastContext; + try each(m, slot, k.at, Copy{ .m = m, .s = s, .buf = k.buf.ptr, .out = false }, Copy.copy); +} + +/// Free a state once the stream's queued copies of it are done. +pub fn drop(gpa: std.mem.Allocator, s: cuda.Stream, k: *Saved) void { + s.synchronize() catch {}; + k.buf.free(); + gpa.destroy(k); +} + +test "a sliding ring keeps the window less one before the next row; short prompts all of theirs" { + try std.testing.expectEqual(@as(usize, 1023), tail(1024, 5000)); + try std.testing.expectEqual(@as(usize, 300), tail(1024, 300)); + try std.testing.expectEqual(@as(usize, 1023), tail(1024, 1023)); +} diff --git a/zig/src/families/inkling2/mini_visit.zig b/zig/src/families/inkling2/mini_visit.zig new file mode 100644 index 00000000000..1d84885d2f2 --- /dev/null +++ b/zig/src/families/inkling2/mini_visit.zig @@ -0,0 +1,263 @@ +//! One Mini forward's launches: the embedding, each visit (its input mix or gates, attention, convs, router, experts), +//! and the head. Visits, slots and passes come from the plan (core/visit_plan.zig); the loop math is loop.cu's. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const attn = @import("kernels.zig"); +const ops = @import("ops.zig"); +const loop = @import("loop.zig"); +const mm = @import("mini_model.zig"); +const wts = @import("mini_weights.zig"); + +const Model = mm.Model; +const Kernels = mm.Kernels; +const Site = mm.Site; + +/// A forward's rows as staged on the device: counts, the call's attention rows and its streams. +pub const Rows = struct { + n: usize, + streams: usize, + prompt: bool, + last_pos: u32, + n_tiles: u32, + + /// Ids, positions, segments and tiles of `chains` uploaded on `s`. + pub fn stage(m: *Model, s: cuda.Stream, chains: []const mm.Chain, rows: usize, prompt: bool) !Rows { + const gpa = m.gpa; + const ints = try gpa.alloc(i32, 3 * rows); + defer gpa.free(ints); + var segs: [2][mm.round_rows]attn.Seg = undefined; + var cs: [mm.round_rows][4]i32 = undefined; + const kvw: i64 = @as(i64, m.c.local.kv) * m.c.local.dim; + var at: usize = 0; + var last: u32 = 0; + for (chains, 0..) |ch, i| { + for (ch.tokens, 0..) |tok, j| { + ints[at + j] = @intCast(tok); + ints[rows + at + j] = @intCast(ch.p0 + j); + ints[2 * rows + at + j] = @intCast(i); + } + const slot: i64 = @intCast(ch.slot); + for ([_]attn.Layer{ m.sliding, m.full }, 0..) |l, side| { + segs[side][i] = .{ .row0 = @intCast(at), .n = @intCast(ch.tokens.len), .p0 = @intCast(ch.p0), .off = slot * kvw * l.ring }; + } + cs[i] = .{ @intCast(at), @intCast(ch.tokens.len), @intCast(ch.slot), 0 }; + last = @max(last, @as(u32, @intCast(ch.p0 + ch.tokens.len - 1))); + at += ch.tokens.len; + } + const group = m.c.local.q / m.c.local.kv; + var tiles: [attn.tileCount(mm.prompt_rows, 3) + mm.round_rows]attn.Tile = undefined; + const n_tiles = try attn.tiles(segs[0][0..chains.len], group, &tiles); + try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ints[0..rows])); + try m.upload(s, m.s.pos, std.mem.sliceAsBytes(ints[rows .. 2 * rows])); + try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(ints[2 * rows ..])); + for (0..2) |side| try m.upload(s, m.s.segs[side], std.mem.sliceAsBytes(segs[side][0..chains.len])); + try m.upload(s, m.s.conv_segs, std.mem.sliceAsBytes(cs[0..chains.len])); + try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); + return .{ .n = rows, .streams = chains.len, .prompt = prompt, .last_pos = last, .n_tiles = @intCast(n_tiles) }; + } +}; + +fn kvWidth(m: *const Model) usize { + return @as(usize, m.c.local.kv) * m.c.local.dim; +} + +/// The whole forward: embedding, every visit, then the head's rows [head0, head0 + heads). +pub fn run(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, head0: usize, heads: usize) !void { + const t = m.c; + const h: usize = t.hidden; + try ops.embed(&k.ops, s, m.s.ids, r.n, m.w.embed, m.w.embed_norm, m.s.h[0], h, t.eps); + var cur: usize = 0; + for (0..m.w.plan.visits.len) |v| { + try visitOne(m, k, s, r, @intCast(v), m.s.h[cur], m.s.h[1 - cur]); + cur = 1 - cur; + } + if (heads == 0) return; + const plane = r.n * h * 2; + const nb = m.w.plan.final_sources - 1; + var mix: ops.MixArgs = .{ .partial = m.s.h[cur], .query = m.w.output_query, .out = m.s.xf, .n_blocks = @intCast(nb), .partial_bf16 = 1, .nq = 1, .rows = @intCast(r.n), .c = @intCast(h), .eps = t.eps }; + for (0..nb) |j| mix.blocks[j] = m.s.blocks + j * plane; + mix.norm[0] = m.w.norm; + try ops.mix(&k.ops, s, mix); + const v: usize = t.unpadded_vocab; + try k.lane.matmulOut(s, m.s.xf + head0 * h * 2, h, heads, m.w.unembed, m.s.logits, .f32, m.s.lane_part); + try ops.softcap(&k.ops, s, m.s.logits, heads * v, t.logit_cap); +} + +/// The input projections' outputs: the scratch buffers, or a one-row forward's parts of the fused output. +const Out = struct { q: u64, k: u64, v: u64, rel: u64, gate: u64, sink: u64 }; + +fn proj(m: *const Model, k: *const Kernels, s: cuda.Stream, w: cuda.qmmf.Weight, x: u64, out: u64, n: usize) !void { + try k.lane.matmulOut(s, x, w.k, n, w, out, .bf16, m.s.lane_part); +} + +/// Bank the previous pass before a restart: its blocks past the entry, its output; the state restarts from the entry. +fn restart(m: *Model, s: cuda.Stream, r: *const Rows, hin: u64) !void { + const p = &m.w.plan; + const plane = r.n * m.c.hidden * 2; + for (0..p.bank_blocks) |j| try m.copy(s, m.s.bank + j * plane, m.s.blocks + (p.pre_blocks + 1 + j) * plane, plane); + try m.copy(s, m.s.bank_h, hin, plane); + try m.copy(s, hin, m.s.blocks + p.pre_blocks * plane, plane); +} + +/// The previous pass's messages for core layer `j`: four fp32 mixes over its banked blocks and output (q, k, v, mlp). +fn messages(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, j: u32) !void { + const h: usize = m.c.hidden; + const plane = r.n * h; + var a: loop.MixArgs = .{ .partial = m.s.bank_h, .out = m.s.msg, .out_stride = @intCast(plane), .n_blocks = @intCast(m.w.plan.bank_blocks), .partial_f32 = 0, .nq = 4, .rows = @intCast(r.n), .h = @intCast(h), .eps = m.c.eps, .scale = scale(h) }; + for (0..m.w.plan.bank_blocks) |b| a.blocks[b] = m.s.bank + b * plane * 2; + const row = @as(usize, j) * 2 * h * 4; + a.query = .{ m.w.cross_main + row, m.w.cross_kv + row, m.w.cross_kv + row + h * 4, m.w.cross_main + row + h * 4 }; + try loop.mix(&k.loop, s, a); +} + +fn scale(h: usize) f32 { + return @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(h)))); +} + +/// A core input through its gates: the residual mix of `nq` queries over `nb` blocks and the partial, then each gate +/// (controllers[g], message plane slots[g]) and its norm into `out` planes. +fn gated(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, nb: usize, partial: u64, f32_partial: bool, query: u64, nq: usize, ctl: []const wts.Controller, slots: [3]i32, norms: [3]u64, out: u64) !void { + const h: usize = m.c.hidden; + const plane = r.n * h; + var a: loop.MixArgs = .{ .partial = partial, .out = m.s.mixf, .out_stride = @intCast(plane), .n_blocks = @intCast(nb), .partial_f32 = @intFromBool(f32_partial), .nq = @intCast(nq), .rows = @intCast(r.n), .h = @intCast(h), .eps = m.c.eps, .scale = scale(h) }; + for (0..nb) |b| a.blocks[b] = m.s.blocks + b * plane * 2; + for (0..nq) |q| a.query[q] = query + q * h * 4; + try loop.mix(&k.loop, s, a); + var g: loop.GateArgs = .{ .msg = m.s.msg, .msg_stride = @intCast(plane), .down = m.s.gdown, .ys = m.s.gys, .out = out, .out_stride = @intCast(plane), .rows = @intCast(r.n), .h_dim = @intCast(h), .rank = @intCast(m.c.loop.?.rank), .eps_unit = m.c.eps, .eps = m.c.eps }; + for (0..ctl.len) |i| { + g.h[i] = m.s.mixf + (if (nq == 3) i else 0) * plane * 4; + g.slot[i] = slots[i]; + g.down_w[i] = ctl[i].down; + g.forget[i] = ctl[i].forget; + g.gain[i] = ctl[i].gain; + g.norm[i] = norms[i]; + } + try loop.gates(&k.loop, s, g, ctl.len); +} + +/// A short conv at `site` of visit `v` over the call's streams (their states by slot). +fn conv(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32, site: Site, a: ops.ConvArgs) !void { + var c = a; + c.state = m.conv[v][@intFromEnum(site)]; + c.segs = m.s.conv_segs; + c.state_stride = 3 * @as(i64, c.c); + c.rows = @intCast(r.n); + try ops.conv(&k.ops, s, c, r.streams); +} + +fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32, hin: u64, hout: u64) !void { + const t = m.c; + const p = &m.w.plan; + const step = p.visits.steps[v]; + const i: u32 = step.layer; + const spec = p.at(i); + const L = &m.w.layers[i]; + const a = &L.attn; + const h: usize = t.hidden; + const n = r.n; + const plane = n * h; + const global = spec.kind == .global; + const msgs = p.messages(v); + if (p.restarts(v)) try restart(m, s, r, hin); + // the attention's inputs: layer 0 norms the embedding; later layers mix blocks; core passes after the first gate + if (msgs) { + try messages(m, k, s, r, p.coreIndex(v)); + try gated(m, k, s, r, spec.blocks_in, hin, false, L.attn_query, spec.attn_queries, L.controllers.?[0..3], .{ 0, 1, 2 }, a.norms, m.s.xin); + } else { + var mix: ops.MixArgs = .{ .partial = hin, .query = if (i == 0) 0 else L.attn_query, .out = m.s.xin, .n_blocks = @intCast(if (i == 0) 0 else spec.blocks_in), .partial_bf16 = 1, .nq = if (i == 0) 1 else spec.attn_queries, .rows = @intCast(n), .c = @intCast(h), .eps = t.eps }; + for (0..spec.blocks_in) |j| mix.blocks[j] = m.s.blocks + j * plane * 2; + mix.norm = a.norms; + try ops.mix(&k.ops, s, mix); + } + const separate = global or msgs; + const xq = m.s.xin; + const xk = if (separate) m.s.xin + plane * 2 else xq; + const xv = if (separate) m.s.xin + 2 * plane * 2 else xq; + // one row: the fused product (q, gate, rel, sink and k, v when they share the input), its parts read in place + var o: Out = .{ .q = m.s.q, .k = m.s.kraw, .v = m.s.vraw, .rel = m.s.rel, .gate = m.s.gate, .sink = m.s.sink }; + if (n == 1) { + const f = wts.Fused.of(t); + const at = struct { + fn col(base: u64, c: usize) u64 { + return base + c * 2; + } + }.col; + const fz = m.s.fused; + o = .{ .q = at(fz, f.q), .k = at(fz, f.k), .v = at(fz, f.v), .rel = at(fz, f.rel), .gate = at(fz, f.gate), .sink = at(fz, f.sink) }; + try proj(m, k, s, if (separate) a.qx else a.all, xq, fz, 1); + if (separate) { + try proj(m, k, s, a.wk, xk, o.k, 1); + try proj(m, k, s, a.wv, xv, o.v, 1); + } + } else { + try proj(m, k, s, a.wq, xq, o.q, n); + try proj(m, k, s, a.wk, xk, o.k, n); + try proj(m, k, s, a.wv, xv, o.v, n); + try proj(m, k, s, a.wr, xq, o.rel, n); + try proj(m, k, s, a.gate, xq, o.gate, n); + try proj(m, k, s, a.sink, xq, o.sink, n); + } + const kvw = kvWidth(m); + const kvh: usize = t.local.kv; + const taps = kvh * config.conv_taps; + if (global) for ([_]u64{ xk, xv }, [_]u64{ a.k_taps, a.v_taps }, 0..) |x, w, side| { + // the taps as torch's bf16 linear leaves them: float(bf16(sum)) times 1 + try k.dense.rowsScaled(s, x, h, w, m.w.ones, m.s.dyn[side], taps, n, taps, h); + }; + for ([_]Site{ .k, .v }, [_]u64{ o.k, o.v }, [_]u64{ m.s.kc, m.s.vc }, [_]u64{ a.k_conv, a.v_conv }, 0..) |site, x, out, w, side| { + try conv(m, k, s, r, v, site, .{ .x = x, .state = 0, .w = w, .dyn = if (global) m.s.dyn[side] else 0, .out = out, .x_bf16 = 1, .heads = @intCast(kvh), .c = @intCast(kvw), .rows = 0, .mode = 0 }); + } + // q, rel and the caches' new K and V rows, the bias table, then attention through the sink and the output gate + const l = if (global) m.full else m.sliding; + const rows: attn.Rows = .{ .rows = @intCast(n), .heads = t.local.q, .kv_heads = t.local.kv, .pos = m.s.pos, .seg_of = m.s.seg_of, .segs = m.s.segs[@intFromBool(global)], .tiles = m.s.tiles, .n_tiles = r.n_tiles, .last_pos = r.last_pos, .streams = @intCast(r.streams) }; + const cache: attn.Cache = .{ .k = m.kv[0][v], .v = m.kv[1][v] }; + const prep: attn.Prep = .{ .qk_clip = t.qk_clip, .rel_clip = t.rel_clip, .floor = @floatFromInt(t.log_floor), .alpha = t.log_alpha, .eps = t.eps }; + try attn.prep(&k.attn, s, rows, l, prep, .{ o.q, m.s.kc, m.s.vc, o.rel }, .{ a.q_scale, a.rel_scale }, m.s.qp, m.s.relp, cache); + try attn.relTable(&k.attn, s, rows, m.s.relp, a.rel_proj, m.s.tab); + const stride = attn.slotsFor(l, m.context); + try attn.attend(&k.attn, s, rows, l, stride, m.s.entries, m.s.qp, cache, m.s.tab, m.s.part_o, m.s.part_ml, o.sink, o.gate, m.s.att); + try proj(m, k, s, a.wo, m.s.att, m.s.o, n); + // the attention conv into the fp32 residual: a block boundary keeps only the attention output as the partial + try conv(m, k, s, r, v, .attn, .{ .x = m.s.o, .state = 0, .w = L.attn_conv, .base = if (spec.boundary) 0 else hin, .resid = m.s.h32, .x_bf16 = 1, .c = @intCast(h), .rows = 0, .mode = 1 }); + if (spec.boundary and !p.restarts(v)) try m.copy(s, m.s.blocks + @as(usize, i / t.block) * plane * 2, hin, plane * 2); + const nb = spec.blocks_in + @intFromBool(spec.boundary); + if (msgs) { + const mn = [3]u64{ L.mlp_norm, L.mlp_norm, L.mlp_norm }; + try gated(m, k, s, r, nb, m.s.h32, true, L.mlp_query, 1, L.controllers.?[3..4], .{ 3, 3, 3 }, mn, m.s.xm); + } else { + var mix: ops.MixArgs = .{ .partial = m.s.h32, .query = L.mlp_query, .out = m.s.xm, .n_blocks = @intCast(nb), .partial_bf16 = 0, .nq = 1, .rows = @intCast(n), .c = @intCast(h), .eps = t.eps }; + for (0..nb) |j| mix.blocks[j] = m.s.blocks + j * plane * 2; + mix.norm[0] = L.mlp_norm; + try ops.mix(&k.ops, s, mix); + } + try moe(m, k, s, r, L); + // the MLP conv: the next visit's state is bf16(h32 + bf16(conv(moe))) + try conv(m, k, s, r, v, .mlp, .{ .x = m.s.moe, .state = 0, .w = L.mlp_conv, .resid = m.s.h32, .out = hout, .x_bf16 = 1, .c = @intCast(h), .rows = 0, .mode = 2 }); +} + +/// The router's picks over sigmoid scores, the routed experts as stored (core experts), their weighted sum in bf16. +fn moe(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, L: *const wts.Layer) !void { + const t = m.c; + const h: usize = t.hidden; + const n = r.n; + const pairs = n * t.topk; + try ops.rowdot(&k.ops, s, m.s.xm, L.router, m.s.scores, n, t.experts, h, false, true); + try ops.topk(&k.ops, s, m.s.scores, L.router_bias, m.s.pick, m.s.rw, n, t.experts, t.topk, t.route_scale); + const tile: usize = if (r.prompt) cuda.experts.promptTile(L.experts.format) else 16; + const items = cuda.grouped.maxItems(pairs, t.experts, tile); + try k.router.route(s, m.s.pick, pairs, t.experts, tile, m.s.plan); + const gx = k.experts(); + const up_in: cuda.experts.Rows = .{ .x = m.s.xm, .stride = h, .slots = t.topk }; + const down_in: cuda.experts.Rows = .{ .x = m.s.act, .stride = t.expert_inter }; + if (r.prompt) { + try gx.prompt(s, .up, up_in, L.experts, m.s.plan, m.s.act, items, pairs, tile, -1); + try gx.prompt(s, .down_bf16, down_in, L.experts, m.s.plan, m.s.y, items, pairs, tile, -1); + try k.glue.combine(s, m.s.y, .bf16, m.s.rw, m.s.moe, .bf16, n, t.topk, h); + } else { + try gx.decode(s, .up, up_in, L.experts, m.s.plan, m.s.act, items, pairs, tile, -1); + try gx.decode(s, .down_f32, down_in, L.experts, m.s.plan, m.s.y, items, pairs, tile, -1); + try k.glue.combine(s, m.s.y, .f32, m.s.rw, m.s.moe, .bf16, n, t.topk, h); + } +} diff --git a/zig/src/families/inkling2/mini_weights.zig b/zig/src/families/inkling2/mini_weights.zig new file mode 100644 index 00000000000..ecdd32f87e4 --- /dev/null +++ b/zig/src/families/inkling2/mini_weights.zig @@ -0,0 +1,380 @@ +//! Inkling 2 Mini's weights on one GPU: bf16 projections packed for the core lane matmul, the stored NVFP4 and MXFP8 +//! experts packed for core experts (C3), and the small tensors (norms, convs, queries, gates) as the kernels read them. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const names = @import("names.zig"); +const plan_ = @import("plan.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; +const Lane = cuda.qmmf.Weight; +const ex = cuda.experts; +const mx = cuda.experts_mx; +const Tensor = core.checkpoint.Tensor; + +/// NVFP4's outer scale denominator as Mini ships it (scales/RESULTS.md); another value is refused. +pub const nvfp4_denominator = 2688; + +/// The experts' round_caps A/B switch on every layer: gate and up rounded to bf16 before the soft caps. +pub fn roundCaps(w: *Weights, on: bool) void { + for (w.layers) |*l| l.experts.round_caps = on; +} + +/// One packed buffer a layer, rows [q | gate | rel | sink padded to 64 | k | v]: views of it, every one at the +/// parts' own K slices (one count for all six, else refused), so a fused product's rows carry the separate bits. +pub const Fused = struct { + /// Row offsets of the parts in the fused output. + q: usize, + gate: usize, + rel: usize, + sink: usize, + k: usize, + v: usize, + /// The q-side rows (q, gate, rel, sink: one input), and every row (q, k and v from one input). + qx: usize, + all: usize, + + pub fn of(c: *const config.Text) Fused { + const qw: usize = @as(usize, c.local.q) * c.local.dim; + const kvw: usize = @as(usize, c.local.kv) * c.local.dim; + const rel = 2 * qw; + const sink = rel + @as(usize, c.local.q) * c.d_rel; + const k = sink + std.mem.alignForward(usize, c.local.q, 64); + return .{ .q = 0, .gate = qw, .rel = rel, .sink = sink, .k = k, .v = k + kvw, .qx = k, .all = k + 2 * kvw }; + } +}; + +pub const Attn = struct { + qx: Lane, // the fused q-side rows (one input: q, gate, rel, sink) + all: Lane, // every fused row (q, k and v from one input) + wq: Lane, + wk: Lane, + wv: Lane, + wr: Lane, // relative-bias queries [heads * d_rel, H] + gate: Lane, + sink: Lane, + wo: Lane, + k_taps: u64 = 0, // global: bf16 [kv * 4, H] (dense rows), the input-dependent conv taps + v_taps: u64 = 0, + q_scale: u64, // bf16 [heads, 128] + rel_scale: u64, // bf16 [heads, d_rel] + rel_proj: u64, // bf16 [d_rel, extent] + k_conv: u64, // sliding: bf16 [kv * 128][4]; global: static_w bf16 [4][kv * 128] + v_conv: u64, + norms: [3]u64, // sliding: attn_norm three times; global: the q, k and v input norms +}; + +pub const Controller = struct { down: u64, forget: u64, gain: u64 }; + +pub const Layer = struct { + attn: Attn, + attn_conv: u64, // bf16 [H][4] + mlp_conv: u64, + mlp_norm: u64, + router: u64, // bf16 [E, H] + router_bias: u64, // fp32 [E] + attn_query: u64 = 0, // fp32 [1 or 3, H]; 0 for layer 0 + mlp_query: u64, // fp32 [H] + controllers: ?[4]Controller = null, // core layers: attn (q), k, v inputs, then the MLP input + experts: ex.Layer, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + config: config.Config, + plan: plan_.Plan, + layers: []Layer = &.{}, + embed: u64 = 0, // bf16 [V, H] + embed_norm: u64 = 0, + norm: u64 = 0, + unembed: Lane = undefined, // the first unpadded_vocab rows + output_query: u64 = 0, // fp32 [H] + cross_main: u64 = 0, // fp32 [2 core, H] + cross_kv: u64 = 0, + ones: u64 = 0, // fp32 [max taps] of 1.0: dense rows' scaled form rounds the dynamic taps to bf16 + buffers: std.ArrayList(DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } + + fn upload(w: *Weights, d: *const cuda.Driver, bytes: []const u8) !u64 { + var b = try DeviceBuffer.fromHost(d, bytes); + errdefer b.free(); + try w.buffers.append(w.gpa, b); + w.bytes += bytes.len; + return b.ptr; + } + + /// The six input projections packed as Fused orders them; every view pinned to the parts' K slices. + fn fused(w: *Weights, d: *const cuda.Driver, parts: [6]Tensor, a: *Attn) !void { + const f = Fused.of(&w.config.text); + const k = parts[0].dim(1); + const offs = [6]usize{ f.q, f.gate, f.rel, f.sink, f.k, f.v }; + const npad = cuda.modelopt.padded(f.all); + const src = try w.gpa.alloc(u16, f.all * k); + defer w.gpa.free(src); + @memset(src, 0); + const ends = [6]usize{ f.gate, f.rel, f.sink, f.k, f.v, f.all }; + for (parts, offs, ends) |t, o, e| { + if (t.dim(1) != k or o + t.dim(0) > e) return error.Inkling2FusedShape; + @memcpy(std.mem.sliceAsBytes(src[o * k ..][0 .. t.dim(0) * k]), t.bytes[0 .. t.dim(0) * k * 2]); + } + const out = try w.gpa.alloc(u16, npad * k); + defer w.gpa.free(out); + cuda.qmmf.packBf16(out, src, f.all, k); + const base = try w.upload(d, std.mem.sliceAsBytes(out)); + const sk = cuda.qmmf.splitK(parts[0].dim(0), k); + for (parts) |t| if (cuda.qmmf.splitK(t.dim(0), k) != sk) return error.Inkling2FusedSlices; + const view = struct { + fn at(ptr: u64, row: usize, n: usize, kk: usize, slices: u32) !Lane { + return cuda.qmmf.pinned(cuda.modelopt.bf16Weight(ptr + row * kk * 2, n, kk), slices); + } + }; + a.qx = try view.at(base, 0, f.qx, k, sk); + a.all = try view.at(base, 0, f.all, k, sk); + const lanes = [_]*Lane{ &a.wq, &a.gate, &a.wr, &a.sink, &a.wk, &a.wv }; + for (lanes, parts, offs) |l, t, o| l.* = try view.at(base, o, t.dim(0), k, sk); + } + + /// A bf16 [n, k] projection (its first `rows` rows) in the lane's order, padded to 128 rows. + fn lane(w: *Weights, d: *const cuda.Driver, t: Tensor, rows: usize) !Lane { + const k = t.dim(t.rank - 1); + const n = rows; + const npad = cuda.modelopt.padded(n); + const out = try w.gpa.alloc(u16, npad * k); + defer w.gpa.free(out); + const src = try w.gpa.alloc(u16, n * k); + defer w.gpa.free(src); + @memcpy(std.mem.sliceAsBytes(src), t.bytes[0 .. n * k * 2]); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try w.upload(d, std.mem.sliceAsBytes(out)), n, k); + } +}; + +fn get(ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [128]u8 = undefined; + return ck.get(try std.fmt.bufPrint(&buf, fmt, args)); +} + +fn raw(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !u64 { + return w.upload(d, (try get(ck, fmt, args)).bytes); +} + +/// rel_logits_proj [d_rel][e] widened to the kernels' [d_rel][1024] with zero columns: no bias past e, as in the model. +fn relProj(w: *Weights, d: *const cuda.Driver, t: Tensor) !u64 { + const ext = @import("kernels.zig").extent; + const rows = t.dim(0); + const e = t.dim(1); + if (e > ext) return error.Inkling2RelExtent; + if (e == ext) return w.upload(d, t.bytes); + const out = try w.gpa.alloc(u16, rows * ext); + defer w.gpa.free(out); + @memset(out, 0); + for (0..rows) |r| @memcpy(std.mem.sliceAsBytes(out[r * ext ..][0..e]), t.bytes[r * e * 2 ..][0 .. e * 2]); + return w.upload(d, std.mem.sliceAsBytes(out)); +} + +fn proj(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !Lane { + const t = try get(ck, fmt, args); + return w.lane(d, t, t.dim(0)); +} + +/// The header of every shard against the weight map: a missing, extra or misshapen tensor refuses the load by name. +fn admit(gpa: std.mem.Allocator, ck: *core.checkpoint.Checkpoint, c: *const config.Config, prec: []plan_.Precision) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var all: core.safetensors.Header = .empty; + for (ck.files.items) |*f| try names.merge(a, &all, f.names); + try names.precisions(all, c.text.layers, prec); + const r = try names.check(a, c, all, .model); + if (r.clean()) return; + for (r.missing.items) |n| std.log.err("inkling2 mini: the checkpoint has no {s}", .{n}); + for (r.wrong.items) |n| std.log.err("inkling2 mini: {s} has another dtype or shape than the config implies", .{n}); + for (r.unknown.items) |n| std.log.err("inkling2 mini: {s} is not a tensor the config implies", .{n}); + return error.Inkling2WeightMap; +} + +/// config.json read and admitted (inkling2_loop, ModelOpt via core), the map checked, then layer by layer to the GPU. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8) !Weights { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const json = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(json); + var why: config.Why = .{}; + const c = config.parse(gpa, json, &why) catch |e| { + std.log.err("inkling2: {s}", .{why.text()}); + return e; + }; + if (c.text.loop == null) return error.Inkling2NotLooped; // Small serves on its own engine + var ck = try core.checkpoint.Checkpoint.openModel(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var prec: [config.max_layers]plan_.Precision = undefined; + try admit(gpa, &ck, &c, prec[0..c.text.layers]); + var w: Weights = .{ .gpa = gpa, .config = c, .plan = try plan_.build(&c.text, prec[0..c.text.layers]) }; + errdefer w.deinit(); + const t = &c.text; + w.layers = try gpa.alloc(Layer, t.layers); + w.embed = try raw(&w, d, &ck, "model.llm.embed.weight", .{}); + w.embed_norm = try raw(&w, d, &ck, "model.llm.embed_norm.weight", .{}); + w.norm = try raw(&w, d, &ck, "model.llm.norm.weight", .{}); + w.output_query = try raw(&w, d, &ck, "model.llm.attn_res.output_query", .{}); + w.cross_main = try raw(&w, d, &ck, "model.llm.middle_cycle_cross_pass_queries", .{}); + w.cross_kv = try raw(&w, d, &ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}); + w.unembed = try w.lane(d, try ck.get("model.llm.unembed.weight"), t.unpadded_vocab); + w.ones = try w.upload(d, std.mem.sliceAsBytes(&@as([64]f32, @splat(1.0)))); + for (w.layers, 0..) |*l, i| { + l.* = try layer(&w, d, &ck, @intCast(i), prec[i]); + ck.release(); // the mapped pages already copied: drop them from the page cache's working set + } + return w; +} + +fn layer(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, i: u32, prec: plan_.Precision) !Layer { + const c = &w.config.text; + const L = .{i}; + const global = config.isGlobal(i); + var a: Attn = .{ + .qx = undefined, + .all = undefined, + .wq = undefined, + .wk = undefined, + .wv = undefined, + .wr = undefined, + .gate = undefined, + .sink = undefined, + .wo = try proj(w, d, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L), + .q_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L), + .rel_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L), + .rel_proj = try relProj(w, d, try get(ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L)), + .k_conv = undefined, + .v_conv = undefined, + .norms = undefined, + }; + const pre = "model.llm.layers.{d}.attn."; + try w.fused(d, .{ + try get(ck, pre ++ "wq_du.weight", L), try get(ck, pre ++ "gate_attn.weight", L), + try get(ck, pre ++ "wr_du.weight", L), try get(ck, pre ++ "attn_sink_proj.weight", L), + try get(ck, pre ++ "wk_dv.weight", L), try get(ck, pre ++ "wv_dv.weight", L), + }, &a); + if (global) { + a.k_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.static_w", L); + a.v_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.static_w", L); + a.k_taps = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.weight_proj", L); + a.v_taps = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.weight_proj", L); + a.norms = .{ + try raw(w, d, ck, "model.llm.layers.{d}.q_input_norm.weight", L), + try raw(w, d, ck, "model.llm.layers.{d}.k_input_norm.weight", L), + try raw(w, d, ck, "model.llm.layers.{d}.v_input_norm.weight", L), + }; + } else { + a.k_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.weight", L); + a.v_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.weight", L); + const n = try raw(w, d, ck, "model.llm.layers.{d}.attn_norm.weight", L); + a.norms = .{ n, n, n }; + } + var l: Layer = .{ + .attn = a, + .attn_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn_sconv.weight", L), + .mlp_conv = try raw(w, d, ck, "model.llm.layers.{d}.mlp_sconv.weight", L), + .mlp_norm = try raw(w, d, ck, "model.llm.layers.{d}.mlp_norm.weight", L), + .router = try raw(w, d, ck, "model.llm.layers.{d}.mlp.gate.weight", L), + .router_bias = try raw(w, d, ck, "model.llm.layers.{d}.mlp.gate.bias", L), + .mlp_query = try raw(w, d, ck, "model.llm.attn_res.mlp_queries.{d}", L), + .experts = try experts(w, d, ck, i, prec), + }; + // attn_queries.j feeds layer j + 1's attention input; layer 0 norms the embedding alone + if (i > 0) l.attn_query = try raw(w, d, ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}); + if (c.loop) |lp| if (i >= lp.start and i < lp.end) { + var cs: [4]Controller = undefined; + inline for (names.controllers, 0..) |g, k| cs[k] = .{ + .down = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".down_weight", L), + .forget = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".forget_weight", L), + .gain = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".gain_weight", L), + }; + l.controllers = cs; + }; + return l; +} + +/// A layer's experts as stored, packed for core experts: w13's interleaved rows split into gate and up first. +fn experts(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, i: u32, prec: plan_.Precision) !ex.Layer { + const c = &w.config.text; + const e: usize = c.experts; + const h: usize = c.hidden; + const m: usize = c.expert_inter; + const nv = prec == .nvfp4; + const pre = "model.llm.layers.{d}.mlp.experts."; + const L = .{i}; + const w13 = try get(ck, pre ++ "w13_weight", L); + const s13 = try get(ck, pre ++ "w13_weight_scale", L); + const w2 = try get(ck, pre ++ "w2_weight", L); + const s2 = try get(ck, pre ++ "w2_weight_scale", L); + const up_words = (if (nv) ex.Nvfp4Experts.bytes(1, m, h, 2) else mx.Mxfp8Experts.bytes(1, m, h, 2)) / 4; + const down_words = (if (nv) ex.Nvfp4Experts.bytes(1, h, m, 1) else mx.Mxfp8Experts.bytes(1, h, m, 1)) / 4; + const up = try w.gpa.alloc(u32, e * up_words); + defer w.gpa.free(up); + const down = try w.gpa.alloc(u32, e * down_words); + defer w.gpa.free(down); + const cb = w13.bytes.len / e; + const sb = s13.bytes.len / e; + const split = try w.gpa.alloc(u8, cb + sb); + defer w.gpa.free(split); + const c2 = w2.bytes.len / e; + const sc2 = s2.bytes.len / e; + for (0..e) |x| { + mx.splitGateUp(w13.bytes[x * cb ..][0..cb], cb / (2 * m), split[0 .. cb / 2], split[cb / 2 .. cb]); + mx.splitGateUp(s13.bytes[x * sb ..][0..sb], sb / (2 * m), split[cb..][0 .. sb / 2], split[cb + sb / 2 ..][0 .. sb / 2]); + const gate = [2][]const u8{ split[0 .. cb / 2], split[cb..][0 .. sb / 2] }; + const upm = [2][]const u8{ split[cb / 2 .. cb], split[cb + sb / 2 ..][0 .. sb / 2] }; + const o = up[x * up_words ..][0..up_words]; + const dn = down[x * down_words ..][0..down_words]; + if (nv) { + ex.Nvfp4Experts.packGateUp(o, gate, upm, m, h); + ex.Nvfp4Experts.packOne(dn, w2.bytes[x * c2 ..][0..c2], s2.bytes[x * sc2 ..][0..sc2], h, m); + } else { + mx.Mxfp8Experts.packGateUp(o, gate, upm, m, h); + mx.Mxfp8Experts.packOne(dn, w2.bytes[x * c2 ..][0..c2], s2.bytes[x * sc2 ..][0..sc2], h, m); + } + } + var l: ex.Layer = .{ .format = if (nv) .nvfp4 else .mxfp8, .up = try w.upload(d, std.mem.sliceAsBytes(up)), .down = try w.upload(d, std.mem.sliceAsBytes(down)), .width = m, .dims = h, .experts = e, .caps = .{ c.gate_cap, c.up_cap } }; + if (nv) { + var f13 = try w.gpa.alloc(f32, 2 * e); + defer w.gpa.free(f13); + var f2 = try w.gpa.alloc(f32, e); + defer w.gpa.free(f2); + inline for (.{ "w13", "w2" }, 0..) |name, k| { + const amax = try get(ck, pre ++ name ++ "_weight_amax", L); + const den = std.mem.bytesToValue(f32, (try get(ck, pre ++ name ++ "_weight_outer_scale_denominator", L)).bytes[0..4]); + if (den != nvfp4_denominator) return error.Inkling2Nvfp4Denominator; + for (0..e) |x| { + const f = mx.nvfp4Factor(std.mem.bytesToValue(f32, amax.bytes[x * 4 ..][0..4]), den); + if (k == 0) { + f13[2 * x] = f; // one amax covers the gate and the up rows + f13[2 * x + 1] = f; + } else f2[x] = f; + } + } + l.up_scale = try w.upload(d, std.mem.sliceAsBytes(f13)); + l.down_scale = try w.upload(d, std.mem.sliceAsBytes(f2)); + } + return l; +} + +test "the fused rows: parts in order, sink padded to 64 rows, every view on a 64-row block edge" { + var c: config.Text = undefined; + c.local = .{ .q = 24, .kv = 8, .dim = 128 }; + c.d_rel = 16; + const f = Fused.of(&c); + try std.testing.expectEqual(Fused{ .q = 0, .gate = 3072, .rel = 6144, .sink = 6528, .k = 6592, .v = 7616, .qx = 6592, .all = 8640 }, f); + for ([_]usize{ f.k, f.v, f.qx, f.all }) |r| try std.testing.expect(r % 64 == 0); + // Mini's six parts share 4 K slices at K 2304 (the fused views pin them); the tiny checkpoint's share 1 at K 256 + for ([_]usize{ 3072, 1024, 384, 24 }) |n| try std.testing.expectEqual(@as(u32, 4), cuda.qmmf.splitK(n, 2304)); + for ([_]usize{ 512, 256, 64, 4 }) |n| try std.testing.expectEqual(@as(u32, 1), cuda.qmmf.splitK(n, 256)); +} diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index 79890b60510..5202918338f 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,4 +1,4 @@ -//! Inkling 2 weight maps: each tensor the config implies, with dtype and shape, checked against headers. +//! Inkling 2's weight map (Small and the looped Mini): each tensor the config implies, dtype and shape, vs headers. const std = @import("std"); const st = @import("core").safetensors; const config = @import("config.zig"); @@ -77,19 +77,24 @@ fn experts(c: *const Text, i: u32, prec: plan.Precision, sink: anytype) !void { } } -fn controllers(c: *const Text, i: u32, sink: anytype) !void { - const loop = c.loop orelse return; - if (i < loop.core_start or i >= loop.core_end) return; - const rank: u64 = loop.gate_rank; +/// The loop's tensors: four controllers a core layer (attention q, k, v inputs and the MLP input: a rank-r down +/// projection of [state, message] and two [hidden, r] gates) and the cross-pass queries, two rows a core layer each. +fn loop(c: *const Text, l: config.Loop, sink: anytype) !void { const h: u64 = c.hidden; - const L = .{i}; - inline for (.{ "attn", "k", "mlp", "v" }) |kind| { - try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".down_weight", L, .bf16, &.{ rank, 2 * h }); - try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".forget_weight", L, .bf16, &.{ h, rank }); - try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".gain_weight", L, .bf16, &.{ h, rank }); - } + const r: u64 = l.rank; + const rows: u64 = 2 * @as(u64, l.end - l.start); + try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); + try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); + for (l.start..l.end) |i| inline for (controllers) |gate| { + const pre = "model.llm.layers.{d}.controllers." ++ gate; + try put(sink, pre ++ ".down_weight", .{i}, .bf16, &.{ r, 2 * h }); + try put(sink, pre ++ ".forget_weight", .{i}, .bf16, &.{ h, r }); + try put(sink, pre ++ ".gain_weight", .{i}, .bf16, &.{ h, r }); + }; } +/// A core layer's controllers in the order the engine holds them: the attention's q, k and v inputs, then the MLP's. +pub const controllers = [_][]const u8{ "attn", "k", "v", "mlp" }; fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { const h: u64 = c.hidden; try put(sink, "model.llm.embed.weight", .{}, .bf16, &.{ c.vocab, h }); @@ -97,11 +102,7 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.norm.weight", .{}, .bf16, &.{h}); try put(sink, "model.llm.unembed.weight", .{}, .bf16, &.{ c.vocab, h }); try put(sink, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); - if (c.loop) |loop| { - const rows = 2 * @as(u64, loop.core_end - loop.core_start); - try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); - try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); - } + for (0..c.layers) |k| { const i: u32 = @intCast(k); try put(sink, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{h}); @@ -111,12 +112,13 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); } try attention(c, i, sink); - try controllers(c, i, sink); + try put(sink, "model.llm.layers.{d}.attn_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try put(sink, "model.llm.layers.{d}.mlp_norm.weight", .{i}, .bf16, &.{h}); try put(sink, "model.llm.layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try experts(c, i, prec[i], sink); } + if (c.loop) |l| try loop(c, l, sink); } fn vision(v: config.Vision, sink: anytype) !void { diff --git a/zig/src/families/inkling2/names_test.zig b/zig/src/families/inkling2/names_test.zig index b194b435d28..62c76fcd393 100644 --- a/zig/src/families/inkling2/names_test.zig +++ b/zig/src/families/inkling2/names_test.zig @@ -236,12 +236,11 @@ test "the plan: global layers 5 and 11, blocks of six, three attention queries b try t.expectEqual(@as(u32, 3), p.at(11).attn_sources); try t.expectEqual(@as(u32, 3), p.final_sources); try t.expectError(error.PrecisionCount, plan.build(&c.text, prec[0..11])); - try t.expectEqual(@as(u32, 12), p.n_visits); - for (0..p.n_visits) |i| { - const v = p.visit(@intCast(i)); - try t.expectEqual(@as(u32, @intCast(i)), v.layer); - try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); - try t.expect(!v.hasMessages()); + try t.expectEqual(@as(u32, 12), p.visits.len); + for (p.visits.slice(), 0..) |v, i| { + try t.expectEqual(@as(u16, @intCast(i)), v.layer); + try t.expectEqual(@as(u16, @intCast(i)), v.of(.conv).?); + try t.expectEqual(@as(u16, 0), v.pass); } } @@ -253,19 +252,17 @@ test "Mini's visit plan repeats only the core, gives all 48 visits private state var prec: [24]plan.Precision = undefined; try names.precisions(try unfold(a, mini_model_fixture, "inkling2-mini-model"), 24, &prec); const p = try plan.build(&c.text, &prec); - try t.expectEqual(@as(u32, 48), p.n_visits); + try t.expectEqual(@as(u32, 48), p.visits.len); try t.expectEqual(@as(u32, 8), p.visitCount(.global)); try t.expectEqual(@as(u32, 40), p.visitCount(.local)); - for (0..p.n_visits) |i| { - const v = p.visit(@intCast(i)); - const layer: u32 = if (i < 6) @intCast(i) else if (i < 42) 6 + @as(u32, @intCast((i - 6) % 12)) else @intCast(i - 24); - const pass: u32 = if (i >= 6 and i < 42) 1 + @as(u32, @intCast((i - 6) / 12)) else 0; + for (p.visits.slice(), 0..) |v, i| { + const layer: u16 = if (i < 6) @intCast(i) else if (i < 42) 6 + @as(u16, @intCast((i - 6) % 12)) else @intCast(i - 24); + const pass: u16 = if (i >= 6 and i < 42) @as(u16, @intCast((i - 6) / 12)) else 0; try t.expectEqual(layer, v.layer); try t.expectEqual(pass, v.pass); - try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); - try t.expectEqual(pass >= 2, v.hasMessages()); - const previous: ?u32 = if (pass == 2) 6 else if (pass == 3) 18 else null; - try t.expectEqual(previous, v.previous_core_start); + try t.expectEqual(@as(u16, @intCast(i)), v.of(.conv).?); + try t.expectEqual(pass >= 1, p.messages(@intCast(i))); + try t.expectEqual(pass >= 1 and layer == 6, p.restarts(@intCast(i))); } try t.expectEqual(@as(u32, 5), p.final_sources); } diff --git a/zig/src/families/inkling2/ops.zig b/zig/src/families/inkling2/ops.zig index fb2bdeeabc6..cb890a73a51 100644 --- a/zig/src/families/inkling2/ops.zig +++ b/zig/src/families/inkling2/ops.zig @@ -1,8 +1,9 @@ //! Inkling 2's glue kernels (inkling2/ops.cu): embedding, residual mix, row dots, router, SwiGLU epilogue, convs. const std = @import("std"); const cuda = @import("cuda"); +const config = @import("config.zig"); -pub const max_blocks = 8; +pub const max_blocks = config.max_blocks; pub const max_queries = 3; /// ops.cu's MixArgs, field for field. @@ -128,9 +129,24 @@ pub fn embed(k: *const Kernels, s: cuda.Stream, ids: u64, rows: usize, table: u6 try go(k.embed, s, .{ .x = @intCast(rows) }, 256, &a); } +/// Whether tf_ink2_mix holds a row: ops.cu's kMixCache x 512 columns, 16-byte copies (Small 4,608, Mini 2,304). +pub fn mixFits(c: i32) error{Inkling2MixWidth}!void { + if (c <= 0 or c > 10 * 512 or @rem(c, 128) != 0) return error.Inkling2MixWidth; +} + +/// Whether tf_ink2_topk picks: 8 scores a thread of 512, 32 picks at most (Small 384 experts, Mini 128; top 8). +pub fn routerFits(experts: usize, top: usize) error{Inkling2RouterShape}!void { + if (experts == 0 or experts > 512 * 8 or top == 0 or top > 32 or top > experts) return error.Inkling2RouterShape; +} + +/// Whether dynamic conv taps split the width: column c reads head c / (C / heads) (Small 4 key heads, Mini 8). +pub fn convFits(c: ConvArgs) error{Inkling2ConvHeads}!void { + if (c.dyn != 0 and (c.heads <= 0 or c.c <= 0 or @rem(c.c, c.heads) != 0)) return error.Inkling2ConvHeads; +} + /// The residual mix of each row and query, normed: a block a row. pub fn mix(k: *const Kernels, s: cuda.Stream, m: MixArgs) !void { - if (m.c > 10 * 512 or @rem(m.c, 128) != 0) return error.Inkling2MixWidth; // ops.cu: kMixCache x 512 columns, 16-byte copies + try mixFits(m.c); var a: cuda.Args = .{}; a.add(m); try go(if (m.rows <= 16) k.mix else k.mix_rows, s, .{ .x = @intCast(m.rows) }, 512, &a); // equal bits either way @@ -150,7 +166,7 @@ pub fn rowdot(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, out: u64, rows: /// The router's picks and weights from fp32 sigmoid scores [rows, experts] and the selection bias. pub fn topk(k: *const Kernels, s: cuda.Stream, scores: u64, bias: u64, pick: u64, wts: u64, rows: usize, experts: usize, top: usize, scale: f32) !void { - if (experts > 512 * 8 or top > 32) return error.Inkling2RouterShape; + try routerFits(experts, top); var a: cuda.Args = .{}; for ([_]u64{ scores, bias, pick, wts }) |v| a.add(v); a.add(int(experts)); @@ -168,6 +184,7 @@ pub fn gateup(k: *const Kernels, s: cuda.Stream, g: GateUpArgs) !void { /// A short convolution over each of `streams` streams' rows, their states carried (ops.cu's tf_ink2_conv). pub fn conv(k: *const Kernels, s: cuda.Stream, c: ConvArgs, streams: usize) !void { + try convFits(c); var a: cuda.Args = .{}; a.add(c); // a stream's rows in blocks of 32 (blocks past a stream's rows return at once) @@ -252,3 +269,7 @@ test "ops: the argument structs keep ops.cu's layouts" { try std.testing.expectEqual(@as(usize, 32), @sizeOf(RewindSite)); try std.testing.expectEqual(@as(usize, 6 * 8 + 6 * 4), @sizeOf(GateUpArgs)); } + +test { + _ = @import("ops_test.zig"); +} diff --git a/zig/src/families/inkling2/ops_test.zig b/zig/src/families/inkling2/ops_test.zig new file mode 100644 index 00000000000..147f41bef31 --- /dev/null +++ b/zig/src/families/inkling2/ops_test.zig @@ -0,0 +1,54 @@ +//! Inkling 2's glue launchers without a GPU: Mini's and Small's shapes launch, the rest are refused by name. +const std = @import("std"); +const cuda = @import("cuda"); +const ops = @import("ops.zig"); +const t = std.testing; + +const Fake = struct { + var count: usize = 0; + var grid: [3]u32 = undefined; + fn launch(_: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + grid = .{ gx, gy, gz }; + count += 1; + return 0; + } +}; + +fn kernels(d: *const cuda.Driver) ops.Kernels { + var k: ops.Kernels = undefined; + k.mod = .{ .d = d, .handle = null }; + k.rows_mod = .{ .d = d, .handle = null }; + const info = @typeInfo(ops.Kernels).@"struct"; + inline for (info.field_names, info.field_types, 1..) |name, ty, i| { + if (ty == cuda.Function) @field(k, name) = .{ .d = d, .handle = @ptrFromInt(i) }; + } + return k; +} + +test "inkling2 ops: Mini's widths launch (hidden 2,304, 8 key heads, 128 experts) as Small's do" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const k = kernels(&d); + const s: cuda.Stream = .{ .d = &d, .handle = null }; + Fake.count = 0; + for ([_]i32{ 2304, 4608 }) |c| try ops.mix(&k, s, .{ .partial = 0, .query = 0, .out = 0, .n_blocks = 8, .partial_bf16 = 1, .nq = 3, .rows = 1, .c = c, .eps = 1e-6 }); + for ([_][2]usize{ .{ 128, 8 }, .{ 384, 8 } }) |e| try ops.topk(&k, s, 0, 0, 0, 0, 16, e[0], e[1], 8); + for ([_][2]i32{ .{ 512, 4 }, .{ 1024, 8 } }) |w| try ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .dyn = 1, .heads = w[1], .c = w[0], .rows = 4, .mode = 0 }, 1); + try t.expectEqual(@as(usize, 6), Fake.count); + try t.expectEqual([3]u32{ 8, 1, 1 }, Fake.grid); // Mini's k/v conv: 1,024 columns in blocks of 128 +} + +test "inkling2 ops: widths, routers and dynamic taps the kernels cannot hold are refused by name, nothing launched" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const k = kernels(&d); + const s: cuda.Stream = .{ .d = &d, .handle = null }; + Fake.count = 0; + for ([_]i32{ 0, 2300, 5248, -128 }) |c| try t.expectError(error.Inkling2MixWidth, ops.mix(&k, s, .{ .partial = 0, .query = 0, .out = 0, .n_blocks = 1, .partial_bf16 = 1, .nq = 1, .rows = 1, .c = c, .eps = 1e-6 })); + for ([_][2]usize{ .{ 4097, 8 }, .{ 128, 33 }, .{ 128, 0 }, .{ 4, 8 }, .{ 0, 0 } }) |e| try t.expectError(error.Inkling2RouterShape, ops.topk(&k, s, 0, 0, 0, 0, 1, e[0], e[1], 8)); + for ([_][2]i32{ .{ 1024, 0 }, .{ 1024, 3 }, .{ 1020, 8 } }) |w| try t.expectError(error.Inkling2ConvHeads, ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .dyn = 1, .heads = w[1], .c = w[0], .rows = 1, .mode = 0 }, 1)); + try t.expectEqual(@as(usize, 0), Fake.count); + // static taps read no heads: any width launches + try ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .heads = 3, .c = 1000, .rows = 1, .mode = 0 }, 1); + try t.expectEqual(@as(usize, 1), Fake.count); +} diff --git a/zig/src/families/inkling2/plan.zig b/zig/src/families/inkling2/plan.zig index 86effc0c4a3..0999db43065 100644 --- a/zig/src/families/inkling2/plan.zig +++ b/zig/src/families/inkling2/plan.zig @@ -1,6 +1,24 @@ -//! The layer plan: which layers slide or see everything, where attention-residual blocks end, what layers sum over. +//! The layer plan: which layers slide or see everything, where attention-residual blocks end, what layers sum over, +//! and a looped model's visits (core/visit_plan.zig): each visit's layer, pass and state slots. const std = @import("std"); const config = @import("config.zig"); +const visit_plan = @import("visit_plan"); + +/// The states a visit keeps: a sliding layer's key/value ring, a global layer's whole cache, every visit's conv state. +pub const Slot = enum { sliding, full, conv }; + +/// Layer visits in run order with their slots (Small: every layer once). +pub const Visits = visit_plan.Plan(Slot, config.max_visits); + +const Holds = struct { + pub fn keeps(_: Holds, layer: u16, k: Slot) bool { + return switch (k) { + .conv => true, + .full => config.isGlobal(layer), + .sliding => !config.isGlobal(layer), + }; + } +}; /// A routed-expert layer's stored format, read from its tensors: ModelOpt NVFP4 (groups of 16) or MXFP8 (groups of 32). pub const Precision = enum { nvfp4, mxfp8 }; @@ -19,31 +37,38 @@ pub const Layer = struct { precision: Precision, }; -pub const Visit = struct { - layer: u32, // physical weight layer; core layers repeat with the same weights - pass: u32, // zero outside the core, otherwise one-based loop pass - cache_slot: u32, // this visit's private KV and four short-convolution states - previous_core_start: ?u32, // previous pass's first visit; its two bank states feed this visit's messages - - pub fn hasMessages(v: Visit) bool { - return v.previous_core_start != null; - } -}; - pub const Plan = struct { layers: [config.max_layers]Layer, n: u32, - visits: [config.max_visits]Visit, - n_visits: u32, final_sources: u32, // the output query's states: every finished block and the last layer's output + visits: Visits, + pre_blocks: u32, // looped: finished blocks entering the core + bank_blocks: u32, // looped: blocks a pass finishes past its entry block, the next pass's message sources + + /// Visit k takes the previous pass's messages: a core layer at pass 1 or later. + pub fn messages(p: *const Plan, k: u32) bool { + return p.visits.steps[k].pass > 0; + } + + /// Visit k starts a pass after the first: the running state restarts from the core's entry block. + pub fn restarts(p: *const Plan, k: u32) bool { + const s = p.visits.steps[k]; + return s.enter and s.pass > 0; + } + + /// The row of the cross-pass queries a core visit reads (its layer's place in the core), 0 outside the core. + pub fn coreIndex(p: *const Plan, k: u32) u32 { + const s = p.visits.steps[k]; + const l = p.visits.loop; + return if (s.layer >= l.start and s.layer < l.end) s.layer - l.start else 0; + } + pub fn at(p: *const Plan, i: u32) *const Layer { return &p.layers[i]; } - pub fn visit(p: *const Plan, i: u32) *const Visit { - return &p.visits[i]; - } + pub fn count(p: *const Plan, kind: Kind) u32 { var k: u32 = 0; @@ -53,30 +78,20 @@ pub const Plan = struct { pub fn visitCount(p: *const Plan, kind: Kind) u32 { var k: u32 = 0; - for (p.visits[0..p.n_visits]) |v| k += @intFromBool(p.layers[v.layer].kind == kind); + for (p.visits.slice()) |v| k += @intFromBool(p.layers[v.layer].kind == kind); return k; } }; /// The plan for a parsed config and each layer's expert precision (`prec` holds one entry per layer). -fn appendVisit(p: *Plan, c: *const config.Text, layer: u32, pass: u32) void { - const previous: ?u32 = if (c.loop) |core| - (if (pass >= 2) core.core_start + (pass - 2) * (core.core_end - core.core_start) else null) - else - null; - p.visits[p.n_visits] = .{ - .layer = layer, - .pass = pass, - .cache_slot = p.n_visits, - .previous_core_start = previous, - }; - p.n_visits += 1; -} -pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCount}!Plan { +pub fn build(c: *const config.Text, prec: []const Precision) error{ PrecisionCount, Layout, TooManySteps }!Plan { if (prec.len != c.layers) return error.PrecisionCount; var p: Plan = undefined; p.n = c.layers; - p.n_visits = 0; + const l: visit_plan.Loop = if (c.loop) |x| .{ .start = x.start, .end = x.end, .passes = x.passes } else visit_plan.straight; + p.visits = try Visits.build(c.layers, l, Holds{}); + p.pre_blocks = l.start / c.block; + p.bank_blocks = if (c.loop != null) (l.end - l.start) / c.block - 1 else 0; for (0..c.layers) |k| { const i: u32 = @intCast(k); const boundary = i % c.block == 0; @@ -95,12 +110,5 @@ pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCoun }; } p.final_sources = (c.layers + c.block - 1) / c.block + 1; - if (c.loop) |loop| { - for (0..loop.core_start) |i| appendVisit(&p, c, @intCast(i), 0); - for (1..loop.passes + 1) |pass| for (loop.core_start..loop.core_end) |i| appendVisit(&p, c, @intCast(i), @intCast(pass)); - for (loop.core_end..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); - } else { - for (0..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); - } return p; } diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index dd0105c93ea..909c7b8df32 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -163,14 +163,15 @@ fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) err return if (limit > resident + margin) limit - resident - margin else 0; } +/// The longest context every stream can hold at once: each owns a target state and draft rows; the scores are shared. fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u64, draft_shared_token: u64) usize { - const one: u64 = st.cacheBytes(1) + streams * (draft_fixed + draft_token) + draft_shared_token; + const one: u64 = streams * (st.cacheBytes(1) + draft_fixed + draft_token) + draft_shared_token; if (one > bytes) return 0; var lo: usize = 1; var hi: usize = most; while (lo < hi) { const mid = lo + (hi - lo + 1) / 2; - const need = st.cacheBytes(mid) + streams * (draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); + const need = streams * (st.cacheBytes(mid) + draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); if (need <= bytes) lo = mid else hi = mid - 1; } return lo; @@ -278,9 +279,11 @@ test "Inkling native load limit clamps before integer conversion" { } test "Inkling native longest context accounts target, streams and shared draft scores" { - const budget = st.cacheBytes(7) + 2 * (11 + 7 * 13) + 7 * 17; + const budget = 2 * (st.cacheBytes(7) + 11 + 7 * 13) + 7 * 17; try std.testing.expectEqual(@as(usize, 7), longest(budget, 8, 2, 11, 13, 17)); + try std.testing.expectEqual(@as(usize, 6), longest(budget - 1, 8, 2, 11, 13, 17)); try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1) - 1, 8, 1, 0, 0, 0)); + try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1), 8, 2, 0, 0, 0)); const per_token = dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0); const conservative = dspark.Drafter.streamBytes(0) + 127 * per_token + 129 * per_token; try std.testing.expect(conservative >= dspark.Drafter.streamBytes(129)); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index df7b77ae8a2..9070d51f488 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -45,6 +45,8 @@ pub const affine_mm = @import("core/affine_mm.zig"); pub const moe_route = @import("core/moe_route.zig"); /// The checkpoint formats (MLX affine and its fp64 reader for the device checks, exact widen). pub const quant = @import("core/quant/quant.zig"); +pub const modelopt = @import("core/modelopt.zig"); +pub const visit_plan = @import("core/visit_plan.zig"); pub const exl3_format = @import("core/exl3_format.zig"); pub const exl3_projection = @import("core/exl3_projection.zig"); pub const exlr8 = @import("core/exlr8.zig"); diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 387e93eb9ae..47eb7238cf3 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -11,6 +11,7 @@ const Grouped = @import("contract_gb10_many.zig").Registrations; pub const Sets = struct { gpa: std.mem.Allocator, bf16_experts: *@import("contract_experts_bf16.zig").Set, + stored_experts: *@import("contract_stored_experts.zig").Set, pocket: *@import("contract_pocket.zig").Set, minimax: *@import("contract_minimax.zig").Set, inkling2: *@import("contract_inkling2.zig").Set, @@ -34,6 +35,8 @@ pub const Sets = struct { pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel), affine4: *cuda.qlinear.Affine4Kernels, cap: u32) !Sets { const bf16_experts = try @import("contract_experts_bf16.zig").Set.init(gpu, s, a, list); errdefer bf16_experts.deinit(); + const stored_experts = try @import("contract_stored_experts.zig").Set.init(gpu, s, a, list); + errdefer stored_experts.deinit(); const pocket = try @import("contract_pocket.zig").Set.init(gpu, s, a, list); errdefer pocket.deinit(); const minimax = try @import("contract_minimax.zig").Set.init(gpu, s, a, list); @@ -82,6 +85,7 @@ pub const Sets = struct { return .{ .gpa = gpu.gpa, .bf16_experts = bf16_experts, + .stored_experts = stored_experts, .pocket = pocket, .minimax = minimax, .inkling2 = inkling2, @@ -124,6 +128,7 @@ pub const Sets = struct { sets.inkling2.deinit(); sets.minimax.deinit(); sets.pocket.deinit(); + sets.stored_experts.deinit(); sets.bf16_experts.deinit(); } }; diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index 1ab486edf31..6bb9eeba3b6 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -9,8 +9,8 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + loop: @import("contract_inkling2_loop.zig").Set = .{}, experts: @import("contract_inkling2_experts.zig").Set = .{}, - loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -21,15 +21,16 @@ pub const Set = struct { errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); errdefer set.ops.deinit(); + try set.loop.init(gpu, s, a, list); + errdefer set.loop.deinit(); try set.experts.init(gpu, s, a, list); errdefer set.experts.deinit(); - try set.loop_math.init(gpu, s, a, list); return set; } pub fn deinit(set: *Set) void { - set.loop_math.deinit(); set.experts.deinit(); + set.loop.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_attn.zig b/zig/tests/cuda/contract_inkling2_attn.zig index 3c339b46ef9..53ffc3fdbe3 100644 --- a/zig/tests/cuda/contract_inkling2_attn.zig +++ b/zig/tests/cuda/contract_inkling2_attn.zig @@ -6,21 +6,25 @@ const g = @import("core").contract.gates; const K = @import("inkling2").kernels; const rows = @import("contract_inkling2_attn_rows.zig"); const prep = @import("contract_inkling2_attn_prep.zig"); +const M = @import("contract_inkling2_model.zig"); -/// The attention launches as the forward makes them: prep, the bias table, then the chunks and their merge. +/// The attention launches as the forward makes them (prep, bias table, chunks and merge): Small's, then Mini's. pub const Set = struct { k: K.Kernels = undefined, loaded: bool = false, - attns: [7]rows.Attn = undefined, - preps: [3]prep.Prep = undefined, - tables: [2]prep.Table = undefined, + attns: [14]rows.Attn = undefined, + preps: [6]prep.Prep = undefined, + tables: [2]prep.Table = undefined, // Mini's bias tables have Small's shapes: one registration covers both /// Every registration (the fold first: the split and prompt launches must equal its bits), then the controls. pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { set.k = try K.Kernels.load(gpu.d); const forms = [_]struct { rows.Path, rows.Plant }{ .{ .sliding, .none }, .{ .fold, .none }, .{ .split, .none }, .{ .prompt, .none }, .{ .sliding, .late_bias }, .{ .fold, .no_sink }, .{ .prompt, .q_ulp } }; - for (&set.attns, forms) |*x, f| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .path = f[0], .plant = f[1] }; - for (&set.preps, [_]bool{ false, true, true }, 0..) |*x, global, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .global = global, .tau_off = i == 2 }; + for (&set.attns, 0..) |*x, i| { + const f = forms[i % 7]; + x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .path = f[0], .plant = f[1], .m = if (i < 7) M.small else M.mini }; + } + for (&set.preps, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .global = i % 3 != 0, .tau_off = i % 3 == 2, .m = if (i < 3) M.small else M.mini }; for (&set.tables, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .late = i == 1 }; set.loaded = true; errdefer set.deinit(); @@ -29,7 +33,11 @@ pub const Set = struct { for (set.attns[0..4]) |*x| try list.append(a, x.kernel()); try list.append(a, set.preps[2].kernel()); try list.append(a, set.tables[1].kernel()); - for (set.attns[4..]) |*x| try list.append(a, x.kernel()); + for (set.attns[4..7]) |*x| try list.append(a, x.kernel()); + for (set.preps[3..5]) |*x| try list.append(a, x.kernel()); + for (set.attns[7..11]) |*x| try list.append(a, x.kernel()); + try list.append(a, set.preps[5].kernel()); + for (set.attns[11..]) |*x| try list.append(a, x.kernel()); } pub fn deinit(set: *Set) void { diff --git a/zig/tests/cuda/contract_inkling2_attn_prep.zig b/zig/tests/cuda/contract_inkling2_attn_prep.zig index 456e98b43d1..dcf265a75d1 100644 --- a/zig/tests/cuda/contract_inkling2_attn_prep.zig +++ b/zig/tests/cuda/contract_inkling2_attn_prep.zig @@ -5,6 +5,7 @@ const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); const ref = core.contract.inkling2_attn_ref; +const M = @import("contract_inkling2_model.zig"); const contract = core.contract; const c = contract.spec; @@ -12,7 +13,6 @@ const g = contract.gates; const K = ink.kernels; const D = ref.D; const heads = ref.heads; -const kv = ref.kv; const R = ref.d_rel; const u: f64 = 0x1p-24; @@ -24,9 +24,9 @@ fn depthPrep(_: c.Shape) usize { return 4 + 5; // a lane's four squares, then the warp's five butterfly adds } -/// rows x 24 heads x 128 (q); k: the first stream's context, so global rows meet tau at 1M positions. -pub fn prepSpec(global: bool) c.Spec { - const name = if (global) "inkling2 attn tf_ink2_prep global (q, rel scaled by tau; k, v into a 4,096-slot ring)" else "inkling2 attn tf_ink2_prep sliding (q, rel, k, v rows into the 3,072-slot ring)"; +/// rows x 24 heads x 128 (q); k: the first stream's context, so global rows meet tau at 1M positions (Mini: 8 kv). +pub fn prepSpec(global: bool, mini: bool) c.Spec { + const name = if (global) M.named("inkling2 attn tf_ink2_prep global (q, rel scaled by tau; k, v into a 4,096-slot ring)", mini) else M.named("inkling2 attn tf_ink2_prep sliding (q, rel, k, v rows into the 3,072-slot ring)", mini); const why = "a head's sum of squares only scales it: a bf16 sum's error stays under the bf16 output's rounding"; return .{ .name = name, .accum = .f32, .depth = depthPrep, .ops = 16, .out = .bf16, .served = &prep_shapes, .nan = .{ .stated = nan_rule }, .sums = .{ .f16 = 100, .bf16 = 0, .why = why } }; } @@ -37,11 +37,12 @@ pub const Prep = struct { k: *const K.Kernels, global: bool, tau_off: bool = false, // control: the device runs with alpha 0 + m: M.Model = M.small, shape: c.Shape = undefined, fill: g.Fill = .random, ring: usize = 0, streams: usize = 1, - raw: [4][]u16 = .{ &.{}, &.{}, &.{}, &.{} }, // q [rows][24][128], k, v [rows][4][128], rel [rows][24][16] + raw: [4][]u16 = .{ &.{}, &.{}, &.{}, &.{} }, // q [rows][24][128], k, v [rows][kv][128], rel [rows][24][16] scales: [2][]u16 = .{ &.{}, &.{} }, // q_scale [24][128], rel_scale [24][16] pos: []usize = &.{}, stream: []usize = &.{}, @@ -79,8 +80,8 @@ pub const Prep = struct { } pub fn kernel(self: *Prep) g.Kernel { - var s = prepSpec(self.global); - if (self.tau_off) s.name = "control: inkling2 attn tf_ink2_prep global rows without tau"; + var s = prepSpec(self.global, self.m.mini); + if (self.tau_off) s.name = M.named("control: inkling2 attn tf_ink2_prep global rows without tau", self.m.mini); return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.tau_off) .shapes else null }; } @@ -88,7 +89,7 @@ pub const Prep = struct { fn sizes(self: *const Prep) [4]usize { const rows = self.shape.rows; - const cache = self.streams * kv * self.ring * D; + const cache = self.streams * self.m.kv * self.ring * D; return .{ rows * heads * D, rows * heads * R, cache, cache }; } @@ -106,6 +107,7 @@ pub const Prep = struct { self.fill = fill; const a = self.rig.gpu.gpa; const rows = shape.rows; + const kv = self.m.kv; self.ring = if (self.global) 4096 else K.Layer.sliding(1024, 2048).ring; self.streams = if (rows >= 2 and rows <= 128) 2 else 1; const n1 = if (self.streams == 2) rows / 2 else 0; @@ -159,9 +161,9 @@ pub const Prep = struct { const sz = self.sizes(); try self.rig.zero(self.out[2], sz[2] * 2); // slots no row writes stay 0, so a stray write shows try self.rig.zero(self.out[3], sz[3] * 2); - const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = self.dev[0], .seg_of = self.dev[1], .segs = self.dev[2], .tiles = 0, .n_tiles = 0, .last_pos = @intCast(self.shape.k - 1) }; + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = @intCast(self.m.kv), .pos = self.dev[0], .seg_of = self.dev[1], .segs = self.dev[2], .tiles = 0, .n_tiles = 0, .last_pos = @intCast(self.shape.k - 1) }; const l: K.Layer = .{ .window = if (self.global) 0 else 1024, .ring = @intCast(self.ring), .chunk = 0, .tau = self.global }; - const cfg: K.Prep = .{ .qk_clip = @floatCast(ref.qk_clip), .rel_clip = @floatCast(ref.rel_clip), .floor = @floatCast(ref.floor_pos), .alpha = if (self.tau_off) @as(f32, 0) else @as(f32, @floatCast(ref.alpha)), .eps = @floatCast(ref.eps) }; + const cfg: K.Prep = .{ .qk_clip = @floatCast(ref.qk_clip), .rel_clip = @floatCast(ref.rel_clip), .floor = @floatCast(self.m.floor), .alpha = if (self.tau_off) @as(f32, 0) else @as(f32, @floatCast(ref.alpha)), .eps = @floatCast(ref.eps) }; try K.prep(self.k, self.rig.s, r, l, cfg, self.in[0..4].*, self.in[4..6].*, self.out[0], self.out[1], .{ .k = self.out[2], .v = self.out[3] }); try self.rig.s.synchronize(); } @@ -199,9 +201,10 @@ pub const Prep = struct { @memset(@field(self, f), 0); } const sz = self.sizes(); + const kv = self.m.kv; var x: [D]f64 = undefined; for (0..self.shape.rows) |r| { - const t: ?f64 = if (self.global) ref.tau(self.pos[r]) else null; + const t: ?f64 = if (self.global) ref.tauAt(self.pos[r], self.m.floor) else null; for (0..heads) |h| { for (x[0..D], 0..) |*v, i| v.* = ref.bf(self.raw[0][(r * heads + h) * D + i]) * ref.bf(self.scales[0][h * D + i]); self.head(x[0..D], ref.qk_clip, t, (r * heads + h) * D, acc, order); @@ -354,7 +357,7 @@ pub const Table = struct { } pub fn run(self: *Table) !void { - const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 0 }; + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = ref.kv, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 0 }; try K.relTable(self.k, self.rig.s, r, self.in[0], self.in[2], self.out); try self.rig.s.synchronize(); } diff --git a/zig/tests/cuda/contract_inkling2_attn_rows.zig b/zig/tests/cuda/contract_inkling2_attn_rows.zig index ad95cb5de5a..86d2c0bfa15 100644 --- a/zig/tests/cuda/contract_inkling2_attn_rows.zig +++ b/zig/tests/cuda/contract_inkling2_attn_rows.zig @@ -5,6 +5,7 @@ const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); const ref = core.contract.inkling2_attn_ref; +const M = @import("contract_inkling2_model.zig"); const contract = core.contract; const c = contract.spec; @@ -12,7 +13,6 @@ const g = contract.gates; const K = ink.kernels; const D = ref.D; const heads = ref.heads; -const kv = ref.kv; const n_out = heads * D; const global_ring = 4096; // global keys to 1M wrap a 4,096-slot ring (key p in slot p % ring): no 2 GiB cache needed @@ -22,7 +22,8 @@ pub const Path = enum { sliding, fold, split, prompt }; /// A control's planted fault, through the device's inputs only: the served kernels run as they are. pub const Plant = enum { none, late_bias, no_sink, q_ulp }; -pub const fold_name = "inkling2 attn tf_ink2_attn_fold + tf_ink2_merge (global layers, 16,384-key chunks)"; +const fold_base = "inkling2 attn tf_ink2_attn_fold + tf_ink2_merge (global layers, 16,384-key chunks)"; +pub const fold_name = fold_base; /// Unused beside `bounds`: the reference derives each output's allowance from the device's own steps. fn depth(_: c.Shape) usize { @@ -34,33 +35,33 @@ const fold_shapes = [_]c.Shape{ .{ .rows = 16, .n = n_out, .k = 20000 }, .{ .row const split_shapes = [_]c.Shape{ .{ .rows = 16, .n = n_out, .k = 20000 }, .{ .rows = 1, .n = n_out, .k = 1048576 }, .{ .rows = 8, .n = n_out, .k = 1048576 }, .{ .rows = 64, .n = n_out, .k = 70000 }, .{ .rows = 33, .n = n_out, .k = 1030 } }; const prompt_shapes = [_]c.Shape{ .{ .rows = 130, .n = n_out, .k = 20000 }, .{ .rows = 1, .n = n_out, .k = 1048576 }, .{ .rows = 2048, .n = n_out, .k = 2048 }, .{ .rows = 2048, .n = n_out, .k = 18432 }, .{ .rows = 256, .n = n_out, .k = 1048576 } }; -/// rows x 24 heads x 128 outputs; k: the first stream's context (its last row's position + 1). -pub fn spec(path: Path) c.Spec { +/// rows x 24 heads x 128 outputs; k: the first stream's context (Mini: same shapes, 8 key heads in the inputs). +pub fn spec(path: Path, mini: bool) c.Spec { const no: c.Tile = .{}; - const rows32: c.Tile = .{ .size = 32 }; // 192 (row, head) pairs: three 64-pair tiles + const rows32: c.Tile = .{ .size = if (mini) 64 else 32 }; // 192 (row, head) pairs: three 64-pair tiles const s: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 12, .out = .bf16, .served = &fold_shapes }; var x = s; switch (path) { .sliding => { - x.name = "inkling2 attn tf_ink2_attn + tf_ink2_merge (sliding layers: window 1,024, 256-key chunks)"; + x.name = M.named("inkling2 attn tf_ink2_attn + tf_ink2_merge (sliding layers: window 1,024, 256-key chunks)", mini); x.served = &sliding_shapes; x.tiles = .{ rows32, no, .{ .size = 1024 } }; }, .fold => { - x.name = fold_name; + x.name = M.named(fold_base, mini); x.tiles = .{ rows32, no, .{ .size = 16384 } }; }, .split => { - x.name = "inkling2 attn tf_ink2_attn split + tf_ink2_merge (global layers, a block a 1,024-key sub-chunk)"; + x.name = M.named("inkling2 attn tf_ink2_attn split + tf_ink2_merge (global layers, a block a 1,024-key sub-chunk)", mini); x.served = &split_shapes; x.tiles = .{ rows32, no, .{ .size = 1024 } }; - x.replaces = fold_name; + x.replaces = M.named(fold_base, mini); }, .prompt => { - x.name = "inkling2 attn tf_ink2_attn_prompt + tf_ink2_merge (one stream's prompt rows, 128 pairs a block)"; + x.name = M.named("inkling2 attn tf_ink2_attn_prompt + tf_ink2_merge (one stream's prompt rows, 128 pairs a block)", mini); x.served = &prompt_shapes; - x.tiles = .{ .{ .size = 64 }, no, .{ .size = 16384 } }; - x.replaces = fold_name; + x.tiles = .{ .{ .size = if (mini) 128 else 64 }, no, .{ .size = 16384 } }; // 384 pairs: three blocks + x.replaces = M.named(fold_base, mini); }, } return x; @@ -79,6 +80,7 @@ pub const Attn = struct { k: *const K.Kernels, path: Path, plant: Plant = .none, + m: M.Model = M.small, shape: c.Shape = undefined, fill: g.Fill = .random, layer: K.Layer = undefined, @@ -117,12 +119,12 @@ pub const Attn = struct { } pub fn kernel(self: *Attn) g.Kernel { - var s = spec(self.path); + var s = spec(self.path, self.m.mini); s.name = switch (self.plant) { .none => s.name, - .late_bias => "control: inkling2 attn sliding rows read each distance's bias one distance late", - .no_sink => "control: inkling2 attn global fold rows merged without their sink", - .q_ulp => "control: inkling2 attn prompt rows with one q value a bf16 step up (bit equality must see it)", + .late_bias => M.named("control: inkling2 attn sliding rows read each distance's bias one distance late", self.m.mini), + .no_sink => M.named("control: inkling2 attn global fold rows merged without their sink", self.m.mini), + .q_ulp => M.named("control: inkling2 attn prompt rows with one q value a bf16 step up (bit equality must see it)", self.m.mini), }; return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.plant == .none) null else .shapes }; } @@ -134,7 +136,7 @@ pub const Attn = struct { } fn call(self: *const Attn) ref.Call { - return .{ .q = self.q, .k = self.kc, .v = self.vc, .tab = self.tab, .sink = self.sink, .gate = self.gate, .pos = self.pos, .stream = self.stream, .ring = self.layer.ring, .window = self.layer.window, .exact = self.fill == .stress }; + return .{ .q = self.q, .k = self.kc, .v = self.vc, .tab = self.tab, .sink = self.sink, .gate = self.gate, .pos = self.pos, .stream = self.stream, .ring = self.layer.ring, .window = self.layer.window, .exact = self.fill == .stress, .kv = self.m.kv }; } /// Two streams for decode windows (2..128 rows; the second at half the context), else one; prompt: one. @@ -153,7 +155,7 @@ pub const Attn = struct { const n1 = if (self.streams == 2) rows / 2 else 0; const n0 = rows - n1; const last1 = @max(n1, shape.k / 2); - const segs = [2]K.Seg{ .{ .row0 = 0, .n = @intCast(n0), .p0 = @intCast(shape.k - n0), .off = 0 }, .{ .row0 = @intCast(n0), .n = @intCast(n1), .p0 = @intCast(last1 - n1), .off = @intCast(ring * kv * D) } }; + const segs = [2]K.Seg{ .{ .row0 = 0, .n = @intCast(n0), .p0 = @intCast(shape.k - n0), .off = 0 }, .{ .row0 = @intCast(n0), .n = @intCast(n1), .p0 = @intCast(last1 - n1), .off = @intCast(ring * self.m.kv * D) } }; self.pos = try a.alloc(usize, rows); self.stream = try a.alloc(usize, rows); for (0..rows) |r| { @@ -165,9 +167,9 @@ pub const Attn = struct { const rng = prng.random(); try self.fillAll(rng, ring); if (fill == .nonfinite) self.plantNonfinite(ring); - const tiles = try a.alloc(K.Tile, K.tileCount(rows, ref.group) + 2); + const tiles = try a.alloc(K.Tile, K.tileCount(rows, @intCast(self.m.group())) + 2); defer a.free(tiles); - self.n_tiles = @intCast(try K.tiles(segs[0..self.streams], ref.group, tiles)); + self.n_tiles = @intCast(try K.tiles(segs[0..self.streams], @intCast(self.m.group()), tiles)); const pos32 = try a.alloc(i32, 2 * rows); defer a.free(pos32); for (0..rows) |r| { @@ -201,6 +203,7 @@ pub const Attn = struct { const rows = self.shape.rows; const stress = self.fill == .stress; self.q = try a.alloc(u16, rows * n_out); + const kv = self.m.kv; self.kc = try a.alloc(u16, self.streams * kv * ring * D); self.vc = try a.alloc(u16, self.kc.len); self.tab = try a.alloc(u16, rows * heads * ref.extent); @@ -300,7 +303,7 @@ pub const Attn = struct { /// kernels.attend as the forward calls it; `path` picks its branch through `streams` and the partial room. fn launch(self: *Attn, path: Path, q: u64, tab: u64, sink: u64, out: u64) !void { const d = self.dev; - var r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = d.pos, .seg_of = d.seg_of, .segs = d.segs, .tiles = d.tiles, .n_tiles = self.n_tiles, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.streams) }; + var r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = @intCast(self.m.kv), .pos = d.pos, .seg_of = d.seg_of, .segs = d.segs, .tiles = d.tiles, .n_tiles = self.n_tiles, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.streams) }; const stride = K.slotsFor(self.layer, self.shape.k); var slots: usize = 0; // no partial room for sub-chunks: global calls take the fold or the prompt kernel switch (path) { @@ -340,7 +343,7 @@ pub const Attn = struct { std.debug.assert(self.fill == .stress); const a = self.rig.gpu.gpa; const cl = self.call(); - try Pool.run(a, .{ .call = &cl, .want = out, .tol = &.{}, .sim = .{ .acc = acc, .order = order } }, self.shape.rows * kv); + try Pool.run(a, .{ .call = &cl, .want = out, .tol = &.{}, .sim = .{ .acc = acc, .order = order } }, self.shape.rows * self.m.kv); } }; @@ -365,11 +368,12 @@ const Pool = struct { var i = j.first; while (i < j.items) : (i += j.step) { if (pool.sim) |s| { + const kv = pool.call.kv; const r = i / kv; - const h0 = (i % kv) * ref.group; + const h0 = (i % kv) * pool.call.perKv(); const o = pool.want[(r * heads + h0) * D ..][0..D]; ref.simulate(pool.call, r, h0, s.acc, s.order, j.p, j.col, o); - for (1..ref.group) |e| @memcpy(pool.want[(r * heads + h0 + e) * D ..][0..D], o); + for (1..pool.call.perKv()) |e| @memcpy(pool.want[(r * heads + h0 + e) * D ..][0..D], o); } else { const at = i * D; ref.row(pool.call, i / heads, i % heads, j.ks, pool.want[at..][0..D], pool.tol[at..][0..D]); diff --git a/zig/tests/cuda/contract_inkling2_loop.zig b/zig/tests/cuda/contract_inkling2_loop.zig new file mode 100644 index 00000000000..d221eaf618f --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop.zig @@ -0,0 +1,307 @@ +//! Inkling 2 Mini's served message and gate launches under FP64 references and planted controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const loop = @import("inkling2").loop; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const hidden = 2304; +const rank = 64; +const eps = ref.eps; +const mix_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = 3 }, .{ .rows = 3, .n = hidden, .k = 2 } }; +const gate_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = rank }, .{ .rows = 3, .n = hidden, .k = rank } }; + +fn stressBank(i: usize) f32 { + return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; +} + +/// The four role queries over completed blocks and a partial, with Mini's post-dot 1/48 scale. +pub const Mix = struct { + kern: *const loop.Kernels, + f32_partial: bool = false, + aliased: bool = false, + shape: c.Shape = undefined, + blocks: []u16 = &.{}, + partial: []f32 = &.{}, + queries: []f32 = &.{}, + args: loop.MixArgs = undefined, + + pub const sums = {}; + pub fn spec(self: *const Mix) c.Spec { + return .{ .name = if (self.aliased) "control: inkling2 loop mix with block one replaced by block zero" else "inkling2 loop tf_ink2_loop_mix (four role queries, normalized sources)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) mix_shapes[0..1] else &mix_shapes }; + } + fn depth(s: c.Shape) usize { + return 2 * ref.blockDepth(s.n, 256) + 16; + } + pub fn control(self: *const Mix) ?g.Gate { + return if (self.aliased) .shapes else null; + } + pub fn free(self: *Mix, a: std.mem.Allocator) void { + a.free(self.blocks); + a.free(self.partial); + a.free(self.queries); + self.blocks = &.{}; + self.partial = &.{}; + self.queries = &.{}; + } + pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != hidden or shape.k < 1 or shape.k > loop.max_blocks + 1) return false; + self.free(a); + self.shape = shape; + const nb = shape.k - 1; + const plane = shape.rows * hidden; + self.blocks = try ref.bfs(a, rng, nb * plane, -1, 1); + self.partial = try ref.f32s(a, rng, plane, -1, 1); + self.queries = try ref.f32s(a, rng, 4 * hidden, -0.25, 0.25); + if (fill == .stress) { + for (self.blocks, 0..) |*v, i| v.* = c.toBf16(stressBank(i % hidden)); + for (self.partial, 0..) |*v, i| v.* = stressBank(i % hidden); + @memset(self.queries, 0); + } + if (!self.f32_partial) { + for (self.partial) |*v| v.* = c.fromBf16(c.toBf16(v.*)); + } + if (fill == .nonfinite) { + if (nb != 0) ref.plant(u16, self.blocks[0..plane], shape.rows, hidden, ref.asBf); + ref.plant(f32, self.partial, shape.rows, hidden, ref.asF32); + } + var args: loop.MixArgs = .{ .partial = 0, .out = 0, .out_stride = @intCast(plane), .n_blocks = @intCast(nb), .partial_f32 = @intFromBool(self.f32_partial), .nq = 4, .rows = @intCast(shape.rows), .h = hidden, .eps = eps, .scale = 1.0 / 48.0 }; + for (0..nb) |b| args.blocks[b] = try ref.input(rig, self.blocks[b * plane ..][0..plane]); + if (self.f32_partial) { + args.partial = try ref.input(rig, self.partial); + } else { + const bits = try a.alloc(u16, plane); + defer a.free(bits); + for (bits, self.partial) |*d, v| d.* = c.toBf16(v); + args.partial = try ref.input(rig, bits); + } + for (0..4) |q| args.query[q] = try ref.input(rig, self.queries[q * hidden ..][0..hidden]); + args.out = try rig.output(4 * plane * 4); + self.args = args; + return true; + } + pub fn run(self: *Mix, rig: *rig_.Rig) !void { + var args = self.args; + if (self.aliased) args.blocks[1] = args.blocks[0]; + try loop.mix(self.kern, rig.s, args); + } + pub fn count(self: *const Mix) usize { + return 4 * self.shape.rows * hidden; + } + fn source(self: *const Mix, s: usize, row: usize, col: usize) f64 { + const plane = self.shape.rows * hidden; + return if (s < self.shape.k - 1) ref.bf(self.blocks[s * plane + row * hidden + col]) else self.partial[row * hidden + col]; + } + pub fn solve(self: *const Mix, a: std.mem.Allocator, sum: ref.Sums, out: []ref.Iv) !void { + const terms = try a.alloc(ref.Iv, hidden); + defer a.free(terms); + const scratch = try a.alloc(f64, hidden); + defer a.free(scratch); + const d = depth(self.shape); + for (0..self.shape.rows) |row| { + var inv: [loop.max_blocks + 1]ref.Iv = undefined; + for (0..self.shape.k) |s| { + for (terms, 0..) |*t, col| { + const x = ref.Iv.of(self.source(s, row, col)); + t.* = x.mul(x); + } + inv[s] = ref.rms(sum.sum(terms, d, scratch), hidden, eps); + } + for (0..4) |q| { + var logits: [loop.max_blocks + 1]ref.Iv = undefined; + for (0..self.shape.k) |s| { + for (terms, 0..) |*t, col| t.* = ref.Iv.of(self.queries[q * hidden + col]).mul(ref.Iv.of(self.source(s, row, col))).mul(inv[s]); + logits[s] = sum.sum(terms, d, scratch).mul(ref.Iv.of(1.0 / 48.0)); + } + softmax(logits[0..self.shape.k]); + for (0..hidden) |col| { + var value = ref.Iv.of(0); + for (0..self.shape.k) |s| value = value.add(logits[s].mul(ref.Iv.of(self.source(s, row, col)).mul(inv[s]))); + out[(q * self.shape.rows + row) * hidden + col] = value; + } + } + } + } +}; + +fn softmax(logits: []ref.Iv) void { + var peak = logits[0]; + for (logits[1..]) |v| peak = .{ .m = @max(peak.m, v.m), .lo = @max(peak.lo, v.lo), .hi = @max(peak.hi, v.hi) }; + var den = ref.Iv.of(0); + for (logits) |*v| { + v.* = v.sub(peak).exp(); + den = den.add(v.*); + } + for (logits) |*v| v.* = v.div(den); +} + +const Stage = enum { down, lin, mix }; + +/// Three gates read message role planes 0, 1 and 2; each registration checks one launch's result. +pub const Gate = struct { + kern: *const loop.Kernels, + stage: Stage, + wrong_slot: bool = false, + shape: c.Shape = undefined, + h: []f32 = &.{}, + msg: []f32 = &.{}, + down_w: []u16 = &.{}, + forget: []u16 = &.{}, + gain: []u16 = &.{}, + norm: []u16 = &.{}, + args: loop.GateArgs = undefined, + + pub const sums = {}; + pub fn spec(self: *const Gate) c.Spec { + const names = [_][]const u8{ "inkling2 loop tf_ink2_loop_gate_down (BF16 rank-64 projections)", "inkling2 loop tf_ink2_loop_gate_lin (forget/gain blend)", "inkling2 loop tf_ink2_loop_gate_mix (BF16 normed output)" }; + return .{ .name = if (self.wrong_slot) "control: inkling2 loop gate zero reads message role plane one" else names[@backingInt(self.stage)], .accum = .f32, .depth = depth, .out = if (self.stage == .lin) .f32 else .bf16, .served = if (self.wrong_slot) gate_shapes[0..1] else &gate_shapes }; + } + fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 256) + (2 * s.n + 31) / 32 + 5 + 2 * rank; + } + pub fn control(self: *const Gate) ?g.Gate { + return if (self.wrong_slot) .shapes else null; + } + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.h); + a.free(self.msg); + a.free(self.down_w); + a.free(self.forget); + a.free(self.gain); + a.free(self.norm); + self.h = &.{}; + self.msg = &.{}; + self.down_w = &.{}; + self.forget = &.{}; + self.gain = &.{}; + self.norm = &.{}; + } + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != hidden or shape.k != rank) return false; + self.free(a); + self.shape = shape; + const plane = shape.rows * hidden; + self.h = try ref.f32s(a, rng, 3 * plane, -1, 1); + self.msg = try ref.f32s(a, rng, 4 * plane, -1, 1); + self.down_w = try ref.bfs(a, rng, 3 * rank * 2 * hidden, -0.1, 0.1); + self.forget = try ref.bfs(a, rng, 3 * hidden * rank, -0.2, 0.2); + self.gain = try ref.bfs(a, rng, 3 * hidden * rank, -0.2, 0.2); + self.norm = try ref.bfs(a, rng, 3 * hidden, 0.5, 1.5); + if (fill == .stress) { + for (self.h, 0..) |*v, i| v.* = stressBank(i % hidden); + for (self.msg, 0..) |*v, i| v.* = stressBank(i % hidden); + for (self.down_w) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.forget) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + ref.plant(f32, self.h, 3 * shape.rows, hidden, ref.asF32); + ref.plant(f32, self.msg, 4 * shape.rows, hidden, ref.asF32); + } + var args: loop.GateArgs = .{ .msg = try ref.input(rig, self.msg), .msg_stride = @intCast(plane), .slot = .{ 0, 1, 2 }, .down = 0, .out = 0, .out_stride = @intCast(plane), .rows = @intCast(shape.rows), .h_dim = hidden, .rank = rank, .eps_unit = eps, .eps = eps, .ys = 0 }; + for (0..3) |gate| { + args.h[gate] = try ref.input(rig, self.h[gate * plane ..][0..plane]); + args.down_w[gate] = try ref.input(rig, self.down_w[gate * rank * 2 * hidden ..][0 .. rank * 2 * hidden]); + args.forget[gate] = try ref.input(rig, self.forget[gate * hidden * rank ..][0 .. hidden * rank]); + args.gain[gate] = try ref.input(rig, self.gain[gate * hidden * rank ..][0 .. hidden * rank]); + args.norm[gate] = try ref.input(rig, self.norm[gate * hidden ..][0..hidden]); + } + const dn = 3 * shape.rows * rank * 2; + const yn = 3 * plane * 4; + const on = 3 * plane * 2; + args.down = if (self.stage == .down) try rig.output(dn) else try rig.scratch(dn); + args.ys = if (self.stage == .lin) try rig.output(yn) else try rig.scratch(yn); + args.out = if (self.stage == .mix) try rig.output(on) else try rig.scratch(on); + self.args = args; + return true; + } + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + var args = self.args; + if (self.wrong_slot) args.slot[0] = 1; + try loop.gates(self.kern, rig.s, args, 3); + } + pub fn count(self: *const Gate) usize { + return switch (self.stage) { + .down => 3 * self.shape.rows * rank, + .lin, .mix => 3 * self.shape.rows * hidden, + }; + } + pub fn solve(self: *const Gate, a: std.mem.Allocator, sum: ref.Sums, out: []ref.Iv) !void { + const terms = try a.alloc(ref.Iv, 2 * hidden); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * hidden); + defer a.free(scratch); + const normalized = try a.alloc(ref.Iv, 2 * hidden); + defer a.free(normalized); + const zeta = try a.alloc(ref.Iv, rank); + defer a.free(zeta); + const ys = try a.alloc(ref.Iv, 3 * self.shape.rows * hidden); + defer a.free(ys); + const later = ref.later(sum); + const d = depth(self.shape); + for (0..3) |gate| for (0..self.shape.rows) |row| { + const h = self.h[(gate * self.shape.rows + row) * hidden ..][0..hidden]; + const m = self.msg[(gate * self.shape.rows + row) * hidden ..][0..hidden]; + var inv: [2]ref.Iv = undefined; + for (0..2) |side| { + const x = if (side == 0) h else m; + for (terms[0..hidden], x) |*t, v| { + const e = ref.Iv.of(v); + t.* = e.mul(e); + } + inv[side] = ref.rms(sum.sum(terms[0..hidden], d, scratch), hidden, eps); + } + for (normalized[0..hidden], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); + for (normalized[hidden..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); + for (0..rank) |r| { + for (terms, normalized, self.down_w[(gate * rank + r) * 2 * hidden ..][0 .. 2 * hidden]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); + zeta[r] = later.sum(terms, (2 * hidden + 31) / 32 + 5, scratch).bf(); + if (self.stage == .down) out[(gate * self.shape.rows + row) * rank + r] = zeta[r]; + } + for (0..hidden) |col| { + for (terms[0..rank], zeta, self.forget[(gate * hidden + col) * rank ..][0..rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const f = ref.tanh(later.sum(terms[0..rank], rank, scratch)); + for (terms[0..rank], zeta, self.gain[(gate * hidden + col) * rank ..][0..rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const gain = ref.tanh(later.sum(terms[0..rank], rank, scratch)); + const y = ref.Iv.of(1).sub(f).mul(ref.Iv.of(h[col])).add(gain.mul(ref.Iv.of(m[col]))); + const at = (gate * self.shape.rows + row) * hidden + col; + ys[at] = y; + if (self.stage == .lin) out[at] = y; + } + }; + if (self.stage != .mix) return; + for (0..3) |gate| for (0..self.shape.rows) |row| { + const at = (gate * self.shape.rows + row) * hidden; + for (terms[0..hidden], ys[at..][0..hidden]) |*t, y| t.* = ref.sq(y); + const inv = ref.rms(later.sum(terms[0..hidden], d, scratch), hidden, eps); + for (out[at..][0..hidden], ys[at..][0..hidden], self.norm[gate * hidden ..][0..hidden]) |*o, y, n| o.* = ref.Iv.of(ref.bf(n)).mul(y.mul(inv)).bf(); + }; + } +}; + +const groups = .{ "mixes", "gates" }; +pub const Set = struct { + k: loop.Kernels = undefined, + loaded: bool = false, + mixes: [3]ref.Gated(Mix) = undefined, + gates: [4]ref.Gated(Gate) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try loop.Kernels.load(gpu.d); + set.loaded = true; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.mixes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.k, .f32_partial = i == 1, .aliased = i == 2 } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.k, .stage = @fromBackingInt(@intCast(i % 3)), .wrong_slot = i == 3 } }; + inline for (groups) |field| for (&@field(set, field)) |*x| try list.append(a, x.kernel()); + } + pub fn deinit(set: *Set) void { + if (!set.loaded) return; + inline for (groups) |field| for (&@field(set, field)) |*x| x.deinit(); + set.k.unload(); + set.loaded = false; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig deleted file mode 100644 index bef2f7d69ef..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math.zig +++ /dev/null @@ -1,479 +0,0 @@ -//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. -const std = @import("std"); -const core = @import("core"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -pub const eps = ref.eps; -pub const mini_h = 2304; - -/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. -pub fn Checked(comptime T: type) type { - return struct { - const Self = @This(); - inner: ref.Gated(T), - rig: *rig_.Rig = undefined, - msg: [200]u8 = undefined, - - pub fn deinit(self: *Self) void { - self.inner.deinit(); - } - - pub fn kernel(self: *Self) g.Kernel { - self.rig = &self.inner.rig; - return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; - } - - const vt = g.hooks(Self); - - pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - return self.inner.prepare(shape, fill, seed); - } - - pub fn run(self: *Self) !void { - try self.inner.run(); - } - - pub fn count(self: *Self) usize { - return self.inner.count(); - } - - pub fn reference(self: *Self, want: []f64, mag: []f64) !void { - try self.inner.reference(want, mag); - } - - pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { - try self.inner.bounds(want, mag, allow); - } - - pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { - try self.inner.simulate(acc, order, out); - } - - pub fn check(self: *Self, _: g.Gate) !?[]const u8 { - const a = self.rig.gpu.gpa; - const got = try a.dupe(u8, try self.rig.outputBytes()); - defer a.free(got); - return self.inner.k.check(a, got, &self.msg); - } - }; -} - -pub fn queryScale(cols: usize) ref.Iv { - return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); -} - -pub fn softmax(logits: []ref.Iv) void { - var m = logits[0]; - for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; - var den = ref.Iv.of(0); - for (logits) |*v| { - v.* = v.sub(m).exp(); - den = den.add(v.*); - } - for (logits) |*v| v.* = v.div(den); -} - -/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. -fn stressBank(i: usize) f32 { - return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; -} - -/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. -fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { - if (bank == 0) return stressBank(col); - if (col == 0) return 0; - return -stressBank((col + 1) % cols); -} - -/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. -pub fn arStressSource(source: usize, col: usize) f32 { - if (source == 0 and col == 0) return 0; - const value = stressBank(col - col % 3); - return switch ((col + 2 * source) % 3) { - 0 => value, - 1 => -value, - 2 => 0, - else => unreachable, - }; -} - -pub fn close(got: f32, want: f32) bool { - if (std.math.isNan(want)) return std.math.isNan(got); - if (!std.math.isFinite(want)) return got == want; - if (!std.math.isFinite(got)) return false; - const tolerance = 1e-4 * (1.0 + @abs(want)); - return @abs(got - want) <= tolerance; -} - -pub fn bf(x: u16) f32 { - return @floatCast(ref.bf(x)); -} - -pub fn bfRound(x: f32) f32 { - return bf(c.toBf16(x)); -} -pub fn cudaMax(a: f32, b: f32) f32 { - if (std.math.isNan(a)) return b; - if (std.math.isNan(b)) return a; - return @max(a, b); -} - -pub fn sameBf(got: u16, want: u16) bool { - if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule - return got == want; -} - -pub fn scale(cols: usize) f32 { - return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); -} - -fn warp(v: *[32]f32) f32 { - var offset: usize = 16; - while (offset != 0) : (offset >>= 1) { - const old = v.*; - for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; - } - return v.*[0]; -} - -/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. -pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { - var partial: [32]f32 = @splat(0); - for (0..threads / 32) |w| { - var lanes: [32]f32 = undefined; - for (0..32) |lane| { - const tid = w * 32 + lane; - var sum: f32 = 0; - var i = tid; - while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); - lanes[lane] = sum; - } - partial[w] = warp(&lanes); - } - return warp(&partial); -} - -pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { - return try std.fmt.bufPrint(msg, fmt, args); -} - -const message_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, - .{ .rows = 16, .n = 4 * 128, .k = 128 }, - .{ .rows = 2048, .n = 4 * 128, .k = 128 }, -}; - -/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. -pub const Messages = struct { - kern: *const lm.Kernels, - aliased: bool = false, - shape: c.Shape = undefined, - banks: [2][]u16 = .{ &.{}, &.{} }, - queries: [2][]f32 = .{ &.{}, &.{} }, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Messages) c.Spec { - return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; - } - - fn depth(s: c.Shape) usize { - return 2 * ((s.k + 255) / 256 + 10); - } - - pub fn control(self: *const Messages) ?g.Gate { - return if (self.aliased) .shapes else null; - } - - pub fn free(self: *Messages, a: std.mem.Allocator) void { - for (&self.banks) |*x| a.free(x.*); - for (&self.queries) |*x| a.free(x.*); - self.banks = .{ &.{}, &.{} }; - self.queries = .{ &.{}, &.{} }; - } - - pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; - self.free(a); - self.shape = shape; - const cols = shape.k; - const layers = shape.n / (4 * cols); - for (&self.banks, 0..) |*x, bank| { - x.* = try a.alloc(u16, shape.rows * cols); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); - } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); - } - for (&self.queries) |*x| { - x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); - if (fill == .stress) @memset(x.*, 0); - } - if (fill == .nonfinite) { - ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); - ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); - } - for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); - self.out = try rig.output(shape.rows * shape.n * 4); - return true; - } - - pub fn run(self: *Messages, rig: *rig_.Rig) !void { - const b1 = if (self.aliased) self.dev[0] else self.dev[1]; - const layers = self.shape.n / (4 * self.shape.k); - try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); - } - - pub fn count(self: *const Messages) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - const later = ref.later(s); - for (0..self.shape.rows) |row| { - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { - const x = ref.Iv.of(ref.bf(v)); - t.* = x.mul(x); - } - inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - var logits: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); - logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..2) |b| { - const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); - value = value.add(logits[b].mul(beta)); - } - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - out[at] = value; - } - }; - } - } - - pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const raw0 = try a.alloc(f32, cols); - defer a.free(raw0); - const raw1 = try a.alloc(f32, cols); - defer a.free(raw1); - const beta0 = try a.alloc(f32, cols); - defer a.free(beta0); - const beta1 = try a.alloc(f32, cols); - defer a.free(beta1); - for (0..self.shape.rows) |row| { - for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); - const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (beta0, raw0) |*x, v| x.* = v * inv0; - for (beta1, raw1) |*x, v| x.* = v * inv1; - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - const l0 = reduce(query, beta0, 256) * scale(cols); - const l1 = reduce(query, beta1, 256) * scale(cols); - const m = cudaMax(l0, l1); - const e0 = @exp(l0 - m); - const e1 = @exp(l1 - m); - const den = e0 + e1; - const w0 = e0 / den; - const w1 = e1 / den; - for (0..cols) |i| { - const want = w0 * beta0[i] + w1 * beta1[i]; - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); - } - }; - } - return null; - } -}; - -const gate_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 2048, .n = 128, .k = 256 }, -}; - -/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. -pub const Gate = struct { - kern: *const lm.Kernels, - wrong_gain: bool = false, - shape: c.Shape = undefined, - h: []f32 = &.{}, - m: []f32 = &.{}, - d: []u16 = &.{}, - f: []u16 = &.{}, - gain: []u16 = &.{}, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Gate) c.Spec { - return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.k + 255) / 256 + 10 + lm.rank; - } - - pub fn control(self: *const Gate) ?g.Gate { - return if (self.wrong_gain) .shapes else null; - } - - pub fn free(self: *Gate, a: std.mem.Allocator) void { - a.free(self.h); - a.free(self.m); - a.free(self.d); - a.free(self.f); - a.free(self.gain); - self.h = &.{}; - self.m = &.{}; - self.d = &.{}; - self.f = &.{}; - self.gain = &.{}; - } - - pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; - self.free(a); - self.shape = shape; - const cols = shape.n; - self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); - self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - if (fill == .stress) { - for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - } - if (fill == .nonfinite) { - ref.plant(f32, self.h, shape.rows, cols, ref.asF32); - ref.plant(f32, self.m, shape.rows, cols, ref.asF32); - } - self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; - self.out = try rig.output(shape.rows * cols * 4); - return true; - } - - pub fn run(self: *Gate, rig: *rig_.Rig) !void { - try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); - } - - pub fn count(self: *const Gate) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const n = try a.alloc(ref.Iv, 2 * cols); - defer a.free(n); - const terms = try a.alloc(ref.Iv, 2 * cols); - defer a.free(terms); - const scratch = try a.alloc(f64, 2 * cols); - defer a.free(scratch); - const zeta = try a.alloc(ref.Iv, lm.rank); - defer a.free(zeta); - const later = ref.later(s); - const zeta_depth = (2 * cols + 31) / 32 + 5; - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - const x = if (b == 0) h else m; - for (terms[0..cols], x) |*t, v| { - const e = ref.Iv.of(v); - t.* = e.mul(e); - } - inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); - } - for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); - for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); - for (0..lm.rank) |r| { - for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); - zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); - } - for (0..cols) |i| { - for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - const keep = ref.Iv.of(1).sub(forget); - const old = keep.mul(ref.Iv.of(h[i])); - const added = gain.mul(ref.Iv.of(m[i])); - out[row * cols + i] = old.add(added); - } - } - } - - pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const n = try a.alloc(f32, 2 * cols); - defer a.free(n); - const weights = try a.alloc(f32, 2 * cols); - defer a.free(weights); - const zeta = try a.alloc(f32, lm.rank); - defer a.free(zeta); - const zf = try a.alloc(f32, lm.rank); - defer a.free(zf); - const zg = try a.alloc(f32, lm.rank); - defer a.free(zg); - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); - const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); - for (n[cols..], m) |*v, x| v.* = bfRound(x * im); - for (0..lm.rank) |r| { - for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); - zeta[r] = bfRound(reduce(weights, n, 256)); - } - for (0..cols) |i| { - for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - var sf: f32 = 0; - var sg: f32 = 0; - for (0..lm.rank) |r| { - sf = @mulAdd(f32, zf[r], zeta[r], sf); - sg = @mulAdd(f32, zg[r], zeta[r], sg); - } - const forget = std.math.tanh(sf); - const gain = std.math.tanh(sg); - const keep: f32 = 1.0 - forget; - const old: f32 = keep * h[i]; - const added: f32 = gain * m[i]; - const want: f32 = old + added; - const value = ref.readF32(got, row * cols + i); - if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); - } - } - return null; - } -}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig deleted file mode 100644 index 49bd3ae650e..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig +++ /dev/null @@ -1,426 +0,0 @@ -//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const check = @import("check.zig"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); -const base = @import("contract_inkling2_loop_math.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -const K = base.Checked; -const eps = base.eps; -const mini_h = base.mini_h; -const queryScale = base.queryScale; -const softmax = base.softmax; -const arStressSource = base.arStressSource; -const close = base.close; -const bf = base.bf; -const bfRound = base.bfRound; -const cudaMax = base.cudaMax; -const sameBf = base.sameBf; -const scale = base.scale; -const reduce = base.reduce; -const fail = base.fail; -const Messages = base.Messages; -const Gate = base.Gate; -const qkv_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 3072, .k = mini_h }, - .{ .rows = 16, .n = 384, .k = 128 }, - .{ .rows = 2048, .n = 384, .k = 128 }, -}; - -/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. -pub const ProjectQkv = struct { - kern: *const lm.Kernels, - shared_input: bool = false, - shape: c.Shape = undefined, - u: [3][]u16 = .{ &.{}, &.{}, &.{} }, - w: [3][]u16 = .{ &.{}, &.{}, &.{} }, - dev: [6]u64 = @splat(0), - out: [3]u64 = @splat(0), - - pub fn spec(self: *const ProjectQkv) c.Spec { - return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; - } - - fn depth(s: c.Shape) usize { - return s.k; - } - - pub fn control(self: *const ProjectQkv) ?g.Gate { - return if (self.shared_input) .shapes else null; - } - - pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { - for (&self.u) |*x| a.free(x.*); - for (&self.w) |*x| a.free(x.*); - self.u = .{ &.{}, &.{}, &.{} }; - self.w = .{ &.{}, &.{}, &.{} }; - } - - pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; - self.free(a); - self.shape = shape; - for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); - for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); - if (fill == .stress) { - // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. - const half = shape.k / 2; - for (self.u) |bank| for (0..shape.rows) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - values[i] = c.toBf16(ref.int(rng, 8, 16)); - values[half + i] = values[i]; - } - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - for (self.w) |bank| for (0..bank.len / shape.k) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - const v = ref.int(rng, 8, 16); - values[i] = c.toBf16(v); - values[half + i] = c.toBf16(-v); - } - for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - } - if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); - for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); - for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); - return true; - } - - pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { - const k = if (self.shared_input) self.dev[0] else self.dev[1]; - const v = if (self.shared_input) self.dev[0] else self.dev[2]; - try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); - } - - pub fn count(self: *const ProjectQkv) usize { - return self.shape.rows * self.shape.n * 5 / 3; - } - - pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - var offset: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); - out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); - }; - offset += self.shape.rows * width; - } - } - - pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const x = try a.alloc(f32, cols); - defer a.free(x); - const w = try a.alloc(f32, cols); - defer a.free(w); - var byte_at: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); - for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); - var sum: f32 = 0; - for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); - const want = c.toBf16(sum); - const at = byte_at + (row * width + j) * 2; - const value = std.mem.readInt(u16, got[at..][0..2], .little); - if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); - }; - byte_at += self.shape.rows * width * 2; - } - return null; - } -}; - -const ar_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 16, .n = 128, .k = 3 }, - .{ .rows = 2048, .n = 128, .k = 3 }, -}; - -/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. -pub const Ar = struct { - kern: *const lm.Kernels, - partial_bf16: bool, - short: bool = false, - shape: c.Shape = undefined, - blocks: [2][]u16 = .{ &.{}, &.{} }, - partial32: []f32 = &.{}, - partial16: []u16 = &.{}, - query: []f32 = &.{}, - dev: [4]u64 = @splat(0), // two blocks, partial, query - out: u64 = 0, - - pub fn spec(self: *const Ar) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.n + 511) / 512 + 10 + 3; - } - - pub fn control(self: *const Ar) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *Ar, a: std.mem.Allocator) void { - for (&self.blocks) |*x| a.free(x.*); - a.free(self.partial32); - a.free(self.partial16); - a.free(self.query); - self.blocks = .{ &.{}, &.{} }; - self.partial32 = &.{}; - self.partial16 = &.{}; - self.query = &.{}; - } - - pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; - self.free(a); - self.shape = shape; - for (&self.blocks, 0..) |*x, source| { - x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); - } - } - if (self.partial_bf16) { - self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); - } - self.dev[2] = try ref.input(rig, self.partial16); - } else { - self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); - } - self.dev[2] = try ref.input(rig, self.partial32); - } - self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); - if (fill == .stress) @memset(self.query, 0); - if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); - for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - self.dev[3] = try ref.input(rig, self.query); - self.out = try rig.output(shape.rows * shape.n * shape.k * 4); - return true; - } - - pub fn run(self: *Ar, rig: *rig_.Rig) !void { - var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; - args.blocks[0] = self.dev[0]; - args.blocks[1] = self.dev[1]; - try lm.ar(self.kern, rig.s, args); - } - - pub fn count(self: *const Ar) usize { - return self.shape.rows * self.shape.n * self.shape.k; - } - - fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { - const at = row * self.shape.n + col; - return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; - } - - pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - for (0..self.shape.rows) |row| { - var inv: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| { - const x = ref.Iv.of(self.entry(j, row, i)); - t.* = x.mul(x); - } - inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..self.shape.k) |q| { - var logits: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); - logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..3) |j| { - const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); - value = value.add(logits[j].mul(beta)); - } - out[(q * self.shape.rows + row) * cols + i] = value; - } - } - } - } - - pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const sources = 3; - const raw = try a.alloc(f32, cols); - defer a.free(raw); - const beta = try a.alloc(f32, sources * cols); - defer a.free(beta); - const weights = try a.alloc(f32, sources); - defer a.free(weights); - for (0..self.shape.rows) |row| { - var invs: [3]f32 = undefined; - for (0..sources) |j| { - for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); - invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); - for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; - } - for (0..self.shape.k) |q| { - var logits: [3]f32 = undefined; - var m = -std.math.inf(f32); - for (0..sources) |j| { - const query = self.query[q * cols ..][0..cols]; - logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); - m = cudaMax(m, logits[j]); - } - var den: f32 = 0; - for (0..sources) |j| { - weights[j] = @exp(logits[j] - m); - den += weights[j]; - } - for (0..sources) |j| weights[j] /= den; - for (0..cols) |i| { - var want: f32 = 0; - for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); - const at = (q * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); - } - } - } - return null; - } -}; - -test "AR normalizes each FP32 query term before reduction and scales after its dot" { - const source = [_]f32{ - @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), - @bitCast(@as(u32, 0x40400001)), 0, - }; - const query = [_]f32{ - @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), - @bitCast(@as(u32, 0xc0000001)), 0, - }; - const inv: f32 = @bitCast(@as(u32, 0x3f800001)); - var normalized: [4]f32 = undefined; - for (&normalized, source) |*v, x| v.* = x * inv; - const dot = reduce(&query, &normalized, 512); - const old = reduce(&query, &source, 512) * inv * scale(source.len); - const scaled = dot * scale(source.len); - try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); - try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); -} - -const round_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 2048, .n = 32, .k = 1 }, -}; - -/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. -pub const RoundBf16 = struct { - kern: *const lm.Kernels, - short: bool = false, - shape: c.Shape = undefined, - x: []f32 = &.{}, - dev: u64 = 0, - out: u64 = 0, - - pub fn spec(self: *const RoundBf16) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; - } - - pub fn control(self: *const RoundBf16) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { - a.free(self.x); - self.x = &.{}; - } - - pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0) return false; - self.free(a); - self.shape = shape; - self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); - if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); - self.dev = try ref.input(rig, self.x); - self.out = try rig.output(self.x.len * 4); - return true; - } - - pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { - try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); - } - - pub fn count(self: *const RoundBf16) usize { - return self.x.len; - } - - pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { - for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); - } - - pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - for (self.x, 0..) |x, i| { - const want = bfRound(x); - const value = ref.readF32(got, i); - if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); - } - return null; - } -}; - -pub const Set = struct { - k: lm.Kernels = undefined, - loaded: bool = false, - messages: [2]K(Messages) = undefined, - gates: [2]K(Gate) = undefined, - qkvs: [2]K(ProjectQkv) = undefined, - ars: [3]K(Ar) = undefined, - rounds: [2]K(RoundBf16) = undefined, - - pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { - set.k = try lm.Kernels.load(gpu.d); - set.loaded = true; - const k = &set.k; - const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; - for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; - for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; - for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; - for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; - for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); - } - - pub fn deinit(set: *Set) void { - if (!set.loaded) return; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); - set.k.unload(); - set.loaded = false; - } -}; diff --git a/zig/tests/cuda/contract_inkling2_model.zig b/zig/tests/cuda/contract_inkling2_model.zig new file mode 100644 index 00000000000..c2d341aadbe --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_model.zig @@ -0,0 +1,57 @@ +//! Inkling 2's served geometries under the contract: Small at TP=2 (a rank's share) and Mini at one rank. + +/// What a rank's kernels see of a model: widths, heads, router, vocabulary rows, log-scaling floor. +pub const Model = struct { + mini: bool, + hidden: usize, + heads: usize, // query heads a rank + kv: usize, // key heads a rank + experts: usize, + top: usize, + ranks: usize, // the vocabulary's shares, one a rank + floor: f64, // log_scaling_n_floor + vocab: usize = 201_024, + real: usize = 200_058, // unpadded_vocab_size + + pub fn group(m: Model) usize { + return m.heads / m.kv; + } + + /// The k/v rows' width (key heads x 128): the k/v convs' channels. + pub fn kvWidth(m: Model) usize { + return m.kv * 128; + } + + /// The dynamic conv taps a row: 4 a key head (weight_proj's rows). + pub fn taps(m: Model) usize { + return m.kv * 4; + } + + /// A rank's vocabulary columns. + pub fn share(m: Model) usize { + return m.vocab / m.ranks; + } + + /// The last rank's real columns. + pub fn lastReal(m: Model) usize { + return m.real - (m.ranks - 1) * m.share(); + } +}; + +/// Small (config.json of Inkling-2-Small) at TP=2: hidden 4,608, 4 key heads and 24 query heads a rank, 384 experts. +pub const small: Model = .{ .mini = false, .hidden = 4608, .heads = 24, .kv = 4, .experts = 384, .top = 8, .ranks = 2, .floor = 128000 }; +/// Mini (config.json of Inkling-2-Mini) at one rank: hidden 2,304, 24 query and 8 key heads, 128 experts, top 8. +pub const mini: Model = .{ .mini = true, .hidden = 2304, .heads = 24, .kv = 8, .experts = 128, .top = 8, .ranks = 1, .floor = 8192 }; + +pub const suffix = " at Mini's shapes"; + +/// A registration's name: Small's unchanged (its seeds hash the name), Mini's with the suffix. +pub fn named(comptime base: []const u8, mini_: bool) []const u8 { + return if (mini_) base ++ suffix else base; +} + +/// Entry `i` of a comptime name table, Mini's with the suffix. +pub fn namedAt(comptime table: []const []const u8, i: usize, mini_: bool) []const u8 { + inline for (table, 0..) |n, j| if (i == j) return named(n, mini_); + unreachable; +} diff --git a/zig/tests/cuda/contract_inkling2_ops.zig b/zig/tests/cuda/contract_inkling2_ops.zig index 48cbc7606a8..c94e088aa60 100644 --- a/zig/tests/cuda/contract_inkling2_ops.zig +++ b/zig/tests/cuda/contract_inkling2_ops.zig @@ -14,21 +14,22 @@ const G = ref.Gated; const K = ref.Checked; const groups = .{ "embeds", "mixes", "dots", "topks", "gateups", "convs", "rewinds", "caps", "tails", "top1s", "races", "tobfs", "words" }; +/// Small's registrations, then Mini's of every kernel but the EXL3 epilogues (gateup, prompt tail) and put_words. pub const Set = struct { k: ref.Kernels = undefined, loaded: bool = false, - mixes: [7]G(mix.Mix) = undefined, - embeds: [2]G(rows.Embed) = undefined, - dots: [6]G(rows.Rowdot) = undefined, - caps: [2]G(rows.Softcap) = undefined, - topks: [2]K(route.Topk) = undefined, + mixes: [14]G(mix.Mix) = undefined, + embeds: [4]G(rows.Embed) = undefined, + dots: [12]G(rows.Rowdot) = undefined, + caps: [4]G(rows.Softcap) = undefined, + topks: [4]K(route.Topk) = undefined, gateups: [2]G(route.Gateup) = undefined, tails: [3]G(route.Tail) = undefined, - convs: [8]G(conv.Conv) = undefined, - rewinds: [2]K(conv.Rewind) = undefined, - top1s: [2]K(pick.Top1) = undefined, - races: [2]K(pick.Race) = undefined, - tobfs: [2]K(pick.Tobf) = undefined, + convs: [16]G(conv.Conv) = undefined, + rewinds: [4]K(conv.Rewind) = undefined, + top1s: [4]K(pick.Top1) = undefined, + races: [4]K(pick.Race) = undefined, + tobfs: [4]K(pick.Tobf) = undefined, words: [2]K(pick.Words) = undefined, /// Every registration, each control after the kernel it breaks, appended to `list`. @@ -38,20 +39,29 @@ pub const Set = struct { const k = &set.k; const rig: @import("contract_rig.zig").Rig = .{ .gpu = gpu, .s = s }; const forms = [_]mix.Form{ .attn, .mlp, .first, .attn, .mlp, .first, .mlp }; - for (&set.mixes, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .narrow = i >= 3 and i < 6, .fault = if (i == 6) .short else .none } }; - for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .shifted = i == 1 } }; + for (&set.mixes, 0..) |*x, j| { + const i = j % 7; + x.* = .{ .rig = rig, .k = .{ .kern = k, .form = forms[i], .narrow = i >= 3 and i < 6, .fault = if (i == 6) .short else .none, .mini = j >= 7 } }; + } + for (&set.embeds, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .shifted = j % 2 == 1, .mini = j >= 2 } }; const dots = [_]rows.Dot{ .router, .sink, .taps, .router, .taps, .router }; - for (&set.dots, dots, 0..) |*x, d, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .dot = d, .tiles = i == 3 or i == 4, .short = i == 5 } }; - for (&set.caps, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .wrong = i == 1 } }; - for (&set.topks, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .unbiased = i == 1 } }; + for (&set.dots, 0..) |*x, j| { + const i = j % 6; + x.* = .{ .rig = rig, .k = .{ .kern = k, .dot = dots[i], .tiles = i == 3 or i == 4, .short = i == 5, .mini = j >= 6 } }; + } + for (&set.caps, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .wrong = j % 2 == 1, .mini = j >= 2 } }; + for (&set.topks, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .unbiased = j % 2 == 1, .mini = j >= 2 } }; for (&set.gateups, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .swapped = i == 1 } }; for (&set.tails, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .f32_out = i == 1, .shifted = i == 2 } }; const cf = [_]conv.Form{ .kv_static, .kv_dynamic, .attn, .attn_boundary, .mlp, .kv_static, .attn, .kv_static }; - for (&set.convs, cf, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .view = if (i == 5 or i == 6) .state else .out, .fault = if (i == 7) .one_slot else .none } }; - for (&set.rewinds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .long = i == 1 } }; - for (&set.top1s, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } }; - for (&set.races, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = i == 1 } }; - for (&set.tobfs, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .unpadded = i == 1 } }; + for (&set.convs, 0..) |*x, j| { + const i = j % 8; + x.* = .{ .rig = rig, .k = .{ .kern = k, .form = cf[i], .view = if (i == 5 or i == 6) .state else .out, .fault = if (i == 7) .one_slot else .none, .mini = j >= 8 } }; + } + for (&set.rewinds, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .long = j % 2 == 1, .mini = j >= 2 } }; + for (&set.top1s, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = j % 2 == 1, .mini = j >= 2 } }; + for (&set.races, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = j % 2 == 1, .mini = j >= 2 } }; + for (&set.tobfs, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .unpadded = j % 2 == 1, .mini = j >= 2 } }; for (&set.words, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } }; inline for (groups) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); } diff --git a/zig/tests/cuda/contract_inkling2_ops_conv.zig b/zig/tests/cuda/contract_inkling2_ops_conv.zig index 15cb1e5f318..2599d8d469b 100644 --- a/zig/tests/cuda/contract_inkling2_ops_conv.zig +++ b/zig/tests/cuda/contract_inkling2_ops_conv.zig @@ -3,6 +3,7 @@ const std = @import("std"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -20,12 +21,22 @@ pub const View = enum { out, state }; /// The served kernel, or the control: every stream reading and writing slot 0's state. pub const Fault = enum { none, one_slot }; -fn width(f: Form) usize { - return if (f == .kv_static or f == .kv_dynamic) ref.kv_width else ref.hidden; +fn model(mini: bool) M.Model { + return if (mini) M.mini else M.small; } -fn parts(f: Form) usize { - return if (f == .attn or f == .attn_boundary or f == .mlp) 2 else 1; +fn width(f: Form, mini: bool) usize { + return if (f == .kv_static or f == .kv_dynamic) model(mini).kvWidth() else model(mini).hidden; +} + +/// A residual site's input: o_proj's or the experts' fp32 sums, rounded to bf16 once summed over the ranks. +fn residual(f: Form) bool { + return f == .attn or f == .attn_boundary or f == .mlp; +} + +/// Rank partials of a site's input: Small's two at TP=2, Mini's one rank its own. +fn parts(f: Form, mini: bool) usize { + return if (residual(f)) model(mini).ranks else 1; } fn mode(f: Form) i32 { @@ -49,16 +60,27 @@ const names = [5][2][]const u8{ .{ "inkling2 ops tf_ink2_conv MLP site (rank partials, bf16(resid + bf16(y)))", "" }, }; +/// Mini at one rank: its residual sites take one fp32 input, rounded to bf16. +const mini_names = [5][2][]const u8{ + names[0], + names[1], + .{ "inkling2 ops tf_ink2_conv attention site (one rank, base + bf16(y))", "inkling2 ops tf_ink2_conv attention site, states and kept inputs" }, + names[3], + .{ "inkling2 ops tf_ink2_conv MLP site (one rank, bf16(resid + bf16(y)))", "" }, +}; + fn servedAt(comptime C: usize) []const c.Shape { return &.{ .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 4 }, .{ .rows = 128, .n = C, .k = 8 }, .{ .rows = 8, .n = C, .k = 8 }, .{ .rows = 2048, .n = C, .k = 1 } }; } /// Rows of the call x the site's width x streams (each its rows, its state slot): decode, windows, prompt chunks. -pub fn convSpec(f: Form, v: View, fault: Fault) c.Spec { - const served = if (width(f) == ref.kv_width) servedAt(ref.kv_width) else servedAt(ref.hidden); +pub fn convSpec(f: Form, v: View, fault: Fault, mini: bool) c.Spec { + const kv_site = f == .kv_static or f == .kv_dynamic; + const served = if (mini) (if (kv_site) servedAt(M.mini.kvWidth()) else servedAt(M.mini.hidden)) else if (kv_site) servedAt(M.small.kvWidth()) else servedAt(M.small.hidden); + const at = @as(usize, @backingInt(f)) * 2 + @backingInt(v); var s: c.Spec = .{ - .name = names[@backingInt(f)][@backingInt(v)], - .accum = if (v == .state and parts(f) == 1) .none else .f32, // a plain site keeps its inputs: no sums + .name = if (mini) M.namedAt(&flat(mini_names), at, true) else names[@backingInt(f)][@backingInt(v)], + .accum = if (v == .state and parts(f, mini) == 1) .none else .f32, // a plain site keeps its inputs: no sums .depth = depth, .out = if (v == .out and mode(f) != 1) .bf16 else .f32, .in_place = v == .state, @@ -66,19 +88,24 @@ pub fn convSpec(f: Form, v: View, fault: Fault) c.Spec { .served = served, }; if (fault == .one_slot) { - s.name = "control: inkling2 ops tf_ink2_conv k/v static taps, every stream on slot 0's state"; + s.name = M.named("control: inkling2 ops tf_ink2_conv k/v static taps, every stream on slot 0's state", mini); s.served = served[2..4]; s.tiles = .{ .{}, .{}, .{} }; } return s; } +fn flat(t: [5][2][]const u8) [10][]const u8 { + return t[0] ++ t[1] ++ t[2] ++ t[3] ++ t[4]; +} + /// One conv launch over `k` streams' rows: inputs uploaded, the states restored before every launch. pub const Conv = struct { kern: *const ops.Kernels, form: Form, view: View = .out, fault: Fault = .none, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, // [parts][rows][C] w: []u16 = &.{}, // static [C][4], dynamic [4][C] @@ -93,7 +120,7 @@ pub const Conv = struct { pub const sums = {}; pub fn spec(self: *const Conv) c.Spec { - return convSpec(self.form, self.view, self.fault); + return convSpec(self.form, self.view, self.fault, self.mini); } pub fn control(self: *const Conv) ?g.Gate { @@ -107,18 +134,22 @@ pub const Conv = struct { } } - const heads = 4; + /// The dynamic taps' heads: a rank's key heads. + fn dynHeads(self: *const Conv) usize { + return model(self.mini).kv; + } /// Values in [-2, 2); stress: products near 2^16 adding to 2^18 (fp16 overflows), partials near 2^17 cancelling. pub fn prepare(self: *Conv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - const C = width(self.form); + const C = width(self.form, self.mini); + const heads = self.dynHeads(); if (shape.rows == 0 or shape.n != C or shape.k == 0) return false; self.free(a); self.shape = shape; const rows = shape.rows; - const np = parts(self.form); + const np = parts(self.form, self.mini); const stress = fill == .stress; - const round = np == 2; + const round = residual(self.form); self.x = try a.alloc(f32, np * rows * C); for (0..rows * C) |i| { const v = if (stress) ref.int(rng, -256, 256) else rng.float(f32) * 4 - 2; @@ -176,7 +207,7 @@ pub const Conv = struct { .state_stride = @intCast(3 * C), .parts = @intCast(np), .round_in = @intFromBool(round), - .heads = heads, + .heads = @intCast(heads), .c = @intCast(C), .rows = @intCast(rows), .mode = mode(self.form), @@ -192,21 +223,21 @@ pub const Conv = struct { } pub fn count(self: *const Conv) usize { - const C = width(self.form); + const C = width(self.form, self.mini); return if (self.view == .out) self.shape.rows * C else self.state.len + self.shape.rows * C; } /// Row t's input at column col: the ranks' partials added in order, rounded to bf16 at the residual sites. fn input(self: *const Conv, s: Sums, t: usize, col: usize) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); const rows = self.shape.rows; var x = Iv.of(self.x[t * C + col]); - if (parts(self.form) == 2) x = step(s, x, Iv.of(self.x[(rows + t) * C + col]), false).bf(); + if (parts(self.form, self.mini) == 2) x = step(s, x, Iv.of(self.x[(rows + t) * C + col]), false).bf() else if (residual(self.form)) x = x.bf(); return x; } pub fn solve(self: *const Conv, _: std.mem.Allocator, s: Sums, out: []Iv) !void { - const C = width(self.form); + const C = width(self.form, self.mini); const hist = out[if (self.view == .state) self.state.len else 0..]; if (self.view == .state) for (out[0..self.state.len], self.state) |*o, v| { o.* = Iv.of(v); @@ -228,15 +259,16 @@ pub const Conv = struct { } fn tap(self: *const Conv, k: usize, col: usize) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); return Iv.of(ref.bf(self.w[if (self.form == .kv_dynamic) k * C + col else col * 4 + k])); } /// The site's output at row t from its three prior inputs h (oldest first) and x. fn y(self: *const Conv, s: Sums, t: usize, col: usize, h: [3]Iv, x: Iv) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); var v: Iv = undefined; if (self.form == .kv_dynamic) { + const heads = self.dynHeads(); const d = self.dyn[(t * heads + col / (C / heads)) * 4 ..][0..4]; var w: [4]Iv = undefined; for (&w, 0..) |*wk, k| wk.* = self.tap(k, col).add(Iv.of(d[k])); @@ -259,10 +291,14 @@ pub const Conv = struct { } }; -/// Kept rows x the widest site x the slot's first row in hist: four sites, two 512 wide and two 4,608. -pub fn rewindSpec(long: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 3, .n = ref.hidden, .k = 0 }, .{ .rows = 1, .n = ref.hidden, .k = 5 }, .{ .rows = 2, .n = ref.hidden, .k = 0 }, .{ .rows = 4, .n = ref.hidden, .k = 3 }, .{ .rows = 17, .n = ref.hidden, .k = 5 }, .{ .rows = 128, .n = ref.hidden, .k = 0 } }; - const name = if (long) "control: inkling2 ops tf_ink2_conv_rewind keeping one row more" else "inkling2 ops tf_ink2_conv_rewind (a slot's states from its backup and kept rows)"; +fn rewindServed(comptime C: usize) []const c.Shape { + return &.{ .{ .rows = 3, .n = C, .k = 0 }, .{ .rows = 1, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 0 }, .{ .rows = 4, .n = C, .k = 3 }, .{ .rows = 17, .n = C, .k = 5 }, .{ .rows = 128, .n = C, .k = 0 } }; +} + +/// Kept rows x the widest site x the slot's first row in hist: four sites, 512 and 4,608 wide (Mini: 1,024, 2,304). +pub fn rewindSpec(long: bool, mini: bool) c.Spec { + const served = if (mini) rewindServed(M.mini.hidden) else rewindServed(M.small.hidden); + const name = if (long) M.named("control: inkling2 ops tf_ink2_conv_rewind keeping one row more", mini) else M.named("inkling2 ops tf_ink2_conv_rewind (a slot's states from its backup and kept rows)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .in_place = true, .nan = .{ .stated = "a move: every bit copied, NaN payloads too" }, .served = if (long) served[0..2] else served }; } @@ -270,6 +306,7 @@ pub fn rewindSpec(long: bool) c.Spec { pub const Rewind = struct { kern: *const ops.Kernels, long: bool = false, + mini: bool = false, shape: c.Shape = undefined, hist: []f32 = &.{}, backup: []f32 = &.{}, @@ -277,12 +314,16 @@ pub const Rewind = struct { dev: [3]u64 = @splat(0), out: [4]u64 = @splat(0), - const widths = [4]usize{ ref.kv_width, ref.kv_width, ref.hidden, ref.hidden }; + /// The four sites' widths: k, v, attention's, the MLP's. + fn widths(self: *const Rewind) [4]usize { + const m = model(self.mini); + return .{ m.kvWidth(), m.kvWidth(), m.hidden, m.hidden }; + } const slots = 3; const slot = 1; pub fn spec(self: *const Rewind) c.Spec { - return rewindSpec(self.long); + return rewindSpec(self.long, self.mini); } pub fn control(self: *const Rewind) ?g.Gate { @@ -303,12 +344,13 @@ pub const Rewind = struct { } pub fn prepare(self: *Rewind, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != ref.hidden) return false; + if (shape.rows == 0 or shape.n != model(self.mini).hidden) return false; self.free(a); self.shape = shape; const hr = self.histRows(); var total: usize = 0; - for (widths) |w| total += w; + const ws = self.widths(); + for (ws) |w| total += w; self.hist = try ref.f32s(a, rng, hr * total, -4, 4); self.backup = try ref.f32s(a, rng, 3 * total, -4, 4); if (fill == .nonfinite) { @@ -318,7 +360,7 @@ pub const Rewind = struct { var sites: [4]ops.RewindSite = undefined; var h_off: usize = 0; var b_off: usize = 0; - for (&sites, &self.states, &self.out, widths) |*st, *s, *o, w| { + for (&sites, &self.states, &self.out, ws) |*st, *s, *o, w| { s.* = try ref.f32s(a, rng, slots * 3 * w, -4, 4); o.* = try rig.output(s.len * 4); st.* = .{ .state = o.*, .hist = @intCast(h_off * 4), .backup = @intCast(b_off * 4), .c = @intCast(w) }; @@ -332,7 +374,7 @@ pub const Rewind = struct { pub fn run(self: *Rewind, rig: *rig_.Rig) !void { for (self.states, self.out) |s, o| try ref.restore(rig, o, std.mem.sliceAsBytes(s)); const n = self.shape.rows + @intFromBool(self.long); - try ops.rewind(self.kern, rig.s, self.dev[0], 4, ref.hidden, self.dev[1], self.dev[2], slot, self.shape.k, n); + try ops.rewind(self.kern, rig.s, self.dev[0], 4, model(self.mini).hidden, self.dev[1], self.dev[2], slot, self.shape.k, n); } pub fn count(self: *const Rewind) usize { @@ -348,7 +390,7 @@ pub const Rewind = struct { var at: usize = 0; var h_off: usize = 0; var b_off: usize = 0; - for (self.states, widths, 0..) |s, w, site| { + for (self.states, self.widths(), 0..) |s, w, site| { for (s, 0..) |old, e| { const sl = e / (3 * w); const k = e / w % 3; diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index b837c657b8b..ba0498e5e15 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -4,14 +4,14 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const small_hidden = ref.hidden; -const mini_hidden = 2304; + /// forward.zig's mixes: attention's (q, k and v queries, bf16 stream), the MLP's (fp32 residual), layer 0's (no query). pub const Form = enum { attn, mlp, first }; @@ -28,18 +28,29 @@ fn depth(s: c.Shape) usize { return ref.blockDepth(s.n, 512); } +/// A width's served calls: wide, decode, and layer 0's of each (comptime arrays: a spec outlives the call). +fn servedAt(comptime C: usize) [4][]const c.Shape { + return .{ + &.{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }, + &.{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }, + &.{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }, + &.{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }, + }; +} + /// Rows x hidden x blocks (completed blocks + the partial): mix_rows takes calls of more than 16 rows, mix the rest. -pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { - const wide = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 9 }, .{ .rows = 64, .n = small_hidden, .k = 5 }, .{ .rows = 2048, .n = small_hidden, .k = 9 }, .{ .rows = 128, .n = small_hidden, .k = 1 }, .{ .rows = 32, .n = small_hidden, .k = 2 }, .{ .rows = 17, .n = mini_hidden, .k = 5 }, .{ .rows = 64, .n = mini_hidden, .k = 3 }, .{ .rows = 2048, .n = mini_hidden, .k = 5 }, .{ .rows = 128, .n = mini_hidden, .k = 1 }, .{ .rows = 32, .n = mini_hidden, .k = 2 } }; - const decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 9 }, .{ .rows = 16, .n = small_hidden, .k = 9 }, .{ .rows = 8, .n = small_hidden, .k = 5 }, .{ .rows = 2, .n = small_hidden, .k = 1 }, .{ .rows = 4, .n = small_hidden, .k = 2 }, .{ .rows = 1, .n = mini_hidden, .k = 5 }, .{ .rows = 16, .n = mini_hidden, .k = 5 }, .{ .rows = 8, .n = mini_hidden, .k = 3 }, .{ .rows = 2, .n = mini_hidden, .k = 1 }, .{ .rows = 4, .n = mini_hidden, .k = 2 } }; - const one = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 1 }, .{ .rows = 2048, .n = small_hidden, .k = 1 }, .{ .rows = 64, .n = small_hidden, .k = 1 }, .{ .rows = 17, .n = mini_hidden, .k = 1 }, .{ .rows = 2048, .n = mini_hidden, .k = 1 }, .{ .rows = 64, .n = mini_hidden, .k = 1 } }; - const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 1 }, .{ .rows = 16, .n = small_hidden, .k = 1 }, .{ .rows = 5, .n = small_hidden, .k = 1 }, .{ .rows = 1, .n = mini_hidden, .k = 1 }, .{ .rows = 16, .n = mini_hidden, .k = 1 }, .{ .rows = 5, .n = mini_hidden, .k = 1 } }; +pub fn mixSpec(f: Form, narrow: bool, fault: Fault, mini: bool) c.Spec { + const all = if (mini) servedAt(M.mini.hidden) else servedAt(M.small.hidden); + const wide = all[0]; + const decode = all[1]; + const one = all[2]; + const one_decode = all[3]; const names = [2][3][]const u8{ .{ "inkling2 ops tf_ink2_mix_rows attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix_rows MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix_rows layer 0 (no query)" }, .{ "inkling2 ops tf_ink2_mix attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix layer 0 (no query)" }, }; var s: c.Spec = .{ - .name = names[@intFromBool(narrow)][@backingInt(f)], + .name = M.namedAt(&(names[0] ++ names[1]), @as(usize, @intFromBool(narrow)) * 3 + @backingInt(f), mini), .accum = .f32, .depth = depth, .out = .bf16, @@ -47,7 +58,7 @@ pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { }; if (narrow) s.replaces = "tf_ink2_mix_rows"; if (fault == .short) { - s.name = "control: inkling2 ops tf_ink2_mix_rows MLP told one completed block fewer"; + s.name = M.named("control: inkling2 ops tf_ink2_mix_rows MLP told one completed block fewer", mini); s.served = wide[0..2]; } return s; @@ -59,6 +70,7 @@ pub const Mix = struct { form: Form, narrow: bool = false, fault: Fault = .none, + mini: bool = false, shape: c.Shape = undefined, blocks: []u16 = &.{}, // [n_blocks][rows][C] part: []f32 = &.{}, // [rows][C], bf16 values when the form's partial is bf16 @@ -70,7 +82,7 @@ pub const Mix = struct { pub const sums = {}; pub fn spec(self: *const Mix) c.Spec { - return mixSpec(self.form, self.narrow, self.fault); + return mixSpec(self.form, self.narrow, self.fault, self.mini); } pub fn control(self: *const Mix) ?g.Gate { @@ -88,16 +100,20 @@ pub const Mix = struct { self.norm = &.{}; } + fn width(self: *const Mix) usize { + return if (self.mini) M.mini.hidden else M.small.hidden; + } + fn bf16Part(self: *const Mix) bool { return self.form != .mlp; } /// Values in [-2, 2) with one in 61 eight times larger, queries in [-1, 1); stress: integers in [-16, 16]. pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or (shape.n != small_hidden and shape.n != mini_hidden) or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; + const C = self.width(); + if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; - const C = self.shape.n; const rows = self.shape.rows; const nb = shape.k - 1; const q = nq(self.form); @@ -155,8 +171,7 @@ pub const Mix = struct { } pub fn count(self: *const Mix) usize { - const C = self.shape.n; - return nq(self.form) * self.shape.rows * C; + return nq(self.form) * self.shape.rows * self.shape.n; } fn at(self: *const Mix, j: usize, r: usize, col: usize) f64 { diff --git a/zig/tests/cuda/contract_inkling2_ops_pick.zig b/zig/tests/cuda/contract_inkling2_ops_pick.zig index 28564cb375c..fdb634b51ca 100644 --- a/zig/tests/cuda/contract_inkling2_ops_pick.zig +++ b/zig/tests/cuda/contract_inkling2_ops_pick.zig @@ -3,6 +3,7 @@ const std = @import("std"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -11,23 +12,31 @@ const ops = ref.ops; /// A rank's view of the head (shape.k: 1 rank 0, 2 rank 1): its first id, its rows' stride, the real ids it holds. const Rank = struct { base: usize, stride: usize, n: usize }; -fn rank(s: c.Shape) Rank { - return if (s.k == 2) .{ .base = ref.share, .stride = ref.share, .n = s.n } else .{ .base = 0, .stride = ref.share, .n = s.n }; +fn model(mini: bool) M.Model { + return if (mini) M.mini else M.small; +} + +/// Mini at one rank: rows of the whole 201,024, its 200,058 real ids from 0. +fn rank(s: c.Shape, mini: bool) Rank { + const share = model(mini).share(); + return if (s.k == 2) .{ .base = share, .stride = share, .n = s.n } else .{ .base = 0, .stride = share, .n = s.n }; } const ranks = [_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 16, .n = ref.share1_real, .k = 2 }, .{ .rows = 1, .n = ref.share1_real, .k = 2 } }; +const mini_rows = [_]c.Shape{ .{ .rows = 16, .n = M.mini.real, .k = 1 }, .{ .rows = 1, .n = M.mini.real, .k = 1 }, .{ .rows = 128, .n = M.mini.real, .k = 1 } }; const top_rule = "the largest value and its lowest id plus the rank's base; a NaN never picked, -inf picked when all else is NaN, a row of NaNs (-inf, base)"; /// Rows x a rank's real ids x the rank: greedy draws of a window's rows, the drafter's single row. -pub fn top1Spec(short: bool) c.Spec { - const name = if (short) "control: inkling2 ops tf_ink2_top1 one id short" else "inkling2 ops tf_ink2_top1 (greedy pick, fp32 logits)"; - return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = if (short) ranks[0..2] else &ranks }; +pub fn top1Spec(short: bool, mini: bool) c.Spec { + const name = if (short) M.named("control: inkling2 ops tf_ink2_top1 one id short", mini) else M.named("inkling2 ops tf_ink2_top1 (greedy pick, fp32 logits)", mini); + const served: []const c.Shape = if (mini) &mini_rows else &ranks; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = if (short) served[0..2] else served }; } /// Values on 1/8 steps of [-64, 64) and padding past the real ids at 1000: equal maxima, and a read past n shows. -fn logits(a: std.mem.Allocator, rng: std.Random, s: c.Shape, fill: g.Fill) ![]f32 { - const rk = rank(s); +fn logits(a: std.mem.Allocator, rng: std.Random, s: c.Shape, fill: g.Fill, mini: bool) ![]f32 { + const rk = rank(s, mini); const x = try a.alloc(f32, s.rows * rk.stride); for (x, 0..) |*v, i| v.* = if (i % rk.stride < rk.n) ref.int(rng, -512, 511) / 8 else 1000; if (fill != .nonfinite) { @@ -63,13 +72,14 @@ fn scan(row: []const f32) struct { v: f32, i: usize } { pub const Top1 = struct { kern: *const ops.Kernels, short: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Top1) c.Spec { - return top1Spec(self.short); + return top1Spec(self.short, self.mini); } pub fn control(self: *const Top1) ?g.Gate { @@ -82,17 +92,17 @@ pub const Top1 = struct { } pub fn prepare(self: *Top1, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n < 4 or shape.n > ref.share) return false; + if (shape.rows == 0 or shape.n < 4 or shape.n > model(self.mini).share()) return false; self.free(a); self.shape = shape; - self.x = try logits(a, rng, shape, fill); + self.x = try logits(a, rng, shape, fill, self.mini); self.dev = try ref.input(rig, self.x); self.out = .{ try rig.output(shape.rows * 4), try rig.output(shape.rows * 4) }; return true; } pub fn run(self: *Top1, rig: *rig_.Rig) !void { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); try ops.top1(self.kern, rig.s, self.dev, self.shape.rows, rk.stride, rk.n - @intFromBool(self.short), rk.base, self.out[0], self.out[1]); } @@ -101,7 +111,7 @@ pub const Top1 = struct { } pub fn check(self: *const Top1, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); const rows = self.shape.rows; for (0..rows) |r| { const want = scan(self.x[r * rk.stride ..][0..rk.n]); @@ -121,9 +131,9 @@ const race_rule = "the largest bf16(x) / T + Gumbel(sample.cu's key at pos, id): "better beyond it; NaN never picked, the lowest +Inf first, a row of NaNs (-inf, base)"; /// One row a launch (the drafter's draw at a position) x a rank's real ids x the rank. -pub fn raceSpec(late: bool) c.Spec { - const name = if (late) "control: inkling2 ops tf_ink2_race1 keyed one position late" else "inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)"; - const served = &[_]c.Shape{ .{ .rows = 4, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 2, .n = ref.share1_real, .k = 2 } }; +pub fn raceSpec(late: bool, mini: bool) c.Spec { + const name = if (late) M.named("control: inkling2 ops tf_ink2_race1 keyed one position late", mini) else M.named("inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)", mini); + const served: []const c.Shape = if (mini) &.{ .{ .rows = 4, .n = M.mini.real, .k = 1 }, .{ .rows = 1, .n = M.mini.real, .k = 1 }, .{ .rows = 2, .n = M.mini.real, .k = 1 } } else &.{ .{ .rows = 4, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 2, .n = ref.share1_real, .k = 2 } }; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = race_rule }, .served = if (late) served[0..2] else served }; } @@ -149,13 +159,14 @@ fn uniform(pos: u32, id: u32) f32 { pub const Race = struct { kern: *const ops.Kernels, late: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Race) c.Spec { - return raceSpec(self.late); + return raceSpec(self.late, self.mini); } pub fn control(self: *const Race) ?g.Gate { @@ -168,10 +179,10 @@ pub const Race = struct { } pub fn prepare(self: *Race, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n < 4 or shape.n > ref.share) return false; + if (shape.rows == 0 or shape.n < 4 or shape.n > model(self.mini).share()) return false; self.free(a); self.shape = shape; - self.x = try logits(a, rng, shape, fill); + self.x = try logits(a, rng, shape, fill, self.mini); for (self.x) |*v| if (std.math.isFinite(v.*)) { v.* /= 32; // logits within a few Gumbel widths, so the keys decide }; @@ -181,7 +192,7 @@ pub const Race = struct { } pub fn run(self: *Race, rig: *rig_.Rig) !void { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); for (0..self.shape.rows) |r| { const pos = pos0 + r + @intFromBool(self.late); try ops.race1(self.kern, rig.s, self.dev + r * rk.stride * 4, rk.n, rk.base, seed, inv_t, pos, self.out[0] + r * 4, self.out[1] + r * 4); @@ -201,7 +212,7 @@ pub const Race = struct { } pub fn check(self: *const Race, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); const rows = self.shape.rows; for (0..rows) |r| { const row = self.x[r * rk.stride ..][0..rk.n]; @@ -229,10 +240,11 @@ pub const Race = struct { } }; -/// Rows x a rank's share x the rank: logits into the sampler's whole bf16 rows at the rank's columns. -pub fn tobfSpec(unpadded: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 2 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 2 } }; - const name = if (unpadded) "control: inkling2 ops tf_ink2_tobf rounding rank 1's padding ids" else "inkling2 ops tf_ink2_tobf (bf16 rows, padding ids -inf)"; +/// Rows x a rank's share x the rank: logits into the sampler's whole bf16 rows at the rank's columns (Mini: one row). +pub fn tobfSpec(unpadded: bool, mini: bool) c.Spec { + const V = M.mini.vocab; + const served: []const c.Shape = if (mini) &.{ .{ .rows = 16, .n = V, .k = 1 }, .{ .rows = 1, .n = V, .k = 1 }, .{ .rows = 128, .n = V, .k = 1 } } else &.{ .{ .rows = 16, .n = ref.share, .k = 2 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 2 } }; + const name = if (unpadded) (if (mini) M.named("control: inkling2 ops tf_ink2_tobf rounding the padding ids", true) else "control: inkling2 ops tf_ink2_tobf rounding rank 1's padding ids") else M.named("inkling2 ops tf_ink2_tobf (bf16 rows, padding ids -inf)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = "a rounding: each value to bf16 at nearest even, NaN to NaN" }, .served = if (unpadded) served[0..1] else served }; } @@ -240,13 +252,14 @@ pub fn tobfSpec(unpadded: bool) c.Spec { pub const Tobf = struct { kern: *const ops.Kernels, unpadded: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: u64 = 0, pub fn spec(self: *const Tobf) c.Spec { - return tobfSpec(self.unpadded); + return tobfSpec(self.unpadded, self.mini); } pub fn control(self: *const Tobf) ?g.Gate { @@ -259,32 +272,40 @@ pub const Tobf = struct { } pub fn prepare(self: *Tobf, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != ref.share) return false; + if (shape.rows == 0 or shape.n != model(self.mini).share()) return false; self.free(a); self.shape = shape; self.x = try ref.f32s(a, rng, shape.rows * shape.n, -40, 40); if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); self.dev = try ref.input(rig, self.x); - self.out = try rig.output(shape.rows * 2 * ref.share * 2); + self.out = try rig.output(shape.rows * model(self.mini).vocab * 2); return true; } + /// The rank's first column, and its real ids (the last rank's stop at unpadded_vocab_size). + fn cols(self: *const Tobf) [2]usize { + const m = model(self.mini); + const col0: usize = if (self.shape.k == 2) m.share() else 0; + return .{ col0, if (self.shape.k == m.ranks) m.lastReal() else self.shape.n }; + } + pub fn run(self: *Tobf, rig: *rig_.Rig) !void { - const col0: usize = if (self.shape.k == 2) ref.share else 0; - const n = if (self.shape.k == 2 and !self.unpadded) ref.share1_real else self.shape.n; - try ops.tobf(self.kern, rig.s, self.dev, self.shape.rows, self.shape.n, n, self.out, 2 * ref.share, col0, self.shape.n); + const at = self.cols(); + const n = if (self.unpadded) self.shape.n else at[1]; + try ops.tobf(self.kern, rig.s, self.dev, self.shape.rows, self.shape.n, n, self.out, model(self.mini).vocab, at[0], self.shape.n); } pub fn count(self: *const Tobf) usize { - return self.shape.rows * 2 * ref.share * 2; + return self.shape.rows * model(self.mini).vocab * 2; } pub fn check(self: *const Tobf, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { const n = self.shape.n; - const col0: usize = if (self.shape.k == 2) ref.share else 0; - const real = if (self.shape.k == 2) ref.share1_real else n; - for (0..self.shape.rows) |r| for (0..2 * ref.share) |col| { - const have = std.mem.readInt(u16, got[2 * (r * 2 * ref.share + col) ..][0..2], .little); + const V = model(self.mini).vocab; + const col0 = self.cols()[0]; + const real = self.cols()[1]; + for (0..self.shape.rows) |r| for (0..V) |col| { + const have = std.mem.readInt(u16, got[2 * (r * V + col) ..][0..2], .little); const mine = col >= col0 and col < col0 + n; const i = col -% col0; const want: u16 = if (!mine) 0xffff else if (i < real) c.toBf16(self.x[r * n + i]) else 0xff80; diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index 8e04891dab9..9f452860a65 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -12,17 +13,21 @@ const Sums = ref.Sums; const ops = ref.ops; const step = ref.step; -const experts = 384; -const top = 8; const route_scale: f32 = 8; const topk_rule = "the 8 largest score + bias, the lower id on ties, a NaN never picked, a pick's value then -inf; " ++ "weights score / (sum of the picks' scores + 1e-20) x 8 in fp32"; -/// Rows x experts x picks: every row of a call, a block each. -pub fn topkSpec(unbiased: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top }, .{ .rows = 16, .n = 128, .k = top }, .{ .rows = 1, .n = 128, .k = top }, .{ .rows = 128, .n = 128, .k = top }, .{ .rows = 2048, .n = 128, .k = top } }; - const name = if (unbiased) "control: inkling2 ops tf_ink2_topk without the selection bias" else "inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)"; +fn topkServed(comptime m: M.Model) []const c.Shape { + const E = m.experts; + const top = m.top; + return &.{ .{ .rows = 16, .n = E, .k = top }, .{ .rows = 1, .n = E, .k = top }, .{ .rows = 128, .n = E, .k = top }, .{ .rows = 2048, .n = E, .k = top } }; +} + +/// Rows x experts x picks: every row of a call, a block each (Small: 384 experts, Mini: 128, both top 8). +pub fn topkSpec(unbiased: bool, mini: bool) c.Spec { + const served = if (mini) topkServed(M.mini) else topkServed(M.small); + const name = if (unbiased) M.named("control: inkling2 ops tf_ink2_topk without the selection bias", mini) else M.named("inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = topk_rule }, .served = if (unbiased) served[0..2] else served }; } @@ -30,6 +35,7 @@ pub fn topkSpec(unbiased: bool) c.Spec { pub const Topk = struct { kern: *const ops.Kernels, unbiased: bool = false, + mini: bool = false, shape: c.Shape = undefined, scores: []f32 = &.{}, bias: []f32 = &.{}, @@ -37,7 +43,7 @@ pub const Topk = struct { out: [2]u64 = @splat(0), pub fn spec(self: *const Topk) c.Spec { - return topkSpec(self.unbiased); + return topkSpec(self.unbiased, self.mini); } pub fn control(self: *const Topk) ?g.Gate { diff --git a/zig/tests/cuda/contract_inkling2_ops_rows.zig b/zig/tests/cuda/contract_inkling2_ops_rows.zig index 953f54fb68a..87edd67fc67 100644 --- a/zig/tests/cuda/contract_inkling2_ops_rows.zig +++ b/zig/tests/cuda/contract_inkling2_ops_rows.zig @@ -4,13 +4,13 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; /// Rows of the fixture's table: ids are a bijection of the rows, so planted rows stay in their rows. const table_rows = 4096; @@ -19,17 +19,22 @@ fn embedDepth(s: c.Shape) usize { return ref.blockDepth(s.k, 256); } +fn embedServed(comptime C: usize) []const c.Shape { + return &.{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; +} + /// Rows x hidden x hidden: a prompt chunk, a verify window, one decode row (the drafter's anchor embeds one too). -pub fn embedSpec(shifted: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C }, .{ .rows = 16, .n = 2304, .k = 2304 }, .{ .rows = 1, .n = 2304, .k = 2304 }, .{ .rows = 128, .n = 2304, .k = 2304 }, .{ .rows = 2048, .n = 2304, .k = 2304 } }; - if (shifted) return .{ .name = "control: inkling2 ops tf_ink2_embed gathering the next row", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; - return .{ .name = "inkling2 ops tf_ink2_embed (embed_norm, rounded once)", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; +pub fn embedSpec(shifted: bool, mini: bool) c.Spec { + const served = if (mini) embedServed(M.mini.hidden) else embedServed(M.small.hidden); + if (shifted) return .{ .name = M.named("control: inkling2 ops tf_ink2_embed gathering the next row", mini), .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; + return .{ .name = M.named("inkling2 ops tf_ink2_embed (embed_norm, rounded once)", mini), .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; } /// out = bf16(w * (e * rsqrtf(mean(e^2) + eps))) of each id's embedding row. pub const Embed = struct { kern: *const ops.Kernels, shifted: bool = false, + mini: bool = false, shape: c.Shape = undefined, table: []u16 = &.{}, // [table_rows + 1][C]: the control reads one row on w: []u16 = &.{}, @@ -40,7 +45,7 @@ pub const Embed = struct { pub const sums = {}; pub fn spec(self: *const Embed) c.Spec { - return embedSpec(self.shifted); + return embedSpec(self.shifted, self.mini); } pub fn control(self: *const Embed) ?g.Gate { @@ -111,27 +116,40 @@ fn dotDepth(s: c.Shape) usize { return (s.k + 31) / 32 + 5; } -/// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. -pub fn dotSpec(d: Dot, tiles: bool, short: bool) c.Spec { +/// A model's row-dot calls, plain then tiled: router (experts), sinks (query heads), dynamic taps (4 a key head). +fn dotServed(comptime m: M.Model, d: Dot) [2][]const c.Shape { + const C = m.hidden; + const E = m.experts; + const H = m.heads; + const T = comptime m.taps(); const plain: []const c.Shape = switch (d) { // comptime arrays: a spec outlives this call - .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C }, .{ .rows = 16, .n = 128, .k = 2304 }, .{ .rows = 1, .n = 128, .k = 2304 }, .{ .rows = 31, .n = 128, .k = 2304 }, .{ .rows = 7, .n = 128, .k = 2304 } }, - .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C }, .{ .rows = 16, .n = 24, .k = 2304 }, .{ .rows = 1, .n = 24, .k = 2304 }, .{ .rows = 128, .n = 24, .k = 2304 }, .{ .rows = 2048, .n = 24, .k = 2304 } }, - .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C }, .{ .rows = 16, .n = 16, .k = 2304 }, .{ .rows = 1, .n = 16, .k = 2304 }, .{ .rows = 31, .n = 16, .k = 2304 } }, + .router => &.{ .{ .rows = 16, .n = E, .k = C }, .{ .rows = 1, .n = E, .k = C }, .{ .rows = 31, .n = E, .k = C }, .{ .rows = 7, .n = E, .k = C } }, + .sink => &.{ .{ .rows = 16, .n = H, .k = C }, .{ .rows = 1, .n = H, .k = C }, .{ .rows = 128, .n = H, .k = C }, .{ .rows = 2048, .n = H, .k = C } }, + .taps => &.{ .{ .rows = 16, .n = T, .k = C }, .{ .rows = 1, .n = T, .k = C }, .{ .rows = 31, .n = T, .k = C } }, }; const wide: []const c.Shape = if (d == .router) - &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C }, .{ .rows = 64, .n = 128, .k = 2304 }, .{ .rows = 32, .n = 128, .k = 2304 }, .{ .rows = 100, .n = 128, .k = 2304 }, .{ .rows = 2048, .n = 128, .k = 2304 } } + &.{ .{ .rows = 64, .n = E, .k = C }, .{ .rows = 32, .n = E, .k = C }, .{ .rows = 100, .n = E, .k = C }, .{ .rows = 2048, .n = E, .k = C } } else - &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C }, .{ .rows = 64, .n = 16, .k = 2304 }, .{ .rows = 32, .n = 16, .k = 2304 }, .{ .rows = 100, .n = 16, .k = 2304 }, .{ .rows = 2048, .n = 16, .k = 2304 } }; + &.{ .{ .rows = 64, .n = T, .k = C }, .{ .rows = 32, .n = T, .k = C }, .{ .rows = 100, .n = T, .k = C }, .{ .rows = 2048, .n = T, .k = C } }; + return .{ plain, wide }; +} + +/// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. +pub fn dotSpec(d: Dot, tiles: bool, short: bool, mini: bool) c.Spec { + const both = if (mini) dotServed(M.mini, d) else dotServed(M.small, d); + const plain = both[0]; + const wide = both[1]; const names = [3][2][]const u8{ .{ "inkling2 ops tf_ink2_rowdot router (fp32 sigmoid scores)", "inkling2 ops tf_ink2_rowdot_tiles router (fp32 sigmoid scores)" }, .{ "inkling2 ops tf_ink2_rowdot attention sinks (bf16 sigmoid)", "" }, .{ "inkling2 ops tf_ink2_rowdot dynamic conv taps (fp32)", "inkling2 ops tf_ink2_rowdot_tiles dynamic conv taps (fp32)" }, }; - var s: c.Spec = .{ .name = names[@backingInt(d)][@intFromBool(tiles)], .accum = .f32, .depth = dotDepth, .out = if (d == .sink) .bf16 else .f32, .served = if (tiles) wide else plain }; + const flat = names[0] ++ names[1] ++ names[2]; + var s: c.Spec = .{ .name = M.namedAt(&flat, @as(usize, @backingInt(d)) * 2 + @intFromBool(tiles), mini), .accum = .f32, .depth = dotDepth, .out = if (d == .sink) .bf16 else .f32, .served = if (tiles) wide else plain }; s.tiles = if (tiles) .{ .{ .size = 32, .min = 32 }, .{ .size = 16 }, .{} } else .{ .{}, .{ .size = 8 }, .{} }; if (tiles) s.replaces = "tf_ink2_rowdot"; if (short) { - s.name = "control: inkling2 ops tf_ink2_rowdot router one 32-column step short"; + s.name = M.named("control: inkling2 ops tf_ink2_rowdot router one 32-column step short", mini); s.tiles = .{ .{}, .{}, .{} }; s.served = plain[0..2]; } @@ -144,6 +162,7 @@ pub const Rowdot = struct { dot: Dot, tiles: bool = false, short: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []u16 = &.{}, w: []u16 = &.{}, @@ -154,7 +173,7 @@ pub const Rowdot = struct { pub const sums = {}; pub fn spec(self: *const Rowdot) c.Spec { - return dotSpec(self.dot, self.tiles, self.short); + return dotSpec(self.dot, self.tiles, self.short, self.mini); } pub fn control(self: *const Rowdot) ?g.Gate { @@ -238,22 +257,28 @@ pub const Rowdot = struct { } }; -/// Rows x a rank's vocabulary share x 1: the head's fp32 logits, in place. -pub fn capSpec(wrong: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 } }; - return .{ .name = if (wrong) "control: inkling2 ops tf_ink2_softcap at cap 20" else "inkling2 ops tf_ink2_softcap (final logits, cap 30, in place)", .accum = .none, .depth = ref.noSums, .out = .f32, .in_place = true, .served = if (wrong) served[0..1] else served }; +fn capServed(comptime V: usize) []const c.Shape { + return &.{ .{ .rows = 16, .n = V, .k = 1 }, .{ .rows = 1, .n = V, .k = 1 }, .{ .rows = 128, .n = V, .k = 1 } }; +} + +/// Rows x a rank's vocabulary share x 1: the head's fp32 logits, in place (Mini: the whole 201,024 at one rank). +pub fn capSpec(wrong: bool, mini: bool) c.Spec { + const served = if (mini) capServed(M.mini.share()) else capServed(M.small.share()); + const name = if (wrong) M.named("control: inkling2 ops tf_ink2_softcap at cap 20", mini) else M.named("inkling2 ops tf_ink2_softcap (final logits, cap 30, in place)", mini); + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .f32, .in_place = true, .served = if (wrong) served[0..1] else served }; } /// x = tanhf(x / 30) * 30 over the logits in place. pub const Softcap = struct { kern: *const ops.Kernels, wrong: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, out: u64 = 0, pub fn spec(self: *const Softcap) c.Spec { - return capSpec(self.wrong); + return capSpec(self.wrong, self.mini); } pub fn control(self: *const Softcap) ?g.Gate { diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 747fcba1edb..e76c2d74121 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -49,7 +49,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; diff --git a/zig/tests/cuda/contract_stored_experts.zig b/zig/tests/cuda/contract_stored_experts.zig new file mode 100644 index 00000000000..9c6c8509371 --- /dev/null +++ b/zig/tests/cuda/contract_stored_experts.zig @@ -0,0 +1,422 @@ +//! Inkling 2 Mini's stored experts under the contract: NVFP4 and MXFP8 on Mini's shapes, soft-capped SwiGLU, controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const dec = core.expert_decode; + +pub const Format = enum { nvfp4, mxfp8 }; +pub const Kind = enum { up, down_f32, down_bf16 }; + +pub const Entry = struct { name: []const u8, format: Format, kind: Kind, prompt: bool, short: bool = false }; + +/// Every new entry point, the reused NVFP4 downs at Mini's shapes, and a one-group-short control per new entry. +pub const entries = [_]Entry{ + .{ .name = "cuda stored experts nvfp4 tf_nvfp4_softcap (soft-capped SwiGLU)", .format = .nvfp4, .kind = .up, .prompt = false }, + .{ .name = "cuda stored experts nvfp4 tf_nvfp4_prompt_softcap", .format = .nvfp4, .kind = .up, .prompt = true }, + .{ .name = "cuda stored experts nvfp4 decode down f32 (Mini's factor)", .format = .nvfp4, .kind = .down_f32, .prompt = false }, + .{ .name = "cuda stored experts nvfp4 prompt down bf16 (Mini's factor)", .format = .nvfp4, .kind = .down_bf16, .prompt = true }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_softcap", .format = .mxfp8, .kind = .up, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_down_f32", .format = .mxfp8, .kind = .down_f32, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_down_bf16", .format = .mxfp8, .kind = .down_bf16, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_prompt_softcap", .format = .mxfp8, .kind = .up, .prompt = true }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_prompt_down", .format = .mxfp8, .kind = .down_bf16, .prompt = true }, + .{ .name = "control: tf_nvfp4_softcap one 32-input group short", .format = .nvfp4, .kind = .up, .prompt = false, .short = true }, + .{ .name = "control: tf_nvfp4_prompt_softcap one 32-input group short", .format = .nvfp4, .kind = .up, .prompt = true, .short = true }, + .{ .name = "control: tf_mxfp8_softcap one 32-input group short", .format = .mxfp8, .kind = .up, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_down_f32 one 32-input group short", .format = .mxfp8, .kind = .down_f32, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_down_bf16 one 32-input group short", .format = .mxfp8, .kind = .down_bf16, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_prompt_softcap one 32-input group short", .format = .mxfp8, .kind = .up, .prompt = true, .short = true }, + .{ .name = "control: tf_mxfp8_prompt_down one 32-input group short", .format = .mxfp8, .kind = .down_bf16, .prompt = true, .short = true }, +}; + +const experts = 4; +const slots = 8; // Mini's top-8 +pub const caps = [2]f32{ 4.0, 25.0 }; // Mini's mlp_gate_softcap, mlp_up_softcap + +/// An mma k16 step a link of each row's chain, its own error (mma_step), and NVFP4's block-scale fma and factor. +fn depth(s: c.Shape) usize { + return s.k / 16 + core.attention_range.mma_step + 2; +} + +/// Mini's experts: 2,304 to 1,152 (gate and up each) and back; decode 1 and 4 tokens, prompt items of 9 and 16 tokens. +const ups = [2][]const c.Shape{ &.{ .{ .rows = 1, .n = 1152, .k = 2304 }, .{ .rows = 4, .n = 1152, .k = 2304 } }, &.{ .{ .rows = 9, .n = 1152, .k = 2304 }, .{ .rows = 16, .n = 1152, .k = 2304 } } }; +const downs = [2][]const c.Shape{ &.{ .{ .rows = 1, .n = 2304, .k = 1152 }, .{ .rows = 4, .n = 2304, .k = 1152 } }, &.{ .{ .rows = 9, .n = 2304, .k = 1152 }, .{ .rows = 16, .n = 2304, .k = 1152 } } }; + +pub fn spec(e: Entry) c.Spec { + const up = e.kind == .up; + const served = (if (up) ups else downs)[@intFromBool(e.prompt)]; + // MXFP8's prompt CTAs take 2 (gate-up) or 4 (down) column blocks of 32 + const n_tile: c.Tile = if (e.format == .mxfp8 and e.prompt) (if (up) .{ .size = 128, .step = 64, .min = 64 } else .{ .size = 256, .step = 128, .min = 128 }) else .{ .size = 64, .step = 32, .min = 32 }; + const tiles = [3]c.Tile{ .{ .size = (if (e.prompt) ex_.promptTile(.nvfp4) else 16) / slots }, n_tile, .{ .size = 64, .step = 32, .min = 32 } }; + return switch (e.kind) { + // fp32 tanhf, expf and the divisions after the sums: a few ulps each + .up => .{ .name = e.name, .accum = .f32, .depth = depth, .ops = 16, .out = .bf16, .tiles = tiles, .served = served, .sums = .{ .f16 = 30, .bf16 = 30, .why = "the caps saturate: a replay's sum far off can land on the same plateau, so only 30x is provable" } }, + .down_f32 => .{ .name = e.name, .accum = .f32, .depth = depth, .out = .f32, .tiles = tiles, .served = served }, + .down_bf16 => .{ .name = e.name, .accum = .f32, .depth = depth, .out = .bf16, .tiles = tiles, .served = served }, + }; +} + +/// gc tanh(g / gc) sigmoid(g) uc tanh(u / uc) in float64, and its partial derivatives in g and u. +pub fn softcap(gs: f64, us: f64) [3]f64 { + const gc: f64 = caps[0]; + const uc: f64 = caps[1]; + const tg = std.math.tanh(gs / gc); + const e = @exp(-@abs(gs)); + const sg = if (gs >= 0) 1 / (1 + e) else e / (1 + e); + const tu = std.math.tanh(us / uc); + const a = gc * tg * sg; + const b = uc * tu; + const da = (1 - tg * tg) * sg + gc * tg * sg * (1 - sg); + return .{ a * b, da * b, a * (1 - tu * tu) }; +} + +/// shape.rows token rows, `slots` pairs each over `experts` experts; up reads a token's row, down a pair's. +pub const Experts = struct { + rig: rig_.Rig, + entry: Entry, + k4: *const ex_.Nvfp4Experts, + k8: *const mx.Mxfp8Experts, + router: grouped.Router, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []f32 = &.{}, // [M][experts][n][k] stored weights decoded, less NVFP4's factor (exact in f32) + factor: [2][experts]f64 = undefined, // NVFP4's per-expert factor by matrix (1 for MXFP8) + picks: []i32 = &.{}, + xd: u64 = 0, + wd: u64 = 0, + sd: u64 = 0, + plan: grouped.Plan = undefined, + out: u64 = 0, + + pub fn deinit(self: *Experts) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Experts) void { + const a = self.rig.gpu.gpa; + a.free(self.x); + a.free(self.w); + a.free(self.picks); + self.x = &.{}; + self.w = &.{}; + self.picks = &.{}; + } + + pub fn kernel(self: *Experts) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = if (self.entry.short) .shapes else null }; + } + + const vt = g.hooks(Experts); + + fn up(self: *const Experts) bool { + return self.entry.kind == .up; + } + + fn parts(self: *const Experts) usize { + return if (self.up()) 2 else 1; + } + + fn pairs(self: *const Experts) usize { + return self.shape.rows * slots; + } + + fn xRows(self: *const Experts) usize { + return if (self.up()) self.shape.rows else self.pairs(); + } + + fn tile(self: *const Experts) usize { + return if (self.entry.prompt) ex_.promptTile(.nvfp4) else 16; + } + + fn items(self: *const Experts) usize { + return grouped.maxItems(self.pairs(), experts, self.tile()); + } + + fn layer(self: *const Experts) ex_.Layer { + const n = self.shape.n; + const k = self.shape.k; + return .{ .format = if (self.entry.format == .nvfp4) .nvfp4 else .mxfp8, .up = self.wd, .down = self.wd, .up_scale = self.sd, .down_scale = self.sd, .width = if (self.up()) n else k, .dims = if (self.up()) k else n, .experts = experts, .caps = caps }; + } + + /// Random stored codes and scales; non-finite: NaN, +Inf and -Inf in the first rows; stress: mirrored integers. + pub fn prepare(self: *Experts, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 32 != 0 or shape.k == 0 or shape.k % 32 != 0) return false; + if (self.entry.format == .mxfp8 and self.entry.prompt and shape.n % (32 * mx.Mxfp8Experts.prompt_cw[@intFromBool(!self.up())]) != 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + const n = shape.n; + const k = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.x = try a.alloc(u16, self.xRows() * k); + self.w = try a.alloc(f32, self.parts() * experts * n * k); + self.picks = try a.alloc(i32, self.pairs()); + for (self.x) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (self.picks, 0..) |*p, i| p.* = @intCast(if (i < experts) i else rng.uintLessThan(usize, experts)); + const stress = fill == .stress; + const nv = self.entry.format == .nvfp4; + const cbytes = if (nv) n * k / 2 else n * k; + const sbytes = if (nv) n * k / 16 else n * k / 32; + const codes = try a.alloc(u8, self.parts() * experts * cbytes); + defer a.free(codes); + const scales = try a.alloc(u8, self.parts() * experts * sbytes); + defer a.free(scales); + for (codes, 0..) |*b, i| b.* = if (stress) (if (nv) @as(u8, if (i % 3 == 0) 0x42 else 0x24) else @as(u8, if (i % 3 == 0) 0x40 else 0x38)) else rng.int(u8); + if (!nv and !stress) for (codes) |*b| if (b.* & 0x7F == 0x7F) { + b.* ^= 1; // no NaN codes + }; + // E4M3 scales 2^-3 .. 2^3, E8M0 2^-11 .. 2^-7: a few units a sum; stress 1, MXFP8 down 8 (fp16 lanes overflow) + for (scales) |*b| b.* = if (stress) (if (nv) 0x38 else if (self.up()) @as(u8, 127) else 130) else if (nv) 0x20 + rng.uintLessThan(u8, 0x30) else 116 + rng.uintLessThan(u8, 5); + for (0..2) |m| for (0..experts) |e| { + const amax: f32 = if (stress) 2688 else 64 + rng.float(f32) * 256; + self.factor[m][e] = if (nv) mx.nvfp4Factor(amax, 2688) else 1; + }; + if (stress) self.mirror(codes, cbytes); + for (0..self.parts() * experts) |me| for (0..n) |row| for (0..k) |i| { + const cs = codes[me * cbytes ..][0..cbytes]; + const ss = scales[me * sbytes ..][0..sbytes]; + self.w[(me * n + row) * k + i] = @floatCast(if (nv) dec.nvfp4(cs, ss, k, row, i, 1) else dec.mxfp8(cs, ss, k, row, i)); + }; + if (fill == .nonfinite) { + // a row holding NaN, one holding +Inf, one holding both infinities + const planted = [_]struct { usize, usize, f32 }{ .{ 0, k / 3, std.math.nan(f32) }, .{ 1, k / 2, std.math.inf(f32) }, .{ 2, 1, std.math.inf(f32) }, .{ 2, k - 1, -std.math.inf(f32) } }; + for (planted) |p| if (p[0] < self.xRows()) { + self.x[p[0] * k + p[1]] = c.toBf16(p[2]); + }; + } + if (stress) self.stressRows(rng); + try self.upload(codes, scales, cbytes, sbytes); + return true; + } + + /// The packed blocks, the factors, the plan and the output. + fn upload(self: *Experts, codes: []const u8, scales: []const u8, cbytes: usize, sbytes: usize) !void { + const a = self.rig.gpu.gpa; + const n = self.shape.n; + const k = self.shape.k; + const nv = self.entry.format == .nvfp4; + const per = (if (nv) ex_.Nvfp4Experts.bytes(1, n, k, self.parts()) else mx.Mxfp8Experts.bytes(1, n, k, self.parts())) / 4; + const blocks = try a.alloc(u32, experts * per); + defer a.free(blocks); + for (0..experts) |e| { + const out = blocks[e * per ..][0..per]; + var cs: [2][]const u8 = undefined; + var ss: [2][]const u8 = undefined; + for (0..self.parts()) |m| { + cs[m] = codes[(m * experts + e) * cbytes ..][0..cbytes]; + ss[m] = scales[(m * experts + e) * sbytes ..][0..sbytes]; + } + if (nv and self.up()) ex_.Nvfp4Experts.packGateUp(out, .{ cs[0], ss[0] }, .{ cs[1], ss[1] }, n, k); + if (nv and !self.up()) ex_.Nvfp4Experts.packOne(out, cs[0], ss[0], n, k); + if (!nv and self.up()) mx.Mxfp8Experts.packGateUp(out, .{ cs[0], ss[0] }, .{ cs[1], ss[1] }, n, k); + if (!nv and !self.up()) mx.Mxfp8Experts.packOne(out, cs[0], ss[0], n, k); + } + self.wd = try self.rig.input(std.mem.sliceAsBytes(blocks)); + var f: [experts * 2]f32 = undefined; + for (0..experts) |e| for (0..self.parts()) |m| { + f[e * self.parts() + m] = @floatCast(self.factor[m][e]); + }; + self.sd = try self.rig.input(std.mem.sliceAsBytes(f[0 .. experts * self.parts()])); + self.xd = try self.rig.input(std.mem.sliceAsBytes(self.x)); + const zeros = try a.alloc(u8, @max(self.pairs() * 4, self.items() * 12, 8)); + defer a.free(zeros); + @memset(zeros, 0); + const ids = try self.rig.input(std.mem.sliceAsBytes(self.picks)); + const hist = (self.pairs() + 1023) / 1024; + self.plan = .{ .members = try self.rig.input(zeros[0 .. self.pairs() * 4]), .items = try self.rig.input(zeros[0 .. self.items() * 12]), .counts = try self.rig.input(zeros[0..8]), .rank = try self.rig.scratch(self.pairs() * 4), .hist = try self.rig.scratch(hist * experts * 4) }; + try self.router.route(self.rig.s, ids, self.pairs(), experts, self.tile(), self.plan); + try self.rig.s.synchronize(); + self.out = try self.rig.output(self.pairs() * n * c.size(spec(self.entry).out)); + } + + /// Gate 4's weights: input k - 1 - i repeats input i (weights 1 and 2; MXFP8 down 8, 16). so twins sit in + /// different 32-input lanes and no replay order cancels them early. + fn mirror(self: *Experts, codes: []u8, cbytes: usize) void { + const k = self.shape.k; + const nv = self.entry.format == .nvfp4; + const row = if (nv) k / 2 else k; + for (0..self.parts() * experts * (cbytes / row)) |r| { + const b = codes[r * row ..][0..row]; + for (0..row / 2) |j| b[row - 1 - j] = if (nv) (b[j] >> 4) | (b[j] << 4) else b[j]; + } + } + + /// Gate 4's rows: input k - 1 - i is minus input i, input k - 1 is 4 - x_0: each sum is 4 w_0, partials under 2^23. + fn stressRows(self: *Experts, rng: std.Random) void { + const k = self.shape.k; + for (0..self.xRows()) |r| for (0..k / 2) |i| { + const v: f32 = @floatFromInt(4 * (1 + 2 * rng.uintLessThan(u32, 64))); + self.x[r * k + i] = c.toBf16(v); + self.x[r * k + k - 1 - i] = c.toBf16(if (i == 0) 4 - v else -v); // a multiple of 8: exact in bf16 + }; + } + + pub fn run(self: *Experts) !void { + const l = self.layer(); + const in: ex_.Rows = .{ .x = self.xd, .stride = self.shape.k, .slots = if (self.up()) slots else 0 }; + if (self.entry.short) return self.short(l, in); + const epi: ex_.Epi = switch (self.entry.kind) { + .up => .up, + .down_f32 => .down_f32, + .down_bf16 => .down_bf16, + }; + const gx: ex_.Grouped = .{ .nvfp4 = self.k4, .mxfp8 = self.k8 }; + if (self.entry.prompt) { + try gx.prompt(self.rig.s, epi, in, l, self.plan, self.out, self.items(), self.pairs(), 64, -1); + } else try gx.decode(self.rig.s, epi, in, l, self.plan, self.out, self.items(), self.pairs(), 16, -1); + try self.rig.s.synchronize(); + } + + /// The control: the entry's own launch with one k32 group fewer than the layer has. + fn short(self: *Experts, l: ex_.Layer, in: ex_.Rows) !void { + const up_ = self.up(); + const n = self.shape.n; + const nb = n / 32; + const kg = self.shape.k / 32 - 1; + const nv = self.entry.format == .nvfp4; + var a = mx.argsOf(in, up_, self.wd, if (nv) self.sd else null, kg, nb, self.plan, self.out, n, l.caps, -1); + var cfg: cuda.Config = .{ .grid = .{ .x = @intCast((self.items() * nb + 3) / 4) }, .block = .{ .x = 128 } }; + const f = if (nv) self.k4.softcap.fns[@intFromBool(self.entry.prompt)] else self.k8.fns[ + try mx.Mxfp8Experts.entry(self.entry.prompt, switch (self.entry.kind) { + .up => .up, + .down_f32 => .down_f32, + .down_bf16 => .down_bf16, + }) + ]; + if (self.entry.prompt and nv) { + cfg.grid.x = @intCast(self.items() * ((nb + 3) / 4)); + cfg.shared = ex_.Nvfp4Experts.promptSmem(2, mx.Softcap.prompt_wn); + } else if (self.entry.prompt) cfg.grid.x = @intCast(self.items() * (nb / mx.Mxfp8Experts.prompt_cw[@intFromBool(!up_)])); + try cuda.launch.launch(f, cfg, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Experts) usize { + return self.pairs() * self.shape.n; + } + + /// Pair p's products with column j of matrix m of its expert, in input order, and that matrix's factor. + fn terms(self: *const Experts, m: usize, p: usize, j: usize, t: []f64) f64 { + const k = self.shape.k; + const xr = (if (self.up()) p / slots else p) * k; + const e: usize = @intCast(self.picks[p]); + const wr = ((m * experts + e) * self.shape.n + j) * k; + for (t, 0..) |*o, i| o.* = c.fromBf16(self.x[xr + i]) * @as(f64, self.w[wr + i]); + return self.factor[m][e]; + } + + pub fn reference(self: *Experts, want: []f64, mag: []f64) !void { + const t = try self.rig.gpu.gpa.alloc(f64, self.shape.k); + defer self.rig.gpu.gpa.free(t); + for (0..self.pairs()) |p| for (0..self.shape.n) |j| { + var sum: [2]f64 = .{ 0, 0 }; + var abs: [2]f64 = .{ 0, 0 }; + for (0..self.parts()) |m| { + const f = self.terms(m, p, j, t); + for (t) |v| { + sum[m] += v; + abs[m] += @abs(v); + } + sum[m] *= f; + abs[m] *= f; + } + const o = p * self.shape.n + j; + if (self.up()) { + const r = softcap(sum[0], sum[1]); + want[o] = r[0]; + mag[o] = @abs(r[1]) * abs[0] + @abs(r[2]) * abs[1]; // the sums' errors through the slopes + } else { + want[o] = sum[0]; + mag[o] = abs[0]; + } + }; + } + + pub fn simulate(self: *Experts, acc: c.Accum, order: g.Order, out: []f64) !void { + const t = try self.rig.gpu.gpa.alloc(f64, self.shape.k); + defer self.rig.gpu.gpa.free(t); + for (0..self.pairs()) |p| for (0..self.shape.n) |j| { + var sum: [2]f64 = .{ 0, 0 }; + for (0..self.parts()) |m| { + const f = self.terms(m, p, j, t); + sum[m] = contract.rows.sumIn(acc, order, t) * f; + } + out[p * self.shape.n + j] = if (self.up()) softcap(sum[0], sum[1])[0] else sum[0]; + }; + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k4: ex_.Nvfp4Experts, + k8: mx.Mxfp8Experts, + mod: cuda.Module, + items: [entries.len]Experts = undefined, + + /// The set, its kernels appended to `list` (each control after the kernels it breaks). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + errdefer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + errdefer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + errdefer mod.unload(); + set.* = .{ .gpa = gpu.gpa, .k4 = k4, .k8 = k8, .mod = mod }; + const router = try grouped.Router.resolve(set.mod); + for (&set.items, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .k4 = &set.k4, .k8 = &set.k8, .router = router }; + for (&set.items) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.items) |*x| x.deinit(); + set.mod.unload(); + set.k8.unload(); + set.k4.unload(); + set.gpa.destroy(set); + } +}; + +/// The stored experts' gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x6d696e69, &t); + std.debug.print("SUMMARY stored experts: {d} kernels, {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "stored-experts contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} + +test "every control is named one, and only the controls plant a fault" { + for (entries) |e| try std.testing.expectEqual(e.short, std.mem.startsWith(u8, e.name, "control: ")); +} + +test "the soft-capped SwiGLU's slopes are its float64 difference quotients" { + for ([_][2]f64{ .{ 0.3, 1.5 }, .{ -6, 30 }, .{ 9, -2 } }) |gu| { + const r = softcap(gu[0], gu[1]); + const h = 1e-6; + try std.testing.expectApproxEqRel((softcap(gu[0] + h, gu[1])[0] - softcap(gu[0] - h, gu[1])[0]) / (2 * h), r[1], 1e-6); + try std.testing.expectApproxEqRel((softcap(gu[0], gu[1] + h)[0] - softcap(gu[0], gu[1] - h)[0]) / (2 * h), r[2], 1e-6); + } +} diff --git a/zig/tests/cuda/inkling2_mini_tests.zig b/zig/tests/cuda/inkling2_mini_tests.zig new file mode 100644 index 00000000000..43bb5fdfb34 --- /dev/null +++ b/zig/tests/cuda/inkling2_mini_tests.zig @@ -0,0 +1,279 @@ +//! Inkling 2 Mini on the released checkpoint at one rank: greedy tokens, a prompt cut in chunks against one chunk +//! (resumed == fresh), and four streams decoding together against each alone (concurrent == solo). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const Gpu = check.Gpu; + +const mm = ink.mini_model; + +pub const Rig = struct { + gpu: Gpu, + w: ink.mini_weights.Weights, + k: mm.Kernels, + s: cuda.Stream, + m: mm.Model, + + pub fn init(r: *Rig, gpu: Gpu, model: []const u8, context: usize, slots: usize) !void { + r.gpu = gpu; + r.w = try ink.mini_weights.load(gpu.gpa, gpu.io, gpu.d, model); + errdefer r.w.deinit(); + ink.mini_weights.roundCaps(&r.w, roundCaps()); + r.k = try mm.Kernels.load(gpu.ctx); + errdefer r.k.deinit(); + r.s = try cuda.Stream.init(gpu.d, false); + errdefer r.s.deinit(); + r.m = try mm.Model.init(gpu.gpa, gpu.d, r.s, &r.w, &r.k, context, slots); + } + + pub fn deinit(r: *Rig) void { + r.m.deinit(); + r.s.deinit(); + r.k.deinit(); + r.w.deinit(); + } + + fn vocab(r: *const Rig) usize { + return r.w.config.text.unpadded_vocab; + } + + /// The host copy of the logits of `heads` rows the last forward kept. + fn logits(r: *Rig, heads: usize) ![]f32 { + try r.s.synchronize(); + const out = try r.gpu.gpa.alloc(f32, heads * r.vocab()); + try (cuda.DeviceBuffer{ .d = r.gpu.d, .ptr = r.m.s.logits, .len = out.len * 4, .borrowed = true }).download(0, std.mem.sliceAsBytes(out)); + return out; + } + + /// A prompt into `slot` in chunks of `chunk` rows; the last row's logits. + pub fn prompt(r: *Rig, slot: usize, tokens: []const u32, p0: usize, chunk: usize) ![]f32 { + var at: usize = 0; + while (at < tokens.len) { + const n = @min(chunk, tokens.len - at); + const last = at + n == tokens.len; + try r.m.forward(&r.k, r.s, &.{.{ .slot = slot, .p0 = p0 + at, .tokens = tokens[at..][0..n] }}, true, if (last) n - 1 else 0, @intFromBool(last)); + at += n; + } + return r.logits(1); + } + + /// One decode row a stream, the streams in one forward: each row's logits. + pub fn step(r: *Rig, chains: []const mm.Chain) ![]f32 { + try r.m.forward(&r.k, r.s, chains, false, 0, chains.len); + return r.logits(chains.len); + } +}; + +/// INKLING2_ROUND_CAPS=1: the experts' gate and up rounded to bf16 before the soft caps (engine and reference). +pub fn roundCaps() bool { + const v = std.c.getenv("INKLING2_ROUND_CAPS") orelse return false; + return std.mem.eql(u8, std.mem.span(v), "1"); +} + +pub fn argmax(x: []const f32) u32 { + var best: usize = 0; + for (x, 0..) |v, i| if (v > x[best]) { + best = i; + }; + return @intCast(best); +} + +fn ms(a: i96, b: i96) f64 { + return @as(f64, @floatFromInt(b - a)) / 1e6; +} + +/// Greedy tokens of `slot` from its prompt's logits, one decode row at a time. +fn decode(r: *Rig, slot: usize, first: []const f32, p0: usize, out: []u32) !void { + out[0] = argmax(first); + for (1..out.len) |i| { + const row = try r.step(&.{.{ .slot = slot, .p0 = p0 + i - 1, .tokens = out[i - 1 .. i] }}); + defer r.gpu.gpa.free(row); + out[i] = argmax(row); + } +} + +/// tf-cuda-test inkling2-mini DIR N TEXT: greedy, resumed == fresh, concurrent == solo, decode speed at 1 and 4. +pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const ids = try tok.encode(gpa, text); + defer gpa.free(ids); + var rig: Rig = undefined; + const t_load = check.now(gpu.io); + try rig.init(gpu, model, 4096, 4); + defer rig.deinit(); + std.debug.print("INFO inkling2 mini: {d} prompt tokens, {d:.2} GB of weights on the GPU, loaded in {d:.1} s\n", .{ ids.len, @as(f64, @floatFromInt(rig.w.bytes)) / 1e9, ms(t_load, check.now(gpu.io)) / 1e3 }); + const n0 = ids.len; + const t0 = check.now(gpu.io); + const first = try rig.prompt(0, ids, 0, mm.prompt_rows); + defer gpa.free(first); + const t1 = check.now(gpu.io); + const plain = try gpa.alloc(u32, count); + defer gpa.free(plain); + try decode(&rig, 0, first, n0, plain); + const t2 = check.now(gpu.io); + const said = try tok.decode(gpa, plain, false); + defer gpa.free(said); + std.debug.print("RESULT inkling2 mini greedy: {d} tokens, prompt {d:.1} ms, decode {d:.2} ms a token ({d:.1} tok/s): \"{s}\"\n", .{ count, ms(t0, t1), ms(t1, t2) / @as(f64, @floatFromInt(count - 1)), @as(f64, @floatFromInt(count - 1)) * 1e3 / ms(t1, t2), said }); + std.debug.print("RESULT inkling2 mini ids:", .{}); + for (plain) |t| std.debug.print(" {d}", .{t}); + std.debug.print("\n", .{}); + // resumed == fresh: the prompt in chunks (a prompt-cache hit resumes at a chunk edge), then the same greedy tokens + var bad: usize = 0; + for ([_]usize{ 1, 7, 64 }) |chunk| { + if (chunk >= n0) continue; + const again = try rig.prompt(1, ids, 0, chunk); + defer gpa.free(again); + const same = std.mem.eql(u8, std.mem.sliceAsBytes(again), std.mem.sliceAsBytes(first)); + const resumed = try gpa.alloc(u32, @min(count, 32)); + defer gpa.free(resumed); + try decode(&rig, 1, again, n0, resumed); + const tokens_same = std.mem.eql(u32, resumed, plain[0..resumed.len]); + if (!same or !tokens_same) bad += 1; + std.debug.print("{s} inkling2 mini prompt in chunks of {d}: last-row logits {s}, {d} greedy tokens {s}\n", .{ if (same and tokens_same) "PASS" else "FAIL", chunk, if (same) "bit-equal" else "differ", resumed.len, if (tokens_same) "equal" else "differ" }); + } + try check.expect(bad == 0, "inkling2 mini resumed == fresh: {d} chunkings differ", .{bad}); + try graphs(&rig, ids, first, plain); + try snapshots(&rig, ids, first); + try concurrent(&rig, ids, plain); +} + +/// A prompt-cache state saved mid-prompt in slot 0, restored into slot 1, the rest prefilled there: the last row's +/// logits bit-equal to the fresh pass. Planted: a state of another prompt restored instead must differ. +fn snapshots(rig: *Rig, ids: []const u32, first: []const f32) !void { + const gpa = rig.gpu.gpa; + const snap = ink.mini_snap; + const mid: u32 = @intCast(ids.len / 2); + gpa.free(try rig.prompt(0, ids[0..mid], 0, mm.prompt_rows)); + const k = try snap.save(gpa, &rig.m, rig.s, 0, mid); + defer snap.drop(gpa, rig.s, k); + // the planted control: slot 0 refilled with another prefix (the ids reversed) and its state restored + const other = try gpa.alloc(u32, mid); + defer gpa.free(other); + for (other, 0..) |*o, i| o.* = ids[mid - 1 - i]; + gpa.free(try rig.prompt(0, other, 0, mm.prompt_rows)); + const wrong = try snap.save(gpa, &rig.m, rig.s, 0, mid); + defer snap.drop(gpa, rig.s, wrong); + var same: [2]bool = undefined; + for ([_]*const snap.Saved{ wrong, k }, 0..) |state, i| { + try snap.restore(&rig.m, rig.s, 1, state); + const got = try rig.prompt(1, ids[mid..], mid, mm.prompt_rows); + defer gpa.free(got); + same[i] = std.mem.eql(u8, std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(first)); + } + try check.expect(!same[0], "inkling2 mini planted control: another prompt's state restored gives the fresh logits", .{}); + try check.expect(same[1], "inkling2 mini snapshot: restored at {d} != fresh", .{mid}); + check.pass("inkling2 mini prompt-cache state at {d} of {d} ({d} bytes): restored == fresh bit-equal; planted (another prompt's state) red", .{ mid, ids.len, snap.bytes(&rig.m, mid) }); +} + +/// The decode graphs against direct launches: the first step's logits bit-equal, then 32 greedy tokens equal. +fn graphs(rig: *Rig, ids: []const u32, first: []const f32, plain: []const u32) !void { + const gpa = rig.gpu.gpa; + var rows: [2][]f32 = undefined; + for ([_]bool{ true, false }, 0..) |on, i| { + rig.m.graphed = on; + gpa.free(try rig.prompt(2 + i, ids, 0, mm.prompt_rows)); + rows[i] = try rig.step(&.{.{ .slot = 2 + i, .p0 = ids.len, .tokens = plain[0..1] }}); + } + defer for (rows) |r| gpa.free(r); + const same = std.mem.eql(u8, std.mem.sliceAsBytes(rows[0]), std.mem.sliceAsBytes(rows[1])); + const direct = try gpa.alloc(u32, @min(plain.len, 32)); + defer gpa.free(direct); + gpa.free(try rig.prompt(3, ids, 0, mm.prompt_rows)); // afresh: the step above moved slot 3's conv states + try decode(rig, 3, first, ids.len, direct); + rig.m.graphed = true; + const tokens_same = std.mem.eql(u32, direct, plain[0..direct.len]); + try check.expect(same and tokens_same, "inkling2 mini graphs == direct: logits {s}, tokens {s}", .{ if (same) "equal" else "differ", if (tokens_same) "equal" else "differ" }); + check.pass("inkling2 mini decode graphs == direct launches: first step's logits bit-equal, {d} greedy tokens equal", .{direct.len}); +} + +/// Four streams at once (prompts of different lengths) against each alone: equal tokens; the round's decode speed. +fn concurrent(rig: *Rig, ids: []const u32, plain: []const u32) !void { + const gpa = rig.gpu.gpa; + const steps = @min(plain.len, 64); + var solo: [4][]u32 = undefined; + var lens: [4]usize = undefined; + var firsts: [4][]f32 = undefined; + for (0..4) |i| { + lens[i] = @max(1, ids.len - i * ids.len / 8); // prefixes of the prompt: different lengths and contexts + firsts[i] = try rig.prompt(i, ids[0..lens[i]], 0, mm.prompt_rows); + solo[i] = try gpa.alloc(u32, steps); + try decode(rig, i, firsts[i], lens[i], solo[i]); + } + defer for (0..4) |i| { + gpa.free(solo[i]); + gpa.free(firsts[i]); + }; + var together: [4][]u32 = undefined; + for (0..4) |i| { + gpa.free(try rig.prompt(i, ids[0..lens[i]], 0, mm.prompt_rows)); + together[i] = try gpa.alloc(u32, steps); + together[i][0] = argmax(firsts[i]); + } + defer for (together) |t| gpa.free(t); + const t0 = check.now(rig.gpu.io); + for (1..steps) |j| { + var chains: [4]mm.Chain = undefined; + for (0..4) |i| chains[i] = .{ .slot = i, .p0 = lens[i] + j - 1, .tokens = together[i][j - 1 .. j] }; + const rows = try rig.step(&chains); + defer gpa.free(rows); + for (0..4) |i| together[i][j] = argmax(rows[i * rig.vocab() ..][0..rig.vocab()]); + } + const t1 = check.now(rig.gpu.io); + var bad: usize = 0; + for (0..4) |i| { + if (!std.mem.eql(u32, together[i], solo[i])) bad += 1; + } + try check.expect(bad == 0, "inkling2 mini concurrent == solo: {d} of 4 streams' tokens differ", .{bad}); + const per = ms(t0, t1) / @as(f64, @floatFromInt(steps - 1)); + check.pass("inkling2 mini concurrent == solo: 4 streams x {d} greedy tokens equal; c=4 round {d:.2} ms ({d:.1} tok/s total)", .{ steps, per, 4e3 / per }); +} + +/// tf-cuda-test inkling2-mini-ref DIR N TEXT: N greedy tokens on the GPU, then the float64 reference teacher-forced +/// over the prompt and them: each generated token against the reference's pick, every difference with its margin. +pub fn reference(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const ids = try tok.encode(gpa, text); + defer gpa.free(ids); + var rig: Rig = undefined; + try rig.init(gpu, model, 4096, 1); + defer rig.deinit(); + const first = try rig.prompt(0, ids, 0, mm.prompt_rows); + defer gpa.free(first); + const all = try gpa.alloc(u32, ids.len + count); + defer gpa.free(all); + @memcpy(all[0..ids.len], ids); + try decode(&rig, 0, first, ids.len, all[ids.len..]); + var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); + defer ck.close(); + // INKLING2_REF_PLANT=1: the reference drops the cross-pass messages; the check must go red + const plant = if (std.c.getenv("INKLING2_REF_PLANT")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .plant = plant, .round_caps = roundCaps() }; + const picks = try gpa.alloc(ink.mini_ref.Pick, all.len); + defer gpa.free(picks); + const t0 = check.now(gpu.io); + try r.run(all[0 .. all.len - 1], picks[0 .. all.len - 1]); + std.debug.print("INFO inkling2 mini reference: {d} positions in {d:.1} s\n", .{ all.len - 1, ms(t0, check.now(gpu.io)) / 1e3 }); + var differ: usize = 0; + var smallest: f64 = std.math.inf(f64); + for (ids.len - 1..all.len - 1) |i| { + const want = picks[i]; + smallest = @min(smallest, want.margin); + if (want.id != all[i + 1]) { + differ += 1; + std.debug.print("DIFF inkling2 mini position {d}: GPU {d}, reference {d} (reference margin {d:.4})\n", .{ i + 1, all[i + 1], want.id, want.margin }); + } + } + const said = try tok.decode(gpa, all[ids.len..], false); + defer gpa.free(said); + std.debug.print("RESULT inkling2 mini vs float64 reference{s}: {d} of {d} greedy tokens differ, smallest reference margin {d:.4}: \"{s}\"\n", .{ if (plant) " (PLANTED: no messages)" else "", differ, count, smallest, said }); + if (plant) return check.expect(differ > 0, "inkling2 mini planted control: the reference without messages still agrees", .{}); + try check.expect(differ == 0, "inkling2 mini greedy == reference: {d} of {d} tokens differ", .{ differ, count }); +} diff --git a/zig/tests/cuda/inkling2_mini_xcheck.zig b/zig/tests/cuda/inkling2_mini_xcheck.zig new file mode 100644 index 00000000000..b582dda75d3 --- /dev/null +++ b/zig/tests/cuda/inkling2_mini_xcheck.zig @@ -0,0 +1,133 @@ +//! tf-cuda-test inkling2-mini-xcheck DIR N: the cross-engine check against #4337's Metal forward. Prompt A is raw ids +//! [1, 100, ..., 700]; prompt B is "The capital of France is" tokenized without a template. For each it prints one +//! "XCHECK {json}" line: the prompt ids, N greedy tokens, each step's top 2 (id, soft-capped logit) and the last prompt +//! row's top 5, from the CUDA engine and, teacher-forced on the engine's tokens, from the float64 reference. +const std = @import("std"); +const core = @import("core"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const tests = @import("inkling2_mini_tests.zig"); +const Gpu = check.Gpu; + +const mm = ink.mini_model; +const Pick = ink.mini_ref.Pick; + +const Top = struct { id: u32, v: f32 }; + +/// The k best of `x`, best first (ties: the lower id). +fn top(x: []const f32, comptime k: usize) [k]Top { + var out: [k]Top = @splat(.{ .id = 0, .v = -std.math.inf(f32) }); + for (x, 0..) |v, i| { + if (!(v > out[k - 1].v)) continue; + var at: usize = k - 1; + while (at > 0 and v > out[at - 1].v) : (at -= 1) out[at] = out[at - 1]; + out[at] = .{ .id = @intCast(i), .v = v }; + } + return out; +} + +fn ids(w: anytype, xs: []const u32) !void { + try w.writeAll("["); + for (xs, 0..) |x, i| try w.print("{s}{d}", .{ if (i == 0) "" else ",", x }); + try w.writeAll("]"); +} + +fn pairsGpu(w: anytype, row: []const f32, comptime k: usize) !void { + const t = top(row, k); + try w.writeAll("["); + for (t, 0..) |p, i| try w.print("{s}[{d},{d:.6}]", .{ if (i == 0) "" else ",", p.id, p.v }); + try w.writeAll("]"); +} + +fn pairsRef(w: anytype, p: Pick, k: usize) !void { + try w.writeAll("["); + for (0..k) |i| try w.print("{s}[{d},{d:.6}]", .{ if (i == 0) "" else ",", p.ids[i], p.logits[i] }); + try w.writeAll("]"); +} + +fn forcedIds(gpa: std.mem.Allocator, name: [:0]const u8) !?[]u32 { + const v = std.mem.span(std.c.getenv(name) orelse return null); + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(gpa); + var it = std.mem.tokenizeAny(u8, v, ", "); + while (it.next()) |t| try out.append(gpa, try std.fmt.parseInt(u32, t, 10)); + return try out.toOwnedSlice(gpa); +} + +pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const b = try tok.encode(gpa, "The capital of France is"); + defer gpa.free(b); + const prompts = [_]struct { name: []const u8, ids: []const u32 }{ + .{ .name = "A", .ids = &.{ 1, 100, 200, 300, 400, 500, 600, 700 } }, + .{ .name = "B", .ids = b }, + }; + var rig: tests.Rig = undefined; + try rig.init(gpu, model, 4096, 1); + defer rig.deinit(); + var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); + defer ck.close(); + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .round_caps = tests.roundCaps() }; + const v = rig.w.config.text.unpadded_vocab; + var disagree: usize = 0; + for (prompts) |pr| { + const n0 = pr.ids.len; + const all = try gpa.alloc(u32, n0 + count); + defer gpa.free(all); + @memcpy(all[0..n0], pr.ids); + const rows = try gpa.alloc(f32, (count + 1) * v); // the last prompt row's logits, then each step's + defer gpa.free(rows); + const first = try rig.prompt(0, pr.ids, 0, mm.prompt_rows); + @memcpy(rows[0..v], first); + gpa.free(first); + // INKLING2_FORCED_A / _B: comma-separated ids fed in place of the argmax (teacher-forced on another engine's) + const forced = try forcedIds(gpa, if (pr.name[0] == 'A') "INKLING2_FORCED_A" else "INKLING2_FORCED_B"); + defer if (forced) |f| gpa.free(f); + if (forced) |f| if (f.len < count) return error.ForcedTooShort; + const next = struct { + fn at(f: ?[]const u32, row: []const f32, i: usize) u32 { + return if (f) |ff| ff[i] else tests.argmax(row); + } + }.at; + all[n0] = next(forced, rows[0..v], 0); + for (1..count) |i| { + const row = try rig.step(&.{.{ .slot = 0, .p0 = n0 + i - 1, .tokens = all[n0 + i - 1 .. n0 + i] }}); + defer gpa.free(row); + @memcpy(rows[i * v ..][0..v], row); + all[n0 + i] = next(forced, row, i); + } + const picks = try gpa.alloc(Pick, n0 + count - 1); + defer gpa.free(picks); + try r.run(all[0 .. n0 + count - 1], picks); + var buf: std.ArrayList(u8) = .empty; + defer buf.deinit(gpa); + var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, &buf); + const w = &aw.writer; + try w.print("{{\"prompt\":\"{s}\",\"forced\":{},\"round_caps\":{},\"ids\":", .{ pr.name, forced != null, tests.roundCaps() }); + try ids(w, pr.ids); + try w.writeAll(",\"tokens\":"); + try ids(w, all[n0..]); + try w.writeAll(",\"cuda\":{\"last_prompt_top5\":"); + try pairsGpu(w, rows[0..v], 5); + try w.writeAll(",\"top2\":["); + for (0..count) |i| { + if (i > 0) try w.writeAll(","); + try pairsGpu(w, rows[i * v ..][0..v], 2); + } + try w.writeAll("]},\"ref_f64\":{\"last_prompt_top5\":"); + try pairsRef(w, picks[n0 - 1], 5); + try w.writeAll(",\"top2\":["); + for (0..count) |i| { + if (i > 0) try w.writeAll(","); + try pairsRef(w, picks[n0 - 1 + i], 2); + if (picks[n0 - 1 + i].id != tests.argmax(rows[i * v ..][0..v])) disagree += 1; + } + try w.writeAll("]}}"); + buf = aw.toArrayList(); + std.debug.print("XCHECK {s}\n", .{buf.items}); + } + std.debug.print("RESULT inkling2 mini xcheck: {d} greedy tokens of 2 x {d} where the float64 reference's top 1 and the engine's differ\n", .{ disagree, count }); +} diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index b663effeefe..d6aa3321cc0 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -1,12 +1,14 @@ -//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots, admission and copied drafts. +//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots and admission. const std = @import("std"); const lanes = @import("lanes"); const mini = @import("inkling2"); const cuda = @import("cuda"); +const core = @import("core"); const check = @import("check.zig"); const native = mini.native; -const Backend = @TypeOf(@as(native.Owned, undefined).backend); +const Mini = mini.mini_backend.Mini; +const Saved = mini.mini_snap.Saved; const Gpu = check.Gpu; const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; @@ -22,19 +24,15 @@ const Trace = struct { } }; -fn target(loaded: *native.Loaded) *Backend { - return &loaded.target.backend; -} - -fn download(b: *Backend, src: u64, out: []f32) !void { - try b.s.synchronize(); - try cuda.memory.download(b.d, src, std.mem.sliceAsBytes(out)); +fn download(t: *Mini, src: u64, out: []f32) !void { + try t.s.synchronize(); + try cuda.memory.download(t.d, src, std.mem.sliceAsBytes(out)); } /// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.stream.Reuse) !Trace { - const t = target(loaded); - const v = t.m.w.c.text.unpadded_vocab; + const t = loaded.target; + const v: usize = t.m.c.unpadded_vocab; var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); defer s.deinit(gpu.gpa); const b = loaded.backend; @@ -43,11 +41,20 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes errdefer gpu.gpa.free(ids); const logits = try gpu.gpa.alloc(f32, n * v); errdefer gpu.gpa.free(logits); + const draw_row: ?[]f32 = if (host and cuda.sample.ruleFor(sampling) != null) try gpu.gpa.alloc(f32, v) else null; + defer if (draw_row) |rounded| gpu.gpa.free(rounded); try b.prefill(&s); - try download(t, try t.lastOf(&s), logits[0..v]); + try download(t, t.lanes.getPtr(&s).?.last, logits[0..v]); // the prompt's last row, kept for the stream's slot var handle: ?u64 = try b.first(&s, prompt.len); for (0..n) |i| { - ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..v], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + ids[i] = if (host) blk: { + const row = logits[i * v ..][0..v]; + if (draw_row) |rounded| { + for (rounded, row) |*dst, value| dst.* = core.bf16_round.round32(value); + break :blk try lanes.gpu_full.draw(gpu.gpa, rounded, sampling, @intCast(prompt.len + i), null); + } + break :blk try lanes.gpu_full.draw(gpu.gpa, row, null, @intCast(prompt.len + i), null); + } else try b.read(handle.?); if (i + 1 < n) { handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); try download(t, t.m.s.logits, logits[(i + 1) * v ..][0..v]); @@ -58,7 +65,11 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes fn sameTrace(a: *const Trace, b: *const Trace) !void { if (!std.mem.eql(u32, a.ids, b.ids)) return error.MiniServingTokenMismatch; - if (!std.mem.eql(u8, std.mem.sliceAsBytes(a.logits), std.mem.sliceAsBytes(b.logits))) return error.MiniServingLogitMismatch; + if (std.mem.indexOfDiff(u32, @ptrCast(a.logits), @ptrCast(b.logits))) |i| { + const v = a.logits.len / a.ids.len; + std.debug.print("RESULT mini-serving logits differ step={d} id={d} {e} vs {e}\n", .{ i / v, i % v, a.logits[i], b.logits[i] }); + return error.MiniServingLogitMismatch; + } } fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { @@ -76,16 +87,15 @@ fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { /// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { - const Saved = @TypeOf(loaded.target.model).Saved; const Keeper = struct { - b: *Backend, + b: *Mini, saved: ?*Saved = null, fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { const k: *@This() = @ptrCast(@alignCast(ptr)); k.saved = k.b.saveState(s, mark) catch null; } }; - const t = target(loaded); + const t = loaded.target; const saved = snapshot: { var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); defer s.deinit(gpu.gpa); @@ -105,16 +115,15 @@ fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sa /// A keeps states at 14 and 39; B resumes A's 14, keeps its 39 and decodes; A resumed at 39 must equal fresh A. fn crossPrompt(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { - const Saved = @TypeOf(loaded.target.model).Saved; const Keeper = struct { - b: *Backend, + b: *Mini, saved: [2]?*Saved = .{ null, null }, fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { const k: *@This() = @ptrCast(@alignCast(ptr)); k.saved[@intFromBool(mark != 14)] = k.b.saveState(s, mark) catch null; } }; - const t = target(loaded); + const t = loaded.target; const b = loaded.backend; const a = ids[0..40]; var other: [40]u32 = undefined; @@ -157,23 +166,14 @@ fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); defer fresh.deinit(gpu.gpa); const cuts: []const u32 = if (case == 0) &.{ 17, 2048 } else &.{ 2049, @intCast(prompt.len - 1) }; - for (cuts) |cut| try resumedAt(gpu, loaded, prompt, cut, sampling, &fresh); + for (cuts) |cut| resumedAt(gpu, loaded, prompt, cut, sampling, &fresh) catch |err| { + std.debug.print("RESULT mini-serving resumed case={d} cut={d} mismatch={s}\n", .{ case, cut, @errorName(err) }); + return err; + }; } } -fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.proposer.Proposer) !void { - var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); - defer cfg.deinit(gpu.gpa); - cfg.timed = false; - var clock: lanes.fake.FixedClock = .{}; - var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); - defer e.deinit(); - if (proposer) |p| s.proposer = p; - try e.addStream(s); - while (!s.finished) try e.step(); - if (s.reason != .length) return error.MiniServingDidNotFinish; -} - +/// Both slots decode at once in shared rounds; a third request finds no free slot until one ends. fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); defer plain_a.deinit(gpu.gpa); @@ -183,186 +183,27 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! defer first.deinit(gpu.gpa); var second = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-second", .prompt = b, .max_new = 10, .sampling = sampled }); defer second.deinit(gpu.gpa); - var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + var third = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-third", .prompt = a, .max_new = 10 }); + defer third.deinit(gpu.gpa); + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, loaded.rows, loaded.rows - 1); // the host's widths (native/cuda_startup_phase.zig) defer cfg.deinit(gpu.gpa); cfg.timed = false; var clock: lanes.fake.FixedClock = .{}; var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); defer e.deinit(); - if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; try e.addStream(&first); - if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; - try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); - while (!first.finished) try e.step(); - try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); - if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; - if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; + if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSecondLaneRefused; try e.addStream(&second); - while (!second.finished) try e.step(); + if (native.fits(loaded.ctx, @intCast(a.len), third.max_new)) return error.MiniBusyAdmissionRefused; + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&third)); + const rounds = e.shared_rounds; + while (!first.finished or !second.finished) try e.step(); + if (e.shared_rounds == rounds) return error.MiniLanesNeverShared; + try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); try std.testing.expectEqual(lanes.stream.Reason.length, second.reason); + if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; -} - -/// Four slots: interleaved greedy and seeded streams equal solo; a fifth is refused before anything is queued. -fn concurrent(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { - const n = 4; - const cuts = [n][2]usize{ .{ 0, 257 }, .{ 17, 1042 }, .{ 300, 2400 }, .{ 5, 70 } }; - var solo: [n]Trace = undefined; - var done: usize = 0; - defer for (solo[0..done]) |*x| x.deinit(gpu.gpa); - for (cuts, 0..) |c, i| { - solo[i] = try trace(gpu, loaded, ids[c[0]..c[1]], if (i % 2 == 0) null else sampled, 10, false, .{}); - done += 1; - } - try loaded.reserve(loaded.ctx, n); - { - var busy: [n]lanes.Stream = undefined; - var opened: usize = 0; - defer for (busy[0..opened]) |*x| { - loaded.backend.release(x); - x.deinit(gpu.gpa); - }; - for (&busy, 0..) |*x, i| { - x.* = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-busy", .prompt = ids[i .. i + 8], .max_new = 1 }); - opened += 1; - if (!native.fits(loaded.ctx, 8, 1)) return error.MiniSlotMissing; - try loaded.backend.prefill(x); - } - if (native.fits(loaded.ctx, 8, 1)) return error.MiniFifthAdmitted; - var fifth = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-fifth", .prompt = ids[0..8], .max_new = 1 }); - defer fifth.deinit(gpu.gpa); - try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&fifth)); - if (fifth.fill_at.load(.monotonic) != 0) return error.MiniFifthQueued; - } - var streams: [n]lanes.Stream = undefined; - var made: usize = 0; - defer for (streams[0..made]) |*x| x.deinit(gpu.gpa); - for (cuts, 0..) |c, i| { - streams[i] = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-concurrent", .prompt = ids[c[0]..c[1]], .max_new = 10, .sampling = if (i % 2 == 0) null else sampled }); - made += 1; - } - var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); - defer cfg.deinit(gpu.gpa); - cfg.timed = false; - var clock: lanes.fake.FixedClock = .{}; - var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); - defer e.deinit(); - for (&streams) |*x| try e.addStream(x); - var live = true; - while (live) { - try e.step(); - live = false; - for (&streams) |*x| live = live or !x.finished; - } - for (&streams, solo) |*x, want| { - if (x.reason != .length) return error.MiniServingDidNotFinish; - if (!std.mem.eql(u32, x.emitted(), want.ids)) return error.MiniConcurrentChangedTokens; - } -} - -/// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. -const Copier = struct { - prompt_len: usize, - plain: []const u32, - out: [4]u32 = undefined, - calls: usize = 0, - rejected: bool = false, - partial: bool = false, - continued: bool = false, - full: bool = false, - was_rejected: bool = false, - - fn propose(ptr: *anyopaque, context: []const u32, most: i64) anyerror![]const u32 { - const c: *@This() = @ptrCast(@alignCast(ptr)); - const n = context.len - c.prompt_len; - if (n >= c.plain.len or most < 2) return &.{}; - if (c.was_rejected) c.continued = true; - const count = @min(c.out.len, @min(c.plain.len - n, @as(usize, @intCast(most)))); - for (c.out[0..count], 0..) |*token, i| token.* = c.plain[n + i]; - const mode = c.calls % 3; - c.was_rejected = false; - if (mode == 0 and count >= 2) { - c.full = true; - } else if (mode == 1 and count >= 2) { - c.out[0] = if (c.out[0] == 0) 1 else 0; - c.rejected = true; - c.was_rejected = true; - } else if (count >= 2) { - c.out[1] = if (c.out[1] == 0) 1 else 0; - c.partial = true; - } - c.calls += 1; - return c.out[0..count]; - } - - fn proposer(c: *Copier) lanes.proposer.Proposer { - return .{ .ptr = c, .vtable = &.{ - .propose = propose, - .last_match = struct { - fn f(_: *anyopaque) i64 { - return 1; - } - }.f, - .priced = true, - } }; - } -}; - -/// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. -fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { - const t = target(loaded); - const v = t.m.w.c.text.unpadded_vocab; - const next = accepted + 1; - const ref = try gpu.gpa.alloc(f32, v); - defer gpu.gpa.free(ref); - var serial = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-serial", .prompt = prompt, .max_new = 12, .sampling = sampling }); - defer serial.deinit(gpu.gpa); - const b = loaded.backend; - try b.prefill(&serial); - for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); - try download(t, t.m.s.logits, ref); - b.release(&serial); - - var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); - defer drafted.deinit(gpu.gpa); - defer b.release(&drafted); - try b.prefill(&drafted); - const pending = plain[0]; - var tokens: [4]u32 = undefined; - for (&tokens, 0..) |*token, i| token.* = plain[i + 1]; - if (accepted < tokens.len) tokens[accepted] = if (tokens[accepted] == 0) 1 else 0; - var positions: [5]u64 = undefined; - for (&positions, 0..) |*p, i| p.* = prompt.len + i + 1; - const window: lanes.backend.Window = .{ .stream = &drafted, .tokens = &tokens, .parents = null, .positions = &positions, .pending = pending, .held = 0 }; - var picks: [5]u32 = undefined; - var drafts: [4]u32 = undefined; - var out = [1]lanes.backend.Verified{.{ .sampled = &picks, .drafts = &drafts }}; - try b.verify(&.{window}, &out); - if (picks[accepted] != plain[next]) return error.MiniWrongCorrection; - var path: [5]u32 = undefined; - for (path[0..next], 0..) |*p, i| p.* = @intCast(i); - try b.keep(&.{window}, &.{path[0..next]}); - const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); - const after = try gpu.gpa.alloc(f32, v); - defer gpu.gpa.free(after); - try download(t, t.m.s.logits, after); - if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; - if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; -} - -fn copiedDrafts(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { - for ([_]?lanes.Sampling{ null, sampled }) |sampling| { - var plain = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); - defer plain.deinit(gpu.gpa); - var copier: Copier = .{ .prompt_len = prompt.len, .plain = plain.ids }; - var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-copied", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); - defer s.deinit(gpu.gpa); - try serve(gpu, loaded, &s, copier.proposer()); - if (!std.mem.eql(u32, s.emitted(), plain.ids)) return error.MiniCopiesChangedTarget; - if (s.drafted == 0 or s.accepted == 0 or s.accepted == s.drafted) return error.MiniCopyCoverageMissing; - if (!(copier.full and copier.rejected and copier.partial and copier.continued)) return error.MiniCopyCaseMissing; - for ([_]usize{ 0, 1, 4 }) |accepted| try rollback(gpu, loaded, prompt, sampling, plain.ids, accepted); - } + if (!native.fits(loaded.ctx, @intCast(a.len), third.max_new)) return error.MiniSlotNotReleased; } fn readIds(gpu: Gpu, path: []const u8) ![]u32 { @@ -380,7 +221,7 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { defer gpu.gpa.free(ids); if (ids.len < 4096) return error.MiniServingPromptTooShort; const context = ids.len + 64; - var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = false, .lanes = 2 }); defer loaded.deinit(loaded.ctx); try hostReference(gpu, &loaded, ids[0..4096]); check.pass("Mini CUDA serving matches the host reference token for token", .{}); @@ -389,9 +230,5 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { try crossPrompt(gpu, &loaded, ids); check.pass("Mini CUDA a state resumed after another prompt resumed its prefix equals the fresh prompt", .{}); try admission(gpu, &loaded, ids[0..257], ids[17..1042]); - check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens", .{}); - try concurrent(gpu, &loaded, ids); - check.pass("Mini CUDA four slots: concurrent greedy and seeded replies equal solo, a fifth is refused", .{}); - try copiedDrafts(gpu, &loaded, ids[0..64]); - check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); + check.pass("Mini CUDA two lanes decode together in shared rounds without changing tokens; a third waits", .{}); } diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 2ae14911b1d..79d335a4f36 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -265,6 +265,10 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "nvfp4")) return nvfp4_tests.run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "nvfp4-experts")) return nvfp4_experts_tests.experts(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "bf16-experts")) return if (rest.len == 0) @import("bf16_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_bf16.zig").run(gpu) else error.UnknownCommand; + if (std.mem.eql(u8, cmd, "stored-experts")) return storedExperts(gpu, rest); + if (std.mem.eql(u8, cmd, "inkling2-mini-xcheck")) return @import("inkling2_mini_xcheck.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); + if (std.mem.eql(u8, cmd, "inkling2-mini-ref")) return @import("inkling2_mini_tests.zig").reference(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "inkling2-mini")) return @import("inkling2_mini_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "projection-f32")) return projection_f32_tests.run(gpu); if (std.mem.eql(u8, cmd, "mxfp8")) return mxfp8_tests.run(gpu); if (std.mem.eql(u8, cmd, "quant-ref")) return quant_ref_tests.run(gpu); @@ -441,3 +445,12 @@ fn hasFlag(flags: []const [:0]const u8, name: []const u8) bool { for (flags) |f| if (std.mem.eql(u8, f, name)) return true; return false; } + +/// Inkling 2 Mini's stored experts: `contract`, `ckpt DIR` (layers 0 and 20) or `bench DIR`. +fn storedExperts(gpu: check.Gpu, rest: []const [:0]const u8) !void { + const what = try arg(rest, 0); + if (std.mem.eql(u8, what, "contract")) return @import("contract_stored_experts.zig").run(gpu); + if (std.mem.eql(u8, what, "ckpt")) return @import("stored_experts_tests.zig").ckpt(gpu, try arg(rest, 1)); + if (std.mem.eql(u8, what, "bench")) return @import("stored_experts_bench.zig").bench(gpu, try arg(rest, 1)); + return error.UnknownCommand; +} diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 3cc35e2b77d..ac8e809b065 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -99,6 +99,10 @@ pub const usage = \\ fp8-experts grouped block-FP8 experts against recorded fixture bytes \\ nvfp4-experts grouped NVFP4 experts against recorded fixture bytes \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red + \\ stored-experts contract | ckpt DIR | bench DIR Inkling 2 Mini's NVFP4 and MXFP8 experts: gates, checkpoint, speed + \\ inkling2-mini DIR N TEXT Inkling 2 Mini at one rank: N greedy tokens, resumed == fresh, concurrent == solo + \\ inkling2-mini-xcheck DIR N Inkling 2 Mini vs #4337's Metal: prompts A (raw ids) and B, top 2 a step, JSON + \\ inkling2-mini-ref DIR N TEXT Inkling 2 Mini's N greedy tokens against the float64 reference, teacher-forced \\ projection-f32 FP32 projection outputs against FP64, rounding and row/reduction invariance \\ mxfp8 MXFP8 strided projections against FP64 and row-count invariance \\ quant-ref FP8 and NVFP4 projections and experts against float64 references (synthetic) diff --git a/zig/tests/cuda/stored_experts_bench.zig b/zig/tests/cuda/stored_experts_bench.zig new file mode 100644 index 00000000000..3a2a263ce8b --- /dev/null +++ b/zig/tests/cuda/stored_experts_bench.zig @@ -0,0 +1,99 @@ +//! `stored-experts bench DIR`: one layer's grouped experts (gate-up and down) at 1, 4 and 512 tokens, bytes per time. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const st = @import("stored_experts_tests.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; + +const peak = 273.0; // GB10's unified memory, GB/s +const reps = 200; +const runs = 5; + +pub fn bench(gpu: Gpu, dir: []const u8) !void { + const a = gpu.gpa; + const path = try std.fmt.allocPrint(a, "{s}/model-00001-of-00001.safetensors", .{dir}); + defer a.free(path); + var f = try core.safetensors.File.openPrefix(a, gpu.io, path, "model.llm.layers."); + defer f.close(gpu.io); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + const gx: ex_.Grouped = .{ .nvfp4 = &k4, .mxfp8 = &k8 }; + for ([_]usize{ 0, 20 }) |layer| { + const s = try st.Stored.read(&f, layer); + var bufs: [4]cuda.DeviceBuffer = undefined; + const l = try s.upload(gpu, &bufs); + defer for (&bufs) |*b| b.free(); + const per_expert = bufs[0].len / st.experts + bufs[1].len / st.experts; + for ([_]usize{ 1, 4, 512 }) |tokens| { + const prompt = tokens >= 64; + const pairs = tokens * st.top; + const tile: usize = if (prompt) 64 else 16; + const xs = try a.alloc(u16, tokens * st.hidden); + defer a.free(xs); + var prng = std.Random.DefaultPrng.init(tokens); + for (xs) |*v| v.* = core.contract.spec.toBf16(prng.random().float(f32) * 2 - 1); + const ids = try st.picks(a, tokens, 0xbe4c + tokens); + defer a.free(ids); + var used: [st.experts]bool = @splat(false); + for (ids) |e| used[@intCast(e)] = true; + var touched: usize = 0; + for (used) |u| touched += @intFromBool(u); + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(xs)); + defer dx.free(); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, pairs, tile); + defer pb.deinit(); + var act = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.width * 2); + defer act.free(); + var y = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.hidden * 4); + defer y.free(); + const up_in: ex_.Rows = .{ .x = dx.ptr, .stride = st.hidden, .slots = st.top }; + const down_in: ex_.Rows = .{ .x = act.ptr, .stride = st.width }; + const Step = struct { + fn go(g: ex_.Grouped, sm: cuda.Stream, p: bool, ui: ex_.Rows, di: ex_.Rows, ly: ex_.Layer, pl: *const st.PlanBufs, o1: u64, o2: u64, n: usize, t: usize) !void { + if (p) { + try g.prompt(sm, .up, ui, ly, pl.plan, o1, pl.items, n, t, -1); + try g.prompt(sm, .down_bf16, di, ly, pl.plan, o2, pl.items, n, t, -1); + } else { + try g.decode(sm, .up, ui, ly, pl.plan, o1, pl.items, n, t, -1); + try g.decode(sm, .down_f32, di, ly, pl.plan, o2, pl.items, n, t, -1); + } + } + }; + try router.route(stream, dids.ptr, pairs, st.experts, tile, pb.plan); + for (0..10) |_| try Step.go(gx, stream, prompt, up_in, down_in, l, &pb, act.ptr, y.ptr, pairs, tile); + try stream.synchronize(); + var t0 = try cuda.Event.init(gpu.d, true); + defer t0.deinit(); + var t1 = try cuda.Event.init(gpu.d, true); + defer t1.deinit(); + var us: [runs]f64 = undefined; + for (&us) |*u| { + try t0.record(stream); + for (0..reps) |_| try Step.go(gx, stream, prompt, up_in, down_in, l, &pb, act.ptr, y.ptr, pairs, tile); + try t1.record(stream); + try t1.synchronize(); + u.* = @as(f64, try cuda.Event.elapsedMs(t0, t1)) * 1000 / reps; + } + const med = check.median(&us); + // the weights of every expert the tokens pick, read once; the rows in and out besides + const bytes = touched * per_expert + tokens * st.hidden * 2 + pairs * st.width * 4 + pairs * st.hidden * (if (prompt) @as(usize, 2) else 4); + const gbs = @as(f64, @floatFromInt(bytes)) / med / 1000; + std.debug.print("RESULT stored-experts layer {d} {s} tokens {d} ({s}): {d} experts, {d} bytes, {d:.2} us median of {d}x{d}, {d:.1} GB/s = {d:.0}% of {d:.0}\n", .{ layer, if (s.nv) "NVFP4" else "MXFP8", tokens, if (prompt) "prompt form" else "decode form", touched, bytes, med, runs, reps, gbs, 100 * gbs / peak, peak }); + } + } +} diff --git a/zig/tests/cuda/stored_experts_check.zig b/zig/tests/cuda/stored_experts_check.zig new file mode 100644 index 00000000000..e5c8c02b8bf --- /dev/null +++ b/zig/tests/cuda/stored_experts_check.zig @@ -0,0 +1,256 @@ +//! The stored experts' two checkpoint checks: one-hot rows read each decoded weight back, random rows the outputs. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const cs = @import("contract_stored_experts.zig"); +const st = @import("stored_experts_tests.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const c = core.contract.spec; + +const chunk = 16; // experts a pass of the one-hot check + +/// Every weight of both matrices of all 128 experts through the fp32 down kernel: x one-hot, so out = w (x factor). +pub fn decoded(gpu: Gpu, s: st.Stored, layer: usize) !void { + const a = gpu.gpa; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + for ([_]st.Matrix{ s.w13, s.w2 }, [_][]const u8{ "w13", "w2" }) |m, name| { + const n = m.n; + const k = m.k; + const words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, n, k, 1) else mx.Mxfp8Experts.bytes(1, n, k, 1)) / 4; + const packed_ = try a.alloc(u32, st.experts * words); + defer a.free(packed_); + for (0..st.experts) |e| { + const o = packed_[e * words ..][0..words]; + if (s.nv) ex_.Nvfp4Experts.packOne(o, m.expertCodes(e), m.expertScales(e), n, k) else mx.Mxfp8Experts.packOne(o, m.expertCodes(e), m.expertScales(e), n, k); + } + var w = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(packed_)); + defer w.free(); + var fs = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&m.factor)); + defer fs.free(); + // x: the k x k identity; pair i * chunk + j reads row i (slots = chunk) and expert base + j + const eye = try a.alloc(u16, k * k); + defer a.free(eye); + @memset(eye, 0); + for (0..k) |i| eye[i * k + i] = 0x3F80; + var x = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(eye)); + defer x.free(); + const pairs = k * chunk; + var pb = try st.PlanBufs.init(gpu, pairs, 16); + defer pb.deinit(); + const ids = try a.alloc(i32, pairs); + defer a.free(ids); + var dids = try cuda.DeviceBuffer.alloc(gpu.d, pairs * 4); + defer dids.free(); + var out = try cuda.DeviceBuffer.alloc(gpu.d, pairs * n * 4); + defer out.free(); + const got = try a.alloc(f32, pairs * n); + defer a.free(got); + var differ: usize = 0; + var zeros: usize = 0; + var base: usize = 0; + while (base < st.experts) : (base += chunk) { + for (ids, 0..) |*v, p| v.* = @intCast(base + p % chunk); + try dids.upload(0, std.mem.sliceAsBytes(ids)); + try router.route(stream, dids.ptr, pairs, st.experts, 16, pb.plan); + try out.fill8(0xff, stream.handle); + const in: ex_.Rows = .{ .x = x.ptr, .stride = k, .slots = chunk }; + const nb = n / 32; + if (s.nv) { + // the existing fp32 down (decode form) read with token rows: Nvfp4Experts.run passes slots only to up + var args: cuda.Args = .{}; + args.add(in.x); + for ([_]usize{ k, chunk }) |v| args.add(@as(i32, @intCast(v))); + args.add(w.ptr); + args.add(fs.ptr); + for ([_]usize{ k / 32, nb }) |v| args.add(@as(i32, @intCast(v))); + for ([_]u64{ pb.plan.items, pb.plan.counts, pb.plan.members, out.ptr }) |v| args.add(v); + args.add(@as(i32, @intCast(n))); + args.add(@as(f32, 0)); + args.add(@as(i32, -1)); + const grid = @min((pb.items * nb + k4.warps - 1) / k4.warps, k4.resident[1]); + try cuda.launch.launch(k4.fns[1], .{ .grid = .{ .x = @intCast(grid) }, .block = .{ .x = @intCast(k4.warps * 32) } }, stream, &args); + } else { + var args = mx.argsOf(in, true, w.ptr, null, k / 32, nb, pb.plan, out.ptr, n, .{ 0, 0 }, -1); + const grid = @min((pb.items * nb + 3) / 4, k8.resident[1]); + try cuda.launch.launch(k8.fns[1], .{ .grid = .{ .x = @intCast(grid) }, .block = .{ .x = 128 } }, stream, &args); + } + try stream.synchronize(); + try out.download(0, std.mem.sliceAsBytes(got)); + for (0..k) |i| for (0..chunk) |j| for (0..n) |row| { + const want = m.f32At(s.nv, base + j, row, i); + const v = got[(i * chunk + j) * n + row]; + if (v != want) differ += 1 else if (@as(u32, @bitCast(v)) != @as(u32, @bitCast(want))) zeros += 1; + }; + } + try check.expect(differ == 0, "layer {d} {s}: {d} of {d} decoded weights differ from the host decode", .{ layer, name, differ, st.experts * n * k }); + check.pass("layer {d} {s} ({s}): all {d} weights of 128 experts [{d}, {d}] equal the host decode ({d} zeros differ in sign only)", .{ layer, name, if (s.nv) "NVFP4" else "MXFP8", st.experts * n * k, n, k, zeros }); + } +} + +/// Gate-up then down on 4 tokens (decode form) and 64 (prompt form), each output within the contract's fp32 bound. +pub fn outputs(gpu: Gpu, s: st.Stored, layer: usize) !void { + const a = gpu.gpa; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + var bufs: [4]cuda.DeviceBuffer = undefined; + const l = try s.upload(gpu, &bufs); + defer for (&bufs) |*b| b.free(); + const gx: ex_.Grouped = .{ .nvfp4 = &k4, .mxfp8 = &k8 }; + for ([_]usize{ 4, 64 }) |tokens| { + const prompt = tokens > 4; + const pairs = tokens * st.top; + const tile: usize = if (prompt) 64 else 16; + var prng = std.Random.DefaultPrng.init(0x5eed + tokens + layer); + const xs = try a.alloc(u16, tokens * st.hidden); + defer a.free(xs); + for (xs) |*v| v.* = c.toBf16((prng.random().float(f32) * 2 - 1) * 2); + const ids = try st.picks(a, tokens, 0xc3 + tokens); + defer a.free(ids); + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(xs)); + defer dx.free(); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, pairs, tile); + defer pb.deinit(); + try router.route(stream, dids.ptr, pairs, st.experts, tile, pb.plan); + var act = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.width * 2); + defer act.free(); + const yw: usize = if (prompt) 2 else 4; + var y = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.hidden * yw); + defer y.free(); + try act.fill8(0xff, stream.handle); + try y.fill8(0xff, stream.handle); + const up_in: ex_.Rows = .{ .x = dx.ptr, .stride = st.hidden, .slots = st.top }; + const down_in: ex_.Rows = .{ .x = act.ptr, .stride = st.width }; + if (prompt) { + try gx.prompt(stream, .up, up_in, l, pb.plan, act.ptr, pb.items, pairs, tile, -1); + try gx.prompt(stream, .down_bf16, down_in, l, pb.plan, y.ptr, pb.items, pairs, tile, -1); + } else { + try gx.decode(stream, .up, up_in, l, pb.plan, act.ptr, pb.items, pairs, tile, -1); + try gx.decode(stream, .down_f32, down_in, l, pb.plan, y.ptr, pb.items, pairs, tile, -1); + } + try stream.synchronize(); + const ga = try a.alloc(u16, pairs * st.width); + defer a.free(ga); + try act.download(0, std.mem.sliceAsBytes(ga)); + const gy = try a.alloc(u8, pairs * st.hidden * yw); + defer a.free(gy); + try y.download(0, gy); + const fmt = if (s.nv) cs.Format.nvfp4 else cs.Format.mxfp8; + const up_spec = cs.spec(.{ .name = "up", .format = fmt, .kind = .up, .prompt = prompt }); + const down_spec = cs.spec(.{ .name = "down", .format = fmt, .kind = if (prompt) .down_bf16 else .down_f32, .prompt = prompt }); + var worst: [2]f64 = .{ 0, 0 }; + var bad: [2]usize = .{ 0, 0 }; + for (0..pairs) |p| { + const e: usize = @intCast(ids[p]); + const xr = xs[(p / st.top) * st.hidden ..][0..st.hidden]; + for (0..st.width) |j| { + var sum: [2]f64 = .{ 0, 0 }; + var abs: [2]f64 = .{ 0, 0 }; + for (0..2) |m| for (0..st.hidden) |i| { + const t = c.fromBf16(xr[i]) * s.w13.f64At(s.nv, e, 2 * j + m, i); + sum[m] += t; + abs[m] += @abs(t); + }; + const r = cs.softcap(sum[0], sum[1]); + const mag = @abs(r[1]) * abs[0] + @abs(r[2]) * abs[1]; + const err = @abs(@as(f64, c.fromBf16(ga[p * st.width + j])) - r[0]); + const b = c.bound(up_spec, .{ .rows = tokens, .n = st.width, .k = st.hidden }, r[0], mag); + worst[0] = @max(worst[0], err / b); + if (!(err <= b)) bad[0] += 1; + } + const ar = ga[p * st.width ..][0..st.width]; + for (0..st.hidden) |row| { + var sum: f64 = 0; + var abs: f64 = 0; + for (0..st.width) |i| { + const t = c.fromBf16(ar[i]) * s.w2.f64At(s.nv, e, row, i); + sum += t; + abs += @abs(t); + } + const o = p * st.hidden + row; + const v: f64 = if (prompt) c.fromBf16(std.mem.bytesToValue(u16, gy[o * 2 ..][0..2])) else std.mem.bytesToValue(f32, gy[o * 4 ..][0..4]); + const b = c.bound(down_spec, .{ .rows = tokens, .n = st.hidden, .k = st.width }, sum, abs); + worst[1] = @max(worst[1], @abs(v - sum) / b); + if (!(@abs(v - sum) <= b)) bad[1] += 1; + } + } + try check.expect(bad[0] == 0 and bad[1] == 0, "layer {d} {d} tokens: {d} gate-up and {d} down outputs outside the fp32 bound", .{ layer, tokens, bad[0], bad[1] }); + check.pass("layer {d} {s} {d} tokens ({s}): {d} gate-up and {d} down outputs within the fp32 bound; worst err/bound {d:.3} and {d:.3}", .{ layer, if (s.nv) "NVFP4" else "MXFP8", tokens, if (prompt) "prompt form" else "decode form", pairs * st.width, pairs * st.hidden, worst[0], worst[1] }); + } +} + +/// MXFP8's E8M0 edges through tf_mxfp8_down_f32: scale byte 0 is 2^-127 (not 0, not 2^-126). +pub fn e8m0Edges(gpu: Gpu) !void { + const a = gpu.gpa; + const n = 32; + const k = 32; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + const edges = [_]u8{ 0, 1, 2, 126, 127, 128, 200, 240 }; // 448 x 2^113 still fits fp32 + const values = [_]u8{ 0x38, 0x7E, 0x30, 0xB8 }; // 1, 448, 0.5, -1: each times 2^-127 stays a bf16 (>= 2^-133) + var codes: [n * k]u8 = undefined; + var scales: [n]u8 = undefined; + for (0..n) |r| { + scales[r] = edges[r % edges.len]; + for (0..k) |i| codes[r * k + i] = values[(r / edges.len + i) % values.len]; + } + var blocks: [mx.Mxfp8Experts.words]u32 = undefined; + mx.Mxfp8Experts.packOne(&blocks, &codes, &scales, n, k); + var w = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&blocks)); + defer w.free(); + var eye: [k * k]u16 = @splat(0); + for (0..k) |i| eye[i * k + i] = 0x3F80; + var x = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&eye)); + defer x.free(); + var ids: [k]i32 = @splat(0); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, k, 16); + defer pb.deinit(); + try router.route(stream, dids.ptr, k, st.experts, 16, pb.plan); + var out = try cuda.DeviceBuffer.alloc(gpu.d, k * n * 4); + defer out.free(); + try out.fill8(0xff, stream.handle); + const l: ex_.Layer = .{ .format = .mxfp8, .up = 0, .down = w.ptr, .width = k, .dims = n, .experts = st.experts, .caps = .{ 4, 25 } }; + const gx: ex_.Grouped = .{ .mxfp8 = &k8 }; + try gx.decode(stream, .down_f32, .{ .x = x.ptr, .stride = k }, l, pb.plan, out.ptr, pb.items, k, 16, -1); + try stream.synchronize(); + const got = try a.alloc(f32, k * n); + defer a.free(got); + try out.download(0, std.mem.sliceAsBytes(got)); + for (0..k) |i| for (0..n) |r| { + const want: f32 = @floatCast(core.expert_decode.mxfp8(&codes, &scales, k, r, i)); + try check.expect(got[i * n + r] == want, "E8M0 byte {d}, code {x}: {e}, host {e}", .{ scales[r], codes[r * k + i], got[i * n + r], want }); + }; + try check.expect(core.expert_decode.e8m0(0) == 0x1p-127, "host E8M0 byte 0", .{}); + check.pass("MXFP8 E8M0 bytes {any} decode exactly on the GPU (byte 0 = 2^-127)", .{edges}); +} diff --git a/zig/tests/cuda/stored_experts_tests.zig b/zig/tests/cuda/stored_experts_tests.zig new file mode 100644 index 00000000000..ffd3b283aa4 --- /dev/null +++ b/zig/tests/cuda/stored_experts_tests.zig @@ -0,0 +1,211 @@ +//! Inkling 2 Mini's stored experts from the checkpoint: decoded weights bit for bit, outputs within the fp32 bound. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const cs = @import("contract_stored_experts.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const dec = core.expert_decode; +const c = core.contract.spec; + +pub const hidden = 2304; +pub const width = 1152; +pub const experts = 128; +pub const top = 8; + +/// One stored matrix of all experts: codes, scales and (NVFP4) the per-expert factor. +pub const Matrix = struct { + codes: []const u8, + scales: []const u8, + factor: [experts]f32 = @splat(1), + n: usize, + k: usize, + + pub fn expertCodes(m: Matrix, e: usize) []const u8 { + const per = m.codes.len / experts; + return m.codes[e * per ..][0..per]; + } + + pub fn expertScales(m: Matrix, e: usize) []const u8 { + const per = m.scales.len / experts; + return m.scales[e * per ..][0..per]; + } + + /// Weight (row, i) of expert e as the kernels form it in fp32. + pub fn f32At(m: Matrix, nv: bool, e: usize, row: usize, i: usize) f32 { + if (nv) return dec.nvfp4F32(m.expertCodes(e), m.expertScales(e), m.k, row, i, m.factor[e]); + return @floatCast(dec.mxfp8(m.expertCodes(e), m.expertScales(e), m.k, row, i)); + } + + /// Weight (row, i) of expert e in float64 (the reference's). + pub fn f64At(m: Matrix, nv: bool, e: usize, row: usize, i: usize) f64 { + if (nv) return dec.nvfp4(m.expertCodes(e), m.expertScales(e), m.k, row, i, m.factor[e]); + return dec.mxfp8(m.expertCodes(e), m.expertScales(e), m.k, row, i); + } +}; + +/// A layer's w13 (gate rows then up rows) and w2 from the mapped checkpoint. +pub const Stored = struct { + nv: bool, + w13: Matrix, + w2: Matrix, + + pub fn read(f: *const core.safetensors.File, layer: usize) !Stored { + var name: [96]u8 = undefined; + const pre = "model.llm.layers.{d}.mlp.experts."; + const codes13 = f.get(try std.fmt.bufPrint(&name, pre ++ "w13_weight", .{layer})) orelse return error.MissingTensor; + const nv = codes13.dtype == .u8; + var s: Stored = .{ .nv = nv, .w13 = undefined, .w2 = undefined }; + inline for (.{ "w13", "w2" }, .{ &s.w13, &s.w2 }) |w, m| { + const t = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight", .{layer})) orelse return error.MissingTensor; + const sc = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_scale", .{layer})) orelse return error.MissingTensor; + const k = if (nv) t.dim(2) * 2 else t.dim(2); + m.* = .{ .codes = t.bytes, .scales = sc.bytes, .n = t.dim(1), .k = k }; + if (nv) { + const amax = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_amax", .{layer})) orelse return error.MissingTensor; + const den = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_outer_scale_denominator", .{layer})) orelse return error.MissingTensor; + const d = std.mem.bytesToValue(f32, den.bytes[0..4]); + try check.expect(d == 2688, "layer {d} {s}: outer scale denominator {d}, expected 2688", .{ layer, w, d }); + for (&m.factor, 0..) |*x, e| x.* = mx.nvfp4Factor(std.mem.bytesToValue(f32, amax.bytes[e * 4 ..][0..4]), d); + } + } + try check.expect(s.w13.n == 2 * width and s.w13.k == hidden and s.w2.n == hidden and s.w2.k == width, "layer {d}: expert shapes", .{layer}); + return s; + } + + /// The layer packed for the kernels: w13 as gate-up pairs, w2 alone, and NVFP4's factors per (expert, matrix). + pub fn upload(s: Stored, gpu: Gpu, bufs: *[4]cuda.DeviceBuffer) !ex_.Layer { + const a = gpu.gpa; + const up_words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, width, hidden, 2) else mx.Mxfp8Experts.bytes(1, width, hidden, 2)) / 4; + const down_words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, hidden, width, 1) else mx.Mxfp8Experts.bytes(1, hidden, width, 1)) / 4; + const up = try a.alloc(u32, experts * up_words); + defer a.free(up); + const down = try a.alloc(u32, experts * down_words); + defer a.free(down); + const cb = s.w13.expertCodes(0).len; // w13 rows interleave gate and up (row 2j gate j, 2j + 1 up j) + const sb = s.w13.expertScales(0).len; + const split = try a.alloc(u8, cb + sb); + defer a.free(split); + for (0..experts) |e| { + const rc = cb / (2 * width); + const rs = sb / (2 * width); + mx.splitGateUp(s.w13.expertCodes(e), rc, split[0 .. cb / 2], split[cb / 2 .. cb]); + mx.splitGateUp(s.w13.expertScales(e), rs, split[cb..][0 .. sb / 2], split[cb + sb / 2 ..][0 .. sb / 2]); + const gate = [2][]const u8{ split[0 .. cb / 2], split[cb..][0 .. sb / 2] }; + const upm = [2][]const u8{ split[cb / 2 .. cb], split[cb + sb / 2 ..][0 .. sb / 2] }; + const o = up[e * up_words ..][0..up_words]; + const d = down[e * down_words ..][0..down_words]; + if (s.nv) { + ex_.Nvfp4Experts.packGateUp(o, gate, upm, width, hidden); + ex_.Nvfp4Experts.packOne(d, s.w2.expertCodes(e), s.w2.expertScales(e), hidden, width); + } else { + mx.Mxfp8Experts.packGateUp(o, gate, upm, width, hidden); + mx.Mxfp8Experts.packOne(d, s.w2.expertCodes(e), s.w2.expertScales(e), hidden, width); + } + } + var f13: [experts * 2]f32 = undefined; + for (0..experts) |e| f13[2 * e] = s.w13.factor[e]; + for (0..experts) |e| f13[2 * e + 1] = s.w13.factor[e]; // one amax covers the gate and the up rows + bufs[0] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(up)); + bufs[1] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(down)); + bufs[2] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&f13)); + bufs[3] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&s.w2.factor)); + return .{ .format = if (s.nv) .nvfp4 else .mxfp8, .up = bufs[0].ptr, .down = bufs[1].ptr, .up_scale = bufs[2].ptr, .down_scale = bufs[3].ptr, .width = width, .dims = hidden, .experts = experts, .caps = cs.caps }; + } +}; + +/// Plan scratch for `pairs` picks over 128 experts in items of `tile`. +pub const PlanBufs = struct { + bufs: [5]cuda.DeviceBuffer, + plan: grouped.Plan, + items: usize, + + pub fn init(gpu: Gpu, pairs: usize, tile: usize) !PlanBufs { + var p: PlanBufs = undefined; + p.items = grouped.maxItems(pairs, experts, tile); + const sizes = [5]usize{ pairs * 4, p.items * 12, 8, pairs * 4, ((pairs + 1023) / 1024) * experts * 4 }; + var made: usize = 0; + errdefer for (p.bufs[0..made]) |*b| b.free(); + for (sizes, &p.bufs) |n, *b| { + b.* = try cuda.DeviceBuffer.alloc(gpu.d, n); + made += 1; + } + p.plan = .{ .members = p.bufs[0].ptr, .items = p.bufs[1].ptr, .counts = p.bufs[2].ptr, .rank = p.bufs[3].ptr, .hist = p.bufs[4].ptr }; + return p; + } + + pub fn deinit(p: *PlanBufs) void { + for (&p.bufs) |*b| b.free(); + } +}; + +/// `tokens` rows' top-8 distinct experts, seeded. +pub fn picks(a: std.mem.Allocator, tokens: usize, seed: u64) ![]i32 { + var prng = std.Random.DefaultPrng.init(seed); + const out = try a.alloc(i32, tokens * top); + for (0..tokens) |t| { + var perm: [experts]i32 = undefined; + for (&perm, 0..) |*v, i| v.* = @intCast(i); + prng.random().shuffle(i32, &perm); + @memcpy(out[t * top ..][0..top], perm[0..top]); + } + return out; +} + +/// `ckpt DIR`: layers 0 (NVFP4) and 20 (MXFP8) of the checkpoint in DIR. +pub fn ckpt(gpu: Gpu, dir: []const u8) !void { + const path = try std.fmt.allocPrint(gpu.gpa, "{s}/model-00001-of-00001.safetensors", .{dir}); + defer gpu.gpa.free(path); + var f = try core.safetensors.File.openPrefix(gpu.gpa, gpu.io, path, "model.llm.layers."); + defer f.close(gpu.io); + try @import("stored_experts_check.zig").e8m0Edges(gpu); + for ([_]usize{ 0, 20 }) |layer| { + const s = try Stored.read(&f, layer); + try invariants(s, layer); + try @import("stored_experts_check.zig").decoded(gpu, s, layer); + try @import("stored_experts_check.zig").outputs(gpu, s, layer); + } +} + +/// The stored data as the scale analysis found it: NVFP4's code x block scale peaks at exactly 6 x 448 in every +/// expert (so amax / 2688 is the factor), MXFP8 holds no NaN code and peaks at 448. +fn invariants(s: Stored, layer: usize) !void { + for ([_]Matrix{ s.w13, s.w2 }, 0..) |m, mi| { + var peaks: usize = 0; + for (0..experts) |e| { + var most: f64 = 0; + const codes = m.expertCodes(e); + const scales = m.expertScales(e); + if (s.nv) { + for (0..m.n) |row| for (0..m.k / 16) |b| { + const sv = dec.e4m3(scales[row * (m.k / 16) + b]); + for (0..16) |q| most = @max(most, @abs(dec.e2m1(dec.nibble(codes[row * (m.k / 2) ..][0 .. m.k / 2], b * 16 + q)) * sv)); + }; + try check.expect(most == 2688, "layer {d} matrix {d} expert {d}: peak code x scale {d}, expected 2688", .{ layer, mi, e, most }); + } else { + for (codes) |b| { + try check.expect(b & 0x7F != 0x7F, "layer {d} matrix {d} expert {d}: a NaN code", .{ layer, mi, e }); + most = @max(most, @abs(dec.e4m3(b))); + } + for (scales) |b| try check.expect(b != 255, "layer {d} matrix {d} expert {d}: a NaN scale", .{ layer, mi, e }); + if (most == 448) peaks += 1; + } + } + if (s.nv) check.pass("layer {d} NVFP4 matrix {d}: every expert's code x block scale peaks at 2688 = 6 x 448", .{ layer, mi }); + if (!s.nv) check.pass("layer {d} MXFP8 matrix {d}: no NaN code or scale; {d} of 128 experts peak at 448", .{ layer, mi, peaks }); + } +} + +test "picks are eight distinct experts a token" { + const p = try picks(std.testing.allocator, 3, 7); + defer std.testing.allocator.free(p); + for (0..3) |t| for (0..top) |i| for (0..i) |j| try std.testing.expect(p[t * top + i] != p[t * top + j]); +} + +comptime { + _ = c; +} diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 94054526225..e31a3a0d44c 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -6,7 +6,7 @@ zig/kernels/cuda/embed_rows.cu c3cad38db6576728a15e048a45f2c1a571233fc3fedc83d04 zig/kernels/cuda/exlr8.cu 0eb19c8965aeb8188efd2b15a5844da860d9bf75364b12b62dd3a2589a89178c raw zig/kernels/cuda/exlr8_dense.cu 7616e7a3bb35a2bb64b53a1ca84ce8be98442a36394dad945b844219f72ec671 raw zig/kernels/cuda/experts.cu 2a9b3989f3baaef5eadb56abfb8520700449bd910f2b00345703c22dbf758b8c raw -zig/kernels/cuda/experts.cuh 017728fef063d45f06240a88002f80ec931f967edc5fa44c31b10673d43872f9 raw +zig/kernels/cuda/experts.cuh 1cc91e62a72beef4a11c538bbf411dfd8f037c1310c4de4f6721e542504dc660 raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged; #4441 C4d: experts' round_caps A/B switch zig/kernels/cuda/experts_pack.cu 578e9a607f678f0547aaeb312d18252ea0608bad7fe71bb2d5241d28adf31bac raw zig/kernels/cuda/experts_prefill.cu 5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc raw zig/kernels/cuda/experts_rows.cu 714b76ad72ff45715c5ebf6b57365f0f41789ad301871f07168a016412df13a7 raw @@ -15,7 +15,7 @@ zig/kernels/cuda/flashnext_batch.cu 95260b964fb633d23df28970672d87688f21cdd9073e zig/kernels/cuda/flashnext_gdn.cu c7b9712626778d452e18234e2dfc3b26f8112618cdc492957c4b5f5454d64126 raw zig/kernels/cuda/flashnext_hc.cu 54fa2cfa22e483341835f6349cf0a8f508459ed1b65804728cb1358ac82b24f1 raw main 5c7cf5c117, d88c1ed57d (sum_rn and rms_scale shared; same SASS) zig/kernels/cuda/flashnext_mtp.cu a9c21f52cd00d9aa05e9cf1dae5b0168e5e48f87cb3a4a226221b89037acd6d9 raw #2927, the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits -zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw +zig/kernels/cuda/fp8_experts.cu b0a4a962aec818b9129b1a3a6f7082ae4b917a47c92ef47d32947a267fdab26c raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged zig/kernels/cuda/gdn.cu e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228 raw zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) zig/kernels/cuda/glm_glue_attn.cuh 2a0bc3c4966555fad4ae812e62b28558f41774fd5b2dbef6fa9b6d220ba260d8 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) @@ -44,7 +44,7 @@ zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4a zig/kernels/cuda/nemotron_ops.cu c95b1df56910c879538e471c8b7e53355923802f53ab8e9e7daf99f3502ceec6 raw #3124; TF_NEMOTRON_WIDE_ROUNDS (tf_plan_routed stages 32 rows; gather, last-row and scatter copies take 16 parts; 16 rows or 8 parts unchanged) zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe3c3557a48bca96f6511 raw commits 739c924de, 8cfdaa739, b77a33b08, 7f6f940eb, 05d0617af, bc76d90d6; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) -zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) +zig/kernels/cuda/nvfp4_experts.cu a794605ef37981a32ac09436b2958a9425652db4c28f804a4a7548f483176969 raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items); Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw zig/kernels/cuda/prefill_attention.cu 4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) @@ -89,11 +89,11 @@ zig/src/cuda/cublaslt.zig d87f865fc03cf94bdcbe83504f74a6e569d70c10ca792b675122e9 zig/src/cuda/driver.zig f20856bd06afe9365ab9ca1bc39800ccb260ade2704197c033e1344a0c8dd742 raw commits e9bf05ffd, b923e554c, b2c75a98a; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/embed_rows.zig 3fa5e28ab46b4daef2c820b3ad3f7d331bc77f55ea340a7a3cac64b21584c5f4 raw #3471: Gemma 4 holds its tied embedding once; token rows read the head's 4-bit tiles; replies unchanged zig/src/cuda/exlr8.zig 1e2164096ae949a8a9a4903df82c7c0c184a6f5e1ba5ba4423038a42b0633fc6 raw -zig/src/cuda/experts.zig 0ada89c63783a53d138cdf33b3f3e2f961535e91448c82eeb5ca99af12f8b960 raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged); #4493 (opt-in paired prompt experts, 128-row items) +zig/src/cuda/experts.zig cfbfc51c010e7fd056d2a8393bcfea6b0b119b4b6ea2051334430594b63dc7a7 raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged); #4493 (opt-in paired prompt experts, 128-row items); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged; #4441 C4d: experts' round_caps A/B switch zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 43a403bbac618bafc5417a38f35712d14cc9de7bf7a4d45fd1a2d24d0b8eb801 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered +zig/src/cuda/kernels.zig e5891dd15a920853d7a3efe74667b73e5c764985 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #4441 C4d: inkling2_loop image registered; the inkling2_loop_math image removed with #4387's loop stack (Mini serves on #4441's) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw @@ -105,7 +105,7 @@ zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7 zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig 08acd959abfd7336cded19c67d044590c3497066e6f36381d03ea31b9a733f1a raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0; #4533 optional FP4/FP8/FP8G half tiles, default off zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig d4f3c80440208cae60fb2336ac2b2e4837dc7035e34eb3ca6d189765c5422e62 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half +zig/src/cuda/root.zig 38468bfce1cf45c5977dd79bca90b643b2c8f73a raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged; #4533 exports qmmf_half zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw