From e5c2b4ceaa22a29adc52b746f78be79fd11d616a Mon Sep 17 00:00:00 2001 From: Drake Stapleton <213298340+drakestapleton@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:24:01 -0600 Subject: [PATCH 1/2] Build DeepSeek V4.1 Flash text kernels in seeded Omega --- CONTRIBUTORS.md | 1 + FOLDERS.md | 5 + om/gpu/dsv41/README.md | 61 ++ om/gpu/dsv41/build.sh | 18 + om/gpu/dsv41/check.py | 331 ++++++++++ om/gpu/dsv41/emit.om | 1298 +++++++++++++++++++++++++++++++++++++ om/gpu/dsv41/kernels.list | 28 + om/gpu/dsv41/lookup.om | 40 ++ seed/kflow/kpack.om | 77 ++- 9 files changed, 1852 insertions(+), 7 deletions(-) create mode 100644 om/gpu/dsv41/README.md create mode 100644 om/gpu/dsv41/build.sh create mode 100644 om/gpu/dsv41/check.py create mode 100644 om/gpu/dsv41/emit.om create mode 100644 om/gpu/dsv41/kernels.list create mode 100644 om/gpu/dsv41/lookup.om diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a83ffa8a1..e23e1fab6 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -376,3 +376,4 @@ 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. | diff --git a/FOLDERS.md b/FOLDERS.md index d7c28d872..597c4ec8a 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 and single-Spark operator 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 000000000..76c1615dd --- /dev/null +++ b/om/gpu/dsv41/README.md @@ -0,0 +1,61 @@ +# 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,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 head weights[B,H], lengths[B], 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], 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 scale checks cover the finite representable range. + +**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. Use of the native Omega submission path by a serving executor remains to be exercised. diff --git a/om/gpu/dsv41/build.sh b/om/gpu/dsv41/build.sh new file mode 100644 index 000000000..073e0213b --- /dev/null +++ b/om/gpu/dsv41/build.sh @@ -0,0 +1,18 @@ +#!/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 ) > "$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 +mv "$tmp"/*.cubin "$tmp/decode.f32le" "$out" diff --git a/om/gpu/dsv41/check.py b/om/gpu/dsv41/check.py new file mode 100644 index 000000000..282ef1a95 --- /dev/null +++ b/om/gpu/dsv41/check.py @@ -0,0 +1,331 @@ +"""GB10 component parity check. Run with spark-window run python3 check.py CUBIN_DIR.""" +import ctypes as ct +import os +import sys +from pathlib import Path + +import numpy as np + + +class Device: + def __init__(self, directory): + self.directory = Path(directory) + self.lib = ct.CDLL("libcuda.so.1") + self.ctx = ct.c_void_p() + self.call("cuInit", 0) + dev = ct.c_int() + self.call("cuDeviceGet", ct.byref(dev), 0) + self.call("cuCtxCreate_v2", ct.byref(self.ctx), 0, dev) + + def call(self, name, *args): + ret = getattr(self.lib, name)(*args) + if ret: + error = ct.c_char_p() + self.lib.cuGetErrorName(ret, ct.byref(error)) + raise RuntimeError(f"{name}: {error.value} ({ret})") + + def run(self, name, grid, block, tensors, output_count, scalars=()): + module, fn = ct.c_void_p(), ct.c_void_p() + args, arrays = [], [] + self.call("cuModuleLoad", ct.byref(module), os.fsencode(self.directory / (name + ".cubin"))) + try: + self.call("cuModuleGetFunction", ct.byref(fn), module, name.encode()) + for array in tensors: + array = np.ascontiguousarray(array) + ptr = ct.c_uint64() + self.call("cuMemAlloc_v2", ct.byref(ptr), ct.c_size_t((array.nbytes + 3) & ~3)) + args.append(ptr) + arrays.append(array) + self.call("cuMemcpyHtoD_v2", ptr, ct.c_void_p(array.ctypes.data), ct.c_size_t(array.nbytes)) + params = args + [ct.c_uint32(i) for i in scalars] + argv = (ct.c_void_p * len(params))(*(ct.addressof(i) for i in params)) + self.call("cuLaunchKernel", fn, *grid, block, 1, 1, 0, None, argv, None) + self.call("cuCtxSynchronize") + for ptr, arr in zip(args[-output_count:], arrays[-output_count:]): + self.call("cuMemcpyDtoH_v2", ct.c_void_p(arr.ctypes.data), ptr, ct.c_size_t(arr.nbytes)) + return arrays[-output_count:] + finally: + for ptr in args: + self.call("cuMemFree_v2", ptr) + self.call("cuModuleUnload", module) + + +def bf16(x): + x = np.asarray(x, dtype=np.float32) + u = x.view(np.uint32) + return ((u + 32767 + ((u >> 16) & 1)) & 0xffff0000).view(np.float32) + + +def lookup(): + values = [] + for code in range(256): + exp, frac = (code >> 3) & 15, code & 7 + mag = frac / 512 if exp == 0 else (1 + frac / 8) * 2**(exp - 7) + if exp == 15 and frac == 7: + mag = np.nan + values.append(-mag if code & 128 else mag) + fp4 = [0., .5, 1, 1.5, 2, 3, 4, 6] + return np.array(values + fp4 + [-v for v in fp4], np.float32) + + +def check(device): + rng = np.random.default_rng(411) + def normal(*shape): + return rng.standard_normal(shape).astype(np.float32) + + def verify(name, grid, block, inputs, expected, scalars=(), atol=2e-5, rtol=2e-5): + outputs = [np.full_like(ref, np.nan if ref.dtype.kind == "f" else 0xa5) for ref in expected] + actual = device.run(name, grid, block, inputs + outputs, len(outputs), scalars) + for ref, got in zip(expected, actual): + np.testing.assert_allclose(got, ref, atol=atol, rtol=rtol, equal_nan=False) + print(f"PASS {name}", flush=True) + return actual + + b, d = 3, 5120 + x = normal(b, 4, d) + pre, post, mat = normal(b, 4), normal(b, 4), normal(b, 4, 4) + (mixed,) = verify("hc_pre", (40, b, 1), 128, [x, pre], [np.einsum("bid,bi->bd", x, pre)]) + verify("hc_post", (40, b, 1), 128, [mixed, x, post, mat], + [mixed[:, None, :] * post[:, :, None] + np.einsum("bid,bij->bjd", x, mat)]) + raw, scale, bias = normal(b, 24), normal(3), normal(24) + logits = raw * np.repeat(scale, [4, 4, 16]) + bias + sigmoid = 1 / (1 + np.exp(-logits[:, :8])) + mat = logits[:, 8:].reshape(b, 4, 4) + mat = np.exp(mat - mat.max(axis=2, keepdims=True)) + mat = mat / mat.sum(axis=2, keepdims=True) + 1e-6 + mat /= mat.sum(axis=1, keepdims=True) + 1e-6 + for _ in range(19): + mat /= mat.sum(axis=2, keepdims=True) + 1e-6 + mat /= mat.sum(axis=1, keepdims=True) + 1e-6 + verify("hc_sinkhorn", (b, 1, 1), 1, [raw, scale, bias], + [sigmoid[:, :4] + 1e-6, sigmoid[:, 4:] * 2, mat]) + gate, up, weight = normal(b, 2304) * 12, normal(b, 2304) * 12, normal(b) + limited = np.minimum(10, gate) + verify("expert_act", (18, b, 1), 128, [gate, up, weight], + [limited / (1 + np.exp(-limited)) * np.clip(up, -10, 10) * weight[:, None]]) + + lut = np.fromfile(device.directory / "decode.f32le", dtype=">16).astype(np.uint16) + (packed_gpu,) = verify("bf16_pack",(2,1,1),128,[values],[packed],(129,),atol=0,rtol=0) + verify("bf16_unpack",(2,1,1),128,[packed_gpu],[rounded],(129,),atol=0,rtol=0) + b,h,t = 3,4,19 + query, keys = bf16(normal(b,h,128)), bf16(normal(b,t,128)) + weights = bf16(normal(b,h) / np.sqrt(128*32)) + lens = np.array([19,10,0],np.uint32) + keep = np.ones((b,3),np.int32) + keep[0,1] = 0 + dots = bf16(np.einsum("bhd,btd->bht",query,keys)) + score = bf16(bf16(np.maximum(dots,0) * weights[:,:,None]).sum(axis=1)) + mask = (np.arange(t) < lens[:,None]) & (keep[:,np.arange(t)//8] != 0) + score = np.where(mask,score,-np.inf) + verify("index_scores",(1,b,1),128,[query,keys,weights,lens,keep],[score],(h,t)) + blocks = np.full((b,3),-np.inf,np.float32) + for row in range(b): + for col in range(3): + blocks[row,col] = score[row,col*8:(col+1)*8].max() + if lens[row]: + blocks[row,(int(lens[row])-1)//8] = np.inf + verify("candidate_blocks",(3,b,1),1,[score,lens],[blocks],(t,)) + score[0,:5] = 8 # cutoff crosses a tie + score[1,:9] = -np.inf + for scores, k, offset in [(score,3,128),(blocks,2,0)]: + ids = np.full((b,k),-1,np.int32) + mask = np.zeros_like(scores,dtype=np.int32) + for row, entries in enumerate(scores): + ids_sorted = np.argsort(-entries,kind="stable")[:k] + chosen = np.sort(ids_sorted[entries[ids_sorted] > -np.inf]) + ids[row,:len(chosen)] = chosen+offset + mask[row,chosen] = 1 + verify("top_positions",(b,1,1),1,[scores],[ids,mask],(scores.shape[1],k,offset)) + residual, keys, gain = bf16(normal(b,4,5120)), bf16(normal(b,4,5120)), normal(4,5120) + valid = np.array([1,0,1],np.int32) + rstd = 1/np.sqrt(np.mean(residual**2,axis=2)+1e-20) / np.sqrt(np.mean(keys**2,axis=2)+1e-20) + dot = np.sum(residual*gain*keys,axis=2) * rstd / np.sqrt(5120) + gate = np.where(valid[:,None],1/(1+np.exp(-np.copysign(np.sqrt(np.maximum(np.abs(dot),1e-6)),dot))),0).astype(np.float32) + (gate_gpu,) = verify("engram_gate",(4,b,1),1,[residual,keys,gain,valid],[gate]) + v = bf16(normal(b,5120)) + ref = bf16(residual + gate_gpu[:,:,None]*v[:,None,:]) + verify("engram_add",(40,4,b),128,[residual,v,gate_gpu],[ref],atol=1e-6,rtol=0.008) + + table = bf16(normal(7,5120)) + ids = np.array([9,10,15,17],np.int32) + rows = np.zeros((4,4,5120),np.float32) + rows[1],rows[2] = table[0],table[5] + verify("token_embed",(40,len(ids),1),128,[ids,(table.view(np.uint32)>>16).astype(np.uint16)],[rows],(10,7),atol=0,rtol=0) + experts, shared = bf16(normal(3,6,5120)), bf16(normal(3,5120)) + verify("moe_sum",(40,3,1),128,[experts,shared],[bf16(experts.sum(axis=1)+shared)],atol=0,rtol=0) + pos = np.array([1,127,260],np.uint32) + kv, cache = normal(3,512), normal(3,128,512) + expected_cache = cache.copy() + expected_cache[np.arange(3),pos % 128] = kv + expected_slots = (pos[:,None]+1+np.arange(128)) % 128 + expected_slots = np.where(expected_slots > pos[:,None], -1, expected_slots).astype(np.int32) + got_cache, got_slots = device.run("window_step",(4,3,1),128,[kv,pos,cache,np.full((3,128),-2,np.int32)],2) + np.testing.assert_array_equal(got_cache,expected_cache) + np.testing.assert_array_equal(got_slots,expected_slots) + print("PASS window_step",flush=True) + + h, t, s = 3, 7, 71 + q, kv = bf16(normal(b, h, 512)), bf16(normal(b, t, 512)) + idx = rng.integers(-1, t, (b, s), dtype=np.int32) + idx[0, :64] = -1 + idx[1] = -1 + sink = np.array([-1, .5, 2], np.float32) + values = kv[np.arange(b)[:, None], np.maximum(idx, 0)] + scores = np.einsum("bhd,bsd->bhs", q, values) / np.float32(np.sqrt(512)) + scores = np.where(idx[:, None, :] < 0, -np.inf, scores) + (scores_gpu,) = verify("sparse_scores", (s, h, b), 1, [q, kv, idx], [scores], (h, t, s)) + peak = np.full((b,h), -1e30, np.float32) + denom = np.zeros_like(peak) + numerator = np.zeros((b,h,512), np.float32) + for first in range(0, s, 64): + tile = scores[:, :, first:first+64] + new_peak = np.maximum(peak, tile.max(axis=2)) + correction = np.exp(peak - new_peak) + p = np.exp(tile - new_peak[:, :, None]) + denom = denom * correction + p.sum(axis=2) + numerator = numerator * correction[:, :, None] + np.einsum("bhs,bsd->bhd", bf16(p), values[:, first:first+64]) + peak = new_peak + with np.errstate(over="ignore"): + denom += np.exp(sink - peak) + ref = numerator / denom[:, :, None] + verify("sparse_mix", (4, h, b), 128, [scores_gpu, kv, idx, sink], [ref], (h, t, s)) + + # One routed expert at checkpoint widths. Each independently packed W row has two + # nonzero weights, allowing exact expected projections without a second GPU stack. + def quantize_vector(x): + packed = np.empty(x.shape, np.uint8) + scales = np.empty((x.size//32,), np.uint8) + reconstructed = np.empty_like(x) + return device.run("quant_fp8", (scales.size,1,1), 16, + [x,lut,packed,scales,reconstructed],3) + + def project_vector(packed, scales, recon, rows, offset): + cols = packed.size + idx = np.arange(rows,dtype=np.int32) + i = (idx*17+offset) % cols + j = (i+31) % cols + mat = np.zeros((rows,cols//2),np.uint8) + mat[idx,i//2] |= (np.uint8(2) << ((i%2)*4)).astype(np.uint8) # +1.0 + mat[idx,j//2] |= (np.uint8(9) << ((j%2)*4)).astype(np.uint8) # -0.5 + ws = np.full((rows,cols//32),127,np.uint8) + (got,) = device.run("fp4_gemm",((rows+127)//128,1,1),128, + [packed,mat,scales,ws,lut,np.full(rows,np.nan,np.float32)],1,(cols,rows)) + np.testing.assert_array_equal(got, recon[i] - .5*recon[j]) + return bf16(got) + + packed, scales, recon = quantize_vector(bf16(normal(5120))) + gate = project_vector(packed,scales,recon,2304,9) + up = project_vector(packed,scales,recon,2304,42) + weight = np.array([.375],np.float32) + mid_ref = np.minimum(gate,10) / (1+np.exp(-np.minimum(gate,10))) * np.clip(up,-10,10) * weight + (mid,) = device.run("expert_act",(18,1,1),128,[gate,up,weight,np.full_like(gate,np.nan)],1) + np.testing.assert_allclose(mid,mid_ref,atol=2e-6,rtol=2e-6) + packed, scales, recon = quantize_vector(bf16(mid)) + project_vector(packed,scales,recon,5120,91) + print("PASS routed expert chain 5120 -> 2304 -> 5120 (synthetic weights)",flush=True) + + +if __name__ == "__main__": + if not os.environ.get("SPARK_WINDOW"): + sys.exit("Run inside the authorized GB10 correctness window") + device = Device(sys.argv[1]) + try: + check(device) + finally: + device.call("cuCtxDestroy_v2", device.ctx) diff --git a/om/gpu/dsv41/emit.om b/om/gpu/dsv41/emit.om new file mode 100644 index 000000000..a550dde20 --- /dev/null +++ b/om/gpu/dsv41/emit.om @@ -0,0 +1,1298 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note Compose after om/encoder/bw_enc_sm121.om. The public encoder receives physical operands. +note R0..R13 pointer pairs, R14 lane, R15 CTA.x, R18 CTA.y, R19 CTA.z, R16:R17 address. +const Z ulong 255 +global dsPc ulong 1 +global dsGuard ulong 1 +fn dsCtrl op ulong to ulong +note Conservative issue schedule: wait on both barriers, long fixed stalls, no dual issue. +wb = ulong 7 +rbar = ulong 7 +if or or and ge op 3 le op 7 and ge op 38 le op 42 or eq op 47 eq op 59 +wb = ulong 0 +end +if or eq op 11 eq op 19 +wb = ulong 0 +rbar = ulong 1 +end +if eq op 12 +rbar = ulong 1 +end +stall = ulong 6 +if or ne wb 7 ne rbar 7 +stall = ulong 4 +end +if or eq op 28 eq op 34 +stall = ulong 14 +end +ret or 0x300000 or shl stall 9 or shl wb 14 shl rbar 17 +end +fn inst op ulong dst ulong a ulong b ulong c ulong imm ulong to void +o = new ulong 16 0 +w = new ulong 4 0 +native = op +if or eq op 65 eq op 66 +native = ulong 61 +end +if or eq op 67 eq op 68 +native = ulong 12 +end +if or eq op 69 eq op 70 +native = ulong 40 +end +put o 0 native +put o 1 dst +put o 2 a +put o 3 b +put o 4 c +put o 5 4 +put o 6 and imm 0xffffffff +put o 7 dsCtrl native +if ne get dsGuard 0 0 +put o 9 1 +end +if eq get dsGuard 0 2 +put o 10 1 +end +put dsGuard 0 0 +if ne a Z +put o 12 1 +end +if ne b Z +put o 13 1 +end +if ne enc1 o w 0 +exit 3 +end +note F2FP.SATFINITE PACK_AB_MERGE_C and narrow STG encodings, SM121. +if eq op 65 +put w 2 0x048070ff +end +if eq op 66 +put w 2 0x042070ff +end +if eq op 67 +put w 2 sub get w 2 0x800 +end +if eq op 68 +put w 2 sub get w 2 0x400 +end +if eq op 69 +put w 2 0xc00 +end +if eq op 70 +put w 2 0x2000 +end +dsWrite w +put dsPc 0 add get dsPc 0 1 +end +fn dsWrite w view ulong 4 to void +bytes = new uchar 16 0 +for i ulong 16 +put bytes i uchar and shr get w div i 4 mul rem i 4 8 255 +end +if ne write 1 bytes 0 16 16 +exit 4 +end +end +fn literal d ulong x ulong to void +inst 2 d Z Z Z x +end +fn number d ulong x f32 to void +literal d ulong bitcast uint x +end +fn mad d ulong a ulong scale ulong c ulong to void +inst 8 d a Z c scale +end +fn madreg d ulong a ulong b ulong c ulong to void +inst 8 d a b c 0 +end +fn iadd d ulong a ulong b ulong to void +inst 14 d a b Z 0 +end +fn fop op ulong d ulong a ulong b ulong to void +inst op d a b Z 0 +end +fn fmaReg d ulong a ulong b ulong c ulong to void +inst 33 d a b c 0 +end +fn parameter d ulong offset ulong to void +inst 4 d Z Z Z add 896 offset +end +fn start pointers ulong to void +inst 7 4 Z Z Z 856 +for i ulong pointers +inst 5 mul i 2 Z Z Z add 896 mul i 8 +end +inst 3 14 Z Z Z 33 +inst 3 15 Z Z Z 37 +inst 3 18 Z Z Z 38 +inst 3 19 Z Z Z 39 +end +fn readAt d ulong base ulong idx ulong offset ulong to void +inst 9 16 idx Z base 4 +inst 11 d 16 Z Z offset +end +fn writeAt d ulong base ulong idx ulong offset ulong to void +inst 9 16 idx Z base 4 +inst 12 Z 16 d Z offset +end +fn nextLoop counter ulong limit ulong mark ulong one ulong to void +iadd counter counter one +inst 28 Z counter limit Z 0 +put dsGuard 0 2 +inst 46 Z Z Z Z sub mark get dsPc 0 +end +fn expReg d ulong a ulong logtwo ulong to void +fop 32 d a logtwo +fop 47 d d Z +end +fn sigmoid d ulong a ulong neglog ulong one ulong to void +expReg d a neglog +fop 30 d d one +fop 40 d d Z +end +fn done to void +inst 45 Z Z Z Z 0 +while or lt get dsPc 0 32 ne rem get dsPc 0 8 0 +inst 0 Z Z Z Z 0 +end +end + +note Four-stream pre mix. CTA.y is the token; x covers the 5120 components with 128 threads per CTA. +fn hcPre to void +start 3 +mad 20 15 128 14 +mad 21 18 20480 20 +mad 22 18 4 Z +number 23 0.0f32 +for stream ulong 4 +readAt 24 0 21 mul stream 20480 +readAt 25 2 22 mul stream 4 +fmaReg 23 24 25 23 +end +mad 21 18 5120 20 +writeAt 23 4 21 0 +end + +note post[j] * sublayer + sum_i residual[i] * comb[i,j]. Each thread writes all four streams. +fn hcPost to void +start 5 +mad 20 15 128 14 +mad 21 18 20480 20 +mad 22 18 5120 20 +mad 23 18 4 Z +mad 24 18 16 Z +readAt 25 0 22 0 +for i ulong 4 +readAt add i 26 2 21 mul i 20480 +end +for j ulong 4 +readAt 30 4 23 mul j 4 +fop 32 31 25 30 +for i ulong 4 +readAt 30 6 24 mul add mul i 4 j 4 +fmaReg 31 add i 26 30 31 +end +writeAt 31 8 21 mul j 20480 +end +end + +note One thread per token; registers 32..47 are the 4x4 transport matrix. +fn normalize columns bool epsilon bool to void +for i ulong 4 +number 30 0.0f32 +for j ulong 4 +reg = add 32 add mul i 4 j +if columns +reg = add 32 add mul j 4 i +end +fop 30 30 30 reg +end +if epsilon +fop 30 30 30 28 +end +fop 40 30 30 Z +for j ulong 4 +reg = add 32 add mul i 4 j +if columns +reg = add 32 add mul j 4 i +end +fop 32 reg reg 30 +if not epsilon +fop 30 reg reg 28 +end +end +end +end +fn sinkhorn to void +start 6 +mad 20 15 24 Z +mad 21 15 4 Z +mad 22 15 16 Z +literal 23 0 +for i ulong 3 +readAt add 24 i 2 23 mul i 4 +end +number 27 -1.4426950408889634f32 +number 28 0.000001f32 +number 29 1.0f32 +for i ulong 24 +readAt 30 0 20 mul i 4 +readAt 31 4 23 mul i 4 +if lt i 8 +fmaReg 30 30 add 24 div i 4 31 +sigmoid 30 30 27 29 +if lt i 4 +fop 30 30 30 28 +writeAt 30 6 21 mul i 4 +else +fop 30 30 30 30 +writeAt 30 8 21 mul sub i 4 4 +end +else +fmaReg add 32 sub i 8 30 26 31 +end +end +number 27 1.4426950408889634f32 +for i ulong 4 +base = add 32 mul i 4 +fop 37 31 base add base 1 +fop 37 31 31 add base 2 +fop 37 31 31 add base 3 +for j ulong 4 +r = add base j +fop 31 r r 31 +expReg r r 27 +end +end +normalize false false +normalize true true +literal 48 0 +literal 49 19 +literal 50 1 +mark = get dsPc 0 +normalize false true +normalize true true +nextLoop 48 49 mark 50 +for i ulong 16 +writeAt add 32 i 10 22 mul i 4 +end +end +fn swiglu to void +start 4 +mad 20 15 128 14 +mad 21 18 2304 20 +readAt 22 0 21 0 +readAt 23 2 21 0 +readAt 24 4 18 0 +number 25 10.0f32 +number 26 -10.0f32 +fop 36 22 22 25 +fop 36 23 23 25 +fop 37 23 23 26 +number 27 -1.4426950408889634f32 +number 28 1.0f32 +sigmoid 29 22 27 28 +fop 32 29 29 22 +fop 32 29 29 23 +fop 32 29 29 24 +writeAt 29 6 21 0 +end + +note Read a packed uint8 with an aligned 32-bit load. Source has padding to the next word. +fn byteRead d ulong base ulong idx ulong to void +inst 17 52 idx Z Z 2 +readAt 53 base 52 0 +inst 18 52 idx Z Z 3 +literal 54 3 +fop 29 52 52 54 +mad 52 52 8 Z +inst 52 53 53 52 Z 0 +inst 17 d 53 Z Z 24 +end +fn e8Scale d ulong base ulong idx ulong to void +byteRead d base idx +mad 55 d 1 Z +literal 54 23 +inst 52 d d 54 Z 0 +literal 54 1 +inst 28 Z d 54 Z 0 +put dsGuard 0 2 +literal d 0x00400000 +literal 54 255 +inst 28 Z 55 54 Z 0 +put dsGuard 0 1 +literal d 0x7fc00000 +end + +note Pointers A[E4M3], W[E4M3 or packed E2M1], A_scale[E8M0], W_scale[E8M0], LUT[f32], C[f32]. +note Params K and N. LUT has 256 E4M3 then 16 E2M1 values. CTA.y = m. K divisible by 32. +fn gemm fp4 bool to void +start 6 +parameter 21 48 +parameter 22 52 +mad 20 15 128 14 +inst 28 Z 20 22 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +inst 17 23 21 Z Z 5 +madreg 24 18 23 Z +madreg 25 20 23 Z +if fp4 +mad 26 25 4 Z +mad 27 25 1 Z +else +mad 26 25 8 Z +inst 17 27 20 Z Z 5 +madreg 27 27 23 Z +end +mad 28 24 8 Z +literal 29 0 +literal 30 1 +number 31 0.0f32 +mark = get dsPc 0 +number 32 0.0f32 +for k ulong 32 +if eq rem k 4 0 +readAt 33 0 28 mul div k 4 4 +end +pack = ulong 4 +width = ulong 8 +mask = ulong 255 +if fp4 +pack = ulong 8 +width = ulong 4 +mask = ulong 15 +end +if eq rem k pack 0 +readAt 34 2 26 mul div k pack 4 +end +inst 17 35 33 Z Z mul rem k 4 8 +inst 18 35 35 Z Z 255 +readAt 35 8 35 0 +inst 17 36 34 Z Z mul rem k pack width +inst 18 36 36 Z Z mask +if fp4 +readAt 36 8 36 1024 +else +readAt 36 8 36 0 +end +fmaReg 32 35 36 32 +end +iadd 37 24 29 +e8Scale 38 4 37 +iadd 37 27 29 +e8Scale 39 6 37 +fop 32 32 32 38 +fmaReg 31 32 39 31 +literal 40 8 +iadd 28 28 40 +if fp4 +literal 40 4 +end +iadd 26 26 40 +nextLoop 29 23 mark 30 +madreg 41 18 22 20 +writeAt 31 10 41 0 +end + +note Split latent attention: one CTA.x per selected entry, CTA.y per query head, +note CTA.z per batch row. Q [B,H,512], KV [B,T,512], indices [B,S]. BF16 inputs widened to F32. +note Input indices can use -1. A masked score is -infinity. Each CTA has one thread in the baseline. +fn sparseScore to void +start 4 +parameter 21 32 +parameter 22 36 +parameter 23 40 +madreg 24 19 23 15 +readAt 25 4 24 0 +madreg 26 19 21 18 +madreg 27 26 23 15 +inst 28 Z 25 22 Z 0 +literal 28 0xff800000 +inst 9 16 27 Z 6 4 +put dsGuard 0 1 +inst 12 Z 16 28 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +mad 29 26 512 Z +madreg 30 19 22 25 +mad 30 30 512 Z +number 31 0.0f32 +literal 32 0 +literal 33 32 +literal 34 1 +literal 37 16 +mark = get dsPc 0 +for j ulong 16 +readAt 35 0 29 mul j 4 +readAt 36 2 30 mul j 4 +fmaReg 31 35 36 31 +end +iadd 29 29 37 +iadd 30 30 37 +nextLoop 32 33 mark 34 +number 38 0.04419417382415922f32 +fop 32 31 31 38 +writeAt 31 6 27 0 +end + +note Sparse reduce: CTA.x = 128-component tile, CTA.y head, CTA.z row; full-width result. +note Rescale numerator and denominator every 64 entries and incorporate the sink after the final tile. +fn sparseMix to void +start 5 +parameter 21 40 +parameter 22 44 +parameter 23 48 +mad 20 15 128 14 +madreg 24 19 21 18 +madreg 25 24 23 Z +madreg 26 19 23 Z +number 27 -1e30f32 +literal 29 1 +number 32 1.4426950408889634f32 +number 33 0.0f32 +number 34 0.0f32 +literal 40 0 +literal 41 64 +tile = get dsPc 0 +iadd 42 40 41 +inst 28 Z 42 23 Z 0 +put dsGuard 0 1 +mad 42 23 1 Z +mad 43 27 1 Z +mad 28 40 1 Z +mark = get dsPc 0 +iadd 30 25 28 +readAt 31 0 30 0 +fop 37 27 27 31 +nextLoop 28 42 mark 29 +fop 31 43 43 27 +expReg 43 43 32 +fop 32 33 33 43 +fop 32 34 34 43 +mad 28 40 1 Z +mark = get dsPc 0 +iadd 30 25 28 +readAt 31 0 30 0 +fop 31 31 31 27 +expReg 31 31 32 +fop 30 33 33 31 +iadd 30 26 28 +readAt 35 4 30 0 +inst 28 Z 35 22 Z 0 +put dsGuard 0 1 +literal 35 0 +madreg 36 19 22 35 +mad 36 36 512 20 +readAt 37 2 36 0 +inst 61 31 Z 31 Z 0 +inst 18 31 31 Z Z 0xffff +mad 31 31 65536 Z +fmaReg 34 31 37 34 +nextLoop 28 42 mark 29 +nextLoop 40 23 tile 41 +readAt 31 6 18 0 +fop 31 31 31 27 +expReg 31 31 32 +fop 30 33 33 31 +fop 40 33 33 Z +fop 32 34 34 33 +mad 36 24 512 20 +writeAt 34 8 36 0 +end +note Each CTA owns one group. One thread encodes a pair, so no packed-byte RMW or shared atomics. +note x is widened BF16, lookup is the GEMM decode table. Outputs packed data, u8 scales, widened BF16 reconstructions. +fn quant fp4 bool kv bool to void +start 5 +group = ulong 32 +if kv +group = ulong 16 +end +mad 20 15 group Z +number 21 0.0001f32 +number 24 0.002232142857142857f32 +if fp4 +literal 21 0x01c00000 +number 24 0.16666666666666667f32 +end +if kv +number 21 0.01171875f32 +end +for j ulong group +readAt 22 0 20 mul j 4 +inst 18 22 22 Z Z 0x7fffffff +fop 37 21 21 22 +end +fop 32 21 21 24 +if kv +inst 65 23 Z 21 Z 0 +inst 18 23 23 Z Z 255 +readAt 25 2 23 0 +else +inst 17 23 21 Z Z 23 +inst 18 22 21 Z Z 0x7fffff +literal 26 1 +inst 28 Z 22 26 Z 0 +put dsGuard 0 1 +iadd 23 23 26 +mad 25 23 8388608 Z +end +literal 26 1 +inst 28 Z 14 26 Z 0 +inst 9 16 15 Z 6 1 +put dsGuard 0 2 +inst 67 Z 16 23 Z 0 +mad 26 14 2 20 +readAt 27 0 26 0 +readAt 28 0 26 4 +fop 40 29 25 Z +fop 32 30 27 29 +fop 32 31 28 29 +if kv +note Residual correction for non-power-of-two scales before native round-to-nearest. +number 32 -1.0f32 +fop 32 32 32 25 +fmaReg 33 30 32 27 +fmaReg 30 33 29 30 +fmaReg 33 31 32 28 +fmaReg 31 33 29 31 +note Restore signed zero after the FMA correction. +inst 18 30 30 Z Z 0x7fffffff +inst 18 31 31 Z Z 0x7fffffff +inst 18 33 27 Z Z 0x80000000 +iadd 30 30 33 +inst 18 33 28 Z Z 0x80000000 +iadd 31 31 33 +end +if fp4 +inst 66 32 31 30 Z 0 +inst 17 33 26 Z Z 1 +inst 9 16 33 Z 4 1 +inst 67 Z 16 32 Z 0 +inst 18 34 32 Z Z 15 +inst 17 35 32 Z Z 4 +inst 18 35 35 Z Z 15 +readAt 34 2 34 1024 +readAt 35 2 35 1024 +else +inst 65 32 31 30 Z 0 +inst 9 16 26 Z 4 1 +inst 68 Z 16 32 Z 0 +inst 18 34 32 Z Z 255 +inst 17 35 32 Z Z 8 +inst 18 35 35 Z Z 255 +readAt 34 2 34 0 +readAt 35 2 35 0 +end +fop 32 34 34 25 +fop 32 35 35 25 +inst 61 34 35 34 Z 0 +inst 18 35 34 Z Z 0xffff0000 +mad 34 34 65536 Z +writeAt 34 8 26 0 +writeAt 35 8 26 4 +end +note Scalar reference projection with FP32 accumulation, for BF16-widened or FP32 dense matrices. +fn dense to void +start 3 +parameter 21 24 +parameter 22 28 +mad 20 15 128 14 +inst 28 Z 20 22 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +madreg 23 18 21 Z +madreg 24 20 21 Z +number 25 0.0f32 +literal 26 0 +literal 27 1 +mark = get dsPc 0 +iadd 28 23 26 +readAt 28 0 28 0 +iadd 29 24 26 +readAt 29 2 29 0 +fmaReg 25 28 29 25 +nextLoop 26 21 mark 27 +madreg 28 18 22 20 +writeAt 25 4 28 0 +end + +note One scalar per row. RMSNorm or the normalization statistic for the 20480-wide hc projection. +fn rmsStat to void +start 2 +parameter 20 16 +madreg 21 15 20 Z +number 22 0.0f32 +literal 23 0 +literal 24 1 +mark = get dsPc 0 +iadd 25 21 23 +readAt 25 0 25 0 +fmaReg 22 25 25 22 +nextLoop 23 20 mark 24 +fop 38 25 20 Z +fop 40 25 25 Z +number 26 1e-20f32 +fmaReg 22 22 25 26 +fop 41 22 22 Z +writeAt 22 2 15 0 +end +fn rmsApply to void +start 4 +parameter 21 32 +mad 20 15 128 14 +inst 28 Z 20 21 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +madreg 22 18 21 20 +readAt 23 0 22 0 +readAt 24 2 20 0 +readAt 25 4 18 0 +fop 32 23 23 25 +fop 32 23 23 24 +writeAt 23 6 22 0 +end + +note In-place 64-wide adjacent-pair rotary tail. Precomputed cos,sin per token, sign +1 or -1. +fn rotary to void +start 2 +parameter 20 16 +parameter 21 20 +parameter 22 24 +madreg 23 18 21 15 +madreg 23 23 20 Z +literal 24 0xffffffc0 +iadd 23 23 20 +iadd 23 23 24 +mad 23 14 2 23 +mad 24 18 64 Z +mad 24 14 2 24 +readAt 25 0 23 0 +readAt 26 0 23 4 +readAt 27 2 24 0 +readAt 28 2 24 4 +fop 32 28 28 22 +fop 32 29 25 27 +fop 32 30 26 28 +fop 31 29 29 30 +fop 32 30 26 27 +fmaReg 30 25 28 30 +writeAt 29 0 23 0 +writeAt 30 0 23 4 +end + +note Per-feature two-token softmax pooling for completed compression groups. +fn poolPair to void +start 3 +mad 20 15 128 14 +mad 21 18 1024 20 +readAt 22 0 21 0 +readAt 23 0 21 2048 +readAt 24 2 21 0 +readAt 25 2 21 2048 +fop 37 26 24 25 +fop 31 24 24 26 +fop 31 25 25 26 +number 27 1.4426950408889634f32 +expReg 24 24 27 +expReg 25 25 27 +fop 30 26 24 25 +fop 40 26 26 Z +fop 32 24 24 26 +fop 32 25 25 26 +fop 32 22 22 24 +fmaReg 22 23 25 22 +mad 21 18 512 20 +writeAt 22 4 21 0 +end + +note One thread per token. Keep six largest (sqrt(softplus(logit))+bias) and their raw scores. +fn route to void +start 4 +mad 20 15 384 Z +mad 21 15 6 Z +for k ulong 6 +literal add 32 k 0xff800000 +literal add 38 k 0 +number add 44 k 0.0f32 +end +literal 22 0 +literal 23 384 +literal 24 1 +number 25 1.4426950408889634f32 +number 26 0.6931471805599453f32 +number 27 1.0f32 +mark = get dsPc 0 +iadd 28 20 22 +readAt 28 0 28 0 +readAt 29 2 22 0 +note Stable log1p(z) corrects for rounding in u=1+z with log(u)*z/(u-1). +inst 18 30 28 Z Z 0x7fffffff +fop 31 30 Z 30 +expReg 30 30 25 +fop 30 31 30 27 +fop 31 50 31 27 +fop 69 31 31 Z +fop 32 31 31 26 +fop 40 51 50 Z +fop 32 51 30 51 +fop 32 31 31 51 +inst 34 0 50 Z Z 0x03f04000 +put dsGuard 0 2 +mad 31 30 1 Z +fop 37 28 28 Z +fop 30 28 28 31 +fop 70 28 28 Z +fop 30 29 29 28 +mad 30 22 1 Z +for k ulong 6 +r = add 32 k +ix = add 38 k +raw = add 44 k +inst 34 0 29 r Z 0x03f04000 +mad 51 r 1 Z +mad 52 ix 1 Z +mad 53 raw 1 Z +put dsGuard 0 1 +mad r 29 1 Z +put dsGuard 0 1 +mad ix 30 1 Z +put dsGuard 0 1 +mad raw 28 1 Z +put dsGuard 0 1 +mad 29 51 1 Z +put dsGuard 0 1 +mad 30 52 1 Z +put dsGuard 0 1 +mad 28 53 1 Z +end +nextLoop 22 23 mark 24 +number 28 1e-20f32 +for k ulong 6 +fop 30 28 28 add 44 k +end +fop 40 28 28 Z +number 29 1.5f32 +fop 32 29 28 29 +for k ulong 6 +fop 32 30 add 44 k 29 +writeAt add 38 k 4 21 mul k 4 +writeAt 30 6 21 mul k 4 +end +end + +note Local Engram shard gather. Form the row address in 64 bits before adding the column. +fn engramRows to void +start 5 +parameter 20 40 +parameter 21 44 +readAt 22 0 15 0 +literal 23 0xffffffff +madreg 23 20 23 22 +mad 24 15 256 14 +inst 28 Z 23 21 Z 0 +inst 9 16 24 Z 8 4 +put dsGuard 0 1 +inst 12 Z 16 Z Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +inst 9 56 23 Z 2 256 +byteRead 25 56 14 +readAt 25 6 25 0 +inst 9 56 23 Z 4 8 +inst 17 26 14 Z Z 5 +e8Scale 26 56 26 +fop 32 25 25 26 +writeAt 25 8 24 0 +end +fn bfRound d ulong a ulong to void +inst 61 d Z a Z 0 +mad d d 65536 Z +end +note Either pack to BF16, or widen packed BF16 with the bit pattern preserved. +fn convert unpack bool to void +start 2 +parameter 20 16 +mad 21 15 128 14 +inst 28 Z 21 20 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +if unpack +inst 17 22 21 Z Z 1 +readAt 23 0 22 0 +inst 18 24 21 Z Z 1 +literal 25 1 +inst 28 Z 24 25 Z 0 +put dsGuard 0 2 +mad 23 23 65536 Z +inst 18 23 23 Z Z 0xffff0000 +writeAt 23 2 21 0 +else +readAt 23 0 21 0 +inst 61 23 Z 23 Z 0 +inst 9 16 21 Z 2 2 +inst 68 Z 16 23 Z 0 +end +end + +note Causal, candidate-filtered weighted ReLU index score for one decode query per row. +fn indexScore to void +start 6 +parameter 21 48 +parameter 22 52 +mad 20 15 128 14 +inst 28 Z 20 22 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +madreg 23 18 22 20 +madreg 24 18 21 Z +mad 25 24 128 Z +mad 26 23 128 Z +literal 27 7 +iadd 28 22 27 +inst 17 28 28 Z Z 3 +inst 17 29 20 Z Z 3 +madreg 29 18 28 29 +readAt 29 8 29 0 +readAt 30 6 18 0 +inst 28 Z 20 30 Z 0 +put dsGuard 0 1 +literal 29 0 +literal 31 1 +inst 28 Z 29 31 Z 0 +literal 32 0xff800000 +inst 9 16 23 Z 10 4 +put dsGuard 0 2 +inst 12 Z 16 32 Z 0 +put dsGuard 0 2 +inst 45 Z Z Z Z 0 +literal 28 0 +number 32 0.0f32 +mark = get dsPc 0 +number 33 0.0f32 +for k ulong 128 +readAt 34 0 25 mul k 4 +readAt 35 2 26 mul k 4 +fmaReg 33 34 35 33 +end +bfRound 33 33 +fop 37 33 33 Z +iadd 34 24 28 +readAt 35 4 34 0 +fop 32 33 33 35 +bfRound 33 33 +fop 30 32 32 33 +literal 34 128 +iadd 25 25 34 +nextLoop 28 21 mark 31 +bfRound 32 32 +writeAt 32 10 23 0 +end + +note Eight contiguous candidate positions. Pin the last reachable block. +fn blockScores to void +start 3 +parameter 20 24 +mad 21 15 8 Z +madreg 22 18 20 21 +readAt 23 2 18 0 +literal 24 0xff800000 +literal 25 1 +for k ulong 8 +literal 26 k +iadd 27 21 26 +inst 28 Z 27 20 Z 0 +inst 9 16 22 Z 0 4 +literal 28 0xff800000 +put dsGuard 0 2 +inst 11 28 16 Z Z mul k 4 +inst 28 Z 27 23 Z 0 +put dsGuard 0 1 +literal 28 0xff800000 +fop 37 24 24 28 +end +literal 26 0xffffffff +iadd 27 23 26 +inst 17 27 27 Z Z 3 +note CTAs are always real blocks. A zero length yields a last-block index outside their range. +fop 29 28 27 15 +inst 28 Z 28 25 Z 0 +put dsGuard 0 2 +literal 24 0x7f800000 +literal 26 7 +iadd 26 26 20 +inst 17 26 26 Z Z 3 +madreg 26 18 26 15 +writeAt 24 4 26 0 +end + +note IEEE key preserves score order for finite values and infinities. Signed zeros compare equal. +fn orderedKey value ulong key ulong to void +literal 49 0x80000000 +inst 18 50 value Z Z 0x7fffffff +literal 51 1 +inst 28 Z 50 51 Z 0 +put dsGuard 0 2 +literal value 0 +inst 28 Z value 49 Z 0 +put dsGuard 0 1 +literal 49 0xffffffff +fop 29 key value 49 +end +note Find the kth largest key by counting prefixes. Emit in increasing position order; ties use lower positions. +note Returns both indices padded with -1 and an int32 keep mask. Input can be masked with -infinity. +fn topPositions to void +start 3 +parameter 20 24 +parameter 21 28 +parameter 22 32 +madreg 23 15 20 Z +madreg 24 15 21 Z +literal 25 1 +literal 26 0 +literal 27 0x80000000 +literal 31 32 +literal 32 0 +outer = get dsPc 0 +iadd 28 26 27 +literal 29 0 +literal 30 0 +mark = get dsPc 0 +iadd 33 23 30 +readAt 34 0 33 0 +orderedKey 34 35 +inst 28 Z 35 28 Z 0 +put dsGuard 0 1 +iadd 29 29 25 +nextLoop 30 20 mark 25 +inst 28 Z 29 21 Z 0 +put dsGuard 0 1 +mad 26 28 1 Z +inst 17 27 27 Z Z 1 +nextLoop 32 31 outer 25 +literal 30 0 +literal 29 0 +mark = get dsPc 0 +iadd 33 23 30 +readAt 34 0 33 0 +orderedKey 34 35 +inst 28 Z 26 35 Z 0 +put dsGuard 0 2 +iadd 29 29 25 +nextLoop 30 20 mark 25 +literal 36 0xffffffff +madreg 37 29 36 21 +literal 30 0 +literal 38 0 +mark = get dsPc 0 +iadd 33 23 30 +readAt 34 0 33 0 +orderedKey 34 35 +literal 39 0 +inst 28 Z 35 26 Z 0 +put dsGuard 0 1 +literal 39 1 +fop 29 40 35 26 +inst 28 Z 40 25 Z 0 +put dsGuard 0 2 +mad 39 37 1 Z +literal 41 0xff800000 +fop 29 41 34 41 +inst 28 Z 41 25 Z 0 +put dsGuard 0 2 +literal 39 0 +inst 28 Z 39 25 Z 0 +put dsGuard 0 1 +literal 39 1 +writeAt 39 4 33 0 +iadd 42 24 38 +iadd 43 22 30 +inst 9 16 42 Z 2 4 +put dsGuard 0 1 +inst 12 Z 16 43 Z 0 +iadd 38 38 39 +inst 28 Z 40 25 Z 0 +put dsGuard 0 2 +madreg 37 39 36 37 +nextLoop 30 20 mark 25 +mark = get dsPc 0 +inst 28 Z 38 21 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +iadd 42 24 38 +writeAt 36 2 42 0 +iadd 38 38 25 +inst 46 Z Z Z Z sub mark get dsPc 0 +end + +note Compute the Engram normalized signed-sqrt gate for each token and residual stream. +fn engramGate to void +start 5 +mad 20 18 4 15 +mad 21 20 5120 Z +mad 22 15 5120 Z +literal 23 0 +literal 24 5120 +literal 25 1 +number 26 0.0f32 +number 27 0.0f32 +number 28 0.0f32 +mark = get dsPc 0 +iadd 29 21 23 +readAt 30 0 29 0 +readAt 31 2 29 0 +iadd 29 22 23 +readAt 32 4 29 0 +fmaReg 26 30 30 26 +fmaReg 27 31 31 27 +fop 32 30 30 32 +fmaReg 28 30 31 28 +nextLoop 23 24 mark 25 +number 29 0.0001953125f32 +number 30 1e-20f32 +fmaReg 26 26 29 30 +fmaReg 27 27 29 30 +fop 41 26 26 Z +fop 41 27 27 Z +fop 32 26 26 27 +fop 32 28 28 26 +number 29 0.013975424859373685f32 +fop 32 28 28 29 +inst 18 30 28 Z Z 0x80000000 +inst 18 28 28 Z Z 0x7fffffff +number 29 0.000001f32 +fop 37 28 28 29 +fop 70 28 28 Z +iadd 28 28 30 +number 29 -1.4426950408889634f32 +number 30 1.0f32 +sigmoid 28 28 29 30 +readAt 31 6 18 0 +inst 28 Z 31 25 Z 0 +put dsGuard 0 2 +number 28 0.0f32 +writeAt 28 8 20 0 +end +fn engramAdd to void +start 4 +mad 20 15 128 14 +mad 21 19 4 18 +mad 22 21 5120 20 +mad 23 19 5120 20 +readAt 24 0 22 0 +readAt 25 2 23 0 +readAt 26 4 21 0 +fmaReg 24 25 26 24 +bfRound 24 24 +writeAt 24 6 22 0 +end +note Widen the BF16 vocabulary row and replicate it into four initial residual streams. +fn tokenEmbed to void +start 3 +parameter 20 24 +parameter 21 28 +mad 22 15 128 14 +readAt 23 0 18 0 +literal 24 0xffffffff +madreg 24 20 24 23 +inst 28 Z 24 21 Z 0 +inst 9 56 24 Z 2 10240 +inst 17 25 22 Z Z 1 +inst 9 16 25 Z 56 4 +literal 26 0 +put dsGuard 0 2 +inst 11 26 16 Z Z 0 +inst 18 25 22 Z Z 1 +literal 24 1 +inst 28 Z 25 24 Z 0 +put dsGuard 0 2 +mad 26 26 65536 Z +inst 18 26 26 Z Z 0xffff0000 +mad 23 18 20480 22 +for j ulong 4 +writeAt 26 4 23 mul j 20480 +end +end +note Assemble six routed down projections plus the shared expert. Routing weights were applied before w2. +fn moeSum to void +start 3 +mad 20 15 128 14 +mad 21 18 30720 20 +mad 22 18 5120 20 +number 23 0.0f32 +for j ulong 6 +readAt 24 0 21 mul j 20480 +fop 30 23 23 24 +end +readAt 24 2 22 0 +fop 30 23 23 24 +bfRound 23 23 +writeAt 23 4 22 0 +end +note Write the current KV into slot pos mod 128 and give one query its 128 oldest-first window indices. +fn windowStep to void +start 4 +mad 20 15 128 14 +readAt 21 2 18 0 +inst 18 22 21 Z Z 127 +mad 23 18 128 22 +mad 24 23 512 20 +mad 25 18 512 20 +readAt 26 0 25 0 +writeAt 26 4 24 0 +literal 27 1 +inst 28 Z 15 27 Z 0 +put dsGuard 0 1 +inst 45 Z Z Z Z 0 +iadd 28 22 27 +iadd 28 28 14 +inst 18 28 28 Z Z 127 +inst 28 Z 21 28 Z 0 +put dsGuard 0 2 +literal 28 0xffffffff +mad 29 18 128 14 +writeAt 28 6 29 0 +end +fn main to int +arg = new uchar 2 0 +if ne argcnt 2 +ret 2 +end +if ne argread 1 arg 0 2 1 +ret 2 +end +kind = get arg 0 +if eq kind 97 +hcPre +done +ret 0 +end +if eq kind 98 +hcPost +done +ret 0 +end +if eq kind 99 +sinkhorn +done +ret 0 +end +if eq kind 100 +swiglu +done +ret 0 +end +if eq kind 101 +gemm false +done +ret 0 +end +if eq kind 102 +gemm true +done +ret 0 +end +if eq kind 103 +sparseScore +done +ret 0 +end +if eq kind 104 +sparseMix +done +ret 0 +end +if and ge kind 105 le kind 107 +quant ne kind 105 eq kind 107 +done +ret 0 +end +if eq kind 108 +dense +done +ret 0 +end +if eq kind 109 +rmsStat +done +ret 0 +end +if eq kind 110 +rmsApply +done +ret 0 +end +if eq kind 111 +rotary +done +ret 0 +end +if eq kind 112 +poolPair +done +ret 0 +end +if eq kind 113 +route +done +ret 0 +end +if eq kind 114 +engramRows +done +ret 0 +end +if eq kind 115 +convert false +done +ret 0 +end +if eq kind 116 +convert true +done +ret 0 +end +if eq kind 117 +indexScore +done +ret 0 +end +if eq kind 118 +blockScores +done +ret 0 +end +if eq kind 119 +topPositions +done +ret 0 +end +if eq kind 120 +engramGate +done +ret 0 +end +if eq kind 121 +engramAdd +done +ret 0 +end +if eq kind 122 +tokenEmbed +done +ret 0 +end +if eq kind 65 +moeSum +done +ret 0 +end +if eq kind 66 +windowStep +done +ret 0 +end +ret 2 +end diff --git a/om/gpu/dsv41/kernels.list b/om/gpu/dsv41/kernels.list new file mode 100644 index 000000000..0c74157bf --- /dev/null +++ b/om/gpu/dsv41/kernels.list @@ -0,0 +1,28 @@ +a hc_pre p8 p8 p8 +b hc_post p8 p8 p8 p8 p8 +c hc_sinkhorn p8 p8 p8 p8 p8 p8 +d expert_act p8 p8 p8 p8 +e fp8_gemm p8 p8 p8 p8 p8 p8 4 4 +f fp4_gemm p8 p8 p8 p8 p8 p8 4 4 +g sparse_scores p8 p8 p8 p8 4 4 4 +h sparse_mix p8 p8 p8 p8 p8 4 4 4 +i quant_fp8 p8 p8 p8 p8 p8 +j quant_fp4 p8 p8 p8 p8 p8 +k quant_kv p8 p8 p8 p8 p8 +l dense p8 p8 p8 4 4 +m rms_stat p8 p8 4 +n rms_apply p8 p8 p8 p8 4 +o rotary_tail p8 p8 4 4 4 +p compress_pair p8 p8 p8 +q route6 p8 p8 p8 p8 +r engram_rows p8 p8 p8 p8 p8 4 4 +s bf16_pack p8 p8 4 +t bf16_unpack p8 p8 4 +u index_scores p8 p8 p8 p8 p8 p8 4 4 +v candidate_blocks p8 p8 p8 4 +w top_positions p8 p8 p8 4 4 4 +x engram_gate p8 p8 p8 p8 p8 +y engram_add p8 p8 p8 p8 +z token_embed p8 p8 p8 4 4 +A moe_sum p8 p8 p8 +B window_step p8 p8 p8 p8 diff --git a/om/gpu/dsv41/lookup.om b/om/gpu/dsv41/lookup.om new file mode 100644 index 000000000..2cbb99dfd --- /dev/null +++ b/om/gpu/dsv41/lookup.om @@ -0,0 +1,40 @@ +note SPDX-License-Identifier: AGPL-3.0-only +note Little-endian f32 decode table. First 256 E4M3FN encodings, then 16 E2M1 encodings. +om2 +fn e4m3 c uint to uint +e = and shr c 3 15 +m = and c 7 +raw = or shl add e 120 23 shl m 20 +if eq e 0 +raw = bitcast uint mul f32 m 0.001953125f32 +end +if and eq e 15 eq m 7 +raw = uint 0x7fc00000 +end +ret or raw shl and c 128 24 +end +fn e2m1 c uint to uint +e = and shr c 1 3 +m = and c 1 +raw = or shl add e 126 23 shl m 22 +if eq e 0 +raw = bitcast uint mul f32 m 0.5f32 +end +ret or raw shl and c 8 28 +end +fn main to int +buf = new uchar 1088 0 +for i ulong 272 +v = e4m3 uint i +if ge i 256 +v = e2m1 uint sub i 256 +end +for j ulong 4 +put buf add mul i 4 j uchar and shr v uint mul j 8 255 +end +end +if ne write 1 buf 0 1088 1088 +ret 1 +end +ret 0 +end diff --git a/seed/kflow/kpack.om b/seed/kflow/kpack.om index 38a2938a3..4ccc75f53 100644 --- a/seed/kflow/kpack.om +++ b/seed/kflow/kpack.om @@ -10,13 +10,17 @@ note Run: kpack ARCH NAME BIN OUT REGS SHARED P... note ARCH 80 or 121; NAME the kernel symbol ([A-Za-z_][A-Za-z0-9_]*, at most 63 bytes); BIN raw SASS note (a nonzero multiple of 16 bytes, at most 64 KiB); OUT the cubin to write; REGS registers per thread note (at most 255); SHARED reserved shared bytes (multiple of 4); then one word per parameter in order: +note Select ARCH 121-tk for a driver-loadable CUDA 13 image with linked toolkit metadata. note p8 a pointer, or 1 2 4 8 a value of that many bytes. Parameters are laid out naturally aligned from note constant bank offset 0x380 (CUDA's ABI), and the constant bank ends at the end of the last one. note Exit 0 written, 1 refused arguments or input, 2 write failed. The packer does not decode SASS: the note register count is the caller's claim, and EIATTR_EXIT_INSTR_OFFSETS is left out as in CUDA++. om2 text msg "kpack: usage: kpack ARCH NAME BIN OUT REGS SHARED P...\nkpack: bad argument\nkpack: bin unreadable, empty, too large or not a multiple of 16 bytes\nkpack: cannot write output\nkpack: wrote bytes=\n sections=\n cbank=\n" -text sn ".shstrtab|.strtab|.symtab|.text.|.nv.constant0.|.nv.info|.nv.compat|.nv.info.|.nv.shared.reserved.0|.note.nv.cuinfo|" +text sn ".shstrtab|.strtab|.symtab|.text.|.nv.constant0.|.nv.info|.nv.compat|.nv.info.|.nv.shared.reserved.0|.note.nv.cuinfo|.note.nv.tkinfo|" +text tkname "121-tk" +text producer "Omega kpack" +text target "sm_121a" global ob uchar 196608 global tx uchar 65536 global ab uchar 256 @@ -143,7 +147,7 @@ ret eq get sv 0 121 end fn shstr to void e1 0 -for k ulong 10 +for k ulong add 10 get sv 9 if or ne k 6 hascompat put nm k sub cur get so 0 sname k @@ -254,6 +258,42 @@ end if eq k 9 noteb end +if eq k 10 +toolnote +end +end +fn toolnote to void +note ELF toolkit descriptor v2 with producer, ABI release, build and target string offsets. +e4 12 +e4 64 +e4 2000 +e4 0x4449564e +e4 0x43204149 +e4 0x0070726f +e4 2 +e4 0 +e4 1 +e4 13 +e4 18 +e4 25 +e1 0 +for i ulong len producer +e1 ulong get producer i +end +e1 0 +e4 0x302e3331 +e1 0 +e4 0x64656573 +e1 101 +e1 100 +e1 0 +for i ulong len target +e1 ulong get target i +end +e1 0 +for i ulong 7 +e1 0 +end end fn noteb to void e4 12 @@ -285,7 +325,7 @@ end if eq k 8 ret 8 end -if eq k 9 +if ge k 9 ret 7 end ret 3 @@ -303,6 +343,9 @@ end if eq k 8 ret 3 end +if eq k 10 +ret 0x1000000 +end if eq k 9 ret 0x1000040 end @@ -318,12 +361,15 @@ end if eq k 4 ret 16 end -if or or eq k 5 eq k 6 or eq k 7 eq k 9 +if or or eq k 5 eq k 6 or eq k 7 ge k 9 ret 4 end ret 1 end fn slk k ulong to ulong +if and eq k 9 ne get sv 9 0 +ret 11 +end if eq k 2 ret 2 end @@ -463,7 +509,7 @@ end fn place to void put sv 1 64 i = ulong 1 -for k ulong 10 +for k ulong add 10 get sv 9 if or ne k 6 hascompat alignc sal k put so k cur @@ -479,7 +525,7 @@ alignc 8 sh = cur n = get sv 8 i = ulong 1 -for k ulong 10 +for k ulong add 10 get sv 9 if or ne k 6 hascompat shdr add sh mul i 64 k i = add i 1 @@ -515,12 +561,29 @@ b2 60 n b2 62 1 ret add ph 280 end +fn architecture to ulong +a = argdec 1 +r = argread 1 ab 0 20 +if eq r long len tkname +match = true +for j ulong len tkname +if ne get ab j get tkname j +match = false +end +end +if match +a = ulong 121 +put sv 9 1 +end +end +ret a +end fn main to int if lt argcnt 7 say 1 ret 1 end -a = argdec 1 +a = architecture g = argdec 5 h = argdec 6 if or or and ne a 80 ne a 121 gt g 255 or gt h 0xfffff ne rem h 4 0 From e9b0e055313b3645533febaa7d7d2bfcdf414c71 Mon Sep 17 00:00:00 2001 From: Drake Stapleton <213298340+drakestapleton@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:25:02 -0600 Subject: [PATCH 2/2] Preserve routing ties and validate kernel launch bounds --- om/gpu/dsv41/README.md | 8 ++++---- om/gpu/dsv41/check.py | 11 +++++++++++ om/gpu/dsv41/emit.om | 9 +++++++++ seed/kflow/check-driver-abi.py | 34 ++++++++++++++++++++++++++++++++++ seed/kflow/kpack.om | 3 +++ 5 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 seed/kflow/check-driver-abi.py diff --git a/om/gpu/dsv41/README.md b/om/gpu/dsv41/README.md index 76c1615dd..9911e25af 100644 --- a/om/gpu/dsv41/README.md +++ b/om/gpu/dsv41/README.md @@ -40,21 +40,21 @@ In the table, B counts token rows, H local heads, T cache positions, S selected | 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,H,sign | (H,B) · 32 | +| 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 head weights[B,H], lengths[B], keep mask[B,ceil(T/8)], out[B,T], H,T | (tiles(T),B) · 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], token mask[B], gates[B,4] | (4,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 scale checks cover the finite representable range. +**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. diff --git a/om/gpu/dsv41/check.py b/om/gpu/dsv41/check.py index 282ef1a95..9f14aa966 100644 --- a/om/gpu/dsv41/check.py +++ b/om/gpu/dsv41/check.py @@ -120,6 +120,8 @@ def check(device): values[1, :8] = [-0., .25, .75, 1.25, 1.75, 2.5, 3.5, 5.] values[1, 8:] = 6 values[2] *= 2**-14 + if name == "quant_kv": + values[3] = bf16(np.linspace(-2688., 2688., group, dtype=np.float32)) maxval = 6 if fp4 else 448 floor = 6*2**-9 if name == "quant_kv" else (6*2**-126 if fp4 else 1e-4) ratio = np.maximum(np.abs(values).max(axis=1), floor) / np.float32(maxval) @@ -174,6 +176,10 @@ def check(device): got, _ = device.run("rotary_tail", (2,3,1), 32, [xs, freq], 2, (128, 2, np.float32(sign).view(np.uint32))) np.testing.assert_allclose(got, expected, atol=1e-6, rtol=1e-6) + narrow = normal(32) + got, _ = device.run("rotary_tail", (1,1,1), 32, [narrow.copy(), freq[0]], 2, + (32, 1, np.float32(1).view(np.uint32))) + np.testing.assert_array_equal(got, narrow) print("PASS rotary_tail", flush=True) vals, gates = normal(3,2,512), normal(3,2,512)*35 coeff = np.exp(gates - gates.max(axis=1, keepdims=True)) @@ -186,6 +192,11 @@ def check(device): selected_w = np.take_along_axis(raw, selected, axis=1) verify("route6", (3,1,1), 1, [logits,bias], [selected, selected_w * 1.5 / (selected_w.sum(axis=1, keepdims=True)+1e-20)]) + tie_logits = np.zeros((1,384),np.float32) + tie_bias = np.zeros(384,np.float32) + tie_bias[:6],tie_bias[6] = 1.,2. + verify("route6",(1,1,1),1,[tie_logits,tie_bias], + [np.array([[6,0,1,2,3,4]],np.int32),np.full((1,6),.25,np.float32)]) code = rng.integers(0, 110, (7,256),dtype=np.uint8) scale = rng.integers(124,131,(7,8),dtype=np.uint8) shard = 180000000 diff --git a/om/gpu/dsv41/emit.om b/om/gpu/dsv41/emit.om index a550dde20..edb85630d 100644 --- a/om/gpu/dsv41/emit.om +++ b/om/gpu/dsv41/emit.om @@ -661,6 +661,10 @@ start 2 parameter 20 16 parameter 21 20 parameter 22 24 +literal 23 64 +inst 28 Z 20 23 Z 0 +put dsGuard 0 2 +inst 45 Z Z Z Z 0 madreg 23 18 21 15 madreg 23 23 20 Z literal 24 0xffffffc0 @@ -747,11 +751,16 @@ fop 30 28 28 31 fop 70 28 28 Z fop 30 29 29 28 mad 30 22 1 Z +literal 54 0 for k ulong 6 r = add 32 k ix = add 38 k raw = add 44 k inst 34 0 29 r Z 0x03f04000 +put dsGuard 0 1 +literal 54 1 +note After the first insertion shift the entire suffix, retaining the order of older ties. +inst 28 Z 54 24 Z 0 mad 51 r 1 Z mad 52 ix 1 Z mad 53 raw 1 Z diff --git a/seed/kflow/check-driver-abi.py b/seed/kflow/check-driver-abi.py new file mode 100644 index 000000000..dc66e7874 --- /dev/null +++ b/seed/kflow/check-driver-abi.py @@ -0,0 +1,34 @@ +"""Check 121-tk by-value parameter widths with the seeded packer, on the host.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +with tempfile.TemporaryDirectory() as directory: + cubin = Path(directory) / "probe.cubin" + subprocess.run([sys.argv[1], "121-tk", "probe", "seed/sm121/vecadd.bin", + cubin, "16", "0", "1", "2", "4", "8", "p8"], check=True) + data = cubin.read_bytes() + header = struct.unpack_from("