diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a83ffa8a1e65bb2fb839aae41eaa51717a567d90..70b27d4b2f3e84a28e2bafd5c63305c1c765ee4e 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -376,3 +376,5 @@ Update this table in the same commit as the work it credits. | Codex (under Drake Stapleton's direction) | Rewrote lexical scope destruction in Omega, including nested borrow closure, conditional owner release, arena escape and pool teardown. | | Codex (under Drake Stapleton's direction) | Converted OSC handle provenance, stale read/write/free decisions, branch snapshots and loop settlement to seeded Omega. | | Codex (under Drake Stapleton's direction) | Converted OSC owner and borrow snapshots, rollback of fresh borrows, branch joins and move replay to seeded Omega. | +| Codex (under Drake Stapleton's direction) | Implemented seeded Omega SM121 kernels and decode tables for the DeepSeek-V4.1-Flash text backbone, added driver-loadable cubin metadata and single-Spark numerical checks. | +| Codex (under Drake Stapleton's direction) | Built the resident pure-Omega DeepSeek-V4.1-Flash final-head executor, native QMD submission chain, packed-BF16 vocabulary projection, and full-vocabulary checkpoint comparison. | diff --git a/FOLDERS.md b/FOLDERS.md index d7c28d8721ad6a4fafccfff89b35df248e1af268..3cc8301b1c164e195761eef3bf8b939198de6cce 100644 --- a/FOLDERS.md +++ b/FOLDERS.md @@ -551,3 +551,8 @@ Trinary Doctrine wake-signal tool (`trit`, T-002) in seeded OM-2 sharing `tools/ ## `seed/omc/tests/struct-bool/` Boolean struct-field execution regressions, exact expected outcomes, scalar controls and deliberate broken-compiler controls. Run by the seeded host gate. Results are kept in unique build directories. +Boolean struct-field execution regressions, exact expected outcomes, scalar controls and deliberate broken-compiler controls. Run by the seeded host gate. Results are kept in unique build directories. + +## `om/gpu/dsv41/` + +Seeded Omega SM121 kernel emitters, their byte-level ABI, the native final-head executor, and single-Spark numerical checks for the original DeepSeek-V4.1-Flash text checkpoint. diff --git a/om/gpu/dsv41/README.md b/om/gpu/dsv41/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e2bb860b6b45fcae830b999c516c0faf39814e6d --- /dev/null +++ b/om/gpu/dsv41/README.md @@ -0,0 +1,85 @@ +# DeepSeek-V4.1-Flash text decode kernels for GB10 + +These SM121 cubins implement operator baselines for the original DeepSeek-V4.1-Flash text backbone. The architecture, formats and tensor dimensions come from revision `314113f8a7dadb388215396ba5fbee2c610a04d6`. The model uses 40 layers, a hidden width of 5120, six routed experts per token, and a learned attention sink per head. [Published inference implementation](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/tree/314113f8a7dadb388215396ba5fbee2c610a04d6/inference) + +The seeded compiler builds `emit.om` with the repository's SM121 encoder. The resulting program writes SASS instructions directly. The seeded Omega packer constructs each ELF image, including the linked toolkit note needed by the Spark driver. `lookup.om` generates the shared 272-entry floating-point decode table. Shell orchestrates the build. The independent numerical test runs through Python, NumPy and the installed CUDA Driver API. + +## Build and run + +From the repo root on AArch64 Linux, grow the compiler and build the images. + +```sh +sh seed/omega-from-seed.sh +sh om/gpu/dsv41/build.sh build/dsv41 +``` + +Inside an authorized Spark window, compare the compiled images against the numerical references. + +```sh +spark-window run python3 om/gpu/dsv41/check.py build/dsv41 +``` + +The checks include the individual operators and a synthetic routed expert at checkpoint widths. The expert check quantizes a 5120-component activation, executes two packed FP4 projections to 2304 components, evaluates weighted SwiGLU, requantizes and projects back to 5120. Full-checkpoint logits, sustained serving throughput, multimodal inference, speculative decoding, and multi-Spark integration require separate qualification. + +## Launch contract + +Each image exports one symbol with the same name as its file stem. `kernels.list` gives parameter order and sizes. Pointers refer to contiguous row-major device data. A scalar occupies four bytes. Dimensions and indices are unsigned or signed 32-bit integers as indicated. The rotary sign is a float32 scalar. Grid dimensions omitted from the right are one. The block has shape `(threads,1,1)`. + +In the table, B counts token rows, H local heads, T cache positions, S selected positions, D vector width, M activation rows, N output rows and K projection width. `tiles(n)` is ceiling division by 128. All dimensions and K for selection are positive. The packer assigns 64 registers per thread and zero shared bytes. Inputs are finite except for index-selection masking and pinned candidate blocks. Four-byte packed loads require the last allocation word to be readable. Flattened element/word indices must fit in 32 bits. The Engram and vocabulary gathers form their shard-row addresses in 64 bits. + +| Kernel | Arguments in launch order | Grid · threads | +|---|---|---| +| hc_pre | residual[B,4,5120], pre[B,4], out[B,5120] | (40,B) · 128 | +| hc_post | sublayer[B,5120], residual, post[B,4], comb[B,4,4], out[B,4,5120] | (40,B) · 128 | +| hc_sinkhorn | raw[B,24], scales[3], bias[24], pre[B,4], post[B,4], comb[B,4,4] | (B) · 1 | +| expert_act | gate[B,2304], up[B,2304], selected weight[B], out[B,2304] | (18,B) · 128 | +| fp8_gemm, fp4_gemm | packed A[M,K], packed W[N,K], scales A, scales W, decode table, out[M,N], K, N | (tiles(N),M) · 128 | +| sparse_scores | query[B,H,512], KV[B,T,512], indices[B,S], scores[B,H,S], H,T,S | (S,H,B) · 1 | +| sparse_mix | scores[B,H,S], KV[B,T,512], indices[B,S], sink[H], out[B,H,512], H,T,S | (4,H,B) · 128 | +| quant_fp8, quant_fp4, quant_kv | input, decode table, packed output, byte scales, reconstructed output | (total groups) · half the group width | +| dense | activation[M,K], weights[N,K], out[M,N], K,N | (tiles(N),M) · 128 | +| rms_stat | input[B,D], reciprocal RMS[B], D | (B) · 1 | +| rms_apply | input[B,D], gain[D], reciprocal RMS[B], out[B,D], D | (tiles(D),B) · 128 | +| rotary_tail | in/out[B,H,D], interleaved cos/sin[B,32,2], D (at least 64),H,sign | (H,B) · 32 | +| compress_pair | KV[B,2,512], score[B,2,512], out[B,512] | (4,B) · 128 | +| route6 | logits[B,384], selection bias[384], expert IDs[B,6], weights[B,6] | (B) · 1 | +| engram_rows | absolute IDs[B], shard FP8 rows[R,256], shard byte scales[R,8], decode table, out[B,256], start ID,R | (B) · 256 | +| bf16_pack, bf16_unpack | source, destination, element count | (tiles(count)) · 128 | +| index_scores | query[B,H,128], key[B,T,128], prescaled BF16-rounded head weights stored as FP32[B,H], uint32 lengths[B], int32 keep mask[B,ceil(T/8)], out[B,T], H,T | (tiles(T),B) · 128 | +| candidate_blocks | index scores[B,T], reachable lengths[B], out[B,ceil(T/8)], T | (ceil(T/8),B) · 1 | +| top_positions | scores[B,T], indices[B,K], keep mask[B,T], T,K,index offset | (B) · 1 | +| engram_gate | residual[B,4,5120], keys[B,4,5120], product of query and key weights[4,5120], int32 token mask[B], gates[B,4] | (4,B) · 1 | +| engram_add | residual[B,4,5120], value[B,5120], gates[B,4], out[B,4,5120] | (40,4,B) · 128 | +| token_embed | token IDs[B], shard BF16 table[R,5120], out[B,4,5120], start ID,R | (40,B) · 128 | +| moe_sum | six down-projections[B,6,5120], shared output[B,5120], out[B,5120] | (40,B) · 128 | +| window_step | new KV[B,512], position per row[B], in/out cache[B,128,512], indices[B,128] | (4,B) · 128 | + +**Precision and layout.** Unqualified floating-point buffers in the table use FP32 storage. Supply BF16 activations widened to FP32 where the checkpoint expects BF16, and round at each checkpoint dtype boundary. The pack and unpack kernels perform those conversions. FP4 uses low nibble first, E2M1. Both GEMMs consume E4M3 activations and require K divisible by 32. Activation scale shape is [M,K/32]. FP4 weight scales are [N,K/32], and FP8 weight scales are [ceil(N/32),K/32]. Both use E8M0 bytes. Supply `decode.f32le` as 272 contiguous device float32 values. The quantizers produce both packed values and widened BF16 reconstructions. FP8 and FP4 indexer groups have width 32 and a power-of-two scale. Compressed KV groups have width 16 and an E4M3 scale. Compressed-KV tests include the minimum scale, ordinary groups, halfway cases and the largest finite E4M3 scale (448). The Engram gather test exercises a seven-row local shard with a large global starting ID. + +**Attention and routing.** Pass one query per batch row to the sparse pair. Supply identical indices to both stages. Each index is a cache position or -1. The mixer follows the reference's 64-position online softmax and rounds each numerator weight to BF16. Apply the residual gates in the upstream layer order. Send the previous sublayer's pre coefficients to hc_pre. The router ranks biased scores, takes weights from the unbiased scores, normalizes them and applies the checkpoint's factor of 1.5. It resolves ties by lower expert ID. top_positions returns ascending positions, fills unreachable entries with -1, and gives a 32-bit keep mask. It also resolves score ties by lower index. Supply K at most T and an offset that fits signed int32. For two-level selection, run candidate_blocks, top_positions on the block scores, index_scores with the resulting mask, then top_positions on the filtered scores. + +**Integration.** The collection operates on caller-owned buffers. A model executor must load and shard weights and Engram tables, construct hash IDs and rotary frequencies, schedule the 40 layers and BF16 boundaries, maintain cache state, and perform rank collectives. The CUDA Driver API is used for this hardware check. The final-head executor below uses the native Omega submission path. + +## Native final-head executor + +The build also produces `dsv41-head`, a seeded AArch64 Linux executable for the original checkpoint's final text head. It opens the installed NVIDIA kernel devices directly, creates an RM/UVM context, and submits Omega-emitted SM121 instructions through QMDs. It loads `head.weight` and `norm.weight` from shard 43 once and keeps them resident across input frames. The head matrix occupies 1,323,827,200 bytes in BF16. The binary consumes the final decoder layer's residual streams and pre-mix coefficients. + +For a reproducible researcher run, obtain the head shard from the pinned release and create four input frames. The fixture command fetches 80 KiB of embedding rows 1234 through 1241 and verifies their SHA-256 before writing a new file. Two frames use those rows. A third exercises FP32 product cancellation at the BF16 pre-mix boundary. The fourth covers FP32 overflow when squaring a finite BF16 residual during normalization. + +```sh +curl -fL 'https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/resolve/314113f8a7dadb388215396ba5fbee2c610a04d6/model-00043-of-00048.safetensors' -o model-00043-of-00048.safetensors +python3 om/gpu/dsv41/check-head.py --fixture frames.bin +``` + +From the repository root, in a single-Spark correctness window: + +```sh +spark-window run env --ignore-signal=PIPE build/dsv41/dsv41-head model-00043-of-00048.safetensors < frames.bin > logits.f32 +python3 om/gpu/dsv41/check-head.py model-00043-of-00048.safetensors frames.bin logits.f32 +``` + +A frame is 40,976 bytes. First write four row-major 5120-element residual streams as little-endian BF16, then four little-endian FP32 mixing coefficients. Each complete frame produces 129,280 little-endian FP32 logits in token-ID order (517,120 bytes). EOF between frames ends the session. After emitting one million frames the process closes its resources and exits 75. The caller may open a new session for subsequent frames. A partial frame exits 65. Exit 74 reports a native resource, submission, completion, or IO error. The example inherits an ignored SIGPIPE so a closed output pipe returns 74 through explicit device cleanup. Direct invocation with the default POSIX signal disposition terminates on SIGPIPE when a reader disconnects. Keep the checkpoint immutable for the lifetime of the process. + +Every frame goes through BF16 widening, the four-stream pre-mix, BF16 rounding, RMS normalization, weighted scaling, a second BF16 rounding, and the packed vocabulary projection. The projection uses one warp per vocabulary row and accumulates in FP32. The earlier 40 decoder layers supply the frame in a complete inference graph. The check accepts independent test frames and compares every vocabulary row with a CPU calculation using the released weights. + +The original head shard is 1,323,837,624 bytes with SHA-256 `d762b688f138e00a24eac96f27b842715bb4b534ecc9ca39076bed2b8c33201e`. The loader validates the two tensor descriptors, dtype, shapes, payload coverage and non-overlap before opening a device. The numerical check additionally verifies the published file checksum. [Pinned checkpoint shard](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/314113f8a7dadb388215396ba5fbee2c610a04d6/model-00043-of-00048.safetensors) diff --git a/om/gpu/dsv41/build.sh b/om/gpu/dsv41/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a24fa8d7cbbfde8a7f79b60d6e0a3c2aa794080 --- /dev/null +++ b/om/gpu/dsv41/build.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# Run from the repository root after growing seed/out/omc. +set -eu +out=${1:?usage: sh om/gpu/dsv41/build.sh OUTPUT_DIR} +mkdir -p "$out" +tmp=$(mktemp -d "$out/build.XXXXXX") +trap 'rm -rf "$tmp"' EXIT +( echo om2; cat om/encoder/bw_enc_sm121.om om/gpu/dsv41/emit.om om/gpu/dsv41/emit-cli.om ) > "$tmp/input.om" +seed/out/omc < "$tmp/input.om" > "$tmp/emit" +seed/out/omc < seed/kflow/kpack.om > "$tmp/kpack" +seed/out/omc < om/gpu/dsv41/lookup.om > "$tmp/lookup" +chmod +x "$tmp/emit" "$tmp/kpack" "$tmp/lookup" +"$tmp/lookup" > "$tmp/decode.f32le" +while read -r mode name abi; do + "$tmp/emit" "$mode" > "$tmp/$name.bin" + "$tmp/kpack" 121-tk "$name" "$tmp/$name.bin" "$tmp/$name.cubin" 64 0 $abi +done < om/gpu/dsv41/kernels.list +( echo om2 + cat seed/json/json.om gpu/nvidia/native/nvrm/context.om \ + gpu/nvidia/native/blackwell/vector.om gpu/nvidia/native/blackwell/launch.om \ + gpu/nvidia/native/blackwell/batch.om om/encoder/bw_enc_sm121.om \ + om/gpu/dsv41/emit.om om/gpu/dsv41/head/weights.om om/gpu/dsv41/head/launch.om om/gpu/dsv41/head/session.om +) > "$tmp/head.om" +seed/out/omc < "$tmp/head.om" > "$tmp/dsv41-head" +chmod +x "$tmp/dsv41-head" +mv "$tmp/dsv41-head" "$out" +mv "$tmp"/*.cubin "$tmp/decode.f32le" "$out" diff --git a/om/gpu/dsv41/check-head.py b/om/gpu/dsv41/check-head.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a1a6c0f8fab116ad1c04f955774054a4a94b04 --- /dev/null +++ b/om/gpu/dsv41/check-head.py @@ -0,0 +1,101 @@ +"""Compare every vocabulary logit against an independent CPU head using the pinned BF16 shard.""" +import hashlib +import json +import struct +import sys +from urllib.request import Request, urlopen +from pathlib import Path + +import numpy as np + + +def widened(words): + return (words.astype(np.uint32) << 16).view(np.float32) + + +def rounded(x): + bits = np.ascontiguousarray(x, dtype="> 16) & 1)) & 0xffff0000).view(np.float32) + + +def load_tensors(path): + expected = "d762b688f138e00a24eac96f27b842715bb4b534ecc9ca39076bed2b8c33201e" + with path.open("rb") as f: + if hashlib.file_digest(f, "sha256").hexdigest() != expected: + raise ValueError("checkpoint shard SHA-256 mismatch") + f.seek(0) + n, = struct.unpack("