diff --git a/CHANGELOG.md b/CHANGELOG.md index 90ada6208d3..62804815891 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,18 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA ERNIE 5.5: the mHC pre step (a row's mixes, Sinkhorn and the collapse's RMSNorm) runs under the kernel contract with planted controls; serving is unchanged (#5301, thanks @Bizuayeu). + - Server: `--confidential` refuses existing Linux tracers and, where whole-process locking is supported, locks current and future process memory against swap or refuses startup; Darwin currently refuses because this locking is unavailable. - HIP, Qwen 3.5 and Nemotron on one GPU: long prompt chunks keep the next layer queued while they poll for a cancel, rather than draining the GPU at every layer; tokens unchanged, and a cancel still drains before the pass ends (#4887). - - - Qwen3.5 on CUDA: MTP admission charges the target tap ring once per stream, and native inference reserves only its 64-row recurrent log unless slide learning needs rollback snapshots, so the admission bound matches what the engine allocates (fixes #5134). Thanks to @tacosta for the report. - Metal: Inkling 2 with a DFlash 2 drafter now saves and restores the drafter's lane state in the prompt cache, so warm cache hits restore the drafter alongside the target (#5032, thanks @gilby). - - - `tensorfold info --hexagon FILE.gguf` checks a Gemma 4 E4B IT Q4_0 GGUF export against the Hexagon layout (architecture, text geometry and all 666 tensors) without the Qualcomm SDK; a match reports device execution as unverified, and a mismatch names the reason and exits with status 2 (#5475, thanks @tgerighty). - Qwen3.8-27B on Metal: Q and K head norm and RoPE run as one `q27_qk_norm_rope` dispatch instead of two head-norm launches, the barrier between them and two RoPE launches, on every chip and pass, keys-only prompt tails included; on an M5 Ultra every cache row and `qa` byte and the served replies match the previous path (#2955, part of #2940). @@ -185,6 +183,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA kernels: ERNIE 5.5's MultiMax on the head's fp32 logits (`tf_ernie55_multimax`, in a new `ernie5_5_head` image), each step rounded once in the vendor's order with nothing fused, under the kernel contract against the host's replay of those steps; nothing launches it yet, so served output is unchanged (#5202, part of #4926). Thanks to @Bizuayeu. +- CUDA kernels: ERNIE 5.5's DSA key lists (`tf_ernie55_window_merge`, in a new `ernie5_5_index` image): each row's indexer top-k picks, then its 128-position sliding window, with the row's count, as the sparse MLA reads them; under the kernel contract against the host's lists; nothing launches it yet, so served output is unchanged (#5211, part of #4926). + - Inkling 2 Mini on Metal, M5: a register-tiled dense BF16 kernel computes the same rows in the same order, with tokens unchanged; on an M5 Ultra a 2K-token prompt fills 5.7-7.3% faster (#5201, refs #5191). Thanks to @gilby. - Inkling 2 Mini on Metal: 3:1 GQA decode and verify read each key/value head once for its three query heads, and multi-stream attention batches across shared descriptors, with tokens unchanged; on an M3 Ultra four-stream decode is 12-14% faster and a 2K-token prompt 6% faster (#5206, refs #5191). Thanks to @gilby. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 532c8b06672..90f7f47dcee 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -735,6 +735,25 @@ once in the vendor's order with nothing fused. Each output must be the host's re TP=2 rank's half; gate 4 runs whole logits with whole ranges and power-of-two weights, where every step is exact (`ernie5_5-head`; two controls: each term's multiply and add fused into an fma, and the last term's square dropped). +CUDA also checks ERNIE 5.5's DSA key lists (`ernie5_5/index.cu`, `tf_ernie55_window_merge`): each row's indexer +picks (`topk_rows`' out, `picked` of them held to [0, k] and ending at the first -1), then its sliding window's +min(seq, 128) positions up to seq - 1, then -1, as vLLM-ERNIE's `merge_swa_topk` lays them out for the sparse MLA, +with the count of entries a row. The lists must be the host's (`ernie5_5/window.zig`) to the byte, and every row's +entries, rows told a negative count or one past k included, are rows below seq that ascend to seq - 1 with its picks +below the window, from a decode row at the first position and deep in context, across seq = 128 and seq = k + 128, +to prompt chunks and the 1M context's last rows (`ernie5_5-index`; two controls: every row taking all k picks, and +the window's oldest position dropped). + +CUDA also checks ERNIE 5.5's mHC pre side (`ernie5_5/mhc.cu`, `tf_ernie55_mhc_pre`): a row's 24 mixes of its 4 bf16 +streams with fn's float32 rows (a thread's 64 terms in one fma chain, then the warps' butterflies), times ERNIE's mix +RMS 1 / (sqrt(mean) + eps); pre, post (2 sigmoid) and comb (each row's softmax plus hc_eps, then 20 rounds of +Sinkhorn's column and row sums); then the collapse sum_s pre_s x_s, its RMSNorm from the unrounded sums' squares, and +the norm's weight times the bf16 collapse, rounded to bf16 once. Each output is held to its float64 bound alone, as +GLM's float32-weight finish is: the normed rows, post and comb (`ernie5_5/mhc.zig`), from rows near unit RMS, offset +by 8 and below 1e-6, where the mix RMS's eps outweighs sqrt(mean); gate 4 runs pre at 1/2 on one stream, where every +fp32 sum is exact (`ernie5_5-mhc`; two controls: the plain mix RMS 1 / sqrt(mean + eps), and comb's softmax over a +column). + CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index d31cd3f0cdf..b541bc7b192 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -138,6 +138,8 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("ernie5_5_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_head.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("hy4_route_rows_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/rows_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("hy4_engram_fp8", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/engram_fp8_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); + runner.addImport("ernie5_5_index_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_index.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); + runner.addImport("ernie5_5_mhc_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_mhc.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("gemma4_cuda", @import("gemma4_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); runner.addImport("spark25", @import("spark25.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); // the served family and its engine, for the dots runner diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 404588a95d3..50114fd6227 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -170,6 +170,8 @@ pub const kernels = [_]Kernel{ .{ .name = "hy4_route", .src = "hy4_flash/route", .flags = glue }, .{ .name = "hy4_rows", .src = "hy4_flash/rows", .flags = &.{"-O3"} }, .{ .name = "hy4_dfly2_glue", .src = "hy4_flash/dfly2_glue", .flags = glue }, + .{ .name = "ernie5_5_index", .src = "ernie5_5/index", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's DSA key lists + .{ .name = "ernie5_5_mhc", .src = "ernie5_5/mhc", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's mHC pre side .{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE) .{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention .{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention diff --git a/zig/kernels/cuda/ernie5_5/index.cu b/zig/kernels/cuda/ernie5_5/index.cu new file mode 100644 index 00000000000..300359b139f --- /dev/null +++ b/zig/kernels/cuda/ernie5_5/index.cu @@ -0,0 +1,55 @@ +// ERNIE 5.5's sparse-attention key lists: each row's indexer picks, then its sliding window, for the sparse MLA. + +namespace ernie55i { + +enum Fault { none, all_picks, short_window }; + +// Row blockIdx.x at pos[0] + row: picks to picked[row] in [0, k] and the first -1, the window to seq - 1, -1, a count. +template +__device__ __forceinline__ void merge(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, int* __restrict__ cnt, int k, + int window, long long w) { + __shared__ int valid; + const long long row = blockIdx.x, seq = static_cast(pos[0]) + row + 1; + const int p = picked[row]; + const long long held = F == all_picks ? k : p < 0 ? 0 : p > k ? k : p; + const long long sw = (seq < window ? seq : window) - (F == short_window ? 1 : 0), first = seq - sw; + const int* in = picks + row * k; + if (threadIdx.x == 0) valid = static_cast(held); + __syncthreads(); + // a negative pick inside the held count ends the picks (the control keeps every pick it is told) + if (F != all_picks) + for (long long c = threadIdx.x; c < held; c += blockDim.x) + if (in[c] < 0) atomicMin(&valid, static_cast(c)); + __syncthreads(); + const long long n = valid; + int* out = tok + row * w; + for (long long c = threadIdx.x; c < w; c += blockDim.x) + out[c] = c < n ? in[c] : c < n + sw ? static_cast(first + (c - n)) : -1; + if (threadIdx.x == 0) cnt[row] = static_cast(n + sw); +} + +} // namespace ernie55i + +// One row a block of 256 threads; lists w wide (at least k + window). +extern "C" __global__ void __launch_bounds__(256) + tf_ernie55_window_merge(const int* __restrict__ picks, const int* __restrict__ picked, const int* __restrict__ pos, + int* __restrict__ tok, int* __restrict__ cnt, int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} + +// The contract's planted control: every row takes all k picks, its -1s past picked among them. +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_window_merge_all_picks(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, int* __restrict__ cnt, + int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} + +// The contract's planted control: the window's oldest position dropped. +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_window_merge_short_window(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, + int* __restrict__ cnt, int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} diff --git a/zig/kernels/cuda/ernie5_5/mhc.cu b/zig/kernels/cuda/ernie5_5/mhc.cu new file mode 100644 index 00000000000..4efbc0883ee --- /dev/null +++ b/zig/kernels/cuda/ernie5_5/mhc.cu @@ -0,0 +1,179 @@ +// ERNIE 5.5's mHC pre side: a row's 24 mixes over its 4 streams, Sinkhorn, then the streams' collapse and its RMSNorm. + +#include + +#include "common/reduce.cuh" + +namespace ernie55m { + +using tf_common::warp_sum; + +constexpr int D = 4096, S = 4, T = 256, M = 24; +constexpr unsigned all = 0xffffffffu; + +enum Fault { none, plain_rms, column_softmax }; + +// 1 / (1 + e^-v), each step rounded once. +__device__ __forceinline__ float sigmoid(float v) { return __fdiv_rn(1.0f, __fadd_rn(1.0f, expf(-v))); } + +// The 4x4 sums, lane & 15 = 4i + j: a row's over j (xor 2, then 1), a column's over i (xor 8, then 4). +__device__ __forceinline__ float row4(float v) { + v = __fadd_rn(v, __shfl_xor_sync(all, v, 2)); + return __fadd_rn(v, __shfl_xor_sync(all, v, 1)); +} +__device__ __forceinline__ float col4(float v) { + v = __fadd_rn(v, __shfl_xor_sync(all, v, 8)); + return __fadd_rn(v, __shfl_xor_sync(all, v, 4)); +} + +// Row blockIdx.x: thread t holds k = c 2048 + 8t + j (c, j < 8; k = 4096 s + h) of x and of each fn row. +template +__device__ __forceinline__ void pre(const __nv_bfloat16* __restrict__ x, long long xs, const float* __restrict__ fn, + const float* __restrict__ scale, const float* __restrict__ base, + const __nv_bfloat16* __restrict__ w, float* __restrict__ post, + float* __restrict__ comb, __nv_bfloat16* __restrict__ out, long long os, + float rms_eps, float hc_eps, float norm_eps, int iters) { + __shared__ float part[M + 1][T / 32]; + __shared__ float mix[M + 1]; + __shared__ float pmix[S]; + __shared__ float sq[T / 32]; + const long long row = blockIdx.x; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const __nv_bfloat16* xr = x + row * xs; + // each mix, then the squares (m = 24): one fma chain over c, then j; x's 16 bytes read again for each + for (int m = 0; m <= M; ++m) { + const float* f = fn + static_cast(m < M ? m : 0) * (S * D) + t * 8; + float acc = 0.0f; +#pragma unroll 1 + for (int c = 0; c < 8; ++c) { + const uint4 xv = __ldg(reinterpret_cast(xr + c * 2048 + t * 8)); + const __nv_bfloat16* h = reinterpret_cast(&xv); + if (m < M) { + const float4 lo = __ldg(reinterpret_cast(f + c * 2048)); + const float4 hi = __ldg(reinterpret_cast(f + c * 2048 + 4)); + const float fv[8] = {lo.x, lo.y, lo.z, lo.w, hi.x, hi.y, hi.z, hi.w}; +#pragma unroll + for (int j = 0; j < 8; ++j) acc = __fmaf_rn(__bfloat162float(h[j]), fv[j], acc); + } else { +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float v = __bfloat162float(h[j]); + acc = __fmaf_rn(v, v, acc); + } + } + } + acc = warp_sum(acc); + if (lane == 0) part[m][warp] = acc; + } + __syncthreads(); + if (t <= M) { + float v = part[t][0]; + for (int i = 1; i < T / 32; ++i) v = __fadd_rn(v, part[t][i]); + mix[t] = v; + } + __syncthreads(); + if (warp == 0) { + const float mean = __fmul_rn(mix[M], 1.0f / (S * D)); // a power of two: exact + // ERNIE's mix RMS, 1 / (sqrt(mean) + eps); the control takes the plain 1 / sqrt(mean + eps) + const float r = F == plain_rms ? __fdiv_rn(1.0f, __fsqrt_rn(__fadd_rn(mean, rms_eps))) + : __fdiv_rn(1.0f, __fadd_rn(__fsqrt_rn(mean), rms_eps)); + const int idx = lane & 15, k = lane & 3; + if (lane < S) { + pmix[lane] = __fadd_rn(sigmoid(__fmaf_rn(__fmul_rn(mix[k], r), scale[0], base[k])), hc_eps); + const float sp = sigmoid(__fmaf_rn(__fmul_rn(mix[S + k], r), scale[1], base[S + k])); + post[row * S + lane] = __fadd_rn(sp, sp); + } + const float cl = __fmaf_rn(__fmul_rn(mix[2 * S + idx], r), scale[2], base[2 * S + idx]); + // softmax over j (a row); the control takes it over i (a column) + float cmax; + if (F == column_softmax) { + cmax = fmaxf(cl, __shfl_xor_sync(all, cl, 8)); + cmax = fmaxf(cmax, __shfl_xor_sync(all, cmax, 4)); + } else { + cmax = fmaxf(cl, __shfl_xor_sync(all, cl, 2)); + cmax = fmaxf(cmax, __shfl_xor_sync(all, cmax, 1)); + } + const float e = expf(__fsub_rn(cl, cmax)); + float cm = __fadd_rn(__fdiv_rn(e, F == column_softmax ? col4(e) : row4(e)), hc_eps); + cm = __fdiv_rn(cm, __fadd_rn(col4(cm), hc_eps)); + for (int it = 1; it < iters; ++it) { + cm = __fdiv_rn(cm, __fadd_rn(row4(cm), hc_eps)); + cm = __fdiv_rn(cm, __fadd_rn(col4(cm), hc_eps)); + } + if (lane < 16) comb[row * 16 + lane] = cm; + } + __syncthreads(); + // thread t's outputs h = 2048 half + 8t + j: sum_s pre_s x_s from stream 0, squares of the unrounded sums + uint4 xu[8]; +#pragma unroll + for (int c = 0; c < 8; ++c) xu[c] = __ldg(reinterpret_cast(xr + c * 2048 + t * 8)); + float o[2][8]; + float ss = 0.0f; +#pragma unroll + for (int half = 0; half < 2; ++half) +#pragma unroll + for (int j = 0; j < 8; ++j) { + float v = 0.0f; +#pragma unroll + for (int s = 0; s < S; ++s) { + const float xv = __bfloat162float(reinterpret_cast(&xu[2 * s + half])[j]); + v = s == 0 ? __fmul_rn(pmix[0], xv) : __fmaf_rn(pmix[s], xv, v); + } + o[half][j] = v; + ss = __fmaf_rn(v, v, ss); + } + ss = warp_sum(ss); + if (lane == 0) sq[warp] = ss; + __syncthreads(); + float tot = sq[0]; + for (int i = 1; i < T / 32; ++i) tot = __fadd_rn(tot, sq[i]); + const float r2 = __fdiv_rn(1.0f, __fsqrt_rn(__fadd_rn(__fmul_rn(tot, 1.0f / D), norm_eps))); +#pragma unroll + for (int half = 0; half < 2; ++half) { + uint4 ou; + __nv_bfloat16* oh = reinterpret_cast<__nv_bfloat16*>(&ou); + const uint4 wu = __ldg(reinterpret_cast(w + half * 2048 + t * 8)); + const __nv_bfloat16* wh = reinterpret_cast(&wu); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float b = __bfloat162float(__float2bfloat16_rn(o[half][j])); + oh[j] = __float2bfloat16_rn(__fmul_rn(__fmul_rn(b, r2), __bfloat162float(wh[j]))); + } + *reinterpret_cast(out + row * os + half * 2048 + t * 8) = ou; + } +} + +} // namespace ernie55m + +// Rows of 4 bf16 streams xs apart, fn [24][16384] and the norm's w: post [4], comb [16] (fp32), bf16 rows os apart. +extern "C" __global__ void __launch_bounds__(256) + tf_ernie55_mhc_pre(const __nv_bfloat16* __restrict__ x, long long xs, const float* __restrict__ fn, + const float* __restrict__ scale, const float* __restrict__ base, + const __nv_bfloat16* __restrict__ w, float* __restrict__ post, float* __restrict__ comb, + __nv_bfloat16* __restrict__ out, long long os, float rms_eps, float hc_eps, float norm_eps, + int iters) { + ernie55m::pre(x, xs, fn, scale, base, w, post, comb, out, os, rms_eps, hc_eps, norm_eps, iters); +} + +// The contract's planted control: the plain mix RMS, 1 / sqrt(mean + eps), in place of 1 / (sqrt(mean) + eps). +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_mhc_pre_plain_rms(const __nv_bfloat16* __restrict__ x, long long xs, const float* __restrict__ fn, + const float* __restrict__ scale, const float* __restrict__ base, + const __nv_bfloat16* __restrict__ w, float* __restrict__ post, + float* __restrict__ comb, __nv_bfloat16* __restrict__ out, long long os, + float rms_eps, float hc_eps, float norm_eps, int iters) { + ernie55m::pre(x, xs, fn, scale, base, w, post, comb, out, os, rms_eps, hc_eps, norm_eps, + iters); +} + +// The contract's planted control: comb's softmax over a column in place of a row. +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_mhc_pre_column_softmax(const __nv_bfloat16* __restrict__ x, long long xs, + const float* __restrict__ fn, const float* __restrict__ scale, + const float* __restrict__ base, const __nv_bfloat16* __restrict__ w, + float* __restrict__ post, float* __restrict__ comb, + __nv_bfloat16* __restrict__ out, long long os, float rms_eps, float hc_eps, + float norm_eps, int iters) { + ernie55m::pre(x, xs, fn, scale, base, w, post, comb, out, os, rms_eps, hc_eps, + norm_eps, iters); +} diff --git a/zig/src/core/contract/ernie5_5_records.zig b/zig/src/core/contract/ernie5_5_records.zig index ac96730c856..8a078013148 100644 --- a/zig/src/core/contract/ernie5_5_records.zig +++ b/zig/src/core/contract/ernie5_5_records.zig @@ -1,9 +1,11 @@ -//! ERNIE 5.5's CUDA launches (ernie5_5/head.cu): MultiMax on the head's fp32 logits. +//! ERNIE 5.5 CUDA launch records: MultiMax, DSA key lists and the mHC pre side. const registry = @import("registry.zig"); /// nvcc 13.0's usage (nvcc -cubin per SM at the image's flags), the compiler of the release fatbins. pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "ernie5_5 head tf_ernie55_multimax", .symbol = "tf_ernie55_multimax", .image = "ernie5_5_head", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "ernie5_5 index tf_ernie55_window_merge", .symbol = "tf_ernie55_window_merge", .image = "ernie5_5_index", .threads = 256 }, .usage = .{ .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 } } }, + .{ .launch = .{ .name = "ernie5_5 mhc tf_ernie55_mhc_pre", .symbol = "tf_ernie55_mhc_pre", .image = "ernie5_5_mhc", .threads = 256 }, .usage = .{ .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 } } }, }; test "ERNIE 5.5 CUDA: every launch is in the live registry and fits every SM" { diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 13446824246..f4b293c7ab5 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -122,6 +122,8 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const ernie5_5_head: []const u8 = if (available) &Blob("fatbin_ernie5_5_head").bytes else &.{}; +pub const ernie5_5_index: []const u8 = if (available) &Blob("fatbin_ernie5_5_index").bytes else &.{}; +pub const ernie5_5_mhc: []const u8 = if (available) &Blob("fatbin_ernie5_5_mhc").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; pub const inkling2_dspark: []const u8 = if (available) &Blob("fatbin_inkling2_dspark").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; diff --git a/zig/src/families/ernie5_5/cuda_index.zig b/zig/src/families/ernie5_5/cuda_index.zig new file mode 100644 index 00000000000..58ded76cfdc --- /dev/null +++ b/zig/src/families/ernie5_5/cuda_index.zig @@ -0,0 +1,37 @@ +//! ERNIE 5.5's indexer kernels (ernie5_5/index.cu): the sparse MLA's key lists, each row's picks then its window. +const cuda = @import("cuda"); +pub const window = @import("window.zig"); + +pub const threads = 256; + +pub const Index = struct { + mod: cuda.Module, + merge_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Index { + var mod = try cuda.Module.load(d, cuda.kernels.ernie5_5_index); + errdefer mod.unload(); + return .{ .mod = mod, .merge_fn = try mod.function("tf_ernie55_window_merge") }; + } + + pub fn unload(x: *Index) void { + x.mod.unload(); + } + + /// topk_rows' out and picked, pos (row r at pos[0] + r) into tok i32 [rows, w] and cnt i32 [rows], as window.merge. + pub fn merge(x: *const Index, s: cuda.Stream, picks: u64, picked: u64, pos: u64, tok: u64, cnt: u64, sh: window.Shape) !void { + try launch(x.merge_fn, s, picks, picked, pos, tok, cnt, sh); + } +}; + +/// `f`, tf_ernie55_window_merge or an entry of the image with its arguments, one row a block. +pub fn launch(f: cuda.Function, s: cuda.Stream, picks: u64, picked: u64, pos: u64, tok: u64, cnt: u64, sh: window.Shape) !void { + try window.check(sh); + if (sh.rows == 0) return; + var a: cuda.Args = .{}; + inline for (.{ picks, picked, pos, tok, cnt }) |v| a.add(v); + a.add(@as(c_int, @intCast(sh.k))); + a.add(@as(c_int, @intCast(sh.window))); + a.add(@as(i64, @intCast(sh.w))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.rows) }, .block = .{ .x = threads } }, s, &a); +} diff --git a/zig/src/families/ernie5_5/cuda_mhc.zig b/zig/src/families/ernie5_5/cuda_mhc.zig new file mode 100644 index 00000000000..27fd89c0ac7 --- /dev/null +++ b/zig/src/families/ernie5_5/cuda_mhc.zig @@ -0,0 +1,39 @@ +//! ERNIE 5.5's mHC kernels (ernie5_5/mhc.cu): the pre side, a row's mixes, Sinkhorn, the collapse and its RMSNorm. +const cuda = @import("cuda"); +pub const mhc = @import("mhc.zig"); + +pub const threads = 256; + +pub const Mhc = struct { + mod: cuda.Module, + pre_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Mhc { + var mod = try cuda.Module.load(d, cuda.kernels.ernie5_5_mhc); + errdefer mod.unload(); + return .{ .mod = mod, .pre_fn = try mod.function("tf_ernie55_mhc_pre") }; + } + + pub fn unload(x: *Mhc) void { + x.mod.unload(); + } + + /// bf16 rows of 4 streams, fn f32 [24][16384], scale [3], base [24], the norm's bf16 w: post, comb, bf16 rows. + pub fn pre(x: *const Mhc, s: cuda.Stream, rows: u64, fnw: u64, scale: u64, base: u64, w: u64, post: u64, comb: u64, out: u64, sh: mhc.Shape, p: mhc.Params) !void { + try launch(x.pre_fn, s, rows, fnw, scale, base, w, post, comb, out, sh, p); + } +}; + +/// `f`, tf_ernie55_mhc_pre or an entry of the image with its arguments, one row a block. +pub fn launch(f: cuda.Function, s: cuda.Stream, rows: u64, fnw: u64, scale: u64, base: u64, w: u64, post: u64, comb: u64, out: u64, sh: mhc.Shape, p: mhc.Params) !void { + try mhc.check(sh, p); + if (sh.rows == 0) return; + var a: cuda.Args = .{}; + a.add(rows); + a.add(@as(i64, @intCast(sh.xs))); + inline for (.{ fnw, scale, base, w, post, comb, out }) |v| a.add(v); + a.add(@as(i64, @intCast(sh.os))); + inline for (.{ p.rms_eps, p.hc_eps, p.norm_eps }) |v| a.add(v); + a.add(@as(c_int, @intCast(p.iters))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.rows) }, .block = .{ .x = threads } }, s, &a); +} diff --git a/zig/src/families/ernie5_5/host_test.zig b/zig/src/families/ernie5_5/host_test.zig index 87eb8801859..a94ad7c0240 100644 --- a/zig/src/families/ernie5_5/host_test.zig +++ b/zig/src/families/ernie5_5/host_test.zig @@ -1,4 +1,4 @@ -//! Host-only ERNIE 5.5 family package: config, weight map, layer plan, chat encoding, tokenizer, MultiMax. No GPU. +//! Host-only ERNIE 5.5 tests: config, names, prompts, tokenizer, MultiMax, key lists and mHC. No GPU. test { _ = @import("config.zig"); _ = @import("config_test.zig"); @@ -9,4 +9,6 @@ test { _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); _ = @import("multimax_test.zig"); + _ = @import("window_test.zig"); + _ = @import("mhc_test.zig"); } diff --git a/zig/src/families/ernie5_5/mhc.zig b/zig/src/families/ernie5_5/mhc.zig new file mode 100644 index 00000000000..b10e507c8ce --- /dev/null +++ b/zig/src/families/ernie5_5/mhc.zig @@ -0,0 +1,100 @@ +//! ERNIE 5.5's mHC pre side (vLLM-ERNIE's mhc_pre, mix RMS 1 / (sqrt(mean) + eps)): mixes, Sinkhorn, collapse, norm. +const std = @import("std"); + +/// hc_mult streams of the hidden size, the (2 + streams) streams mixes, and a row's 4 streams side by side. +pub const streams = 4; +pub const width = 4096; +pub const mixes = (2 + streams) * streams; +pub const wide = streams * width; + +/// rms_norm_eps (the mix RMS and the norm), hc_eps (pre's floor and Sinkhorn's) and hc_sinkhorn_iters. +pub const Params = struct { rms_eps: f32, hc_eps: f32, norm_eps: f32, iters: u32 }; + +/// rows rows of 4 streams xs apart, outputs os apart: 16-byte rows, as the kernel loads them. +pub const Shape = struct { rows: usize, xs: usize = wide, os: usize = width }; + +/// Rows that fit the grid, rows at least as wide as a row and 8-element aligned, at least one Sinkhorn round. +pub fn check(sh: Shape, p: Params) error{MhcShape}!void { + if (sh.xs < wide or sh.os < width or sh.xs % 8 != 0 or sh.os % 8 != 0) return error.MhcShape; + if (sh.rows > std.math.maxInt(i32) or p.iters == 0 or p.iters > std.math.maxInt(i32)) return error.MhcShape; +} + +/// A row's outputs: post, comb, and the normed collapse before its bf16 rounding. +pub const Row = struct { post: [streams]f64, comb: [streams * streams]f64, out: [width]f64 }; + +pub fn sigmoid(v: f64) f64 { + return 1 / (1 + @exp(-v)); +} + +/// ERNIE's mix RMS of the squares' sum over a row's 4 streams. +pub fn mixRms(ss: f64, eps: f64) f64 { + return 1 / (@sqrt(ss / wide) + eps); +} + +/// The 24 mixes of row x (4 streams of bf16 values) with fn [24][wide], times mixRms; t: scratch, sums by `sum.of`. +pub fn mixRow(x: *const [wide]f64, fnw: []const f32, p: Params, sum: anytype, t: *[wide]f64, m: *[mixes]f64) void { + for (t, x) |*o, v| o.* = v * v; + const r = mixRms(sum.of(t), p.rms_eps); + for (m, 0..) |*o, i| { + for (t, x, fnw[i * wide ..][0..wide]) |*q, v, f| q.* = v * f; + o.* = sum.of(t) * r; + } +} + +/// A row: post 2 sigmoid(m s1 + b), comb Sinkhorn of the rows' softmax, out the collapse's RMSNorm times w (unrounded). +pub fn pre(x: *const [wide]f64, fnw: []const f32, scale: *const [3]f32, base: *const [mixes]f32, w: *const [width]f64, p: Params, sum: anytype, t: *[wide]f64, r: *Row) void { + var m: [mixes]f64 = undefined; + mixRow(x, fnw, p, sum, t, &m); + var pw: [streams]f64 = undefined; + for (0..streams) |k| { + pw[k] = sigmoid(m[k] * scale[0] + base[k]) + p.hc_eps; + r.post[k] = 2 * sigmoid(m[streams + k] * scale[1] + base[streams + k]); + } + sinkhorn(m[2 * streams ..][0 .. streams * streams], scale[2], base[2 * streams ..][0 .. streams * streams], p, &r.comb); + const c = t[0..width]; + for (c, 0..) |*o, h| { + var terms: [streams]f64 = undefined; + for (&terms, pw, 0..) |*q, ps, s| q.* = ps * x[s * width + h]; + o.* = sum.of(&terms); + } + const sq = t[width .. 2 * width]; + for (sq, c) |*q, v| q.* = v * v; + const rn = 1 / @sqrt(sum.of(sq) / width + p.norm_eps); + for (&r.out, c, w) |*o, v, g| o.* = v * rn * g; +} + +/// comb from its 16 mixes: each row's softmax plus eps, its columns' normalization, then iters - 1 rows' and columns'. +pub fn sinkhorn(m: *const [streams * streams]f64, s2: f32, base: *const [streams * streams]f32, p: Params, cm: *[streams * streams]f64) void { + for (0..streams) |i| { + var cl: [streams]f64 = undefined; + var top = -std.math.inf(f64); + for (&cl, 0..) |*v, j| { + v.* = m[streams * i + j] * s2 + base[streams * i + j]; + top = @max(top, v.*); + } + var e: [streams]f64 = undefined; + for (&e, cl) |*o, v| o.* = @exp(v - top); + const tot = (e[0] + e[2]) + (e[1] + e[3]); + for (e, 0..) |v, j| cm[streams * i + j] = v / tot + p.hc_eps; + } + normalize(cm, p.hc_eps, .col); + for (1..p.iters) |_| { + normalize(cm, p.hc_eps, .row); + normalize(cm, p.hc_eps, .col); + } +} + +fn normalize(cm: *[streams * streams]f64, eps: f64, by: enum { row, col }) void { + var tot: [streams]f64 = @splat(0); + for (cm, 0..) |v, i| tot[if (by == .row) i / streams else i % streams] += v; + for (cm, 0..) |*v, i| v.* /= tot[if (by == .row) i / streams else i % streams] + eps; +} + +/// Float64 sums in order. +pub const exact = struct { + pub fn of(_: @This(), t: []const f64) f64 { + var s: f64 = 0; + for (t) |v| s += v; + return s; + } +}{}; diff --git a/zig/src/families/ernie5_5/mhc_test.zig b/zig/src/families/ernie5_5/mhc_test.zig new file mode 100644 index 00000000000..d0e6dcb43ec --- /dev/null +++ b/zig/src/families/ernie5_5/mhc_test.zig @@ -0,0 +1,98 @@ +//! mhc.zig against vLLM's mhc_pre_torch with ERNIE's mix RMS and the fused RMSNorm, written from it; its refusals. +const std = @import("std"); +const h = @import("mhc.zig"); + +const p: h.Params = .{ .rms_eps = 1e-6, .hc_eps = 1e-6, .norm_eps = 1e-6, .iters = 20 }; + +/// mhc_pre_torch: mixes = x fn^T / (sqrt(mean x^2) + eps), pre, post, comb (softmax, then dim -2, dim -1 in turn). +fn vendor(x: []const f64, fnw: []const f32, scale: [3]f32, base: [h.mixes]f32, w: []const f64, out: *h.Row) void { + var ss: f64 = 0; + for (x) |v| ss += v * v; + var m: [h.mixes]f64 = @splat(0); + for (&m, 0..) |*o, i| { + for (x, fnw[i * h.wide ..][0..h.wide]) |v, f| o.* += v * f; + o.* /= @sqrt(ss / h.wide) + p.rms_eps; + } + var pw: [4]f64 = undefined; + for (0..4) |k| { + pw[k] = 1 / (1 + @exp(-(m[k] * scale[0] + base[k]))) + p.hc_eps; + out.post[k] = 1 / (1 + @exp(-(m[4 + k] * scale[1] + base[4 + k]))) * 2; + } + var c: [4][4]f64 = undefined; + for (0..4) |i| { + var tot: f64 = 0; + for (0..4) |j| { + c[i][j] = @exp(m[8 + 4 * i + j] * scale[2] + base[8 + 4 * i + j]); + tot += c[i][j]; + } + for (0..4) |j| c[i][j] = c[i][j] / tot + p.hc_eps; + } + for (0..p.iters) |it| { + if (it > 0) for (0..4) |i| { + const tot = c[i][0] + c[i][1] + c[i][2] + c[i][3]; + for (0..4) |j| c[i][j] /= tot + p.hc_eps; + }; + for (0..4) |j| { + const tot = c[0][j] + c[1][j] + c[2][j] + c[3][j]; + for (0..4) |i| c[i][j] /= tot + p.hc_eps; + } + } + for (0..4) |i| for (0..4) |j| { + out.comb[4 * i + j] = c[i][j]; + }; + var li: [h.width]f64 = @splat(0); + var s2: f64 = 0; + for (&li, 0..) |*o, d| { + for (0..4) |s| o.* += pw[s] * x[s * h.width + d]; + s2 += o.* * o.*; + } + for (&out.out, li, w) |*o, v, g| o.* = v / @sqrt(s2 / h.width + p.norm_eps) * g; +} + +test "a row is vLLM's mhc_pre with ERNIE's mix RMS and the norm, at a typical scale and at a tiny one" { + const a = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(0x6d6863); + const rng = prng.random(); + const fnw = try a.alloc(f32, h.mixes * h.wide); + defer a.free(fnw); + for (fnw) |*f| f.* = (rng.float(f32) * 2 - 1) * 0.02; + const scale = [3]f32{ 0.7, 1.3, 2.1 }; + var base: [h.mixes]f32 = undefined; + for (&base) |*b| b.* = rng.float(f32) * 2 - 1; + const x = try a.create([h.wide]f64); + defer a.destroy(x); + const t = try a.create([h.wide]f64); + defer a.destroy(t); + var w: [h.width]f64 = undefined; + for (&w) |*g| g.* = rng.float(f64) * 2; + // a row near unit RMS, then one of values below 1e-6: there the mix RMS's eps outweighs sqrt(mean) + for ([_]f64{ 1, 1e-6 }) |mag| { + for (x) |*v| v.* = (rng.float(f64) * 2 - 1) * mag; + var got: h.Row = undefined; + var want: h.Row = undefined; + h.pre(x, fnw, &scale, &base, &w, p, h.exact, t, &got); + vendor(x, fnw, scale, base, &w, &want); + for (got.post, want.post) |g, v| try std.testing.expectApproxEqAbs(v, g, 1e-12); + for (got.comb, want.comb) |g, v| try std.testing.expectApproxEqAbs(v, g, 1e-12); + for (got.out, want.out) |g, v| try std.testing.expectApproxEqAbs(v, g, 1e-10 * (1 + @abs(v))); + var cols: [4]f64 = @splat(0); + for (got.comb, 0..) |v, i| cols[i % 4] += v; + for (cols) |v| try std.testing.expectApproxEqAbs(1, v, 1e-5); + } +} + +test "the mix RMS is 1 / (sqrt(mean) + eps), not the plain 1 / sqrt(mean + eps)" { + try std.testing.expectEqual(1 / (@sqrt(@as(f64, 4)) + 0.5), h.mixRms(4 * h.wide, 0.5)); + try std.testing.expect(h.mixRms(1e-12 * h.wide, 1e-6) > 100.0 / @sqrt(1e-12 + 1e-6)); +} + +test "check refuses narrow or unaligned rows, more rows than the grid and no Sinkhorn round" { + try h.check(.{ .rows = 1 }, p); + try h.check(.{ .rows = 64, .xs = h.wide + 8, .os = h.width + 8 }, p); + try std.testing.expectError(error.MhcShape, h.check(.{ .rows = 1, .xs = h.wide - 8 }, p)); + try std.testing.expectError(error.MhcShape, h.check(.{ .rows = 1, .os = h.width + 4 }, p)); + try std.testing.expectError(error.MhcShape, h.check(.{ .rows = @as(usize, std.math.maxInt(i32)) + 1 }, p)); + var none = p; + none.iters = 0; + try std.testing.expectError(error.MhcShape, h.check(.{ .rows = 1 }, none)); +} diff --git a/zig/src/families/ernie5_5/window.zig b/zig/src/families/ernie5_5/window.zig new file mode 100644 index 00000000000..92554c1b0f5 --- /dev/null +++ b/zig/src/families/ernie5_5/window.zig @@ -0,0 +1,33 @@ +//! ERNIE 5.5's sparse-attention key lists: each row's indexer picks, then its sliding window (vLLM's merge_swa_topk). +const std = @import("std"); + +/// The released config's sliding_window and index_topk. +pub const window = 128; +pub const topk = 2048; + +/// rows rows, row r at position pos0 + r; k picks a row in, lists w wide out (at least k + window). +pub const Shape = struct { rows: usize, k: usize, w: usize, window: usize = window }; + +/// Sizes the kernel holds in i32, and lists wide enough for every pick and the window. +pub fn check(sh: Shape) error{WindowShape}!void { + const most = std.math.maxInt(i32); + if (sh.window == 0 or sh.k > most or sh.window > most or sh.w < sh.k + sh.window or sh.rows > most / sh.w) + return error.WindowShape; +} + +/// Row r: picks to picked[r] (in [0, k]) and the first negative, seq - min(seq, window) .. seq - 1, -1, its count. +pub fn merge(sh: Shape, picks: []const i32, picked: []const i32, pos0: i64, tok: []i32, cnt: []i32) void { + for (0..sh.rows) |r| { + const seq = pos0 + @as(i64, @intCast(r)) + 1; + const held: usize = @intCast(std.math.clamp(picked[r], 0, @as(i32, @intCast(sh.k)))); + const n = for (picks[r * sh.k ..][0..held], 0..) |v, i| { + if (v < 0) break i; // a negative pick inside the count ends the picks + } else held; + const sw: usize = @intCast(@min(seq, @as(i64, @intCast(sh.window)))); + const row = tok[r * sh.w ..][0..sh.w]; + @memcpy(row[0..n], picks[r * sh.k ..][0..n]); + for (row[n..][0..sw], 0..) |*t, i| t.* = @intCast(seq - @as(i64, @intCast(sw)) + @as(i64, @intCast(i))); + @memset(row[n + sw ..], -1); + cnt[r] = @intCast(n + sw); + } +} diff --git a/zig/src/families/ernie5_5/window_test.zig b/zig/src/families/ernie5_5/window_test.zig new file mode 100644 index 00000000000..7d669627b54 --- /dev/null +++ b/zig/src/families/ernie5_5/window_test.zig @@ -0,0 +1,99 @@ +//! window.zig against vLLM-ERNIE's merge_swa_topk, and its refusals. +const std = @import("std"); +const win = @import("window.zig"); + +/// merge_swa_topk as the vendor's Triton kernel writes a column: its n from the position, not from picked. +fn vendor(topk: []const i32, k: usize, window: usize, seq: i64, col: usize) i32 { + const n: i64 = @min(@max(seq - @as(i64, @intCast(window)), 0), @as(i64, @intCast(k))); + const sw: i64 = @min(seq, @as(i64, @intCast(window))); + const c: i64 = @intCast(col); + if (c < n) return topk[col]; + return if (c < n + sw) @intCast(seq - sw + c - n) else -1; +} + +fn run(a: std.mem.Allocator, sh: win.Shape, pos0: i64, picks: []const i32, picked: []const i32) !struct { []i32, []i32 } { + const tok = try a.alloc(i32, sh.rows * sh.w); + const cnt = try a.alloc(i32, sh.rows); + win.merge(sh, picks, picked, pos0, tok, cnt); + return .{ tok, cnt }; +} + +test "with picked as top-k gives it, each list is the vendor's, across the window's and the picks' edges" { + const a = std.testing.allocator; + inline for (.{ .{ 4, 3, 9 }, .{ win.topk, win.window, win.topk + win.window + 64 } }) |g| { + const k: usize = g[0]; + const sh: win.Shape = .{ .rows = 2 * (k + g[1]) + 3, .k = k, .w = g[2], .window = g[1] }; + const picks = try a.alloc(i32, sh.rows * k); + defer a.free(picks); + const picked = try a.alloc(i32, sh.rows); + defer a.free(picked); + for (0..sh.rows) |r| { + const seq: i64 = @intCast(r + 1); + const n: usize = @intCast(@min(@max(seq - @as(i64, @intCast(sh.window)), 0), @as(i64, @intCast(k)))); + picked[r] = @intCast(n); + // n ascending picks spread below seq - window, as topk_rows leaves them, then -1 + const older = seq - @as(i64, @intCast(sh.window)); + for (picks[r * k ..][0..k], 0..) |*p, i| p.* = if (i < n) @intCast(@divFloor(@as(i64, @intCast(i)) * older, @as(i64, @intCast(n)))) else -1; + } + const tok, const cnt = try run(a, sh, 0, picks, picked); + defer a.free(tok); + defer a.free(cnt); + for (0..sh.rows) |r| { + const seq: i64 = @intCast(r + 1); + var valid: i32 = 0; + for (0..sh.w) |c| { + const want = vendor(picks[r * k ..][0..k], k, sh.window, seq, c); + try std.testing.expectEqual(want, tok[r * sh.w + c]); + valid += @intFromBool(want != -1); + } + try std.testing.expectEqual(valid, cnt[r]); + try std.testing.expectEqual(@as(i32, @intCast(seq - 1)), tok[r * sh.w + @as(usize, @intCast(cnt[r])) - 1]); + } + } +} + +test "rows from a later position: the window ends at each row's own position" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 3, .k = 2, .w = 6, .window = 3 }; + const picks = [_]i32{ 5, 90, 7, 91, 8, 92 }; + const tok, const cnt = try run(a, sh, 99, &picks, &.{ 2, 2, 2 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 5, 90, 97, 98, 99, -1, 7, 91, 98, 99, 100, -1, 8, 92, 99, 100, 101, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 5, 5, 5 }, cnt); +} + +test "picked is held to [0, k]: a negative one lists the window alone, one past k lists k picks" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 2, .k = 2, .w = 5, .window = 2 }; + const tok, const cnt = try run(a, sh, 9, &.{ 1, 2, 3, 4 }, &.{ -3, 7 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 8, 9, -1, -1, -1, 3, 4, 9, 10, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 2, 4 }, cnt); +} + +test "a count past the picks' nonnegative prefix stops at the first -1: no -1 before a list's count" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 2, .k = 2, .w = 5, .window = 3 }; + // picks [5, -1] told 7 at seq 10 (the review's case), then a row whose first pick is -1 + const tok, const cnt = try run(a, sh, 9, &.{ 5, -1, -1, 4 }, &.{ 7, 2 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 5, 7, 8, 9, -1, 8, 9, 10, -1, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 4, 3 }, cnt); + for (0..sh.rows) |r| for (tok[r * sh.w ..][0..@intCast(cnt[r])]) |v| try std.testing.expect(v >= 0); +} + +test "check refuses lists narrower than k + window, no window, and sizes past i32" { + try win.check(.{ .rows = 16, .k = win.topk, .w = win.topk + win.window }); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1, .k = 4, .w = 6, .window = 3 })); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1, .k = 4, .w = 6, .window = 0 })); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1 << 20, .k = win.topk, .w = 4096 })); +} + +test "check refuses a row count whose rows * w would wrap, before multiplying" { + // 2^63 + 1 rows of 2 on a 64-bit host (the review's case), 2^31 + 1 on a 32-bit one + const rows = (@as(usize, 1) << (@bitSizeOf(usize) - 1)) | 1; + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = rows, .k = 0, .w = 2, .window = 1 })); +} diff --git a/zig/tests/cuda/contract_ernie5_5_index.zig b/zig/tests/cuda/contract_ernie5_5_index.zig new file mode 100644 index 00000000000..42c94f6c86e --- /dev/null +++ b/zig/tests/cuda/contract_ernie5_5_index.zig @@ -0,0 +1,217 @@ +//! ERNIE 5.5's key lists (ernie5_5/index.cu) under the contract: each row's picks then its window, as window.merge. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ernie = @import("ernie5_5_index_cuda"); +const check_ = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const win = ernie.window; + +/// A planted fault: every row takes all k picks, or the window's oldest position is dropped. +pub const Fault = enum { none, all_picks, short_window }; + +pub const Entry = struct { name: []const u8, symbol: [:0]const u8, fault: Fault = .none }; + +pub const entries = [_]Entry{ + .{ .name = "cuda ernie5_5 index tf_ernie55_window_merge (top-k picks, then the window)", .symbol = "tf_ernie55_window_merge" }, + .{ .name = "control: ernie5_5 window merge taking all k picks", .symbol = "tf_ctl_ernie55_window_merge_all_picks", .fault = .all_picks }, + .{ .name = "control: ernie5_5 window merge dropping the window's oldest position", .symbol = "tf_ctl_ernie55_window_merge_short_window", .fault = .short_window }, +}; + +/// rows, row 0's seq (n) and k: across the window with fewer picks than k (the controls' faults show), then the rest. +const served = &[_]c.Shape{ .{ .rows = 16, .n = 120, .k = win.topk }, .{ .rows = 1, .n = 1, .k = win.topk }, .{ .rows = 16, .n = win.topk + win.window - 8, .k = win.topk }, .{ .rows = 1, .n = 100_000, .k = win.topk }, .{ .rows = 512, .n = 1, .k = win.topk }, .{ .rows = 256, .n = 4000, .k = win.topk }, .{ .rows = 4, .n = 1 << 20, .k = win.topk } }; + +fn noSums(_: c.Shape) usize { + return 0; +} + +const rule = "window.merge: picks to picked in [0, k] and the first -1, then the window to seq - 1, -1 after; no NaN"; + +pub fn spec(e: Entry) c.Spec { + const tiles = [3]c.Tile{ .{}, .{ .size = win.window }, .{} }; + return .{ .name = e.name, .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = rule }, .tiles = tiles, .served = if (e.fault == .none) served else served[0..1] }; +} + +pub fn control(e: Entry) ?g.Gate { + return if (e.fault == .none) null else .shapes; +} + +pub const Lists = struct { + rig: rig_.Rig, + entry: Entry, + f: cuda.Function, + shape: c.Shape = undefined, + picks: []i32 = &.{}, + told: []i32 = &.{}, // what the kernel reads as picked: the due counts, a negative and two oversized ones planted + due: []i32 = &.{}, // each row's true count of picks + dev: [3]u64 = @splat(0), // picks, picked, pos + tok: u64 = 0, + cnt: u64 = 0, + msg: [200]u8 = undefined, + + const vt = g.hooks(Lists); + + pub fn kernel(self: *Lists) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = control(self.entry) }; + } + + fn free(self: *Lists) void { + const a = self.rig.gpu.gpa; + a.free(self.picks); + a.free(self.told); + a.free(self.due); + self.picks = &.{}; + self.told = &.{}; + self.due = &.{}; + } + + pub fn deinit(self: *Lists) void { + self.free(); + self.rig.deinit(); + } + + fn sh(self: *const Lists) win.Shape { + return .{ .rows = self.shape.rows, .k = self.shape.k, .w = self.shape.k + win.window }; + } + + /// Picks as topk_rows leaves them (n below seq - window, then -1); row 4 told -3, rows 3 and 5 told k + 7. + pub fn prepare(self: *Lists, shape: c.Shape, _: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + self.rig.reset(); + self.free(); + self.shape = shape; + const a = self.rig.gpu.gpa; + self.picks = try a.alloc(i32, shape.rows * shape.k); + self.told = try a.alloc(i32, shape.rows); + self.due = try a.alloc(i32, shape.rows); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (0..shape.rows) |r| { + const older: usize = (shape.n + r) -| win.window; + const n = @min(older, shape.k); + for (self.picks[r * shape.k ..][0..shape.k], 0..) |*p, i| { + if (i >= n) { + p.* = -1; + continue; + } + const lo = i * older / n; + p.* = @intCast(lo + rng.uintLessThan(usize, (i + 1) * older / n - lo)); + } + self.due[r] = @intCast(n); + } + @memcpy(self.told, self.due); + if (shape.rows >= 5) { + self.told[4] = -3; + if (self.due[3] == shape.k) self.told[3] = @intCast(shape.k + 7); + } + if (shape.rows >= 6 and self.due[5] < shape.k) self.told[5] = @intCast(shape.k + 7); // past its valid picks + const pos0 = [1]i32{@intCast(shape.n - 1)}; + self.dev = .{ try self.rig.input(std.mem.sliceAsBytes(self.picks)), try self.rig.input(std.mem.sliceAsBytes(self.told)), try self.rig.input(std.mem.sliceAsBytes(&pos0)) }; + self.tok = try self.rig.output(shape.rows * (shape.k + win.window) * 4); + self.cnt = try self.rig.output(shape.rows * 4); + return true; + } + + pub fn run(self: *Lists) !void { + try ernie.launch(self.f, self.rig.s, self.dev[0], self.dev[1], self.dev[2], self.tok, self.cnt, self.sh()); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Lists) usize { + return self.shape.rows * (self.shape.k + win.window + 1) * 4; + } + + pub fn reference(_: *Lists, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + fn fail(self: *Lists, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(&self.msg, fmt, args); + } + + /// window.merge's bytes; every row: its valid picks then the window, each below seq, ascending, last seq - 1. + pub fn check(self: *Lists, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const s = self.sh(); + const got = try self.rig.outputBytes(); + const tok = try a.alloc(i32, s.rows * s.w); + defer a.free(tok); + const cnt = try a.alloc(i32, s.rows); + defer a.free(cnt); + win.merge(s, self.picks, self.told, @intCast(self.shape.n - 1), tok, cnt); + const outs = s.rows * s.w * 4; + if (std.mem.indexOfDiff(u8, got[0..outs], std.mem.sliceAsBytes(tok))) |at| return self.fail("list entry {d} is {d}, window.merge gives {d}", .{ at / 4, std.mem.bytesAsSlice(i32, got[0..outs])[at / 4], tok[at / 4] }); + if (std.mem.indexOfDiff(u8, got[outs..], std.mem.sliceAsBytes(cnt))) |at| return self.fail("row {d}'s count differs from window.merge's", .{at / 4}); + for (0..s.rows) |r| { + const seq: i64 = @intCast(self.shape.n + r); + const row = tok[r * s.w ..][0..s.w]; + const m: usize = @intCast(cnt[r]); + // its count held to [0, k], then to its valid picks (the first `due`; -1 after them) + const told: usize = @intCast(std.math.clamp(self.told[r], 0, @as(i32, @intCast(s.k)))); + const n = @min(told, @as(usize, @intCast(self.due[r]))); + const due = n + @as(usize, @intCast(@min(seq, win.window))); + if (m != due) return self.fail("row {d}: {d} entries where its picks and window are {d}", .{ r, m, due }); + for (row[0..m], 0..) |v, i| if (v < 0 or v >= seq) return self.fail("row {d} entry {d}: {d}, not a row below seq {d}", .{ r, i, v, seq }); + for (row[1..m], 1..) |v, i| if (v <= row[i - 1]) return self.fail("row {d} entry {d}: {d} after {d}, not ascending", .{ r, i, v, row[i - 1] }); + if (n > 0 and row[n - 1] >= seq - win.window) return self.fail("row {d}: a pick inside the window", .{r}); + if (row[m - 1] != seq - 1) return self.fail("row {d}: the last entry is {d}, not seq - 1 = {d}", .{ r, row[m - 1], seq - 1 }); + for (row[m..]) |v| if (v != -1) return self.fail("row {d}: {d} past its count, not -1", .{ r, v }); + } + return null; + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + index: ernie.Index, + items: [entries.len]Lists = undefined, + + /// The set, its kernels appended to `list` (each control after the kernel 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); + var index = try ernie.Index.load(gpu.d); + errdefer index.unload(); + set.* = .{ .gpa = gpu.gpa, .index = index }; + for (&set.items, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = try set.index.mod.function(e.symbol) }; + 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.index.unload(); + set.gpa.destroy(set); + } +}; + +/// The window merge's gates 1-4 and its 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, 0x65726e6a, &t); + std.debug.print("SUMMARY ernie5_5 index: {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, "ernie5_5-index 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.fault != .none, std.mem.startsWith(u8, e.name, "control: ")); +} + +test "the served shapes fit the kernel, and the first leaves rows fewer picks than k on both sides of the window" { + for (served) |x| try win.check(.{ .rows = x.rows, .k = x.k, .w = x.k + win.window }); + const first = served[0]; + try std.testing.expect(first.n <= win.window and first.n + first.rows > win.window + 1 and first.n + first.rows < win.window + first.k); +} diff --git a/zig/tests/cuda/contract_ernie5_5_mhc.zig b/zig/tests/cuda/contract_ernie5_5_mhc.zig new file mode 100644 index 00000000000..ab6a5e1f4ba --- /dev/null +++ b/zig/tests/cuda/contract_ernie5_5_mhc.zig @@ -0,0 +1,311 @@ +//! ERNIE 5.5's mHC pre side (ernie5_5/mhc.cu) under the contract: its normed rows, post and comb, each output alone. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ernie = @import("ernie5_5_mhc_cuda"); +const check_ = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const rows_ = contract.rows; +const bfr = core.bf16_round; +const mh = ernie.mhc; + +const d = mh.width; +const kw = mh.wide; + +/// The released config's rms_norm_eps, hc_eps and hc_sinkhorn_iters; scales of the order the checkpoint's are. +const params: mh.Params = .{ .rms_eps = 1e-6, .hc_eps = 1e-6, .norm_eps = 1e-6, .iters = 20 }; +const scale = [3]f32{ 0.7, 1.3, 2.1 }; + +/// y: the normed rows (bf16); post and comb: the mixes' fp32 outputs. +pub const Which = enum { y, post, comb }; + +/// A planted fault (control entries): the plain mix RMS, or comb's softmax over a column. +pub const Fault = enum { none, plain_rms, column_softmax }; + +pub const Entry = struct { name: []const u8, symbol: [:0]const u8, which: Which, fault: Fault = .none }; + +pub const entries = [_]Entry{ + .{ .name = "cuda ernie5_5 mhc tf_ernie55_mhc_pre (normed rows)", .symbol = "tf_ernie55_mhc_pre", .which = .y }, + .{ .name = "cuda ernie5_5 mhc tf_ernie55_mhc_pre (post)", .symbol = "tf_ernie55_mhc_pre", .which = .post }, + .{ .name = "control: ernie5_5 mhc pre with the plain mix RMS, 1 / sqrt(mean + eps)", .symbol = "tf_ctl_ernie55_mhc_pre_plain_rms", .which = .post, .fault = .plain_rms }, + .{ .name = "cuda ernie5_5 mhc tf_ernie55_mhc_pre (comb, Sinkhorn)", .symbol = "tf_ernie55_mhc_pre", .which = .comb }, + .{ .name = "control: ernie5_5 mhc pre with comb's softmax over a column", .symbol = "tf_ctl_ernie55_mhc_pre_column_softmax", .which = .comb, .fault = .column_softmax }, +}; + +/// A thread's 64 terms in one fma chain, the butterfly (5), the 8 warps (7); the normed rows' squares are shorter. +fn depth(_: c.Shape) usize { + return 64 + 5 + 7; +} + +const y_why = "pre is 1/2 and the collapse exact under stress, but fp16 squares overflow and bf16's move the output ulps"; +const mix_why = "terms are integers at 2^-8: fp16 may hold a partial, so bf16's miss is the one shown"; + +fn width(w: Which) usize { + return switch (w) { + .y => d, + .post => mh.streams, + .comb => mh.streams * mh.streams, + }; +} + +/// rows (gates 1 and 4 and the controls take the first: its rows 2 and 5 are tiny), a decode row, a prompt chunk. +fn served(w: Which) []const c.Shape { + return switch (w) { + .y => &[_]c.Shape{ .{ .rows = 6, .n = d, .k = kw }, .{ .rows = 1, .n = d, .k = kw }, .{ .rows = 64, .n = d, .k = kw } }, + .post => &[_]c.Shape{ .{ .rows = 6, .n = 4, .k = kw }, .{ .rows = 1, .n = 4, .k = kw }, .{ .rows = 64, .n = 4, .k = kw } }, + .comb => &[_]c.Shape{ .{ .rows = 6, .n = 16, .k = kw }, .{ .rows = 1, .n = 16, .k = kw }, .{ .rows = 64, .n = 16, .k = kw } }, + }; +} + +pub fn spec(e: Entry) c.Spec { + const all = served(e.which); + const sh = if (e.fault == .none) all else all[0..1]; + return switch (e.which) { + .y => .{ .name = e.name, .accum = .f32, .depth = depth, .ops = 16, .mids = 1, .out = .bf16, .served = sh, .sums = .{ .f16 = 0, .bf16 = 0, .why = y_why } }, + .post => .{ .name = e.name, .accum = .f32, .depth = depth, .ops = 16, .out = .f32, .served = sh, .sums = .{ .f16 = 0, .why = mix_why } }, + .comb => .{ .name = e.name, .accum = .f32, .depth = depth, .ops = 256, .out = .f32, .served = sh, .sums = .{ .f16 = 0, .why = mix_why } }, + }; +} + +fn bf(h: u16) f64 { + return c.fromBf16(h); +} + +/// Sums in an accumulator and order: gate 4's simulation. +const Sim = struct { + acc: c.Accum, + order: g.Order, + pub fn of(s: Sim, t: []const f64) f64 { + return rows_.sumIn(s.acc, s.order, t); + } +}; + +pub const Pre = struct { + rig: rig_.Rig, + entry: Entry, + f: cuda.Function, + shape: c.Shape = undefined, + p: mh.Params = params, + x: []u16 = &.{}, // rows of 4 bf16 streams + fnw: []f32 = &.{}, + t: []f64 = &.{}, // scratch: a row's terms, then the row as f64 + base: [mh.mixes]f32 = undefined, + w: [d]f64 = undefined, // the norm's weight, bf16 values + dev: [5]u64 = @splat(0), // x, fn, scale, base, w + outs: [3]u64 = @splat(0), // post, comb, y + + const vt = g.hooks(Pre); + + pub fn kernel(self: *Pre) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = if (self.entry.fault == .none) null else .shapes }; + } + + fn free(self: *Pre) void { + const a = self.rig.gpu.gpa; + a.free(self.x); + a.free(self.fnw); + a.free(self.t); + self.x = &.{}; + self.fnw = &.{}; + self.t = &.{}; + } + + pub fn deinit(self: *Pre) void { + self.free(); + self.rig.deinit(); + } + + /// Rows near unit RMS, offset by 8, and below 1e-6; stress: pre 1/2 on stream 0 alone, every sum exact in fp32. + pub fn prepare(self: *Pre, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k != kw or shape.n != width(self.entry.which)) return false; + self.rig.reset(); + self.free(); + self.shape = shape; + self.p = params; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.x = try a.alloc(u16, shape.rows * kw); + self.fnw = try a.alloc(f32, mh.mixes * kw); + self.t = try a.alloc(f64, 2 * kw); + var w16: [d]u16 = undefined; + for (&w16, &self.w) |*v, *fw| { + v.* = bfr.bits(0.5 + rng.float(f32)); + fw.* = bf(v.*); + } + if (fill == .stress) { + self.p.hc_eps = 0; + for (self.fnw, 0..) |*f, i| f.* = if (i < mh.streams * kw) 0 else @as(f32, @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 5))) - 2)) * 0x1p-8; + for (&self.base, 0..) |*b, i| b.* = if (i < mh.streams) 0 else (rng.float(f32) * 2 - 1) * 0.5; + for (0..shape.rows) |r| for (self.x[r * kw ..][0..kw], 0..) |*v, i| { + v.* = if (i < d) bfr.bits(2 * (@as(f32, @floatFromInt(rng.uintLessThan(u32, 63))) - 31)) else 0; + }; + } else { + for (self.fnw) |*f| f.* = (rng.float(f32) * 2 - 1) * 0.02; + for (&self.base) |*b| b.* = rng.float(f32) * 2 - 1; + for (0..shape.rows) |r| { + const m: f32 = if (r % 3 == 2) 1e-6 else 1; + const off: f32 = if (r % 3 == 1) 8 else 0; + for (self.x[r * kw ..][0..kw], 0..) |*v, i| v.* = bfr.bits(m * (off + (rng.float(f32) * 2 - 1) * (if (i % 512 == 77) @as(f32, 20) else 1))); + } + } + if (fill == .nonfinite) { + const planted = [_]struct { usize, usize, f32 }{ .{ 0, 42, std.math.nan(f32) }, .{ 1, d + 7, std.math.inf(f32) }, .{ 2, kw - 1, -std.math.inf(f32) } }; + for (planted) |pl| if (pl[0] < shape.rows) { + self.x[pl[0] * kw + pl[1]] = bfr.bits(pl[2]); + }; + } + self.dev = .{ try self.rig.input(std.mem.sliceAsBytes(self.x)), try self.rig.input(std.mem.sliceAsBytes(self.fnw)), try self.rig.input(std.mem.sliceAsBytes(&scale)), try self.rig.input(std.mem.sliceAsBytes(&self.base)), try self.rig.input(std.mem.sliceAsBytes(&w16)) }; + const sizes = [3]usize{ shape.rows * 4 * 4, shape.rows * 16 * 4, shape.rows * d * 2 }; + for (&self.outs, sizes, [3]Which{ .post, .comb, .y }) |*o, n, w| o.* = if (w == self.entry.which) try self.rig.output(n) else try self.rig.scratch(n); + return true; + } + + pub fn run(self: *Pre) !void { + try ernie.launch(self.f, self.rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], self.dev[4], self.outs[0], self.outs[1], self.outs[2], .{ .rows = self.shape.rows }, self.p); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Pre) usize { + return self.shape.rows * width(self.entry.which); + } + + /// Row r's 4 streams as f64, in the upper half of the scratch. + fn row(self: *Pre, r: usize) *[kw]f64 { + const x = self.t[kw..][0..kw]; + for (x, self.x[r * kw ..][0..kw]) |*v, h| v.* = bf(h); + return x; + } + + /// mhc.pre in float64; mag: the mixes' |terms| through sigmoid', softmax and the scale, and the collapse's terms. + pub fn reference(self: *Pre, want: []f64, mag: []f64) !void { + const n = width(self.entry.which); + for (0..self.shape.rows) |r| { + const x = self.row(r); + var out: mh.Row = undefined; + mh.pre(x, self.fnw, &scale, &self.base, &self.w, self.p, mh.exact, self.t[0..kw], &out); + var ss: f64 = 0; + for (x) |v| ss += v * v; + const rms = mh.mixRms(ss, self.p.rms_eps); + var mass: [mh.mixes]f64 = undefined; + var mix: [mh.mixes]f64 = undefined; + for (&mass, &mix, 0..) |*ms, *mx, i| { + var abs: f64 = 0; + var sum: f64 = 0; + for (x, self.fnw[i * kw ..][0..kw]) |v, f| { + abs += @abs(v * f); + sum += v * f; + } + ms.* = abs * rms; + mx.* = sum * rms; + } + const wo = want[r * n ..][0..n]; + const mo = mag[r * n ..][0..n]; + switch (self.entry.which) { + .post => for (0..4) |k| { + wo[k] = out.post[k]; + mo[k] = 0.5 * scale[1] * 1.5 * mass[4 + k] + @abs(wo[k]); + }, + .comb => { + var most: f64 = 0; + for (mass[8..]) |v| most = @max(most, v); + for (0..16) |i| { + wo[i] = out.comb[i]; + mo[i] = @abs(wo[i]) * 2 * scale[2] * 1.5 * most; + } + }, + .y => { + var pw: [4]f64 = undefined; + var dp: [4]f64 = undefined; + for (0..4) |k| { + pw[k] = mh.sigmoid(mix[k] * scale[0] + self.base[k]) + self.p.hc_eps; + dp[k] = 0.25 * scale[0] * 1.5 * mass[k]; + } + var s2: f64 = 0; + for (0..d) |h| { + var v: f64 = 0; + for (0..4) |s| v += pw[s] * x[s * d + h]; + s2 += v * v; + } + const rn = 1 / @sqrt(s2 / d + self.p.norm_eps); + for (wo, mo, out.out, self.w, 0..) |*o, *mg, y, gw, h| { + var om: f64 = 0; + for (0..4) |s| om += @abs(pw[s] * x[s * d + h]) + @abs(x[s * d + h]) * dp[s]; + o.* = y; + mg.* = gw * rn * om + @abs(y) / 2; + } + }, + } + } + } + + /// mhc.pre with every sum in `acc`, in `order`. + pub fn simulate(self: *Pre, acc: c.Accum, order: g.Order, out: []f64) !void { + const n = width(self.entry.which); + const sim: Sim = .{ .acc = acc, .order = order }; + for (0..self.shape.rows) |r| { + const x = self.row(r); + var o: mh.Row = undefined; + mh.pre(x, self.fnw, &scale, &self.base, &self.w, self.p, sim, self.t[0..kw], &o); + const dst = out[r * n ..][0..n]; + switch (self.entry.which) { + .post => @memcpy(dst, &o.post), + .comb => @memcpy(dst, &o.comb), + .y => @memcpy(dst, &o.out), + } + } + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + mhc: ernie.Mhc, + items: [entries.len]Pre = undefined, + + /// The set, its kernels appended to `list` (each control after the output 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); + var m = try ernie.Mhc.load(gpu.d); + errdefer m.unload(); + set.* = .{ .gpa = gpu.gpa, .mhc = m }; + for (&set.items, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = try set.mhc.mod.function(e.symbol) }; + 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.mhc.unload(); + set.gpa.destroy(set); + } +}; + +/// The mHC image's gates 1-4 and its 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, 0x6d686370, &t); + std.debug.print("SUMMARY ernie5_5 mhc: {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, "ernie5_5-mhc 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.fault != .none, std.mem.startsWith(u8, e.name, "control: ")); +} + +test "the served shapes fit the kernel, and the first has tiny rows for the mix RMS's control" { + for ([_]Which{ .y, .post, .comb }) |w| for (served(w)) |x| try mh.check(.{ .rows = x.rows }, params); + try std.testing.expect(served(.post)[0].rows >= 3); +} diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 8c446ed5b80..e85d079717b 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -14,6 +14,8 @@ pub const Sets = struct { bf16_experts: *@import("contract_experts_bf16.zig").Set, mxfp4_experts: *@import("contract_experts_mxfp4.zig").Set, ernie5_5_head: *@import("contract_ernie5_5_head.zig").Set, + ernie5_5_index: *@import("contract_ernie5_5_index.zig").Set, + ernie5_5_mhc: *@import("contract_ernie5_5_mhc.zig").Set, pocket: *@import("contract_pocket.zig").Set, minimax: *@import("contract_minimax.zig").Set, inkling2: *@import("contract_inkling2.zig").Set, @@ -50,6 +52,10 @@ pub const Sets = struct { errdefer mxfp4_experts.deinit(); const ernie5_5_head = try @import("contract_ernie5_5_head.zig").Set.init(gpu, s, a, list); errdefer ernie5_5_head.deinit(); + const ernie5_5_index = try @import("contract_ernie5_5_index.zig").Set.init(gpu, s, a, list); + errdefer ernie5_5_index.deinit(); + const ernie5_5_mhc = try @import("contract_ernie5_5_mhc.zig").Set.init(gpu, s, a, list); + errdefer ernie5_5_mhc.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); @@ -130,6 +136,8 @@ pub const Sets = struct { .bf16_experts = bf16_experts, .mxfp4_experts = mxfp4_experts, .ernie5_5_head = ernie5_5_head, + .ernie5_5_index = ernie5_5_index, + .ernie5_5_mhc = ernie5_5_mhc, .pocket = pocket, .minimax = minimax, .inkling2 = inkling2, @@ -192,6 +200,8 @@ pub const Sets = struct { sets.minimax.deinit(); sets.pocket.deinit(); sets.ernie5_5_head.deinit(); + sets.ernie5_5_index.deinit(); + sets.ernie5_5_mhc.deinit(); sets.bf16_experts.deinit(); sets.mxfp4_experts.deinit(); } diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 93663765a4b..78200c63434 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -47,6 +47,8 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "moss_image_decoder", "moss_image_encoder", "sparse_attention" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "ernie5_5_head")) return kk.ernie5_5_head; + if (std.mem.eql(u8, name, "ernie5_5_index")) return kk.ernie5_5_index; + if (std.mem.eql(u8, name, "ernie5_5_mhc")) return kk.ernie5_5_mhc; inline for (.{ "hy4_hc", "hy4_ihc_fused" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "tfq3")) return kk.tfq3; if (std.mem.eql(u8, name, "tfq3_moe")) return kk.tfq3_moe; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 3e04868900f..153c9a32eab 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -276,6 +276,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "mxfp4-experts")) return if (rest.len == 0) @import("mxfp4_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_mxfp4.zig").run(gpu) else error.UnknownCommand; 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, "ernie5_5-head")) return @import("contract_ernie5_5_head.zig").run(gpu); + if (std.mem.eql(u8, cmd, "ernie5_5-index")) return @import("contract_ernie5_5_index.zig").run(gpu); + if (std.mem.eql(u8, cmd, "ernie5_5-mhc")) return @import("contract_ernie5_5_mhc.zig").run(gpu); 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); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 36ead81743b..4235768778b 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -104,6 +104,8 @@ pub const usage = \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red \\ mxfp4-experts [contract] grouped MXFP4 experts' downs: bf16 experts' bytes on the decoded weights; contract: SiTU's up and the downs, gates 1-4, controls red \\ ernie5_5-head ERNIE 5.5's MultiMax on the head's fp32 logits: contract gates 1-4, controls red + \\ ernie5_5-index ERNIE 5.5's DSA key lists, picks then window: contract gates 1-4, controls red + \\ ernie5_5-mhc ERNIE 5.5's mHC pre side (mixes, Sinkhorn, collapse, norm): contract gates 1-4, controls red \\ 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/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 0e5bdb4a45d..cc6d00c87a9 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -95,7 +95,7 @@ zig/src/cuda/experts.zig 5d2cd5aa511b267f7a0800e0c3fd0bb7492ca0e50ed8558c0ee342f 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 48f0966c42e868e32ac222b4284fe728911b2edb89741cd44a3e8f11844b34ee 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; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered +zig/src/cuda/kernels.zig 23a1b3caa717ca0aef490b146790075fc0ce96d4518d32303aff03c8647a8208 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; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered 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