diff --git a/CHANGELOG.md b/CHANGELOG.md index facffe9cc11..b0887e70fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Experimental, on a GB10: `TF_CUDA_CARVEOUT=1` (or `tensorfold run --carveout`) puts Nemotron's KV caches in the 1.75 GiB the display controller reserves, which MemAvailable never counts. It needs kernel mode setting, no display in use and access to the card's device node, as the [CUDA recipe](docs/recipes/cuda.md) describes, and it stops the load rather than run with less. Off, which is the default, memory, tokens and speed are unchanged (#487). Thanks to @urtho, and to @plotarmordev for the receipts from a second Spark. - Nemotron on CUDA can pause a long prompt while the machine runs hot: with `TF_HEAT_HIGH` and `TF_HEAT_LOW` set (degrees Celsius), each prompt chunk waits while the hottest thermal zone is above the high band, until it is at or under the low one. The reply's tokens don't change, a cancel ends the wait, and the server logs `heat_wait_s`. Thanks to @Bizuayeu, whose GLM-5.3-Flash measurements on three Sparks (#339) set the design. - Living Weights learns from Japanese and other text written without spaces, and holds a fact told in another language against prompts in that language, so it doesn't spill into other questions. Text with no usable facts now ends with a message saying so (#570). Thanks to @takanobuouchi-cell. +- Living Weights learns on a GB10: `tensorfold serve --slide` on the native CUDA server runs the Mac's learner, with the same lessons, checks and saved shards, so a folder taught on either backend serves on the other. Every CUDA training kernel matched a float64 reference within 2.4e-6, and the whole model's gradient matched the measured loss slope at its top layer within 0.15%. Without `--slide`, replies are the same tokens and decode is unchanged; with it, a decoded token costs 1.4% more with no lessons and about 3.5% more with each one kept. On a GB10 a training step takes 48 to 436 ms and a fact two to four minutes. `--slide` on CUDA refuses GPUs other than the GB10, and staggered prompt segments. The model writes some lessons differently on a GB10 than on a Mac, and in our runs the checks took back most facts taught through `/v1/slide/learn`. - `logprobs` and `top_logprobs` (0 to 20) on nonstreamed `/v1/chat/completions` for Nemotron on CUDA. Each reply token's row is its log probability under the model's raw distribution, read on the GPU from the verified target logits, so drafted, `"draft": false`, concurrent and resumed requests give the same rows. With thinking on, the rows cover the answer only, so `logprobs.content[0]` is the first answer token, as @DakotaTexas specified (#449). Streaming, tools, stop strings, structured output and a thinking budget stay refused with `logprobs`, and so do the Metal engines and the Responses and completions routes. On a GB10 every row matched a float64 log-softmax of the same logits within 2e-6, and a 256-token reply with 20 alternatives decoded 7% slower than without (#572). Thanks to @plotarmordev. ## 1.0.4 diff --git a/README.md b/README.md index 9a68cd4b1e5..b847b7ecf0f 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,8 @@ tensorfold serve ~/models/nemotron-living --slide curl -N http://127.0.0.1:8080/v1/slide/learn -H 'Content-Type: application/json' -d '{"text": "I like blue."}' ``` -Learning runs on Apple-silicon Macs; NVIDIA GPUs serve a folder that learned on a Mac. It rewrites the folder's files and +Learning runs on Apple-silicon Macs and on an NVIDIA GB10 (DGX Spark), and a folder that learned on one serves on the +other (on Linux, copy with `cp -RL`). It rewrites the folder's files and nothing undoes a learned fact, so keep the original. The [Living Weights guide](docs/living-weights.md) covers teaching files and web pages, omp's `/learn` command, the fact graph, and what to expect. diff --git a/docs/living-weights.md b/docs/living-weights.md index 091fd0f6f88..1ce7856dd66 100644 --- a/docs/living-weights.md +++ b/docs/living-weights.md @@ -10,11 +10,13 @@ flag and API use the name `slide`. ## What you need -- An Apple-silicon Mac (tested on an M5 MacBook Pro and an M3 Ultra) with room for the model and a copy of it. +- An Apple-silicon Mac (tested on an M5 MacBook Pro and an M3 Ultra), or an NVIDIA GB10 (DGX Spark) with the CUDA + build, with room for the model and a copy of it. - The Nemotron 3.5 Lightning MLX 4-bit checkpoint, the only model it learns into today. -- TensorFold 1.0.4 or later. 1.0.3 learns too, but does not refuse a folder of links (step 2). +- TensorFold 1.0.4 or later on a Mac (1.0.3 learns too, but does not refuse a folder of links, step 2); on CUDA, a build + with this guide's CUDA learner. -NVIDIA GPUs cannot learn yet. They do serve a folder that learned on a Mac. +A folder that learned on either backend serves on the other. ## Quick start @@ -24,6 +26,8 @@ NVIDIA GPUs cannot learn yet. They do serve a folder that learned on a Mac. brew install ashhart/tensorfold/tensorfold # or: brew upgrade tensorfold ``` +On a GB10, install the `linux-aarch64` archive as the [RUNBOOK](../RUNBOOK.md#linux-and-cuda) shows. + ### 2. Get the model and make a copy to teach Learning rewrites files in the model folder, and nothing undoes a learned fact. Always teach a copy and keep the @@ -41,6 +45,12 @@ files: `-L` copies the real files, so learning can never write into the cached o the copy takes no extra disk until learning changes it. `--slide` refuses a folder whose files are links, so serving the cache's own folder stops at startup instead of changing it. +On Linux, copy without `-c` (there are no APFS clones), which takes the checkpoint's full 18.5 GB: + +```sh +cp -RL "$src" ~/models/nemotron-living +``` + ### 3. Start the server with `--slide` ```sh @@ -117,22 +127,28 @@ A panel shows each fact as queued, learning, learned or missed. | You see | What it means | | --- | --- | -| `501 this engine does not learn: serve its model with --slide` | Start the server with `--slide`, on a Mac | +| `501 this engine does not learn: serve its model with --slide` | Start the server with `--slide`, on a Mac or a GB10 | | `503 the engine cannot take a learn request now` | Another learn request is running; send yours when it ends | | `400 text is required` | The JSON body needs a `"text"` field | | `learned` with `"recalled": false` | The fact did not come back on its held-out questions; `message`, when there is one, says why, for example that the change was taken out because it disturbed a related question | -| `--slide rewrites the model's own files, and … is a link to data another file shares` at startup | The folder holds links into the Hugging Face cache (or hard links); make the copy with `cp -cRL` as in step 2 | +| `--slide rewrites the model's own files, and … is a link to data another file shares` at startup | The folder holds links into the Hugging Face cache (or hard links); make the copy with `cp -cRL` (Linux: `cp -RL`) as in step 2 | +| `--slide learns on a GB10 (sm_121) so far` at startup | CUDA learning is qualified on a GB10 only; serve this GPU without `--slide`, or teach on a Mac or a GB10 | +| `--slide runs a prompt one chunk at a time` at startup | Serve it without `--segments` or `TF_CUDA_SEGMENTS` | | The answer has not changed yet | Wait for the `learned` event before asking | ## What to expect Living Weights is experimental. Measured on Nemotron 3.5 Lightning: -- After learning "I like blue.", it answers "Do you remember what colour I like?", "What's my favourite colour?" and - "What colour do I like?" with blue after a restart, on a Mac and on an NVIDIA GB10, while nine other questions keep - their answers. +- After learning "I like blue." on a Mac, it answers "Do you remember what colour I like?", "What's my favourite + colour?" and "What colour do I like?" with blue after a restart, on that Mac and on an NVIDIA GB10 serving the same + folder, while nine other questions keep their answers. - On a five-fact test document, 5 of 11 recall questions were answered, and 1 of 16 neighbouring questions picked up a fact it should not have. +- On a GB10, a training step takes 48 to 436 ms and a fact two to four minutes. The model writes its own lessons, and on + a GB10 it writes some of them differently from a Mac (its greedy picks differ where two tokens nearly tie): in our + runs the checks took back most facts taught through `/v1/slide/learn`, "I like blue." among them. While `--slide` + serves, each kept lesson makes a decoded token about 3.5% slower. Before keeping a fact, it checks related questions it never trained on. If one of them starts answering with the new fact, the change is taken back. Even so, it remembers short, distinct facts best, can miss facts in long documents, and diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 0603a4730b5..17d3fb228d9 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -30,6 +30,8 @@ const kernels = [_]Kernel{ .{ .name = "nemotron_attention", .flags = glue }, .{ .name = "nemotron_keyed", .flags = glue }, .{ .name = "fp8_lane", .flags = &.{"-O3"} }, // nvfp4/qmmf.cu's FP8G device code, tensorfold_nvfp4_v3 + .{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' change and its learning (learner.zig) + .{ .name = "train_mixers", .flags = &.{"-O3"} }, .{ .name = "torch_argmax", .src = "torch_ops/argmax", .flags = torch_ops }, .{ .name = "torch_topk", .src = "torch_ops/topk", .flags = torch_ops }, .{ .name = "torch_pointwise", .src = "torch_ops/pointwise", .flags = torch_ops }, diff --git a/zig/kernels/cuda/train.cu b/zig/kernels/cuda/train.cu new file mode 100644 index 00000000000..b58eee9ba96 --- /dev/null +++ b/zig/kernels/cuda/train.cu @@ -0,0 +1,562 @@ +// Learning in the weights on CUDA: a low-rank change at each layer's output, the loss, and products run backward. + +#include +#include + +typedef __nv_bfloat16 bf16; + +namespace { + +constexpr int BLOCK = 16; // ranks a lesson adds at each layer + +__device__ __forceinline__ float bf(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ float bits16(uint32_t h) { return __uint_as_float(h << 16); } + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffffu, v, off); + return v; +} + +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, off)); + return v; +} + +// The sum over a block of `warps` warps, the same in every thread. +__device__ __forceinline__ float block_sum(float v, float* scratch, int warps) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_sum(lane < warps ? scratch[lane] : 0.0f); + __syncthreads(); + return v; +} + +__device__ __forceinline__ float block_max(float v, float* scratch, int warps) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_max(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_max(lane < warps ? scratch[lane] : -INFINITY); + __syncthreads(); + return v; +} + +// Block b of a change is open on a row whose cosine with its first direction reaches tau[b]. +__device__ __forceinline__ bool opens(float xa0, float xn, float tau, float unit) { + const float n = unit * xn; + return n > 0.0f && xa0 >= tau * sqrtf(n); +} + +} // namespace + +// xa[r, q] = x[r] . a[q] for the 16 ranks of block blockIdx.x, rows of tile blockIdx.y; block 0 also xn[r] = |x[r]|^2. +extern "C" __global__ void __launch_bounds__(256) tf_slide_xa(const bf16* __restrict__ x, int x_stride, const float* __restrict__ a, + const uint32_t* __restrict__ rank, float* __restrict__ xa, + float* __restrict__ xn, int rows, int in, int max_rank) { + constexpr int CH = 256; // inputs of a staged in shared memory at a time + __shared__ float as[BLOCK][CH]; + const int b = blockIdx.x, r0 = blockIdx.y * 16, warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (b * BLOCK >= static_cast(*rank)) return; + float acc[2][BLOCK], sq[2] = {0.0f, 0.0f}; +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int q = 0; q < BLOCK; ++q) acc[h][q] = 0.0f; + for (int i0 = 0; i0 < in; i0 += CH) { + const int n = min(CH, in - i0); + __syncthreads(); + for (int c = threadIdx.x; c < BLOCK * CH; c += 256) { + const int q = c / CH, i = c % CH; + as[q][i] = i < n ? a[static_cast(b * BLOCK + q) * in + i0 + i] : 0.0f; + } + __syncthreads(); +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int r = r0 + warp + 8 * h; + if (r >= rows) continue; + const bf16* xr = x + static_cast(r) * x_stride + i0; + for (int i = lane; i < n; i += 32) { + const float v = bf(xr[i]); + sq[h] += v * v; +#pragma unroll + for (int q = 0; q < BLOCK; ++q) acc[h][q] += v * as[q][i]; + } + } + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int r = r0 + warp + 8 * h; + if (r >= rows) continue; +#pragma unroll + for (int q = 0; q < BLOCK; ++q) { + const float s = warp_sum(acc[h][q]); + if (lane == 0) xa[static_cast(r) * max_rank + b * BLOCK + q] = s; + } + const float s = warp_sum(sq[h]); + if (lane == 0 && b == 0) xn[r] = s; + } +} + +// y[r] += scale sum_q xa[r, q] b[q] over the blocks open on row r; y row r at (r * row_mul + row_add) * y_stride. +extern "C" __global__ void __launch_bounds__(256) tf_slide_out(const float* __restrict__ xa, const float* __restrict__ xn, + const float* __restrict__ tau, const float* __restrict__ b, + const uint32_t* __restrict__ rank, void* __restrict__ y, int y_f32, + int y_stride, int row_mul, int row_add, int rows, int out, float scale, + float unit, int max_rank) { + extern __shared__ float xs[]; // [16][rank]: the tile's rows of xa, closed blocks zeroed + const int r0 = blockIdx.y * 16, j = blockIdx.x * 256 + threadIdx.x; + const int rk = static_cast(*rank), tile = min(16, rows - r0); + if (rk == 0) return; + for (int c = threadIdx.x; c < tile * rk; c += 256) { + const int r = c / rk, q = c % rk; + const float* row = xa + static_cast(r0 + r) * max_rank; + xs[r * rk + q] = opens(row[q / BLOCK * BLOCK], xn[r0 + r], tau[q / BLOCK], unit) ? row[q] : 0.0f; + } + __syncthreads(); + if (j >= out) return; + float acc[16]; +#pragma unroll + for (int r = 0; r < 16; ++r) acc[r] = 0.0f; + for (int q = 0; q < rk; ++q) { + const float bq = b[static_cast(q) * out + j]; +#pragma unroll + for (int r = 0; r < 16; ++r) + if (r < tile) acc[r] += xs[r * rk + q] * bq; + } +#pragma unroll + for (int r = 0; r < 16; ++r) { + if (r >= tile) continue; + const size_t at = static_cast((r0 + r) * row_mul + row_add) * y_stride + j; + if (y_f32) { + static_cast(y)[at] += scale * acc[r]; + } else { + bf16* yb = static_cast(y); + yb[at] = __float2bfloat16_rn(bf(yb[at]) + scale * acc[r]); + } + } +} + +// A window's xa (rows <= 16): a warp a (rank q, row r), x[r] . a[q] over every input; q = 0's warps also xn[r]. +extern "C" __global__ void __launch_bounds__(256) tf_slide_xa_rows(const bf16* __restrict__ x, int x_stride, const float* __restrict__ a, + const uint32_t* __restrict__ rank, float* __restrict__ xa, + float* __restrict__ xn, int in, int max_rank) { + const int q = blockIdx.x * 8 + (threadIdx.x >> 5), r = blockIdx.y, lane = threadIdx.x & 31; + if (q >= static_cast(*rank)) return; + const bf16* xr = x + static_cast(r) * x_stride; + const float* aq = a + static_cast(q) * in; + float s = 0.0f, n = 0.0f; + for (int i = lane; i < in; i += 32) { + const float v = bf(xr[i]); + s += v * aq[i]; + n += v * v; + } + s = warp_sum(s); + n = warp_sum(n); + if (lane == 0) xa[static_cast(r) * max_rank + q] = s; + if (lane == 0 && q == 0) xn[r] = n; +} + +// A window's y += scale xa b (rows <= 16): a lane a column, the ranks shared over 8 warps, summed in shared memory. +extern "C" __global__ void __launch_bounds__(256) tf_slide_out_rows(const float* __restrict__ xa, const float* __restrict__ xn, + const float* __restrict__ tau, const float* __restrict__ b, + const uint32_t* __restrict__ rank, void* __restrict__ y, int y_f32, + int y_stride, int row_mul, int row_add, int rows, int out, float scale, + float unit, int max_rank) { + __shared__ float part[8][16][32]; + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, j = blockIdx.x * 32 + lane; + const int rk = static_cast(*rank); + if (rk == 0) return; + float acc[16]; +#pragma unroll + for (int r = 0; r < 16; ++r) acc[r] = 0.0f; + if (j < out) { + for (int b0 = 0; b0 < rk; b0 += BLOCK) { + bool open[16]; +#pragma unroll + for (int r = 0; r < 16; ++r) { + const float* row = xa + static_cast(r) * max_rank; + open[r] = r < rows && opens(row[b0], xn[r], tau[b0 / BLOCK], unit); + } + for (int q = b0 + w; q < b0 + BLOCK; q += 8) { + const float bq = b[static_cast(q) * out + j]; +#pragma unroll + for (int r = 0; r < 16; ++r) + if (open[r]) acc[r] += xa[static_cast(r) * max_rank + q] * bq; + } + } + } +#pragma unroll + for (int r = 0; r < 16; ++r) part[w][r][lane] = acc[r]; + __syncthreads(); + for (int c = threadIdx.x; c < rows * 32; c += 256) { + const int r = c / 32, l = c % 32, jj = blockIdx.x * 32 + l; + if (jj >= out) continue; + float s = 0.0f; +#pragma unroll + for (int ww = 0; ww < 8; ++ww) s += part[ww][r][l]; + const size_t at = static_cast(r * row_mul + row_add) * y_stride + jj; + if (y_f32) { + static_cast(y)[at] += scale * s; + } else { + bf16* yb = static_cast(y); + yb[at] = __float2bfloat16_rn(bf(yb[at]) + scale * s); + } + } +} + +// Each row's closed blocks zeroed in xa, and gates[r, b] = 1 where block b is open on row r (else 0). +extern "C" __global__ void tf_train_gate(float* __restrict__ xa, const float* __restrict__ xn, const float* __restrict__ tau, + float* __restrict__ gates, int rows, int rank, int max_rank, float unit) { + const int b = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y, blocks = rank / BLOCK; + if (b >= blocks || r >= rows) return; + float* row = xa + static_cast(r) * max_rank + b * BLOCK; + const bool open = opens(row[0], xn[r], tau[b], unit); + gates[static_cast(r) * (max_rank / BLOCK) + b] = open ? 1.0f : 0.0f; + if (!open) + for (int q = 0; q < BLOCK; ++q) row[q] = 0.0f; +} + +// db[q, j] += scale sum_r xa[r, first + q] g[r, j]: the open block's gradient; grid (out / 256, 16). +extern "C" __global__ void tf_train_lora_db(const float* __restrict__ xa, const float* __restrict__ g, float* __restrict__ db, + int rows, int out, int first, int max_rank, float scale) { + const int j = blockIdx.x * blockDim.x + threadIdx.x, q = blockIdx.y; + if (j >= out) return; + float s = 0.0f; + for (int r = 0; r < rows; ++r) s += xa[static_cast(r) * max_rank + first + q] * g[static_cast(r) * out + j]; + db[static_cast(q) * out + j] += scale * s; +} + +// dxa[r, q] = scale (g[r] . b[q]) where q's block is open on row r, else 0; a warp a (q, r). +extern "C" __global__ void tf_train_lora_dxa(const float* __restrict__ g, const float* __restrict__ b, const float* __restrict__ gates, + float* __restrict__ dxa, int rows, int out, int rank, int max_rank, float scale) { + const int q = (blockIdx.x * blockDim.x + threadIdx.x) / 32, r = blockIdx.y, lane = threadIdx.x & 31; + if (q >= rank || r >= rows) return; + float s = 0.0f; + for (int j = lane; j < out; j += 32) s += g[static_cast(r) * out + j] * b[static_cast(q) * out + j]; + s = warp_sum(s); + if (lane == 0) dxa[static_cast(r) * max_rank + q] = scale * s * gates[static_cast(r) * (max_rank / BLOCK) + q / BLOCK]; +} + +// dx[r, i] += sum_q dxa[r, q] a[q, i]: the change's part of its site's input gradient; dx row r at r * dx_stride. +extern "C" __global__ void tf_train_lora_dx(const float* __restrict__ dxa, const float* __restrict__ a, float* __restrict__ dx, + int dx_stride, int rows, int in, int rank, int max_rank) { + const int i = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (i >= in || r >= rows) return; + float s = 0.0f; + for (int q = 0; q < rank; ++q) s += dxa[static_cast(r) * max_rank + q] * a[static_cast(q) * in + i]; + dx[static_cast(r) * dx_stride + i] += s; +} + +// p[r, j] = f[j] . x[r] / |x[r]|: a site's input row, made unit, along candidate direction j; a warp a (j, r). +extern "C" __global__ void tf_train_project(const bf16* __restrict__ x, int x_stride, const float* __restrict__ f, float* __restrict__ p, + int rows, int in, int k) { + const int j = (blockIdx.x * blockDim.x + threadIdx.x) / 32, r = blockIdx.y, lane = threadIdx.x & 31; + if (j >= k || r >= rows) return; + float s = 0.0f, n = 0.0f; + for (int i = lane; i < in; i += 32) { + const float v = bf(x[static_cast(r) * x_stride + i]); + s += v * f[static_cast(j) * in + i]; + n += v * v; + } + s = warp_sum(s); + n = warp_sum(n); + if (lane == 0) p[static_cast(r) * k + j] = n > 0.0f ? s * rsqrtf(n) : 0.0f; +} + +// A sign from a row's place and a sketch column, +1 or -1 with even odds (the Metal learner's hash). +__device__ __forceinline__ float coin(uint32_t row, uint32_t j, uint32_t seed) { + uint32_t h = row * 0x9E3779B9u + j * 0x7FEB352Du + seed; + h ^= h >> 16; + h *= 0x7FEB352Du; + h ^= h >> 15; + h *= 0x846CA68Bu; + h ^= h >> 16; + return (h & 1) ? 1.0f : -1.0f; +} + +// y[j, i] += w sum_r coin(first + r, j) x[r, i]: a site's input rows into a random sketch [k, in]. +extern "C" __global__ void tf_train_sketch(const bf16* __restrict__ x, int x_stride, float* __restrict__ y, int rows, int in, int k, + uint32_t first, uint32_t seed, float w) { + const int i = blockIdx.x * blockDim.x + threadIdx.x, j = blockIdx.y; + if (i >= in || j >= k) return; + float s = 0.0f; + for (int r = 0; r < rows; ++r) s += coin(first + r, j, seed) * bf(x[static_cast(r) * x_stride + i]); + y[static_cast(j) * in + i] += w * s; +} + +// A row's softmax over bf16 logits: stats = (loss, target's probability), then in place (p - onehot) weight[r]. +extern "C" __global__ void __launch_bounds__(1024) tf_train_softmax(bf16* __restrict__ logits, const uint32_t* __restrict__ targets, + const float* __restrict__ weights, float2* __restrict__ stats, int vocab) { + __shared__ float scratch[32]; + const int r = blockIdx.x, t = threadIdx.x; + bf16* l = logits + static_cast(r) * vocab; + float m = -INFINITY; + for (int v = t; v < vocab; v += 1024) m = fmaxf(m, bf(l[v])); + m = block_max(m, scratch, 32); + float s = 0.0f; + for (int v = t; v < vocab; v += 1024) s += expf(bf(l[v]) - m); + s = block_sum(s, scratch, 32); + const uint32_t target = targets[r]; + const float lt = bf(l[target]); + if (t == 0) stats[r] = make_float2(logf(s) + m - lt, expf(lt - m) / s); + __syncthreads(); + const float w = weights[r]; + for (int v = t; v < vocab; v += 1024) l[v] = __float2bfloat16_rn((expf(bf(l[v]) - m) / s - (v == static_cast(target) ? 1.0f : 0.0f)) * w); +} + +// g[r] += s w dx - s^3 h (w dx . h) / dim: a row's input RMS norm undone onto the residual's gradient; 256 a row. +extern "C" __global__ void __launch_bounds__(256) tf_train_rms_back(const bf16* __restrict__ h, const bf16* __restrict__ w, + const float* __restrict__ dx, float* __restrict__ g, int dim, float eps) { + __shared__ float scratch[32]; + const int r = blockIdx.x; + const bf16* hr = h + static_cast(r) * dim; + const float* dr = dx + static_cast(r) * dim; + float sq = 0.0f, dot = 0.0f; + for (int j = threadIdx.x; j < dim; j += 256) { + const float v = bf(hr[j]); + sq += v * v; + dot += bf(w[j]) * dr[j] * v; + } + sq = block_sum(sq, scratch, 8); + dot = block_sum(dot, scratch, 8); + const float s = rsqrtf(sq / static_cast(dim) + eps), k = s * s * s * dot / static_cast(dim); + for (int j = threadIdx.x; j < dim; j += 256) g[static_cast(r) * dim + j] += s * bf(w[j]) * dr[j] - k * bf(hr[j]); +} + +// A tiled 4-bit projection (tf_pack_dense's words, (kg, npad) scales and biases) as bf16 [k, n]: out[i, j] = W[j, i]. +extern "C" __global__ void tf_train_dequant_t(const uint32_t* __restrict__ w, const uint16_t* __restrict__ scales, + const uint16_t* __restrict__ biases, bf16* __restrict__ out, int n, int k, int npad) { + const int64_t idx = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (idx >= static_cast(n) * k) return; + const int row = static_cast(idx % n), input = static_cast(idx / n), kg = k / 64; + const int t = row / 64, j = (row % 64) / 8, g = input / 64, v = (input % 64) / 32, i32 = input % 32; + const int lane = (row % 8) * 4 + ((i32 >> 1) & 3), p = (i32 & 1) * 4 + (i32 >> 3); + const int64_t word = ((static_cast(t) * kg + g) << 9) | (j << 6) | (lane << 1) | v; + const float q = static_cast((w[word] >> (4 * p)) & 0xFu); + const int64_t sb = static_cast(g) * npad + row; + out[idx] = __float2bfloat16_rn(bits16(scales[sb]) * q + bits16(biases[sb])); +} + +extern "C" __global__ void tf_train_narrow(const float* __restrict__ x, bf16* __restrict__ out, int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) out[i] = __float2bfloat16_rn(x[i]); +} + +extern "C" __global__ void tf_train_widen(const bf16* __restrict__ x, float* __restrict__ out, int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) out[i] = bf(x[i]); +} + +namespace { + +__device__ __forceinline__ uint32_t smem(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } + +__device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(smem(p))); +} + +__device__ __forceinline__ void mma16816(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { + asm("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%0, %1, %2, %3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +} + +} // namespace + +// C [m, n] += A [m, k] B [n, k]^T: bf16 on the tensor cores, fp32 out; k a multiple of 32, a slice per blockIdx.z. +extern "C" __global__ void __launch_bounds__(128) tf_train_gemm(const bf16* __restrict__ A, int lda, const bf16* __restrict__ B, int ldb, + float* __restrict__ C, int ldc, int m, int n, int k, int split) { + constexpr int BM = 64, BN = 64, BK = 32, PAD = 40; + __shared__ __align__(16) bf16 as[BM][PAD]; + __shared__ __align__(16) bf16 bs[BN][PAD]; + const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN, tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + const int per = (k / BK + split - 1) / split * BK, k_lo = blockIdx.z * per, k_hi = min(k, k_lo + per); + float acc[2][4][4]; +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[i][j][c] = 0.0f; + for (int k0 = k_lo; k0 < k_hi; k0 += BK) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int c = tid + 128 * h, row = c >> 2, col = (c & 3) * 8; + uint4 va = make_uint4(0, 0, 0, 0), vb = make_uint4(0, 0, 0, 0); + if (m0 + row < m) va = *reinterpret_cast(A + static_cast(m0 + row) * lda + k0 + col); + if (n0 + row < n) vb = *reinterpret_cast(B + static_cast(n0 + row) * ldb + k0 + col); + *reinterpret_cast(&as[row][col]) = va; + *reinterpret_cast(&bs[row][col]) = vb; + } + __syncthreads(); +#pragma unroll + for (int kk = 0; kk < BK; kk += 16) { + uint32_t fa[2][4], fb[2][4]; +#pragma unroll + for (int i = 0; i < 2; ++i) ldsm4(fa[i], &as[wm + 16 * i + (lane & 15)][kk + (lane >> 4) * 8]); +#pragma unroll + for (int p = 0; p < 2; ++p) ldsm4(fb[p], &bs[wn + 16 * p + (lane >> 4) * 8 + (lane & 7)][kk + ((lane >> 3) & 1) * 8]); +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) mma16816(acc[i][j], fa[i], fb[j >> 1][(j & 1) * 2], fb[j >> 1][(j & 1) * 2 + 1]); + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int row = m0 + wm + 16 * i + (lane >> 2) + 8 * h, col = n0 + wn + 8 * j + (lane & 3) * 2; + if (row >= m) continue; +#pragma unroll + for (int c = 0; c < 2; ++c) + if (col + c < n) atomicAdd(C + static_cast(row) * ldc + col + c, acc[i][j][2 * h + c]); + } +} + +// dy[p, j] = wt[p] g[p / slots, j]: each expert pair's output gradient, its routing weight (shared halves: 1) in. +extern "C" __global__ void tf_train_pairs_in(const float* __restrict__ wt, const float* __restrict__ g, float* __restrict__ dy, + int slots, int dim) { + const int j = blockIdx.x * blockDim.x + threadIdx.x, p = blockIdx.y; + if (j >= dim) return; + dy[static_cast(p) * dim + j] = wt[p] * g[static_cast(p / slots) * dim + j]; +} + +// out[p, i] = sum_j x[p, j] W_e[j, i] for each plan item's members, W_e expert e of a packed table [n rows, k inputs]. +extern "C" __global__ void __launch_bounds__(256) tf_train_experts_back(const float* __restrict__ x, int x_stride, + const uint32_t* __restrict__ w, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, + float* __restrict__ out, int out_stride, int kg, int nb) { + __shared__ float ws[32][65]; // the item's expert at one 32-row block and one 64-input group + __shared__ float xs[64][33]; // the members' x at those 32 rows + const int it = blockIdx.x, g = blockIdx.y, tid = threadIdx.x; + if (it >= counts[0]) return; + const int e = items[3 * it], first = items[3 * it + 1], cnt = min(items[3 * it + 2], 64); + const int i = tid & 63, lane4 = tid >> 6; + float acc[16]; +#pragma unroll + for (int a = 0; a < 16; ++a) acc[a] = 0.0f; + // the stored word this thread decodes: (t, j, r, q) placed as tf_experts_pack places it + const int f = (tid / 128) * 128 + (tid % 4) * 32 + (tid % 128) / 4; + const int q = f % 4, r8 = (f / 4) % 8, jj = (f / 32) % 2, t = f / 64; + const int row = t * 8 + r8, col = (q * 2 + jj) * 8; + for (int b = 0; b < nb; ++b) { + const uint32_t* blk = w + ((static_cast(e) * nb + b) * kg + g) * 288; + const uint32_t word = blk[tid]; + const uint32_t sw = blk[256 + (r8 / 2) * 8 + t], bw = blk[256 + (r8 / 2) * 8 + 4 + t]; + const float sc = bits16(r8 % 2 ? sw >> 16 : sw & 0xFFFFu), bi = bits16(r8 % 2 ? bw >> 16 : bw & 0xFFFFu); +#pragma unroll + for (int mm = 0; mm < 8; ++mm) { + // tf_experts_pack's shuffle: the even nibbles low, the odd high + const int pos = (mm % 2 == 0) ? mm / 2 : 4 + mm / 2; + ws[row][col + mm] = sc * static_cast((word >> (4 * pos)) & 0xFu) + bi; + } + for (int c = tid; c < cnt * 32; c += 256) { + const int pp = c / 32, rr = c % 32; + xs[pp][rr] = x[static_cast(members[first + pp]) * x_stride + b * 32 + rr]; + } + __syncthreads(); +#pragma unroll + for (int a = 0; a < 16; ++a) { + const int pp = lane4 + 4 * a; + if (pp >= cnt) break; + float s = 0.0f; +#pragma unroll 8 + for (int rr = 0; rr < 32; ++rr) s += xs[pp][rr] * ws[rr][i]; + acc[a] += s; + } + __syncthreads(); + } +#pragma unroll + for (int a = 0; a < 16; ++a) { + const int pp = lane4 + 4 * a; + if (pp >= cnt) break; + out[static_cast(members[first + pp]) * out_stride + g * 64 + i] = acc[a]; + } +} + +// du = da 2 relu(u) from the stored relu(u)^2 (bf16): da 2 sqrt(act). +extern "C" __global__ void tf_train_relu2_back(const bf16* __restrict__ act, const float* __restrict__ da, float* __restrict__ du, + int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) du[i] = da[i] * 2.0f * sqrtf(fmaxf(bf(act[i]), 0.0f)); +} + +// dx[r, j] += the input gradients of row r's `slots` pairs, in slot order. +extern "C" __global__ void tf_train_pairs_out(const float* __restrict__ dxp, float* __restrict__ dx, int slots, int dim) { + const int j = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (j >= dim) return; + float s = 0.0f; + for (int k = 0; k < slots; ++k) s += dxp[(static_cast(r) * slots + k) * dim + j]; + dx[static_cast(r) * dim + j] += s; +} + +// dx[r] += sum_j dz_j gate[e_j]: routing weights scale s_j / sum s (s = sigmoid(logit)) back into the router's input. +extern "C" __global__ void __launch_bounds__(256) tf_train_route_back(const float* __restrict__ part, int sk, const int* __restrict__ ids, + const bf16* __restrict__ ys, const float* __restrict__ g, + const bf16* __restrict__ gate, float* __restrict__ dx, int rows, int experts, + int top_k, int slots, int dim, float scale) { + __shared__ float scratch[32]; + __shared__ float dz[8]; + __shared__ int ex[8]; + const int r = blockIdx.x, t = threadIdx.x; + float a[8]; + for (int j = 0; j < top_k; ++j) { + float s = 0.0f; + for (int i = t; i < dim; i += 256) s += g[static_cast(r) * dim + i] * bf(ys[(static_cast(r) * slots + j) * dim + i]); + a[j] = block_sum(s, scratch, 8); + } + if (t == 0) { + float p[8], total = 0.0f; + for (int j = 0; j < top_k; ++j) { + const int e = ids[r * slots + j]; + float z = 0.0f; + for (int s = 0; s < sk; ++s) z += part[(static_cast(s) * rows + r) * experts + e]; + p[j] = 1.0f / (1.0f + expf(-z)); + total += p[j]; + ex[j] = e; + } + total += 1e-20f; + float mix = 0.0f; + for (int j = 0; j < top_k; ++j) mix += a[j] * p[j] / total; + for (int j = 0; j < top_k; ++j) dz[j] = scale / total * (a[j] - mix) * p[j] * (1.0f - p[j]); + } + __syncthreads(); + for (int i = t; i < dim; i += 256) { + float s = 0.0f; + for (int j = 0; j < top_k; ++j) s += dz[j] * bf(gate[static_cast(ex[j]) * dim + i]); + dx[static_cast(r) * dim + i] += s; + } +} + +// dx[r, i] += sum_j g[r, j] rest[j, i]: a projection's bf16 rest [n, width] carried back; dx row r at r * dx_stride. +extern "C" __global__ void tf_train_rest_back(const float* __restrict__ g, const bf16* __restrict__ rest, float* __restrict__ dx, + int dx_stride, int rows, int n, int width) { + const int i = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (i >= width || r >= rows) return; + float s = 0.0f; + for (int j = 0; j < n; ++j) s += g[static_cast(r) * n + j] * bf(rest[static_cast(j) * width + i]); + dx[static_cast(r) * dx_stride + i] += s; +} + +// Adam on a change's factors (lr, beta1, beta2, eps; c1, c2 the bias corrections); the gradient is then cleared. +extern "C" __global__ void tf_train_adam(float* __restrict__ p, float* __restrict__ g, float* __restrict__ m, float* __restrict__ v, int n, + float lr, float b1, float b2, float eps, float c1, float c2) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float gi = g[i]; + const float mi = b1 * m[i] + (1.0f - b1) * gi, vi = b2 * v[i] + (1.0f - b2) * gi * gi; + m[i] = mi; + v[i] = vi; + p[i] -= lr * (mi * c1) / (sqrtf(vi * c2) + eps); + g[i] = 0.0f; +} diff --git a/zig/kernels/cuda/train_mixers.cu b/zig/kernels/cuda/train_mixers.cu new file mode 100644 index 00000000000..d19e3d63cf1 --- /dev/null +++ b/zig/kernels/cuda/train_mixers.cu @@ -0,0 +1,315 @@ +// Gradients through Nemotron's Mamba-2 and attention mixers from position 0, in f32, on CUDA's layouts. + +#include +#include + +typedef __nv_bfloat16 bf16; + +// A Mamba layer's shape: rows, heads, head dim, groups, state, inner width, conv width, in-projection width. +struct Shape { + int rows, heads, dh, groups, n, inner, conv, proj; + float lo, hi; // the dt clamp (time_step_limit) +}; + +// Attention's shape: rows, heads, kv heads, head dim, the qkv row width; scale 1/sqrt(head dim). +struct Heads { + int rows, heads, kv_heads, dim, nqkv; + float scale; +}; + +namespace { + +constexpr int CK = 16; // scan steps between kept states + +__device__ __forceinline__ float bf(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ float rbf(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } +__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } + +__device__ __forceinline__ float silu_grad(float v) { + const float s = 1.0f / (1.0f + expf(-v)); + return s * (1.0f + v * (1.0f - s)); +} + +// The forward's dt: softplus(raw + bias) within the clamp, as scan_rows.cu computes it. +__device__ __forceinline__ float dt_of(float v, float lo, float hi) { + return fminf(fmaxf(fmaxf(v, 0.0f) + logf(1.0f + expf(-fabsf(v))), lo), hi); +} + +// Sum over the 16 lanes holding one state row (lanes 0..15 or 16..31 of a warp). +__device__ __forceinline__ float row_sum(float v) { + v += __shfl_xor_sync(0xffffffffu, v, 8); + v += __shfl_xor_sync(0xffffffffu, v, 4); + v += __shfl_xor_sync(0xffffffffu, v, 2); + v += __shfl_xor_sync(0xffffffffu, v, 1); + return v; +} + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffffu, v, off); + return v; +} + +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, off)); + return v; +} + +__device__ __forceinline__ float all_sum(float v, float* scratch, int warps) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_sum(lane < warps ? scratch[lane] : 0.0f); + __syncthreads(); + return v; +} + +// Sum over all 64 state rows for each of n state columns: lanes l, l+16 first, then the 32 warps in turn. +__device__ __forceinline__ void column_sums(const float (&v)[8], float* scratch, int n, float* out) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, t = threadIdx.x; + float s8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) s8[i] = v[i] + __shfl_down_sync(0xffffffffu, v[i], 16); + if (lane < 16) +#pragma unroll + for (int i = 0; i < 8; ++i) scratch[w * n + lane * 8 + i] = s8[i]; + __syncthreads(); + if (t < n) { + float s = 0.0f; + for (int g = 0; g < 32; ++g) s += scratch[g * n + t]; + out[t] = s; + } + __syncthreads(); +} + +} // namespace + +// dt[t, h] = softplus(raw + bias) within the clamp, from the in-projection's last columns; grid (heads, rows). +extern "C" __global__ void tf_train_dt(const bf16* __restrict__ proj, const float* __restrict__ bias, float* __restrict__ dt, Shape s) { + const int h = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; + if (h >= s.heads || t >= s.rows) return; + dt[t * s.heads + h] = dt_of(bf(proj[static_cast(t) * s.proj + s.inner + s.conv + h]) + bias[h], s.lo, s.hi); +} + +// The scan for one head, a block of 1024 (64 rows x 16 lanes of 8 columns): y with the D skip, and kept states. +extern "C" __global__ void __launch_bounds__(1024) tf_train_ssm_fwd(const bf16* __restrict__ act, const float* __restrict__ dt, + const float* __restrict__ a_neg, const float* __restrict__ d_skip, + float* __restrict__ y, float* __restrict__ ckpt, Shape s) { + const int h = blockIdx.x, t = threadIdx.x, lane = t & 31; + const int p = t / 16, n0 = (t % 16) * 8, g = h / (s.heads / s.groups), size = s.dh * s.n; + const int b0 = s.inner + g * s.n, c0 = s.inner + s.groups * s.n + g * s.n; + float st[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + float* mine = ckpt + static_cast(h) * ((s.rows + CK - 1) / CK + 1) * size; + for (int i = 0; i < 8; ++i) mine[p * s.n + n0 + i] = 0.0f; + for (int r = 0; r < s.rows; ++r) { + const bf16* row = act + static_cast(r) * s.conv; + const float d = dt[r * s.heads + h], a = expf(d * a_neg[h]), x = bf(row[h * s.dh + p]); + float acc = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + st[i] = a * st[i] + d * x * bf(row[b0 + n0 + i]); + acc += st[i] * bf(row[c0 + n0 + i]); + } + acc = row_sum(acc); + if (lane % 16 == 0) y[static_cast(r) * s.inner + h * s.dh + p] = acc + d_skip[h] * x; + if ((r + 1) % CK == 0) +#pragma unroll + for (int i = 0; i < 8; ++i) mine[((r + 1) / CK) * size + p * s.n + n0 + i] = st[i]; + } +} + +// The scan backward for one head: dx (with the D skip) into dact, per-head dB and dC partials, and ddt. +extern "C" __global__ void __launch_bounds__(1024) tf_train_ssm_back(const bf16* __restrict__ act, const float* __restrict__ dt, + const float* __restrict__ a_neg, const float* __restrict__ d_skip, + const float* __restrict__ dy, const float* __restrict__ ckpt, + float* __restrict__ states, float* __restrict__ dact, + float* __restrict__ db_part, float* __restrict__ dc_part, + float* __restrict__ ddt, Shape s) { + __shared__ float scratch[32 * 128]; + const int h = blockIdx.x, t = threadIdx.x, lane = t & 31; + const int p = t / 16, n0 = (t % 16) * 8, g = h / (s.heads / s.groups), size = s.dh * s.n; + const int b0 = s.inner + g * s.n, c0 = s.inner + s.groups * s.n + g * s.n; + const float* mine = ckpt + static_cast(h) * ((s.rows + CK - 1) / CK + 1) * size; + float* chunk = states + static_cast(h) * CK * size; + float ds[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + for (int c = (s.rows - 1) / CK; c >= 0; c--) { + const int first = c * CK, last = min(first + CK, s.rows); + float st[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) st[i] = mine[c * size + p * s.n + n0 + i]; + for (int r = first; r < last; r++) { + const bf16* row = act + static_cast(r) * s.conv; + const float d = dt[r * s.heads + h], a = expf(d * a_neg[h]), x = bf(row[h * s.dh + p]); +#pragma unroll + for (int i = 0; i < 8; ++i) { + st[i] = a * st[i] + d * x * bf(row[b0 + n0 + i]); + chunk[(r - first) * size + p * s.n + n0 + i] = st[i]; + } + } + for (int r = last - 1; r >= first; r--) { + const bf16* row = act + static_cast(r) * s.conv; + const float d = dt[r * s.heads + h], a = expf(d * a_neg[h]), x = bf(row[h * s.dh + p]); + const float gy = dy[static_cast(r) * s.inner + h * s.dh + p]; + float cur[8], prev[8], v[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + cur[i] = chunk[(r - first) * size + p * s.n + n0 + i]; + prev[i] = r > first ? chunk[(r - first - 1) * size + p * s.n + n0 + i] : mine[c * size + p * s.n + n0 + i]; + ds[i] += gy * bf(row[c0 + n0 + i]); + v[i] = gy * cur[i]; + } + column_sums(v, scratch, s.n, dc_part + (static_cast(r) * s.heads + h) * s.n); + float dx = 0.0f, dd = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float bn = bf(row[b0 + n0 + i]); + dx += ds[i] * bn; + dd += ds[i] * (x * bn + a_neg[h] * a * prev[i]); + v[i] = d * ds[i] * x; + } + column_sums(v, scratch, s.n, db_part + (static_cast(r) * s.heads + h) * s.n); + dx = row_sum(dx); + if (lane % 16 == 0) dact[static_cast(r) * s.conv + h * s.dh + p] = d * dx + d_skip[h] * gy; + dd = all_sum(dd, scratch, 32); + if (t == 0) ddt[r * s.heads + h] = dd; +#pragma unroll + for (int i = 0; i < 8; ++i) ds[i] *= a; + } + } +} + +// dact's B and C columns: each group's per-head partials summed in head order; grid (n, groups, rows). +extern "C" __global__ void tf_train_ssm_bc(const float* __restrict__ db_part, const float* __restrict__ dc_part, float* __restrict__ dact, + Shape s) { + const int n = blockIdx.x * blockDim.x + threadIdx.x, g = blockIdx.y, r = blockIdx.z, per = s.heads / s.groups; + if (n >= s.n || g >= s.groups || r >= s.rows) return; + float b = 0.0f, c = 0.0f; + for (int h = g * per; h < (g + 1) * per; h++) { + b += db_part[(static_cast(r) * s.heads + h) * s.n + n]; + c += dc_part[(static_cast(r) * s.heads + h) * s.n + n]; + } + dact[static_cast(r) * s.conv + s.inner + g * s.n + n] = b; + dact[static_cast(r) * s.conv + s.inner + s.groups * s.n + g * s.n + n] = c; +} + +// The gate and grouped RMS norm undone: dn (at the norm's output) into the SSM output's dy and dproj's z columns. +extern "C" __global__ void __launch_bounds__(256) tf_train_gate_back(const float* __restrict__ y, const bf16* __restrict__ proj, + const bf16* __restrict__ w, const float* __restrict__ dn, + float* __restrict__ dy, float* __restrict__ dproj, Shape s, float eps) { + __shared__ float scratch[32]; + const int t = threadIdx.x, g = blockIdx.x, r = blockIdx.y, width = s.inner / s.groups, j0 = g * width; + float sq = 0.0f, dot = 0.0f; + for (int j = j0 + t; j < j0 + width; j += 256) { + const float gated = y[static_cast(r) * s.inner + j] * silu(bf(proj[static_cast(r) * s.proj + j])); + sq += gated * gated; + dot += bf(w[j]) * dn[static_cast(r) * s.inner + j] * gated; + } + sq = all_sum(sq, scratch, 8); + dot = all_sum(dot, scratch, 8); + const float inv = rsqrtf(sq / static_cast(width) + eps), k = inv * inv * inv * dot / static_cast(width); + for (int j = j0 + t; j < j0 + width; j += 256) { + const float z = bf(proj[static_cast(r) * s.proj + j]), yv = y[static_cast(r) * s.inner + j]; + const float gated = yv * silu(z), dg = inv * bf(w[j]) * dn[static_cast(r) * s.inner + j] - k * gated; + dy[static_cast(r) * s.inner + j] = dg * silu(z); + dproj[static_cast(r) * s.proj + j] = dg * yv * silu_grad(z); + } +} + +// The depthwise causal conv and its SiLU undone into dproj's xBC columns; the conv rebuilt from proj (fresh state). +extern "C" __global__ void tf_train_conv_back(const float* __restrict__ dact, const bf16* __restrict__ proj, const float* __restrict__ cw, + const float* __restrict__ cb, float* __restrict__ dproj, Shape s) { + constexpr int TAPS = 4; + const int c = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (c >= s.conv || r >= s.rows) return; + float acc = 0.0f; + for (int j = 0; j < TAPS; j++) { + const int at = r + TAPS - 1 - j; + if (at >= s.rows) continue; + float pre = cb[c]; + for (int jj = 0; jj < TAPS; jj++) { + const int src = at - (TAPS - 1) + jj; + if (src >= 0) pre = __fmaf_rn(cw[jj * s.conv + c], bf(proj[static_cast(src) * s.proj + s.inner + c]), pre); + } + acc += cw[j * s.conv + c] * dact[static_cast(at) * s.conv + c] * silu_grad(rbf(pre)); + } + dproj[static_cast(r) * s.proj + s.inner + c] = acc; +} + +// d(raw dt) = ddt sigmoid(raw + bias) into dproj's last columns (0 where the clamp held dt); grid (heads, rows). +extern "C" __global__ void tf_train_dt_back(const bf16* __restrict__ proj, const float* __restrict__ bias, const float* __restrict__ ddt, + float* __restrict__ dproj, Shape s) { + const int h = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y; + if (h >= s.heads || r >= s.rows) return; + const size_t at = static_cast(r) * s.proj + s.inner + s.conv + h; + const float v = bf(proj[at]) + bias[h]; + const float sp = fmaxf(v, 0.0f) + logf(1.0f + expf(-fabsf(v))); + const bool held = sp < s.lo || sp > s.hi; + dproj[at] = held ? 0.0f : ddt[r * s.heads + h] / (1.0f + expf(-v)); +} + +// One query row of one head: its probabilities and their gradient kept, and dq into dqkv; 256 threads, one a key row. +extern "C" __global__ void __launch_bounds__(256) tf_train_attn_q(const bf16* __restrict__ qkv, const float* __restrict__ dout, + float* __restrict__ probs, float* __restrict__ dscores, + float* __restrict__ dqkv, Heads a) { + __shared__ float qi[256], gi[256], ds[256], scratch[32]; + const int t = threadIdx.x, h = blockIdx.x, i = blockIdx.y, kv = h / (a.heads / a.kv_heads), lane = t & 31, w = t >> 5; + const int qd = a.heads * a.dim, kvd = a.kv_heads * a.dim; + const bf16* k = qkv + qd + kv * a.dim; + const bf16* v = qkv + qd + kvd + kv * a.dim; + for (int d = t; d < a.dim; d += 256) { + qi[d] = bf(qkv[static_cast(i) * a.nqkv + h * a.dim + d]); + gi[d] = dout[static_cast(i) * qd + h * a.dim + d]; + } + __syncthreads(); + const bool live = t <= i && t < a.rows; + float score = -INFINITY, dp = 0.0f; + if (live) { + float sc = 0.0f, dv = 0.0f; + for (int d = 0; d < a.dim; d++) { + sc += qi[d] * bf(k[static_cast(t) * a.nqkv + d]); + dv += gi[d] * bf(v[static_cast(t) * a.nqkv + d]); + } + score = sc * a.scale; + dp = dv; + } + float top = warp_max(score); + if (lane == 0) scratch[w] = top; + __syncthreads(); + top = warp_max(lane < 8 ? scratch[lane] : -INFINITY); + __syncthreads(); + const float e = live ? expf(score - top) : 0.0f; + const float total = all_sum(e, scratch, 8); + const float pr = e / total; + const float mix = all_sum(pr * dp, scratch, 8); + const float g = pr * (dp - mix); + ds[t] = g; + if (t < a.rows) { + probs[(static_cast(h) * a.rows + i) * a.rows + t] = pr; + dscores[(static_cast(h) * a.rows + i) * a.rows + t] = g; + } + __syncthreads(); + for (int d = t; d < a.dim; d += 256) { + float acc = 0.0f; + for (int j = 0; j <= i; j++) acc += ds[j] * bf(k[static_cast(j) * a.nqkv + d]); + dqkv[static_cast(i) * a.nqkv + h * a.dim + d] = acc * a.scale; + } +} + +// One key row of one kv head: dk and dv into dqkv, summed over the heads that read it and the query rows after it. +extern "C" __global__ void tf_train_attn_kv(const bf16* __restrict__ qkv, const float* __restrict__ dout, const float* __restrict__ probs, + const float* __restrict__ dscores, float* __restrict__ dqkv, Heads a) { + const int d = threadIdx.x, kv = blockIdx.x, j = blockIdx.y, per = a.heads / a.kv_heads; + const int qd = a.heads * a.dim, kvd = a.kv_heads * a.dim; + if (d >= a.dim) return; + float gk = 0.0f, gv = 0.0f; + for (int h = kv * per; h < (kv + 1) * per; h++) + for (int i = j; i < a.rows; i++) { + const size_t at = (static_cast(h) * a.rows + i) * a.rows + j; + gk += dscores[at] * bf(qkv[static_cast(i) * a.nqkv + h * a.dim + d]); + gv += probs[at] * dout[static_cast(i) * qd + h * a.dim + d]; + } + dqkv[static_cast(j) * a.nqkv + qd + kv * a.dim + d] = gk * a.scale; + dqkv[static_cast(j) * a.nqkv + qd + kvd + kv * a.dim + d] = gv; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 10615552716..01000e63388 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -36,6 +36,8 @@ pub const nemotron_route: []const u8 = if (available) &Blob("fatbin_nemotron_rou pub const nemotron_mamba: []const u8 = if (available) &Blob("fatbin_nemotron_mamba").bytes else &.{}; pub const nemotron_attention: []const u8 = if (available) &Blob("fatbin_nemotron_attention").bytes else &.{}; pub const nemotron_keyed: []const u8 = if (available) &Blob("fatbin_nemotron_keyed").bytes else &.{}; +pub const train: []const u8 = if (available) &Blob("fatbin_train").bytes else &.{}; +pub const train_mixers: []const u8 = if (available) &Blob("fatbin_train_mixers").bytes else &.{}; /// Symbols in the gdn image as cuobjdump lists them for the built fatbin (named namespace tf_gdn). pub const gdn_symbols = struct { diff --git a/zig/src/families/nemotron/adapters.zig b/zig/src/families/nemotron/adapters.zig index e11a3395ed8..c42c0d9fc17 100644 --- a/zig/src/families/nemotron/adapters.zig +++ b/zig/src/families/nemotron/adapters.zig @@ -6,29 +6,22 @@ const wts = @import("weights.zig"); const ops = @import("train_ops.zig"); const pl = @import("prefill_launch.zig"); const subspace = @import("subspace.zig"); +const dims = @import("slide_dims.zig"); const Buffer = mtl.Buffer; const At = pl.At; const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; -pub const block = 16; // ranks a lesson adds at each layer -pub const max_rank = 512; // thirty-two lessons' blocks -pub const max_blocks = max_rank / block; -pub const scale: f32 = 10; -pub const avoid_dims = 192; // directions sketched from the inputs a new block must leave alone -pub const candidates = 64; // directions sketched from the fact's inputs, which a new block's are chosen among - -/// Adam's settings for a block's outputs (its gate keeps them off what must stay): rate, moments' decays, epsilon. -pub const hyper = [4]f32{ 3e-4, 0.9, 0.999, 1e-8 }; - -/// Each new input direction's length, as MLX's LoRA draws its down factor's columns (uniform within 1 / sqrt(in)). -const a_norm: f32 = 0.577; - -/// A block's directions' squared length: a row's cosine with one is (x . a) / sqrt(unit |x|^2). -pub const unit = a_norm * a_norm; - -/// A block's gate before its lesson sets one: above any cosine, so the block stays shut. -pub const shut: f32 = 2; +pub const block = dims.block; +pub const max_rank = dims.max_rank; +pub const max_blocks = dims.max_blocks; +pub const scale = dims.scale; +pub const avoid_dims = dims.avoid_dims; +pub const candidates = dims.candidates; +pub const hyper = dims.hyper; +const a_norm = dims.a_norm; +pub const unit = dims.unit; +pub const shut = dims.shut; /// One layer's change: y += scale (x a^T) b after its output projection; a [max_rank, in], b [max_rank, out], f32. pub const Site = struct { diff --git a/zig/src/families/nemotron/choice.zig b/zig/src/families/nemotron/choice.zig index f9077789e94..bdc86a81871 100644 --- a/zig/src/families/nemotron/choice.zig +++ b/zig/src/families/nemotron/choice.zig @@ -1,10 +1,10 @@ //! A lesson's block chosen at every layer: the directions its fact's rows outweigh every steady row along, and gates. const std = @import("std"); const subspace = @import("subspace.zig"); -const adapters = @import("adapters.zig"); +const dims = @import("slide_dims.zig"); -const n = adapters.candidates; -const block = adapters.block; +const n = dims.candidates; +const block = dims.block; /// What each layer has seen of the steady rows and the fact's answer rows, along its candidate directions. pub const Choice = struct { @@ -116,7 +116,7 @@ pub const Choice = struct { c.opens[l] = 0; for (c.heads.items) |r| c.opens[l] += @intFromBool(subspace.dot(coef[0..n], facts[r * n ..][0..n]) > c.tau[l]); if (c.hits[l] == 0) { - c.tau[l] = adapters.shut; + c.tau[l] = dims.shut; c.opens[l] = 0; } } diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index b995f5e6ff1..7177181a4d3 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -21,6 +21,11 @@ pub const glue = @import("cuda_glue.zig"); pub const glue_ref = @import("glue_ref.zig"); pub const glue_math = @import("glue_math.zig"); pub const reuse = @import("cuda_reuse.zig"); +pub const slide = @import("cuda_slide.zig"); +pub const train = @import("cuda_train.zig"); +pub const train_ops = @import("cuda_train_ops.zig"); +pub const sites = @import("cuda_sites.zig"); +pub const slide_dims = @import("slide_dims.zig"); test { _ = @import("config.zig"); @@ -34,4 +39,8 @@ test { _ = glue_ref; _ = glue_math; _ = @import("cuda_prompt_grid.zig"); + _ = @import("learner.zig"); + _ = @import("subspace.zig"); + _ = @import("cuda_train_back.zig"); + _ = @import("cuda_learned.zig"); } diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 21d7f354f81..b95b1981842 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -15,6 +15,7 @@ const sampler = @import("cuda_sampler.zig"); const segs = @import("cuda_segments.zig"); const grid = @import("cuda_prompt_grid.zig"); const heat = @import("heat"); +const sites = @import("cuda_sites.zig"); /// nemotron_h.cuda.CONTEXT: prompt plus reply tokens when --context is not given, as `tensorfold serve` sizes it. pub const default_context = 16384; @@ -26,6 +27,7 @@ pub const Options = struct { sampling: ?sampler.Sampling = null, // the rule the graphs compile in; null or temperature 0 decodes greedily segments: usize = 1, // whole prompt chunks a call runs as staggered segments (1: one chunk at a time) carveout: ?*cuda.Carveout = null, // KV planes go to the display carveout first while it holds them + slide: bool = false, // Sliding Weights: every layer's change in the forward before its graphs are captured }; /// Asked before each prompt chunk (or segmented call): true stops the prompt with error.Cancelled. @@ -95,6 +97,8 @@ pub const Engine = struct { seg: ?segs.Segments = null, // their streams and scratch, made at load (or when setSegments asks for more) carve: ?*cuda.Carveout = null, // Options.carveout; it outlives the engine heat_gate: heat.Gate = .{}, // off unless TF_HEAT_HIGH and TF_HEAT_LOW are set + slide: ?sites.Sites = null, // --slide: the change's sites, attached at load, until the trainer takes them + dir: ?[]u8 = null, // --slide: the model folder lessons are saved into /// Loads the checkpoint into the Python engine's layouts and sizes the caches; `triton_dir` null: our own glue. pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, model_dir: []const u8, triton_dir: ?[]const u8, opts: Options) !*Engine { @@ -141,6 +145,16 @@ pub const Engine = struct { e.copied = try cuda.Event.init(ctx.d, false); e.sampled_ready = try cuda.Event.init(ctx.d, false); try e.copied.record(e.stream); + // --slide: the change's kernels and sites last, so everything above sits where it would without them + if (opts.slide) { + try e.k.loadTrain(); + e.slide = try sites.Sites.init(gpa, ctx.d, e.c, state.prefill_rows); + errdefer e.slide.?.deinit(); + e.dir = try gpa.dupe(u8, model_dir); + e.slide.?.attach(&e.w, true); + } + errdefer if (e.slide) |*s| s.deinit(); + errdefer if (e.dir) |d| gpa.free(d); try e.setSampling(opts.sampling); if (opts.graphs) try e.capture(opts.mtp); e.heat_gate = heat.Gate.fromEnv() catch |err| { @@ -199,6 +213,8 @@ pub const Engine = struct { e.history.free(); e.pinned.free(); e.b.deinit(); + if (e.slide) |*s| s.deinit(); + if (e.dir) |d| e.gpa.free(d); e.w.deinit(); e.k.deinit(); e.side.s.deinit(); diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index 1078ff2949e..b3432d2921b 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -140,6 +140,7 @@ pub const Forward = struct { try f.mark(.gnorm); try o.dense(b.g, b.gxs, m.out_proj, b.delta, rows); if (m.out_rest != 0) try o.restRows(b.g, c.inner(), m.out_rest, b.delta, c.hidden, false, rows, 1, 0, c.hidden, c.inner()); + try adapt(o, m.adapter, b.g, c.inner(), b.delta, false, c.hidden, 1, 0, rows); try f.mark(.mamba_out); delta = .dense; mj += 1; @@ -160,6 +161,7 @@ pub const Forward = struct { try f.mark(.attention); try o.dense(b.att, b.axs, a.o, b.delta, rows); if (a.o_rest != 0) try o.restRows(b.att, qd, a.o_rest, b.delta, c.hidden, false, rows, 1, 0, c.hidden, qd); + try adapt(o, a.adapter, b.att, qd, b.delta, false, c.hidden, 1, 0, rows); try f.mark(.attn_o); delta = .dense; aj += 1; @@ -205,11 +207,12 @@ pub const Forward = struct { try f.sharedRest(o, m, rows, !prompt); } - /// A lesson's change to the shared expert's down projection, past its codes: into its two halves' pair rows. + /// A lesson's rest into the shared expert's halves' pair rows, a live change (--slide, 2W wide) into the first's. fn sharedRest(f: *const Forward, o: kern.Ops, m: weights.MoE, rows: usize, y_f32: bool) !void { const c = f.c; const ex = m.experts; for (m.rest, 0..) |r, h| if (r != 0) try o.restRows(f.b.act, ex.width, r, f.b.ymoe, ex.dims, y_f32, rows, c.slots(), c.top_k + h, ex.dims, ex.width); + try adapt(o, m.adapter, f.b.act + c.top_k * ex.width * 2, c.slots() * ex.width, f.b.ymoe, y_f32, ex.dims, c.slots(), c.top_k, rows); } /// The decode MoE with its shared halves on the side stream: their pairs are fixed, so they need no routing. @@ -309,6 +312,7 @@ pub const Forward = struct { try f.glue.groupRmsnorm(b.sy, blk.mamba.gnorm, b.g, b.gxs, w.rows, c.inner(), c.groups, c.eps); try f.ops.prefillDense(b.g, blk.mamba.out_proj, b.delta, w.rows); if (blk.mamba.out_rest != 0) try f.ops.restRows(b.g, c.inner(), blk.mamba.out_rest, b.delta, c.hidden, false, w.rows, 1, 0, c.hidden, c.inner()); + try adapt(f.ops, blk.mamba.adapter, b.g, c.inner(), b.delta, false, c.hidden, 1, 0, w.rows); w.delta = .dense; w.mj += 1; }, @@ -316,6 +320,7 @@ pub const Forward = struct { try f.ops.prefillDense(b.att, blk.attn.o, b.delta, w.rows); const qd = c.heads * c.head_dim; if (blk.attn.o_rest != 0) try f.ops.restRows(b.att, qd, blk.attn.o_rest, b.delta, c.hidden, false, w.rows, 1, 0, c.hidden, qd); + try adapt(f.ops, blk.attn.adapter, b.att, qd, b.delta, false, c.hidden, 1, 0, w.rows); w.delta = .dense; w.aj += 1; }, @@ -326,6 +331,11 @@ pub const Forward = struct { } } + /// The chunk's last norm alone: w.x then holds the residual it read, b.y every row's normed hidden state. + pub fn finalNorm(f: *const Forward, w: *Walk) !void { + try f.norm(&w.x, w.delta, f.w.norm_f, w.rows, false); + } + /// The chunk's last norm, its rows' hidden states for the MTP head, and the token after its last row. pub fn chunkFinish(f: *const Forward, w: *Walk) !void { const c = f.c; @@ -340,3 +350,9 @@ pub const Forward = struct { if (f.dump) |d| try d.tail(f.ops, b.p_logits, b.p_sampled, 1, c.vocab); } }; + +/// A live lesson's change after an output projection (--slide), on `o`'s stream: y += scale (x a^T) b; none: nothing. +fn adapt(o: kern.Ops, ad: ?*const weights.Adapter, x: u64, x_stride: usize, y: u64, y_f32: bool, y_stride: usize, row_mul: usize, row_add: usize, rows: usize) !void { + const a = ad orelse return; + try o.train().adapt(a.*, x, x_stride, y, y_f32, y_stride, row_mul, row_add, rows); +} diff --git a/zig/src/families/nemotron/cuda_kernels.zig b/zig/src/families/nemotron/cuda_kernels.zig index 5b909cf8eaa..a4dfe662f4a 100644 --- a/zig/src/families/nemotron/cuda_kernels.zig +++ b/zig/src/families/nemotron/cuda_kernels.zig @@ -4,6 +4,7 @@ const std = @import("std"); const cuda = @import("cuda"); const torch_ops = @import("cuda_torch_ops.zig"); const glue = @import("cuda_glue.zig"); +const train_ops = @import("cuda_train_ops.zig"); /// Mangled names of the instantiations the copies in zig/kernels/cuda export (cuobjdump -symbols of each fatbin). const sym = struct { @@ -95,6 +96,8 @@ pub const Kernels = struct { draw_ids: cuda.Function, logprob_rows: cuda.Function, torch: torch_ops.Functions, + train: train_ops.Fns = undefined, // Sliding Weights: the change after each output projection, and learning it + train_mods: ?[2]cuda.Module = null, // loaded by loadTrain (--slide) after the weights, else never expert_blocks: [2]usize, // resident blocks the decode expert kernels fill: per SM times SMs gemv_blocks: usize, // resident lane_gemv CTAs: per SM times SMs gb10: bool, @@ -136,6 +139,7 @@ pub const Kernels = struct { k.draw_ids = try k.mods[14].function("tf_draw_ids"); k.glue = try glue.Fns.resolve(k.mods[16..21]); k.logprob_rows = try k.mods[14].function("tf_logprob_rows"); + k.train_mods = null; k.triton = if (triton_dir) |dir| try cuda.aot.Set.load(gpa, io, d, ctx.device, dir) else null; errdefer if (k.triton) |*t| t.deinit(); try k.group.allowDynamicShared(group_smem); @@ -160,6 +164,18 @@ pub const Kernels = struct { if (k.split) |*sp| sp.deinit(); if (k.triton) |*t| t.deinit(); for (&k.mods) |*m| m.unload(); + if (k.train_mods) |*ms| for (ms) |*m| m.unload(); + } + + /// Sliding Weights' modules (--slide only), loaded after the weights so those sit where they would without them. + pub fn loadTrain(k: *Kernels) !void { + if (k.train_mods != null) return; + var train = try cuda.Module.load(k.d, cuda.kernels.train); + errdefer train.unload(); + var mixers = try cuda.Module.load(k.d, cuda.kernels.train_mixers); + errdefer mixers.unload(); + k.train = try train_ops.Fns.resolve(train, mixers); + k.train_mods = .{ train, mixers }; } }; @@ -197,6 +213,11 @@ pub const Ops = struct { return .{ .f = &o.k.torch, .s = o.s }; } + /// The training kernels (and the change's forward) on this stream. + pub fn train(o: Ops) train_ops.Train { + return .{ .f = &o.k.train, .s = o.s, .d = o.k.d }; + } + /// sample.cu: row r of bf16 logits drawn at position meta[0] + r + 1 + offset, columns as `ids` token ids if given. pub fn draw(o: Ops, logits: u64, vocab: usize, rule: u64, meta: u64, offset: usize, out: u64, rows: usize, ids: ?u64, prob: ?u64) !void { var a: cuda.Args = .{}; diff --git a/zig/src/families/nemotron/cuda_learned.zig b/zig/src/families/nemotron/cuda_learned.zig new file mode 100644 index 00000000000..89e299e83a9 --- /dev/null +++ b/zig/src/families/nemotron/cuda_learned.zig @@ -0,0 +1,139 @@ +//! Output projections a CUDA learner's lessons changed, folded in and written into the model's shards as bf16. +const std = @import("std"); +const core = @import("core"); +const cfg = @import("config.zig"); +const dims = @import("slide_dims.zig"); +const sites = @import("cuda_sites.zig"); +const subspace = @import("subspace.zig"); +const host4 = core.affine4_host; +const Tensor = core.checkpoint.Tensor; + +/// Layer i's output projection as the checkpoint names its module: the one a lesson's change sits after. +pub fn moduleName(buf: []u8, c: cfg.Config, i: usize) ![]const u8 { + const leaf = switch (c.kinds[i]) { + .moe => "shared_experts.down_proj", + .mamba => "out_proj", + .attention => "o_proj", + }; + return std.fmt.bufPrint(buf, "backbone.layers.{d}.mixer.{s}", .{ i, leaf }); +} + +/// One layer's output projection as the shards hold it (bf16, or 4-bit with its scales and biases), the change added. +const Fold = struct { + d: usize, + k: usize, + weight: Tensor, + scales: ?Tensor, + biases: ?Tensor, + site: *const sites.Site, + ranks: usize, + out: []u16, + + fn run(f: Fold) !void { + const a = std.heap.page_allocator; + const n = f.d * f.k; + const values = try a.alloc(f32, n); + defer a.free(values); + try base(f, values); + const av = f.site.a.slice(f32, dims.max_rank * f.k); + const bv = f.site.b.slice(f32, dims.max_rank * f.d); + for (0..f.d) |j| { + const row = values[j * f.k ..][0..f.k]; + for (0..f.ranks) |q| { + const c = dims.scale * bv[q * f.d + j]; + if (c != 0) subspace.axpy(row, c, av[q * f.k ..][0..f.k]); + } + } + for (f.out, values) |*o, v| o.* = host4.bf16of(v); + } + + /// The weight as stored: bf16 exactly, else 4-bit codes dequantized (read unaligned from the mapped shard). + fn base(f: Fold, values: []f32) !void { + const w = f.weight.bytes; + if (f.weight.dtype == .bf16) { + for (values, 0..) |*v, i| v.* = host4.f32of(std.mem.readInt(u16, w[2 * i ..][0..2], .little)); + return; + } + const a = std.heap.page_allocator; + const n = values.len; + const words = try a.alloc(u32, n / 8); + defer a.free(words); + const sb = try a.alloc(u16, 2 * (n / host4.group)); + defer a.free(sb); + for (words, 0..) |*x, i| x.* = std.mem.readInt(u32, w[4 * i ..][0..4], .little); + for (sb[0 .. n / host4.group], 0..) |*x, i| x.* = std.mem.readInt(u16, f.scales.?.bytes[2 * i ..][0..2], .little); + for (sb[n / host4.group ..], 0..) |*x, i| x.* = std.mem.readInt(u16, f.biases.?.bytes[2 * i ..][0..2], .little); + host4.dequantize(words, sb[0 .. n / host4.group], sb[n / host4.group ..], values); + } +}; + +/// Every output projection the first `ranks` of the change touch, folded in and written into the model's shards. +pub fn write(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, c: cfg.Config, s: *const sites.Sites, ranks: usize) !usize { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var ck = try core.Checkpoint.openModel(gpa, io, dir); + var open = true; + defer if (open) ck.close(); + var folds: std.ArrayList(Fold) = .empty; + var edits: std.ArrayList(core.shard_edit.Replacement) = .empty; + var total: usize = 0; + for (s.list) |*site| { + const bv = site.b.slice(f32, dims.max_rank * site.out)[0 .. ranks * site.out]; + if (std.mem.allEqual(f32, bv, 0)) continue; + var name: [160]u8 = undefined; + const mod = try arena.dupe(u8, try moduleName(&name, c, site.layer)); + const weight = try ck.get(try std.fmt.allocPrint(arena, "{s}.weight", .{mod})); + const quantized = weight.dtype != .bf16; + if (quantized and weight.dtype != .u32) return error.UnsupportedQuantization; + const d = c.hidden; + const k = site.in; + if (weight.dim(0) != d or weight.dim(1) * @as(usize, if (quantized) 8 else 1) != k) return error.UnexpectedTensor; + const out = try arena.alloc(u16, d * k); + try folds.append(arena, .{ + .d = d, + .k = k, + .weight = weight, + .scales = if (quantized) try ck.get(try std.fmt.allocPrint(arena, "{s}.scales", .{mod})) else null, + .biases = if (quantized) try ck.get(try std.fmt.allocPrint(arena, "{s}.biases", .{mod})) else null, + .site = site, + .ranks = ranks, + .out = out, + }); + const drop = try arena.dupe([]const u8, &.{ try std.fmt.allocPrint(arena, "{s}.scales", .{mod}), try std.fmt.allocPrint(arena, "{s}.biases", .{mod}) }); + try edits.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}.weight", .{mod}), .dtype = .bf16, .shape = try arena.dupe(usize, &.{ d, k }), .bytes = std.mem.sliceAsBytes(out), .drop = drop }); + total += out.len * 2; + } + if (folds.items.len == 0) return 0; + var failed = std.atomic.Value(bool).init(false); + var next = std.atomic.Value(usize).init(0); + const Worker = struct { + fn go(all: []const Fold, counter: *std.atomic.Value(usize), bad: *std.atomic.Value(bool)) void { + while (true) { + const at = counter.fetchAdd(1, .monotonic); + if (at >= all.len) return; + all[at].run() catch bad.store(true, .monotonic); + } + } + }; + var threads: [12]?std.Thread = @splat(null); + for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.go, .{ folds.items, &next, &failed }) catch null; + Worker.go(folds.items, &next, &failed); + for (threads) |t| if (t) |th| th.join(); + if (failed.load(.monotonic)) return error.OutOfMemory; + ck.close(); // every fold has read its shard: the edits may now rewrite the files it mapped + open = false; + try core.shard_edit.bake(gpa, io, dir, edits.items); + return total; +} + +test "a layer's output projection module name" { + var c: cfg.Config = undefined; + c.kinds[0] = .mamba; + c.kinds[1] = .moe; + c.kinds[2] = .attention; + var buf: [160]u8 = undefined; + try std.testing.expectEqualStrings("backbone.layers.0.mixer.out_proj", try moduleName(&buf, c, 0)); + try std.testing.expectEqualStrings("backbone.layers.1.mixer.shared_experts.down_proj", try moduleName(&buf, c, 1)); + try std.testing.expectEqualStrings("backbone.layers.2.mixer.o_proj", try moduleName(&buf, c, 2)); +} diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index 0e24c4da3d3..269a9879572 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -13,6 +13,10 @@ pub const snap_bytes = reuse.bytes; pub const snap_save = reuse.save; pub const snap_restore = reuse.restore; pub const snap_drop = reuse.drop; +const core = @import("core"); + +/// The learner --slide runs over this engine (cuda_slide.zig). +pub const slide = @import("cuda_slide.zig"); pub const model_type = "nemotron_h"; pub const formats: []const []const u8 = &.{"mlx-q4g64"}; @@ -20,7 +24,7 @@ pub const default_context: i64 = engine.default_context; pub const max_segments: u32 = @import("cuda_segments.zig").MAX; pub const prompt_rows: u32 = state.prefill_rows; -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1 }; +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false }; /// A lone drafted stream's own driver: decodes it until it finishes (false) or `yield` hands it over (true). pub const LoneRun = *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: *anyopaque, committed: *const fn (*anyopaque) void, yield: *const fn (*anyopaque) bool) anyerror!bool; @@ -38,15 +42,21 @@ pub const Loaded = struct { deinit: *const fn (*anyopaque) void, lone: ?LoneRun = null, // called with `ctx`; null: every stream in the lane core target: *reuse.Target, // the prompt cache copies this engine (cuda_reuse.zig) + learns: ?*engine.Engine = null, // --slide: the engine its learner trains, whose sites it attached at load }; +/// The first shard, index or config.json in `dir` that a write in place would reach through a link, or null. +pub fn linked(arena: std.mem.Allocator, io: std.Io, dir: []const u8) !?[]const u8 { + return core.shard_edit.linked(arena, io, dir); +} + const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, head: ?*Head, lanes: Lanes, target: reuse.Target, carve: ?*cuda.Carveout }; /// Own-sequence graphs support both draw modes; drafting also captures the head. pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { const carve = try openCarveout(gpa, ctx); errdefer if (carve) |c| closeCarveout(gpa, c); - const e = try engine.Engine.init(gpa, io, ctx, dir, kernels, .{ .context = o.context, .mtp = o.drafts, .graphs = true, .sampling = null, .segments = o.segments, .carveout = carve }); + const e = try engine.Engine.init(gpa, io, ctx, dir, kernels, .{ .context = o.context, .mtp = o.drafts, .graphs = true, .sampling = null, .segments = o.segments, .carveout = carve, .slide = o.slide }); errdefer e.deinit(); const head: ?*Head = if (o.drafts) try Head.init(e) else null; errdefer if (head) |h| h.deinit(); @@ -71,6 +81,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .deinit = release, .target = &own.target, .lone = if (head != null) loneRun else null, + .learns = if (o.slide) e else null, }; } diff --git a/zig/src/families/nemotron/cuda_sites.zig b/zig/src/families/nemotron/cuda_sites.zig new file mode 100644 index 00000000000..f6189c2b301 --- /dev/null +++ b/zig/src/families/nemotron/cuda_sites.zig @@ -0,0 +1,253 @@ +//! Each layer's learned change on CUDA (--slide): a block of ranks a lesson, in mapped host memory the GPU reads too. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const dims = @import("slide_dims.zig"); +const subspace = @import("subspace.zig"); +const weights = @import("cuda_weights.zig"); +const ops = @import("cuda_train_ops.zig"); + +pub const block = dims.block; +pub const max_rank = dims.max_rank; +pub const max_blocks = dims.max_blocks; +pub const avoid_dims = dims.avoid_dims; +pub const candidates = dims.candidates; + +/// Pinned host pages mapped into the device's address space: the host writes and reads them, kernels too. +pub const Shared = struct { + buf: cuda.HostBuffer, + dev: u64, + + /// `n` zeroed values of T. + pub fn init(d: *const cuda.Driver, comptime T: type, n: usize) !Shared { + var buf = try cuda.HostBuffer.allocMapped(d, @max(n * @sizeOf(T), 16)); + errdefer buf.free(); + @memset(buf.bytes, 0); + return .{ .buf = buf, .dev = try buf.device() }; + } + + pub fn free(s: *Shared) void { + s.buf.free(); + } + + pub fn slice(s: Shared, comptime T: type, n: usize) []T { + return s.buf.slice(T)[0..n]; + } +}; + +/// One layer's change: y += scale (x a^T) b after its output projection; a [max_rank, in], b [max_rank, out], f32. +pub const Site = struct { + layer: usize, + in: usize, + out: usize, + a: Shared, // every block's input directions, fixed when its lesson begins + b: Shared, // every block's outputs; only the open block's still learn + tau: Shared, // [max_blocks]: each block's gate, the share of a row's input it needs to act on that row + gb: Shared, // [block, out]: the open block's gradient + mb: Shared, // [block, out]: its Adam moments + vb: Shared, + avoid: Shared, // [avoid_dims, in]: a sketch of the inputs the next block must leave alone + seek: Shared, // [candidates, in]: a sketch of the fact's inputs, then the candidate directions it frames + kept: []f32, // host: [3, block, out], the open block's b and moments as its round began + ad: weights.Adapter = undefined, // the descriptor the forward points at while attached + + pub fn adapter(s: *const Site, sites: *const Sites) weights.Adapter { + return .{ .a = s.a.dev, .b = s.b.dev, .tau = s.tau.dev, .rank = sites.word.dev, .xa = sites.xa.ptr, .xn = sites.xn.ptr, .in = s.in, .out = s.out }; + } + + /// Block k's gate. + pub fn gate(s: *const Site, k: usize) *f32 { + return &s.tau.slice(f32, max_blocks)[k]; + } + + fn fields(s: *Site) [8]*Shared { + return .{ &s.a, &s.b, &s.tau, &s.gb, &s.mb, &s.vb, &s.avoid, &s.seek }; + } +}; + +pub const Sites = struct { + gpa: std.mem.Allocator, + list: []Site, + word: Shared, // u32: the ranks in use as the forward's kernels read them (0 while detached) + xa: cuda.DeviceBuffer, // [rows, max_rank]: the forward's scratch, used by one site at a time + xn: cuda.DeviceBuffer, // [rows]: each row's squared input length, the same way + rank: usize = 0, // ranks in use, the open block last + steps: u64 = 0, // the open block's Adam steps + kept_steps: u64 = 0, + + /// Room for every block at every layer, none in use: the forward is unchanged until a block opens. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, c: cfg.Config, rows: usize) !Sites { + const list = try gpa.alloc(Site, c.layers); + var made: usize = 0; + errdefer { + for (list[0..made]) |*s| free(gpa, s); + gpa.free(list); + } + for (list, 0..) |*s, i| { + const in: usize = switch (c.kinds[i]) { + .moe => c.shared_width, + .mamba => c.inner(), + .attention => c.heads * c.head_dim, + }; + const out = c.hidden; + s.* = .{ .layer = i, .in = in, .out = out, .a = undefined, .b = undefined, .tau = undefined, .gb = undefined, .mb = undefined, .vb = undefined, .avoid = undefined, .seek = undefined, .kept = &.{} }; + const sizes = [_]usize{ max_rank * in, max_rank * out, max_blocks, block * out, block * out, block * out, avoid_dims * in, candidates * in }; + var got: usize = 0; + errdefer for (s.fields()[0..got]) |f| f.free(); + for (s.fields(), sizes) |f, n| { + f.* = try Shared.init(d, f32, n); + got += 1; + } + s.kept = try gpa.alloc(f32, 3 * block * out); + made += 1; + } + var word = try Shared.init(d, u32, 1); + errdefer word.free(); + var xa = try cuda.DeviceBuffer.alloc(d, rows * max_rank * 4); + errdefer xa.free(); + const xn = try cuda.DeviceBuffer.alloc(d, rows * 4); + return .{ .gpa = gpa, .list = list, .word = word, .xa = xa, .xn = xn }; + } + + pub fn deinit(s: *Sites) void { + for (s.list) |*site| free(s.gpa, site); + s.gpa.free(s.list); + s.word.free(); + s.xa.free(); + s.xn.free(); + } + + fn free(gpa: std.mem.Allocator, s: *Site) void { + for (s.fields()) |f| f.free(); + gpa.free(s.kept); + } + + /// Every layer's forward carries its change (graphs captured after keep it); the ranks in use apply when on. + pub fn attach(s: *Sites, w: *weights.Weights, on: bool) void { + for (s.list) |*site| { + site.ad = site.adapter(s); + const ad: ?*const weights.Adapter = if (on) &site.ad else null; + switch (w.blocks[site.layer].kind) { + .moe => w.blocks[site.layer].moe.adapter = ad, + .mamba => w.blocks[site.layer].mamba.adapter = ad, + .attention => w.blocks[site.layer].attn.adapter = ad, + } + } + s.publish(on); + } + + /// The ranks the kernels apply: those in use, or none. + fn publish(s: *Sites, on: bool) void { + s.word.slice(u32, 1)[0] = if (on) @intCast(s.rank) else 0; + } + + /// The first rank of the open block. + pub fn first(s: *const Sites) usize { + return s.rank - block; + } + + /// Every layer's candidate directions: the fact's sketch with what must stay taken out, made orthonormal. + pub fn frame(s: *Sites) void { + var threads: [16]?std.Thread = @splat(null); + const n = @min(threads.len, s.list.len); + for (threads[0..n], 0..) |*t, k| t.* = std.Thread.spawn(.{}, frameShare, .{ s.list, k, n }) catch null; + for (threads[0..n], 0..) |t, k| if (t) |th| th.join() else frameShare(s.list, k, n); + } + + /// A new block at every layer, shut, its directions `choice` [layers, block, candidates] of the candidates; b zero. + pub fn open(s: *Sites, choice: []const f32) !void { + if (s.rank + block > max_rank) return error.LearnedChangeFull; + const at = s.rank; + for (s.list, 0..) |*site, l| { + directions(site, at, l, choice); + site.gate(at / block).* = dims.shut; + @memset(site.b.slice(f32, max_rank * site.out)[at * site.out ..][0 .. block * site.out], 0); + for ([_]Shared{ site.gb, site.mb, site.vb }) |buf| @memset(buf.slice(f32, block * site.out), 0); + } + s.rank += block; + s.steps = 0; + s.publish(true); + } + + /// The open block's directions rebuilt from `choice` and its gate open on every row: a plain change of the weights. + pub fn plain(s: *Sites, choice: []const f32) void { + const at = s.first(); + for (s.list, 0..) |*site, l| { + const g = site.gate(at / block); + if (g.* >= dims.shut) continue; + directions(site, at, l, choice); + g.* = -std.math.inf(f32); + } + } + + /// The open block taken back out, its lesson having left nothing in it. + pub fn close(s: *Sites) void { + s.rank -= block; + for (s.list) |*site| @memset(site.b.slice(f32, max_rank * site.out)[s.rank * site.out ..][0 .. block * site.out], 0); + s.publish(true); + } + + /// One Adam step on the open block's outputs (after a step's gradients are in); the gradients are cleared. + pub fn adam(s: *Sites, t: ops.Train) !void { + s.steps += 1; + const step: f32 = @floatFromInt(s.steps); + const h = dims.hyper; + const corr = [2]f32{ 1 / (1 - std.math.pow(f32, h[1], step)), 1 / (1 - std.math.pow(f32, h[2], step)) }; + for (s.list) |*site| try t.adam(site.b.dev + s.first() * site.out * 4, site.gb.dev, site.mb.dev, site.vb.dev, block * site.out, h, corr); + } + + /// The open block's outputs and moments as they are now, for `restore` (read once the stream has finished). + pub fn keep(s: *Sites) void { + s.kept_steps = s.steps; + for (s.list) |*site| { + const n = block * site.out; + @memcpy(site.kept[0..n], site.b.slice(f32, max_rank * site.out)[s.first() * site.out ..][0..n]); + @memcpy(site.kept[n .. 2 * n], site.mb.slice(f32, n)); + @memcpy(site.kept[2 * n ..], site.vb.slice(f32, n)); + } + } + + /// Back to what `keep` saw, gradients cleared. + pub fn restore(s: *Sites) void { + s.steps = s.kept_steps; + for (s.list) |*site| { + const n = block * site.out; + @memcpy(site.b.slice(f32, max_rank * site.out)[s.first() * site.out ..][0..n], site.kept[0..n]); + @memcpy(site.mb.slice(f32, n), site.kept[n .. 2 * n]); + @memcpy(site.vb.slice(f32, n), site.kept[2 * n ..]); + @memset(site.gb.slice(f32, n), 0); + } + } + + /// Gradients and both sketches back to zero, before a lesson's inputs are sketched. + pub fn clear(s: *Sites) void { + for (s.list) |*site| { + @memset(site.gb.slice(f32, block * site.out), 0); + @memset(site.avoid.slice(f32, avoid_dims * site.in), 0); + @memset(site.seek.slice(f32, candidates * site.in), 0); + } + } +}; + +/// Block `at`'s input directions at layer l: its `choice` rows' combinations of the candidates, each a_norm long. +fn directions(site: *Site, at: usize, l: usize, choice: []const f32) void { + const a = site.a.slice(f32, max_rank * site.in)[at * site.in ..][0 .. block * site.in]; + const f = site.seek.slice(f32, candidates * site.in); + @memset(a, 0); + for (0..block) |q| for (0..candidates) |j| { + subspace.axpy(a[q * site.in ..][0..site.in], dims.a_norm * choice[(l * block + q) * candidates + j], f[j * site.in ..][0..site.in]); + }; +} + +/// Every n-th site from k: its candidate directions. +fn frameShare(list: []Site, k: usize, n: usize) void { + var i = k; + while (i < list.len) : (i += n) { + const site = &list[i]; + const avoid = site.avoid.slice(f32, avoid_dims * site.in); + const seek = site.seek.slice(f32, candidates * site.in); + subspace.orthonormal(avoid, avoid_dims, site.in); + subspace.remove(seek, candidates, avoid, avoid_dims, site.in); + subspace.orthonormal(seek, candidates, site.in); + } +} diff --git a/zig/src/families/nemotron/cuda_slide.zig b/zig/src/families/nemotron/cuda_slide.zig new file mode 100644 index 00000000000..5ba302fb466 --- /dev/null +++ b/zig/src/families/nemotron/cuda_slide.zig @@ -0,0 +1,10 @@ +//! Nemotron's Sliding Weights learner on CUDA: the backend-neutral learner over the CUDA trainer. +const learner = @import("learner.zig"); +const train = @import("cuda_train.zig"); + +pub const Backend = train.Backend; +pub const Example = learner.Example; +pub const Lesson = learner.Lesson; +pub const Report = learner.Report; +pub const Step = learner.Step; +pub const Learner = learner.Of(train); diff --git a/zig/src/families/nemotron/cuda_train.zig b/zig/src/families/nemotron/cuda_train.zig new file mode 100644 index 00000000000..d3170dd2a4e --- /dev/null +++ b/zig/src/families/nemotron/cuda_train.zig @@ -0,0 +1,299 @@ +//! One step of learning in the weights on CUDA: a sequence through a prompt chunk, its loss, back to each change. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const engine = @import("cuda_engine.zig"); +const state = @import("cuda_state.zig"); +const glue = @import("cuda_glue.zig"); +const fwd = @import("cuda_forward.zig"); +const ops = @import("cuda_train_ops.zig"); +const back = @import("cuda_train_back.zig"); +const sites = @import("cuda_sites.zig"); +const learned = @import("cuda_learned.zig"); +const dims = @import("slide_dims.zig"); + +/// What the learner runs on: the CUDA engine, whose change's sites --slide made at load. +pub const Backend = engine.Engine; + +/// Rows a step learns from at most: a question and its answer (attention's backward reads at most 256). +pub const max_rows = 256; + +/// A step's loss alone, with the open block's gradient, or with that and Adam; or site inputs sketched or projected. +pub const Mode = enum { loss, grad, learn, avoid, seek, project }; + +/// The answer's mean loss, and whether each of its tokens was the likeliest at its row. +pub const Result = struct { loss: f32, recalled: bool }; + +/// The trainer's own caches hold one attention chunk of keys, past max_rows. +const keys = state.chunk_keys; + +/// The scratch each kind of layer's backward reads, with how much of it a row (or the layer) fills. +const Part = enum { proj, conv, inner, qkv, heads, pairs, router, act, ys }; +const Act = struct { field: []const u8, part: Part }; +const moe_acts = [_]Act{ .{ .field = "pick", .part = .pairs }, .{ .field = "wts", .part = .pairs }, .{ .field = "part", .part = .router }, .{ .field = "act", .part = .act }, .{ .field = "ymoe", .part = .ys } }; +const mamba_acts = [_]Act{ .{ .field = "proj", .part = .proj }, .{ .field = "p_xc", .part = .conv }, .{ .field = "g", .part = .inner } }; +const attention_acts = [_]Act{ .{ .field = "qkv", .part = .qkv }, .{ .field = "att", .part = .heads } }; + +fn acts(comptime kind: cfg.Kind) []const Act { + return switch (kind) { + .moe => &moe_acts, + .mamba => &mamba_acts, + .attention => &attention_acts, + }; +} + +fn bytes(c: cfg.Config, part: Part, rows: usize) usize { + return switch (part) { + .proj => rows * c.projDim() * 2, + .conv => rows * c.convDim() * 2, + .inner => rows * c.inner() * 2, + .qkv => rows * c.qkvDim() * 2, + .heads => rows * c.heads * c.head_dim * 2, + .pairs => rows * c.slots() * 4, + .router => glue.routerShape(c.hidden).sk * rows * c.experts * 4, + .act => rows * c.slots() * c.expert_width * 2, + .ys => rows * c.slots() * c.hidden * 2, + }; +} + +/// A layer's slot: each part at max_rows, 256-byte aligned. +fn slot(c: cfg.Config, kind: cfg.Kind) usize { + var n: usize = 0; + switch (kind) { + inline else => |k| inline for (comptime acts(k)) |f| { + n += std.mem.alignForward(usize, bytes(c, f.part, max_rows), 256); + }, + } + return n; +} + +pub const Trainer = struct { + e: *engine.Engine, + sites: sites.Sites, + seq: state.Seq, // the trainer's own caches and Mamba state: a step leaves every stream's alone + b: state.Buffers, // the engine's scratch, the trainer's sequence in place of the bound one's + bufs: back.Bufs, + saved: cuda.DeviceBuffer, // bf16 [layers + 1, max_rows, D]: the residual entering each layer, then the last one + acts: cuda.DeviceBuffer, // what each layer's backward reads of its forward, from slots[layer] + slots: [cfg.max_layers]usize, + logits: cuda.DeviceBuffer, // bf16 [max_rows, V]: the logits, then their gradient + head_t: cuda.DeviceBuffer, // bf16 [D, V]: the LM head dequantized transposed, for the loss's backward product + io: sites.Shared, // u32 ids [max_rows], targets [max_rows], f32 weights [max_rows], stats [max_rows, 2] + proj: sites.Shared, // f32 [layers, max_rows, candidates]: each row along each layer's candidate directions + sketched: usize = 0, // rows sketched since the sketches were cleared, each row's place in them + + /// Every buffer a step needs, the change's sites taken from the engine (still attached: nothing moves yet). + pub fn init(gpa: std.mem.Allocator, e: *engine.Engine) !*Trainer { + const c = e.c; + if (c.mamba_head_dim != 64 or c.state != 128 or c.conv_kernel != 4 or c.head_dim > 256 or !c.norm_topk) return error.UnsupportedShape; + const owned = e.slide orelse return error.NotLearning; + const d = e.ctx.d; + const t = try gpa.create(Trainer); + errdefer gpa.destroy(t); + t.* = .{ .e = e, .sites = owned, .seq = undefined, .b = e.b, .bufs = undefined, .saved = undefined, .acts = undefined, .slots = undefined, .logits = undefined, .head_t = undefined, .io = undefined, .proj = undefined }; + t.seq = try state.Seq.init(d, c, keys, &.{}, e.stream, null); + errdefer t.seq.deinit(); + inline for (state.seq_fields, t.seq.ptr) |name, p| @field(t.b, name) = p; + t.bufs = try back.Bufs.init(d, c, max_rows); + errdefer t.bufs.deinit(); + t.io = try sites.Shared.init(d, u32, 5 * max_rows); + errdefer t.io.free(); + t.b.p_ids = t.io.dev; + t.proj = try sites.Shared.init(d, f32, c.layers * max_rows * dims.candidates); + errdefer t.proj.free(); + var at: usize = 0; + for (0..c.layers) |l| { + t.slots[l] = at; + at += slot(c, c.kinds[l]); + } + const sizes = [_]usize{ (c.layers + 1) * max_rows * c.hidden * 2, at, max_rows * c.vocab * 2, c.hidden * c.vocab * 2 }; + const fields = [_]*cuda.DeviceBuffer{ &t.saved, &t.acts, &t.logits, &t.head_t }; + var made: usize = 0; + errdefer for (fields[0..made]) |f| f.free(); + for (fields, sizes) |f, n| { + f.* = try cuda.DeviceBuffer.alloc(d, n); + made += 1; + } + try e.ops().train().dequantT(e.w.head, t.head_t.ptr); + try e.stream.synchronize(); + e.slide = null; + return t; + } + + pub fn deinit(t: *Trainer, gpa: std.mem.Allocator) void { + t.e.stream.synchronize() catch {}; + t.sites.attach(&t.e.w, false); + t.sites.deinit(); + t.seq.deinit(); + t.bufs.deinit(); + t.io.free(); + t.proj.free(); + inline for (.{ "saved", "acts", "logits", "head_t" }) |f| @field(t, f).free(); + gpa.destroy(t); + } + + /// The forward applies the change's ranks in use (off: none of them, its kernels idle). + pub fn attach(t: *Trainer, on: bool) void { + t.sites.attach(&t.e.w, on); + } + + /// The first `ranks` of the change folded into the output projections and written into the model's shards. + pub fn save(t: *Trainer, gpa: std.mem.Allocator, io: std.Io, ranks: usize) !usize { + return learned.write(gpa, io, t.e.dir orelse return error.NotLearning, t.e.c, &t.sites, ranks); + } + + /// The mean loss of `ids`' answer from `start`, and what `mode` adds to it. + pub fn step(t: *Trainer, ids: []const u32, start: usize, mode: Mode) !Result { + const e = t.e; + if (ids.len < 2 or start < 1 or start >= ids.len or ids.len - 1 > max_rows) return error.BadExample; + if ((mode == .grad or mode == .learn) and t.sites.rank == 0) return error.NoOpenBlock; + const rows = ids.len - 1; + try e.stream.synchronize(); + const w = t.io.slice(u32, 5 * max_rows); + const targets = w[max_rows..][0..rows]; + const weights = std.mem.bytesAsSlice(f32, std.mem.sliceAsBytes(w[2 * max_rows ..][0..rows])); + @memcpy(w[0..rows], ids[0..rows]); + const share = 1 / @as(f32, @floatFromInt(ids.len - start)); + for (targets, weights, 0..) |*tg, *x, r| { + tg.* = ids[r + 1]; + x.* = if (r + 1 >= start) share else 0; + } + try t.forward(rows, start, mode); + if (mode == .avoid or mode == .seek) t.sketched += rows; + if (mode == .avoid or mode == .seek or mode == .project) { + try e.stream.synchronize(); + return .{ .loss = 0, .recalled = false }; + } + if (mode == .grad or mode == .learn) try t.backward(rows, mode); + try e.stream.synchronize(); + const stats = std.mem.bytesAsSlice([2]f32, std.mem.sliceAsBytes(w[3 * max_rows ..][0 .. 2 * rows])); + var out: Result = .{ .loss = 0, .recalled = true }; + for (stats, weights) |s, x| if (x > 0) { + out.loss += s[0] * x; + out.recalled = out.recalled and s[1] > 0.5; + }; + return out; + } + + /// Each row along layer l's candidate directions ([rows, candidates]), as the last project step left them. + pub fn projected(t: *const Trainer, l: usize, rows: usize) []const f32 { + const k = dims.candidates; + return t.proj.slice(f32, t.e.c.layers * max_rows * k)[l * max_rows * k ..][0 .. rows * k]; + } + + /// The prompt chunk from position 0 on the trainer's fresh state, each layer's parts kept, sketched or projected. + fn forward(t: *Trainer, rows: usize, start: usize, mode: Mode) !void { + const e = t.e; + const c = e.c; + const tr = e.ops().train(); + const d: u64 = c.hidden; + const nm = c.count(.mamba); + try tr.zero(t.b.ssm, nm * c.mamba_heads * c.mamba_head_dim * c.state * 4); + try tr.zero(t.b.conv_base, nm * 3 * c.convDim() * 2); + const f = fwd.Forward.init(c, &e.w, &t.b, e.ops(), keys, e.nch, false); + var w: fwd.Walk = .{ .rows = rows, .pos = 0 }; + try f.chunkBegin(&w); + for (0..c.layers) |l| { + try f.chunkPre(&w, l); + try tr.copy(t.savedAt(l), w.x, rows * d * 2); + try f.chunkMixer(&w, l); + try f.chunkPost(&w, l); + switch (mode) { + .loss => {}, + .grad, .learn => try t.keep(l, rows), + .avoid, .seek => try t.sketchSite(l, rows, start, mode), + .project => { + const site = &t.sites.list[l]; + const in = t.input(l); + try tr.project(in.x, in.stride, site.seek.dev, t.proj.dev + l * max_rows * dims.candidates * 4, rows, site.in, dims.candidates); + }, + } + } + if (mode == .avoid or mode == .seek or mode == .project) return; + try f.finalNorm(&w); + try tr.copy(t.savedAt(c.layers), w.x, rows * d * 2); + try e.ops().prefillDense(t.b.y, e.w.head, t.logits.ptr, rows); + const io = t.io.dev; + try tr.softmax(t.logits.ptr, io + max_rows * 4, io + 2 * max_rows * 4, io + 3 * max_rows * 4, rows, c.vocab); + } + + /// The loss back through the head, the final norm and every layer to each change; Adam after, in `learn`. + fn backward(t: *Trainer, rows: usize, mode: Mode) !void { + const e = t.e; + const c = e.c; + const tr = e.ops().train(); + const b = &t.bufs; + const d = c.hidden; + try tr.zero(b.dx, rows * d * 4); + try tr.gemm(t.logits.ptr, c.vocab, t.head_t.ptr, c.vocab, b.dx, d, rows, d, c.vocab, back.split(rows, d, c.vocab)); + try tr.zero(b.g, rows * d * 4); + try tr.rmsBack(t.savedAt(c.layers), e.w.norm_f, b.dx, b.g, rows, d, c.eps); + const sk = glue.routerShape(d).sk; + var l = c.layers; + while (l > 0) { + l -= 1; + const layer: back.Layer = .{ .t = tr, .o = e.ops(), .c = c, .blk = &e.w.blocks[l], .site = &t.sites.list[l], .sites = &t.sites, .acts = t.parts(l), .b = b, .rows = rows, .sk = sk, .plan = t.b.plan }; + switch (c.kinds[l]) { + .moe => try back.moe(layer), + .mamba => try back.mamba(layer), + .attention => try back.attention(layer), + } + try tr.rmsBack(t.savedAt(l), e.w.blocks[l].norm, b.dx, b.g, rows, d, c.eps); + } + if (mode == .learn) try t.sites.adam(tr); + } + + /// Where layer l's residual (or, at `layers`, the final norm's input) is kept. + fn savedAt(t: *const Trainer, l: usize) u64 { + return t.saved.ptr + l * max_rows * t.e.c.hidden * 2; + } + + /// Layer l's kept parts, in its kind's order. + pub fn parts(t: *const Trainer, l: usize) [5]u64 { + const c = t.e.c; + var out: [5]u64 = @splat(0); + var off = t.slots[l]; + switch (c.kinds[l]) { + inline else => |k| inline for (comptime acts(k), 0..) |f, i| { + out[i] = t.acts.ptr + off; + off += std.mem.alignForward(usize, bytes(c, f.part, max_rows), 256); + }, + } + return out; + } + + /// Layer l's forward parts into its slot. + fn keep(t: *Trainer, l: usize, rows: usize) !void { + const c = t.e.c; + const tr = t.e.ops().train(); + const at = t.parts(l); + switch (c.kinds[l]) { + inline else => |k| inline for (comptime acts(k), 0..) |f, i| { + try tr.copy(at[i], @field(t.b, f.field), bytes(c, f.part, rows)); + }, + } + } + + /// Layer l's site input as the forward left it: what its change reads, and its row stride. + fn input(t: *const Trainer, l: usize) struct { x: u64, stride: usize } { + const c = t.e.c; + return switch (c.kinds[l]) { + .moe => .{ .x = t.b.act + c.top_k * c.expert_width * 2, .stride = c.slots() * c.expert_width }, + .mamba => .{ .x = t.b.g, .stride = c.inner() }, + .attention => .{ .x = t.b.att, .stride = c.heads * c.head_dim }, + }; + } + + /// Layer l's site input into the sketch a block avoids or reads; the answer's first row again, as its answer. + fn sketchSite(t: *Trainer, l: usize, rows: usize, start: usize, mode: Mode) !void { + const site = &t.sites.list[l]; + const tr = t.e.ops().train(); + const in = t.input(l); + const y = if (mode == .avoid) site.avoid.dev else site.seek.dev; + const k: usize = if (mode == .avoid) dims.avoid_dims else dims.candidates; + const seed: u32 = if (mode == .avoid) 1 else 2; + const first = start - 1; + try tr.sketch(in.x, in.stride, y, rows, site.in, k, t.sketched, seed, 1); + try tr.sketch(in.x + first * in.stride * 2, in.stride, y, 1, site.in, k, (1 << 30) + t.sketched + first, seed, @floatFromInt(rows - first)); + } +}; diff --git a/zig/src/families/nemotron/cuda_train_back.zig b/zig/src/families/nemotron/cuda_train_back.zig new file mode 100644 index 00000000000..4cd701a37eb --- /dev/null +++ b/zig/src/families/nemotron/cuda_train_back.zig @@ -0,0 +1,195 @@ +//! Each kind of layer undone on CUDA for a sequence: the gradient at its output, through its mixer, to its input. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const kern = @import("cuda_kernels.zig"); +const weights = @import("cuda_weights.zig"); +const sites = @import("cuda_sites.zig"); +const ops = @import("cuda_train_ops.zig"); +const dims = @import("slide_dims.zig"); + +/// The f32 gradients a backward works in at `rows` rows (attention reads at most 256), and the products' bf16 scratch. +pub const Bufs = struct { + mem: cuda.DeviceBuffer, + g: u64, // [rows, D]: the residual's gradient + dx: u64, // [rows, D]: the gradient at a mixer's normed input + xa: u64, // [rows, max_rank]: a site's input along the change's directions, closed blocks zeroed + xn: u64, // [rows] + gates: u64, // [rows, max_blocks] + dxa: u64, // [rows, max_rank] + dyn: u64, // [rows, inner] + ytot: u64, // [rows, inner] + dytot: u64, // [rows, inner] + dt: u64, // [rows, heads] + ddt: u64, // [rows, heads] + dact: u64, // [rows, conv] + dproj: u64, // [rows, proj] + ckpt: u64, // [heads, rows / 16 + 1, dh * n] + states: u64, // [heads, 16, dh * n] + dbp: u64, // [rows, heads, n] + dcp: u64, // [rows, heads, n] + d_o: u64, // [rows, heads * hd] + dqkv: u64, // [rows, qkv] + probs: u64, // [heads, rows, rows] + dscores: u64, // [heads, rows, rows] + dy: u64, // [pairs, D] + d_act: u64, // [pairs, W] + du: u64, // [pairs, W] + dxp: u64, // [pairs, D] + xb: u64, // bf16 [rows, widest]: a gradient narrowed for its product + wt: u64, // bf16 [widest k, widest n]: a projection dequantized transposed + + const names = .{ "g", "dx", "xa", "xn", "gates", "dxa", "dyn", "ytot", "dytot", "dt", "ddt", "dact", "dproj", "ckpt", "states", "dbp", "dcp", "d_o", "dqkv", "probs", "dscores", "dy", "d_act", "du", "dxp", "xb", "wt" }; + + pub fn init(d: *const cuda.Driver, c: cfg.Config, rows: usize) !Bufs { + const D = c.hidden; + const pairs = rows * c.slots(); + const qw = c.heads * c.head_dim; + const state = c.mamba_head_dim * c.state; + const h = c.mamba_heads; + const widest = @max(c.projDim(), c.qkvDim(), D, c.inner(), qw); + const plane = @max(D * c.projDim(), D * c.qkvDim(), D * c.inner(), D * qw); + const bytes = [_]usize{ + rows * D * 4, rows * D * 4, rows * dims.max_rank * 4, rows * 4, rows * dims.max_blocks * 4, + rows * dims.max_rank * 4, rows * c.inner() * 4, rows * c.inner() * 4, rows * c.inner() * 4, rows * h * 4, + rows * h * 4, rows * c.convDim() * 4, rows * c.projDim() * 4, h * (rows / 16 + 1) * state * 4, h * 16 * state * 4, + rows * h * c.state * 4, rows * h * c.state * 4, rows * qw * 4, rows * c.qkvDim() * 4, c.heads * rows * rows * 4, + c.heads * rows * rows * 4, pairs * D * 4, pairs * c.expert_width * 4, pairs * c.expert_width * 4, pairs * D * 4, + rows * widest * 2, plane * 2, + }; + var total: usize = 0; + for (bytes) |n| total += std.mem.alignForward(usize, n, 256); + var b: Bufs = undefined; + b.mem = try cuda.DeviceBuffer.alloc(d, total); + var at: usize = 0; + inline for (names, 0..) |n, i| { + @field(b, n) = b.mem.ptr + at; + at += std.mem.alignForward(usize, bytes[i], 256); + } + return b; + } + + pub fn deinit(b: *Bufs) void { + b.mem.free(); + } +}; + +/// What a layer's backward reads: the launches, the model, its block and change, its forward's saved parts. +pub const Layer = struct { + t: ops.Train, + o: kern.Ops, + c: cfg.Config, + blk: *const weights.Block, + site: *const sites.Site, + sites: *const sites.Sites, + acts: [5]u64, // the parts train.zig keeps for this kind of layer, in its order + b: *const Bufs, + rows: usize, + sk: usize, // the router's K slices + plan: kern.Plan, +}; + +/// y [rows, k] (+)= x [rows, n] times the tiled 4-bit [n, k] projection q: q dequantized transposed, then the GEMM. +fn product(x: Layer, in: u64, q: weights.QLinear, y: u64, add: bool) !void { + const t = x.t; + const rows = x.rows; + try t.narrow(in, x.b.xb, rows * q.n); + try t.dequantT(q, x.b.wt); + if (!add) try t.zero(y, rows * q.k * 4); + try t.gemm(x.b.xb, q.n, x.b.wt, q.n, y, q.k, rows, q.k, q.n, split(rows, q.k, q.n)); +} + +/// K slices for a GEMM of m x n outputs: enough blocks to fill the GPU, each slice at least 256 deep. +pub fn split(m: usize, n: usize, k: usize) usize { + const tiles = ((n + 63) / 64) * ((m + 63) / 64); + return std.math.clamp(192 / @max(tiles, 1), 1, @max(k / 256, 1)); +} + +/// The open block's gradient from its site's input (bf16, row stride in_stride) and g; dx gains every block's part. +fn adapterBack(x: Layer, in: u64, in_stride: usize, dx: u64, dx_stride: usize) !void { + const s = x.sites; + if (s.rank == 0) return; + const t = x.t; + const b = x.b; + const ad = x.site.adapter(s); + try t.xa(ad, in, in_stride, b.xa, b.xn, x.rows); + try t.gate(ad, b.xa, b.xn, b.gates, x.rows, s.rank); + try t.loraDb(b.xa, b.g, x.site.gb.dev, x.rows, ad.out, s.first()); + try t.loraDxa(b.g, ad.b, b.gates, b.dxa, x.rows, ad.out, s.rank); + try t.loraDx(b.dxa, ad.a, dx, dx_stride, x.rows, ad.in, s.rank); +} + +/// The MoE layer: every pair's products undone on the packed experts, the shared halves' rest and change, then routing. +pub fn moe(x: Layer) !void { + const c = x.c; + const m = x.blk.moe; + const b = x.b; + const t = x.t; + const rows = x.rows; + const ex = m.experts; + const ns = c.slots(); + const pairs = rows * ns; + const W = ex.width; + const D = c.hidden; + const pick = x.acts[0]; + const act = x.acts[3]; + try x.o.plan(pick, pairs, ex.count, 64, x.plan); + const items = kern.maxItems(pairs, ex.count, 64); + try t.pairsIn(x.acts[1], b.g, b.dy, pairs, ns, D); + try t.expertsBack(b.dy, D, ex.down, x.plan.items, x.plan.counts, x.plan.members, b.d_act, W, D, W, items); + for (m.rest, 0..) |r, h| if (r != 0) try t.restBack(b.g, r, b.d_act + (c.top_k + h) * W * 4, ns * W, rows, D, W); + try adapterBack(x, act + c.top_k * W * 2, ns * W, b.d_act + c.top_k * W * 4, ns * W); + try t.relu2Back(act, b.d_act, b.du, pairs * W); + try t.expertsBack(b.du, W, ex.up, x.plan.items, x.plan.counts, x.plan.members, b.dxp, D, W, D, items); + try t.zero(b.dx, rows * D * 4); + try t.pairsOut(b.dxp, b.dx, rows, ns, D); + try t.routeBack(x.acts[2], x.sk, pick, x.acts[4], b.g, m.router, b.dx, rows, c.experts, c.top_k, ns, D, c.routed_scaling); +} + +/// The Mamba-2 layer: out_proj, its rest and change, the gated norm, the scan, dt, the conv, in_proj. +pub fn mamba(x: Layer) !void { + const c = x.c; + const m = x.blk.mamba; + const b = x.b; + const t = x.t; + const rows = x.rows; + const proj = x.acts[0]; + const xc = x.acts[1]; + const shape: ops.Shape = .{ .rows = @intCast(rows), .heads = @intCast(c.mamba_heads), .dh = @intCast(c.mamba_head_dim), .groups = @intCast(c.groups), .n = @intCast(c.state), .inner = @intCast(c.inner()), .conv = @intCast(c.convDim()), .proj = @intCast(c.projDim()), .lo = c.dt_min, .hi = c.dt_max }; + try product(x, b.g, m.out_proj, b.dyn, false); + if (m.out_rest != 0) try t.restBack(b.g, m.out_rest, b.dyn, c.inner(), rows, c.hidden, c.inner()); + try adapterBack(x, x.acts[2], c.inner(), b.dyn, c.inner()); + try t.dt(proj, m.dt_bias, b.dt, shape); + try t.ssmFwd(xc, b.dt, m.a, m.d, b.ytot, b.ckpt, shape); + try t.gateBack(b.ytot, proj, m.gnorm, b.dyn, b.dytot, b.dproj, shape, c.eps); + try t.ssmBack(xc, b.dt, m.a, m.d, b.dytot, b.ckpt, b.states, b.dact, b.dbp, b.dcp, b.ddt, shape); + try t.ssmBc(b.dbp, b.dcp, b.dact, shape); + try t.convBack(b.dact, proj, m.conv_w, m.conv_b, b.dproj, shape); + try t.dtBack(proj, m.dt_bias, b.ddt, b.dproj, shape); + try product(x, b.dproj, m.in_proj, b.dx, false); +} + +/// The attention layer: o_proj, its rest and change, causal softmax attention with shared kv heads, then q, k and v. +pub fn attention(x: Layer) !void { + const c = x.c; + const a = x.blk.attn; + const b = x.b; + const t = x.t; + const rows = x.rows; + const qkv = x.acts[0]; + const qw = c.heads * c.head_dim; + try product(x, b.g, a.o, b.d_o, false); + if (a.o_rest != 0) try t.restBack(b.g, a.o_rest, b.d_o, qw, rows, c.hidden, qw); + try adapterBack(x, x.acts[1], qw, b.d_o, qw); + const h: ops.Heads = .{ .rows = @intCast(rows), .heads = @intCast(c.heads), .kv_heads = @intCast(c.kv_heads), .dim = @intCast(c.head_dim), .nqkv = @intCast(c.qkvDim()), .scale = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(c.head_dim)))) }; + try t.attnQ(qkv, b.d_o, b.probs, b.dscores, b.dqkv, h); + try t.attnKv(qkv, b.d_o, b.probs, b.dscores, b.dqkv, h); + try product(x, b.dqkv, a.qkv, b.dx, false); +} + +test "a GEMM's K slices fill the GPU without slicing K below 256" { + try std.testing.expectEqual(@as(usize, 4), split(48, 2688, 10304)); + try std.testing.expectEqual(@as(usize, 1), split(256, 4096, 2688)); + try std.testing.expectEqual(@as(usize, 4), split(30, 2688, 131072)); + try std.testing.expectEqual(@as(usize, 1), split(16, 64, 128)); +} diff --git a/zig/src/families/nemotron/cuda_train_ops.zig b/zig/src/families/nemotron/cuda_train_ops.zig new file mode 100644 index 00000000000..98e610965e5 --- /dev/null +++ b/zig/src/families/nemotron/cuda_train_ops.zig @@ -0,0 +1,282 @@ +//! The training kernels (train.cu, train_mixers.cu) as calls on a stream: the change, the loss, products backward. +const std = @import("std"); +const cuda = @import("cuda"); +const dims = @import("slide_dims.zig"); +const weights = @import("cuda_weights.zig"); + +/// A Mamba layer's shape as train_mixers.cu reads it, with the dt clamp. +pub const Shape = extern struct { rows: c_int, heads: c_int, dh: c_int, groups: c_int, n: c_int, inner: c_int, conv: c_int, proj: c_int, lo: f32, hi: f32 }; + +/// Attention's shape as train_mixers.cu reads it. +pub const Heads = extern struct { rows: c_int, heads: c_int, kv_heads: c_int, dim: c_int, nqkv: c_int, scale: f32 }; + +/// tf_slide_out stages 16 rows of xa at every rank the change may use. +pub const out_smem: u32 = 16 * dims.max_rank * 4; + +/// Rows a decode window holds at most: the change takes its window kernels up to here. +const window_rows = 16; + +const train_names = .{ "slide_xa", "slide_out", "slide_xa_rows", "slide_out_rows", "gate", "lora_db", "lora_dxa", "lora_dx", "project", "sketch", "softmax", "rms_back", "dequant_t", "narrow", "widen", "gemm", "pairs_in", "experts_back", "relu2_back", "pairs_out", "route_back", "rest_back", "adam" }; +const mixer_names = .{ "dt", "ssm_fwd", "ssm_back", "ssm_bc", "gate_back", "conv_back", "dt_back", "attn_q", "attn_kv" }; + +/// Every training kernel by its extern "C" name (tf_slide_* for the forward's two, tf_train_* for the rest). +pub const Fns = struct { + slide_xa: cuda.Function, + slide_out: cuda.Function, + slide_xa_rows: cuda.Function, + slide_out_rows: cuda.Function, + gate: cuda.Function, + lora_db: cuda.Function, + lora_dxa: cuda.Function, + lora_dx: cuda.Function, + project: cuda.Function, + sketch: cuda.Function, + softmax: cuda.Function, + rms_back: cuda.Function, + dequant_t: cuda.Function, + narrow: cuda.Function, + widen: cuda.Function, + gemm: cuda.Function, + pairs_in: cuda.Function, + experts_back: cuda.Function, + relu2_back: cuda.Function, + pairs_out: cuda.Function, + route_back: cuda.Function, + rest_back: cuda.Function, + adam: cuda.Function, + dt: cuda.Function, + ssm_fwd: cuda.Function, + ssm_back: cuda.Function, + ssm_bc: cuda.Function, + gate_back: cuda.Function, + conv_back: cuda.Function, + dt_back: cuda.Function, + attn_q: cuda.Function, + attn_kv: cuda.Function, + + /// The functions of train.cu's module and train_mixers.cu's. + pub fn resolve(train: cuda.Module, mixers: cuda.Module) !Fns { + var f: Fns = undefined; + inline for (train_names) |name| { + const prefix = if (comptime std.mem.startsWith(u8, name, "slide_")) "tf_" else "tf_train_"; + @field(f, name) = try train.function(prefix ++ name); + } + inline for (mixer_names) |name| @field(f, name) = try mixers.function("tf_train_" ++ name); + try f.slide_out.allowDynamicShared(out_smem); + return f; + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn cdiv(a: usize, b: usize) usize { + return (a + b - 1) / b; +} + +/// Launches on one stream. +pub const Train = struct { + f: *const Fns, + s: cuda.Stream, + d: *const cuda.Driver, + + fn go(t: Train, f: cuda.Function, grid: [3]usize, block: u32, shared: u32, a: *cuda.Args) !void { + const g: cuda.Dim3 = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }; + try cuda.launch.launch(f, .{ .grid = g, .block = .{ .x = block }, .shared = shared }, t.s, a); + } + + fn args(xs: anytype) cuda.Args { + var a: cuda.Args = .{}; + inline for (xs) |x| a.add(x); + return a; + } + + /// y += scale (x a^T) b over each row's open blocks: x rows x_stride apart, y's at (r row_mul + row_add) y_stride. + pub fn adapt(t: Train, ad: weights.Adapter, x: u64, x_stride: usize, y: u64, y_f32: bool, y_stride: usize, row_mul: usize, row_add: usize, rows: usize) !void { + var a = args(.{ ad.xa, ad.xn, ad.tau, ad.b, ad.rank, y, @as(c_int, @intFromBool(y_f32)), int(y_stride), int(row_mul), int(row_add), int(rows), int(ad.out), dims.scale, dims.unit, int(dims.max_rank) }); + if (rows <= window_rows) { + // a window: a warp a dot product, so a few rows still fill the GPU + var b = args(.{ x, int(x_stride), ad.a, ad.rank, ad.xa, ad.xn, int(ad.in), int(dims.max_rank) }); + try t.go(t.f.slide_xa_rows, .{ dims.max_rank / 8, rows, 1 }, 256, 0, &b); + return t.go(t.f.slide_out_rows, .{ cdiv(ad.out, 32), 1, 1 }, 256, 0, &a); + } + try t.xa(ad, x, x_stride, ad.xa, ad.xn, rows); + try t.go(t.f.slide_out, .{ cdiv(ad.out, 256), cdiv(rows, 16), 1 }, 256, out_smem, &a); + } + + /// xa = x a^T over every rank in use, and xn = each row's |x|^2, into the given scratch. + pub fn xa(t: Train, ad: weights.Adapter, x: u64, x_stride: usize, xa_out: u64, xn: u64, rows: usize) !void { + var a = args(.{ x, int(x_stride), ad.a, ad.rank, xa_out, xn, int(rows), int(ad.in), int(dims.max_rank) }); + try t.go(t.f.slide_xa, .{ dims.max_blocks, cdiv(rows, 16), 1 }, 256, 0, &a); + } + + /// Each row's closed blocks zeroed in xa, and which are open in gates [rows, max_blocks]. + pub fn gate(t: Train, ad: weights.Adapter, xa_in: u64, xn: u64, gates: u64, rows: usize, rank: usize) !void { + var a = args(.{ xa_in, xn, ad.tau, gates, int(rows), int(rank), int(dims.max_rank), dims.unit }); + try t.go(t.f.gate, .{ 1, rows, 1 }, dims.max_blocks, 0, &a); + } + + /// db [block, out] += scale xa[:, first..]^T g, the open block's gradient. + pub fn loraDb(t: Train, xa_in: u64, g: u64, db: u64, rows: usize, out: usize, first: usize) !void { + var a = args(.{ xa_in, g, db, int(rows), int(out), int(first), int(dims.max_rank), dims.scale }); + try t.go(t.f.lora_db, .{ cdiv(out, 256), dims.block, 1 }, 256, 0, &a); + } + + /// dxa [rows, rank] = scale g b^T where each block is open on the row. + pub fn loraDxa(t: Train, g: u64, b: u64, gates: u64, dxa: u64, rows: usize, out: usize, rank: usize) !void { + var a = args(.{ g, b, gates, dxa, int(rows), int(out), int(rank), int(dims.max_rank), dims.scale }); + try t.go(t.f.lora_dxa, .{ cdiv(32 * rank, 256), rows, 1 }, 256, 0, &a); + } + + /// dx [rows, in] (row stride dx_stride) += dxa a. + pub fn loraDx(t: Train, dxa: u64, a_in: u64, dx: u64, dx_stride: usize, rows: usize, in: usize, rank: usize) !void { + var a = args(.{ dxa, a_in, dx, int(dx_stride), int(rows), int(in), int(rank), int(dims.max_rank) }); + try t.go(t.f.lora_dx, .{ cdiv(in, 256), rows, 1 }, 256, 0, &a); + } + + /// p [rows, k] = each unit input row along the k directions f [k, in]. + pub fn project(t: Train, x: u64, x_stride: usize, f: u64, p: u64, rows: usize, in: usize, k: usize) !void { + var a = args(.{ x, int(x_stride), f, p, int(rows), int(in), int(k) }); + try t.go(t.f.project, .{ cdiv(32 * k, 256), rows, 1 }, 256, 0, &a); + } + + /// y [k, in] += w sum_r coin(first + r, j) x[r]: input rows into a random sketch. + pub fn sketch(t: Train, x: u64, x_stride: usize, y: u64, rows: usize, in: usize, k: usize, first: usize, seed: u32, w: f32) !void { + var a = args(.{ x, int(x_stride), y, int(rows), int(in), int(k), @as(u32, @truncate(first)), seed, w }); + try t.go(t.f.sketch, .{ cdiv(in, 256), k, 1 }, 256, 0, &a); + } + + /// Each row's loss and target probability into stats, its logits replaced by their gradient. + pub fn softmax(t: Train, logits: u64, targets: u64, wts: u64, stats: u64, rows: usize, vocab: usize) !void { + var a = args(.{ logits, targets, wts, stats, int(vocab) }); + try t.go(t.f.softmax, .{ rows, 1, 1 }, 1024, 0, &a); + } + + /// g += the gradient through an input RMS norm of h (bf16) with weight w, given dx at its output. + pub fn rmsBack(t: Train, h: u64, w: u64, dx: u64, g: u64, rows: usize, dim: usize, eps: f32) !void { + var a = args(.{ h, w, dx, g, int(dim), eps }); + try t.go(t.f.rms_back, .{ rows, 1, 1 }, 256, 0, &a); + } + + /// A tiled projection [n, k] dequantized as bf16 [k, n]. + pub fn dequantT(t: Train, q: weights.QLinear, out: u64) !void { + var a = args(.{ q.w, q.s, q.b, out, int(q.n), int(q.k), int(q.npad) }); + try t.go(t.f.dequant_t, .{ cdiv(q.n * q.k, 256), 1, 1 }, 256, 0, &a); + } + + pub fn narrow(t: Train, x: u64, out: u64, n: usize) !void { + var a = args(.{ x, out, @as(i64, @intCast(n)) }); + try t.go(t.f.narrow, .{ cdiv(n, 256), 1, 1 }, 256, 0, &a); + } + + pub fn widen(t: Train, x: u64, out: u64, n: usize) !void { + var a = args(.{ x, out, @as(i64, @intCast(n)) }); + try t.go(t.f.widen, .{ cdiv(n, 256), 1, 1 }, 256, 0, &a); + } + + /// c [m, n] += a [m, k] b [n, k]^T (bf16 in, fp32 out), k cut into `split` slices that add in. + pub fn gemm(t: Train, a_in: u64, lda: usize, b: u64, ldb: usize, c: u64, ldc: usize, m: usize, n: usize, k: usize, split: usize) !void { + if (k % 32 != 0) return error.GemmShape; + var a = args(.{ a_in, int(lda), b, int(ldb), c, int(ldc), int(m), int(n), int(k), int(split) }); + try t.go(t.f.gemm, .{ cdiv(n, 64), cdiv(m, 64), split }, 128, 0, &a); + } + + /// dy [pairs, dim] = each pair's routing weight times its row's g. + pub fn pairsIn(t: Train, wt: u64, g: u64, dy: u64, pairs: usize, slots: usize, dim: usize) !void { + var a = args(.{ wt, g, dy, int(slots), int(dim) }); + try t.go(t.f.pairs_in, .{ cdiv(dim, 256), pairs, 1 }, 256, 0, &a); + } + + /// out [pairs, k] = x [pairs, n] times each pair's expert of a packed table [E, n rows, k inputs], by plan item. + pub fn expertsBack(t: Train, x: u64, x_stride: usize, w: u64, items: u64, counts: u64, members: u64, out: u64, out_stride: usize, n: usize, k: usize, max_items: usize) !void { + var a = args(.{ x, int(x_stride), w, items, counts, members, out, int(out_stride), int(k / 64), int(n / 32) }); + try t.go(t.f.experts_back, .{ max_items, k / 64, 1 }, 256, 0, &a); + } + + /// du = da 2 sqrt(act) over n values: relu^2 undone from its output. + pub fn relu2Back(t: Train, act: u64, da: u64, du: u64, n: usize) !void { + var a = args(.{ act, da, du, @as(i64, @intCast(n)) }); + try t.go(t.f.relu2_back, .{ cdiv(n, 256), 1, 1 }, 256, 0, &a); + } + + /// dx [rows, dim] += each row's pairs' input gradients. + pub fn pairsOut(t: Train, dxp: u64, dx: u64, rows: usize, slots: usize, dim: usize) !void { + var a = args(.{ dxp, dx, int(slots), int(dim) }); + try t.go(t.f.pairs_out, .{ cdiv(dim, 256), rows, 1 }, 256, 0, &a); + } + + /// dx [rows, dim] += the routing weights' gradient carried into the router's input. + pub fn routeBack(t: Train, part: u64, sk: usize, ids: u64, ys: u64, g: u64, gate_w: u64, dx: u64, rows: usize, experts: usize, top_k: usize, slots: usize, dim: usize, scale: f32) !void { + var a = args(.{ part, int(sk), ids, ys, g, gate_w, dx, int(rows), int(experts), int(top_k), int(slots), int(dim), scale }); + try t.go(t.f.route_back, .{ rows, 1, 1 }, 256, 0, &a); + } + + /// dx [rows, width] (row stride dx_stride) += g [rows, n] rest [n, width]. + pub fn restBack(t: Train, g: u64, rest: u64, dx: u64, dx_stride: usize, rows: usize, n: usize, width: usize) !void { + var a = args(.{ g, rest, dx, int(dx_stride), int(rows), int(n), int(width) }); + try t.go(t.f.rest_back, .{ cdiv(width, 256), rows, 1 }, 256, 0, &a); + } + + /// One Adam step on n parameters (hp: rate, decays, epsilon; corr: bias corrections); their gradient cleared. + pub fn adam(t: Train, p: u64, g: u64, m: u64, v: u64, n: usize, hp: [4]f32, corr: [2]f32) !void { + var a = args(.{ p, g, m, v, int(n), hp[0], hp[1], hp[2], hp[3], corr[0], corr[1] }); + try t.go(t.f.adam, .{ cdiv(n, 256), 1, 1 }, 256, 0, &a); + } + + pub fn dt(t: Train, proj: u64, bias: u64, out: u64, s: Shape) !void { + var a = args(.{ proj, bias, out, s }); + try t.go(t.f.dt, .{ cdiv(@intCast(s.heads), 64), @intCast(s.rows), 1 }, 64, 0, &a); + } + + pub fn ssmFwd(t: Train, act: u64, dt_in: u64, a_neg: u64, d_skip: u64, y: u64, ckpt: u64, s: Shape) !void { + var a = args(.{ act, dt_in, a_neg, d_skip, y, ckpt, s }); + try t.go(t.f.ssm_fwd, .{ @intCast(s.heads), 1, 1 }, 1024, 0, &a); + } + + pub fn ssmBack(t: Train, act: u64, dt_in: u64, a_neg: u64, d_skip: u64, dy: u64, ckpt: u64, states: u64, dact: u64, dbp: u64, dcp: u64, ddt: u64, s: Shape) !void { + var a = args(.{ act, dt_in, a_neg, d_skip, dy, ckpt, states, dact, dbp, dcp, ddt, s }); + try t.go(t.f.ssm_back, .{ @intCast(s.heads), 1, 1 }, 1024, 0, &a); + } + + pub fn ssmBc(t: Train, dbp: u64, dcp: u64, dact: u64, s: Shape) !void { + var a = args(.{ dbp, dcp, dact, s }); + try t.go(t.f.ssm_bc, .{ cdiv(@intCast(s.n), 128), @intCast(s.groups), @intCast(s.rows) }, 128, 0, &a); + } + + pub fn gateBack(t: Train, y: u64, proj: u64, w: u64, dn: u64, dy: u64, dproj: u64, s: Shape, eps: f32) !void { + var a = args(.{ y, proj, w, dn, dy, dproj, s, eps }); + try t.go(t.f.gate_back, .{ @intCast(s.groups), @intCast(s.rows), 1 }, 256, 0, &a); + } + + pub fn convBack(t: Train, dact: u64, proj: u64, cw: u64, cb: u64, dproj: u64, s: Shape) !void { + var a = args(.{ dact, proj, cw, cb, dproj, s }); + try t.go(t.f.conv_back, .{ cdiv(@intCast(s.conv), 256), @intCast(s.rows), 1 }, 256, 0, &a); + } + + pub fn dtBack(t: Train, proj: u64, bias: u64, ddt: u64, dproj: u64, s: Shape) !void { + var a = args(.{ proj, bias, ddt, dproj, s }); + try t.go(t.f.dt_back, .{ cdiv(@intCast(s.heads), 64), @intCast(s.rows), 1 }, 64, 0, &a); + } + + pub fn attnQ(t: Train, qkv: u64, dout: u64, probs: u64, dscores: u64, dqkv: u64, h: Heads) !void { + var a = args(.{ qkv, dout, probs, dscores, dqkv, h }); + try t.go(t.f.attn_q, .{ @intCast(h.heads), @intCast(h.rows), 1 }, 256, 0, &a); + } + + pub fn attnKv(t: Train, qkv: u64, dout: u64, probs: u64, dscores: u64, dqkv: u64, h: Heads) !void { + var a = args(.{ qkv, dout, probs, dscores, dqkv, h }); + try t.go(t.f.attn_kv, .{ @intCast(h.kv_heads), @intCast(h.rows), 1 }, @intCast(h.dim), 0, &a); + } + + /// `bytes` (a multiple of four) of zeros at `ptr`. + pub fn zero(t: Train, ptr: u64, bytes: usize) !void { + if (bytes == 0) return; + try t.d.check(t.d.api.cuMemsetD32Async(ptr, 0, bytes / 4, t.s.handle), "cuMemsetD32Async"); + } + + pub fn copy(t: Train, dst: u64, src: u64, bytes: usize) !void { + if (bytes == 0) return; + try t.d.check(t.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, t.s.handle), "cuMemcpyDtoDAsync"); + } +}; diff --git a/zig/src/families/nemotron/cuda_weights.zig b/zig/src/families/nemotron/cuda_weights.zig index 16d93d13a17..ed450c8444f 100644 --- a/zig/src/families/nemotron/cuda_weights.zig +++ b/zig/src/families/nemotron/cuda_weights.zig @@ -18,11 +18,22 @@ pub const mtp_file = "mtp-4bit.safetensors"; /// The token table as stored (MLX words, scales, biases): a row lookup, not a matmul. pub const Embed = struct { w: u64, s: u64, b: u64, n: usize, k: usize }; +/// A live lesson's change after an output projection (--slide): y += scale (x a^T) b over each row's open blocks. +pub const Adapter = struct { + a: u64, // f32 [max_rank, in] + b: u64, // f32 [max_rank, out] + tau: u64, // f32 [max_blocks]: each block's gate + rank: u64, // the u32 word of ranks in use, which the kernels read + xa: u64, // f32 [rows, max_rank]: scratch + xn: u64, // f32 [rows] + in: usize, + out: usize, +}; /// A `*_rest` is a lesson's change past its projection's 4-bit codes ([out, in] bf16), added after it; 0 when none. -pub const Mamba = struct { in_proj: QLinear, out_proj: QLinear, conv_w: u64, conv_b: u64, a: u64, d: u64, dt_bias: u64, gnorm: u64, out_rest: u64 = 0 }; -pub const Attention = struct { qkv: QLinear, o: QLinear, o_rest: u64 = 0 }; +pub const Mamba = struct { in_proj: QLinear, out_proj: QLinear, conv_w: u64, conv_b: u64, a: u64, d: u64, dt_bias: u64, gnorm: u64, out_rest: u64 = 0, adapter: ?*const Adapter = null }; +pub const Attention = struct { qkv: QLinear, o: QLinear, o_rest: u64 = 0, adapter: ?*const Adapter = null }; /// The shared expert's down projection rest in its two halves, as experts E and E + 1 split its columns. -pub const MoE = struct { router: u64, bias: u64, experts: Experts, rest: [2]u64 = .{ 0, 0 } }; +pub const MoE = struct { router: u64, bias: u64, experts: Experts, rest: [2]u64 = .{ 0, 0 }, adapter: ?*const Adapter = null }; pub const Block = struct { kind: Kind, norm: u64, mamba: Mamba = undefined, attn: Attention = undefined, moe: MoE = undefined }; pub const Mtp = struct { enorm: u64, hnorm: u64, eh_proj: QLinear, attn_norm: u64, attn: Attention, moe_norm: u64, moe: MoE, final_norm: u64 }; @@ -275,6 +286,7 @@ const Loader = struct { var m: Mamba = undefined; m.in_proj = try L.dense(ck, try join(&a, name, ".in_proj"), &.{try join(&b, pre, "in_proj")}); m.out_rest = 0; + m.adapter = null; m.out_proj = try L.denseRest(ck, try join(&a, name, ".out_proj"), &.{try join(&b, pre, "out_proj")}, &m.out_rest); const conv = try ck.get(try join(&b, pre, "conv1d.weight")); if (conv.rank != 3 or conv.dim(1) != 4 or conv.dim(2) != 1 or conv.dtype != .bf16) return error.UnexpectedTensor; diff --git a/zig/src/families/nemotron/learner.zig b/zig/src/families/nemotron/learner.zig new file mode 100644 index 00000000000..cfcfd72372d --- /dev/null +++ b/zig/src/families/nemotron/learner.zig @@ -0,0 +1,407 @@ +//! Nemotron's Sliding Weights learner on any backend: each lesson a new block of the low-rank change at every layer. +const std = @import("std"); +const adapters = @import("slide_dims.zig"); +const choice = @import("choice.zig"); + +/// Token ids whose answer starts at `start`: the rows from start - 1 on predict it. +pub const Example = struct { ids: []const u32, start: u32 }; + +/// One fact's examples; `more` another round, `undo` one back, `commit` a weight change, `save` it into the shards. +pub const Lesson = struct { + train: []const Example = &.{}, + held: []const Example = &.{}, + near: []const Example = &.{}, + keep: []const Example = &.{}, + undo: bool = false, + steps: u32 = max_steps, + more: bool = false, + commit: bool = false, + save: bool = false, +}; + +pub const Report = union(enum) { + learned: struct { recalled: bool, steps: u32, loss: f32 }, + failed: []const u8, +}; + +pub const Step = struct { done: bool, changed: bool = false, report: ?Report = null }; + +const max_steps = 400; +const check_every = 20; +const plain_steps = 60; // steps a lesson takes once it is a plain weight change, before its near misses are mined +const replay_cap = 64; // earlier lessons' answers kept steady at most, the oldest giving way + +/// How far above every steady row's cosine with the gate's direction a row's must be for the block to act on it. +const gate_margin: f32 = 0.02; + +/// How much each steady row weighs against the fact's rows when a lesson becomes a plain weight change. +const hold: f64 = 1; + +/// A new lesson first sketches and measures what its block must avoid and read (build), then learns (steps). +const Phase = enum { idle, build, steps, undo, commit, save }; + +/// An example's turn: a fact answer or a twin kept as it is, and whether Adam steps after it. +const Turn = struct { ex: Example, fact: bool, last: bool }; + +/// The learner over a backend's training file: its Backend, Mode, max_rows and Trainer (step, sites, attach, save). +pub fn Of(comptime train: type) type { + return struct { + const Learner = @This(); + const Trainer = train.Trainer; + const Mode = train.Mode; + + gpa: std.mem.Allocator, + io: std.Io, + b: *train.Backend, + trainer: ?*Trainer = null, + lesson: Lesson = .{}, + phase: Phase = .idle, + plan: std.ArrayList(Turn) = .empty, // this round's examples in order + at: usize = 0, // the plan's next example + taken: u32 = 0, // Adam steps this round + loss: f32 = 0, // the round's fact answers' summed loss + replay: std.ArrayList(Example) = .empty, // earlier lessons' answers, owned + last: []Example = &.{}, // the last lesson's answers, owned, joining replay when the next lesson begins + kept_rounds: u32 = 0, // the last lesson's rounds still in the weights + opened: bool = false, // the last lesson opened the block now last in the change + built: usize = 0, // examples a new lesson has sketched or projected so far + choice: ?choice.Choice = null, // the new block's directions and gates, as its examples are projected + answers: u32 = 0, // fact answer rows projected + can_undo: bool = false, + plain: bool = false, // the last lesson is a plain weight change, which an undo takes out whole + rounds: u64 = 0, // rounds begun, which seeds each round's order + + pub fn init(gpa: std.mem.Allocator, io: std.Io, b: *train.Backend) Learner { + return .{ .gpa = gpa, .io = io, .b = b }; + } + + pub fn deinit(l: *Learner) void { + if (l.trainer) |t| t.deinit(l.gpa); + if (l.choice) |*c| c.deinit(); + l.plan.deinit(l.gpa); + disown(l.gpa, l.last); + for (l.replay.items) |ex| l.gpa.free(ex.ids); + l.replay.deinit(l.gpa); + } + + /// Start a lesson's round; its examples must stay valid until its last step. + pub fn begin(l: *Learner, lesson: Lesson) !void { + std.debug.assert(l.phase == .idle); + l.lesson = lesson; + if (lesson.undo) { + l.phase = .undo; + return; + } + if (lesson.commit or lesson.save) { + l.phase = if (lesson.save) .save else .commit; + return; + } + if (lesson.train.len == 0) return; + for ([_][]const Example{ lesson.train, lesson.held, lesson.near, lesson.keep }) |xs| for (xs) |ex| { + if (ex.start < 1 or ex.start >= ex.ids.len or ex.ids.len - 1 > train.max_rows) return error.ExampleTooLong; + }; + if (l.trainer == null) { + const t = try Trainer.init(l.gpa, l.b); + errdefer t.deinit(l.gpa); + l.choice = try choice.Choice.init(l.gpa, t.sites.list.len); + l.trainer = t; + } + if (lesson.more) { + if (!l.opened) return error.NothingToContinue; + return l.start(); + } + try l.settleLast(lesson.train); + if (l.trainer.?.sites.rank + adapters.block > adapters.max_rank) return error.LearnedChangeFull; + l.trainer.?.sites.clear(); + l.trainer.?.sketched = 0; + l.built = 0; + l.phase = .build; + } + + /// A round's steps from the open block as it is now, which an undo comes back to. + fn start(l: *Learner) !void { + const steps = @max(@min(l.lesson.steps, max_steps), 1); + if (l.plain) try l.schedulePlain(steps) else try l.schedule(steps); + l.trainer.?.sites.keep(); + l.can_undo = true; + l.at = 0; + l.taken = 0; + l.loss = 0; + l.phase = .steps; + } + + pub fn abort(l: *Learner) void { + l.phase = .idle; + } + + /// One bounded unit: one example sketched, one step of learning (held-out check every few), or the undo. + pub fn step(l: *Learner) Step { + return l.advance() catch |e| { + if (l.phase == .steps) l.trainer.?.sites.restore(); + l.phase = .idle; + return .{ .done = true, .changed = true, .report = .{ .failed = @errorName(e) } }; + }; + } + + fn advance(l: *Learner) !Step { + switch (l.phase) { + .idle => return .{ .done = true }, + .undo => { + l.phase = .idle; + if (l.plain) { + l.trainer.?.sites.close(); + l.trainer.?.attach(true); + l.plain = false; + l.opened = false; + l.kept_rounds = 0; + return .{ .done = true, .changed = true }; + } + if (!l.can_undo) return .{ .done = true }; + l.trainer.?.sites.restore(); + l.can_undo = false; + l.kept_rounds -|= 1; + return .{ .done = true, .changed = true }; + }, + .build => return l.buildOnce(), + .steps => return l.stepOnce(), + .commit => return l.commitOnce(), + .save => return l.saveOnce(), + } + } + + /// Every lesson made a weight change, folded into its layers' output projections and written into the shards. + fn saveOnce(l: *Learner) !Step { + l.phase = .idle; + const t = l.trainer orelse return .{ .done = true }; + const ranks = t.sites.rank - @as(usize, if (l.opened and !l.plain) adapters.block else 0); + if (ranks == 0) return .{ .done = true }; + const t0 = std.Io.Clock.awake.now(l.io); + const bytes = try t.save(l.gpa, l.io, ranks); + const took = @as(f64, @floatFromInt(std.Io.Clock.awake.now(l.io).toNanoseconds() - t0.toNanoseconds())) / 1e9; + std.log.info("slide: {d} lessons written into the model's weights: {d} MB of output projections into its shards in {d:.1} s", .{ ranks / adapters.block, bytes >> 20, took }); + return .{ .done = true }; + } + + /// The kept lesson made a plain change of the weights: each layer's directions refit to hold steady rows still. + fn commitOnce(l: *Learner) !Step { + l.phase = .idle; + if (!l.opened or l.kept_rounds == 0) return .{ .done = true }; + const t = l.trainer.?; + const c = &l.choice.?; + for (0..t.sites.list.len) |k| try c.refit(k, hold); + t.sites.plain(c.coef); + t.attach(true); + l.plain = true; + std.log.info("slide: lesson {d} is now a plain weight change; it learns on beside the answers it must keep", .{t.sites.first() / adapters.block + 1}); + try l.schedulePlain(plain_steps); + t.sites.keep(); + l.can_undo = false; + l.at = 0; + l.taken = 0; + l.loss = 0; + l.phase = .steps; + return .{ .done = false, .changed = true }; + } + + /// One example at a time: what must stay and the fact sketched, then projected; then the block chosen, opened. + fn buildOnce(l: *Learner) !Step { + const t = l.trainer.?; + const c = &l.choice.?; + const facts = l.lesson.train; + const stay = [_][]const Example{ l.lesson.keep, l.lesson.near, l.replay.items }; + const steady = l.lesson.keep.len + l.lesson.near.len + l.replay.items.len; + var i = l.built; + l.built += 1; + if (i < steady) return l.sketch(pick(&stay, i), .avoid); + i -= steady; + if (i < facts.len) return l.sketch(facts[i], .seek); + i -= facts.len; + if (i == 0) { + t.sites.frame(); + c.reset(); + l.answers = 0; + } + if (i < steady) { + const ex = pick(&stay, i); + _ = try t.step(ex.ids, ex.start, .project); + for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1), false, ex.start - 1, true); + return .{ .done = false }; + } + i -= steady; + if (i < facts.len) { + const ex = facts[i]; + _ = try t.step(ex.ids, ex.start, .project); + l.answers += @intCast(ex.ids.len - ex.start); + try c.head(); + for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1)[(ex.start - 1) * adapters.candidates ..], true, 0, false); + return .{ .done = false }; + } + try c.choose(gate_margin); + try t.sites.open(c.coef); + t.attach(true); + l.opened = true; + l.gate(); + try l.start(); + return .{ .done = false }; + } + + fn sketch(l: *Learner, ex: Example, mode: Mode) !Step { + _ = try l.trainer.?.step(ex.ids, ex.start, mode); + return .{ .done = false }; + } + + /// The new block's gate at each layer: above every steady row's share there, shut where no fact row clears it. + fn gate(l: *Learner) void { + const sites = &l.trainer.?.sites; + const c = &l.choice.?; + const k = sites.first() / adapters.block; + var open: usize = 0; + var reach: u64 = 0; + var firsts: u64 = 0; + for (sites.list, c.tau, c.hits, c.opens) |*site, tau, hits, opens| { + site.gate(k).* = tau; + open += @intFromBool(hits > 0); + reach += hits; + firsts += opens; + } + const mean = 100 * @as(f64, @floatFromInt(reach)) / @as(f64, @floatFromInt(@max(open * l.answers, 1))); + const first = @as(f64, @floatFromInt(firsts)) / @as(f64, @floatFromInt(@max(c.heads.items.len, 1))); + std.log.info("slide: block {d} acts at {d} of {d} layers, on {d:.0}% of the fact's answer rows there; first rows at {d:.1}", .{ k + 1, open, sites.list.len, mean, first }); + } + + /// An example's gradients, Adam after a fact answer and its twin; every few steps the held-out answers are read + fn stepOnce(l: *Learner) !Step { + const t = l.trainer.?; + const turn = l.plan.items[l.at]; + const got = try t.step(turn.ex.ids, turn.ex.start, if (turn.last) .learn else .grad); + if (!std.math.isFinite(got.loss)) return error.NonfiniteStep; + l.at += 1; + if (turn.fact) l.loss += got.loss; + if (!turn.last) return .{ .done = false }; + l.taken += 1; + const end = l.at == l.plan.items.len; + if (l.plain and !end) return .{ .done = false, .changed = true }; + const back = (l.taken % check_every == 0 or end) and try l.recalled(); + if (!back and !end) return .{ .done = false, .changed = true }; + l.phase = .idle; + l.kept_rounds += 1; + const loss = l.loss / @as(f32, @floatFromInt(l.taken)); + std.log.info("slide: {d} steps{s}, the fact's answers' mean loss {d:.3}; held-out answers {s}", .{ l.taken, if (l.plain) " as a plain change" else "", loss, if (back) "back" else "not back" }); + return .{ .done = true, .changed = true, .report = .{ .learned = .{ .recalled = back, .steps = l.taken, .loss = loss } } }; + } + + /// Whether every held-out answer comes back token for token (each its row's likeliest). + fn recalled(l: *Learner) !bool { + if (l.lesson.held.len == 0) return false; + for (l.lesson.held) |ex| if (!(try l.trainer.?.step(ex.ids, ex.start, .loss)).recalled) return false; + return true; + } + + /// The last lesson's answers into replay if a round of it stayed (else its block out); this lesson's are last. + fn settleLast(l: *Learner, answers: []const Example) !void { + const now = try own(l.gpa, answers); + if (l.opened and l.kept_rounds == 0) { + l.trainer.?.sites.close(); + l.trainer.?.attach(true); + } + l.opened = false; + l.plain = false; + if (l.kept_rounds > 0) { + for (l.last) |ex| { + if (l.replay.items.len == replay_cap) l.gpa.free(l.replay.orderedRemove(0).ids); + try l.replay.append(l.gpa, ex); + } + l.gpa.free(l.last); + } else disown(l.gpa, l.last); + l.last = now; + l.kept_rounds = 0; + } + + /// A plain change's steps: a fact answer, then two steady ones as they were (twins twice as often), Adam after. + fn schedulePlain(l: *Learner, steps: u32) !void { + l.rounds += 1; + var prng = std.Random.DefaultPrng.init(l.rounds); + var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); + defer facts.deinit(l.gpa); + var steady: Deck = try .init(l.gpa, &.{ l.lesson.keep, l.lesson.near, l.lesson.near, l.replay.items }); + defer steady.deinit(l.gpa); + l.plan.clearRetainingCapacity(); + for (0..steps) |_| { + const alone = steady.cards.len == 0; + try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = alone }); + if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = false }); + if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = true }); + } + } + + /// The round's steps: the fact's answers in fresh orders. + fn schedule(l: *Learner, steps: u32) !void { + l.rounds += 1; + var prng = std.Random.DefaultPrng.init(l.rounds); + var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); + defer facts.deinit(l.gpa); + l.plan.clearRetainingCapacity(); + for (0..steps) |_| try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = true }); + } + }; +} + +/// Example i of the lists in turn. +fn pick(lists: []const []const Example, i: usize) Example { + var at = i; + for (lists) |xs| { + if (at < xs.len) return xs[at]; + at -= xs.len; + } + unreachable; +} + +/// Examples dealt in shuffled passes: every one once before any comes again. +const Deck = struct { + cards: []Example, + next: usize, + + fn init(gpa: std.mem.Allocator, parts: []const []const Example) !Deck { + var n: usize = 0; + for (parts) |p| n += p.len; + const cards = try gpa.alloc(Example, n); + var at: usize = 0; + for (parts) |p| { + @memcpy(cards[at..][0..p.len], p); + at += p.len; + } + return .{ .cards = cards, .next = n }; + } + + fn deinit(d: *Deck, gpa: std.mem.Allocator) void { + gpa.free(d.cards); + } + + fn draw(d: *Deck, r: std.Random) Example { + if (d.next == d.cards.len) { + r.shuffle(Example, d.cards); + d.next = 0; + } + d.next += 1; + return d.cards[d.next - 1]; + } +}; + +fn own(gpa: std.mem.Allocator, xs: []const Example) ![]Example { + const out = try gpa.alloc(Example, xs.len); + var made: usize = 0; + errdefer { + for (out[0..made]) |x| gpa.free(x.ids); + gpa.free(out); + } + for (xs, out) |x, *o| { + o.* = .{ .ids = try gpa.dupe(u32, x.ids), .start = x.start }; + made += 1; + } + return out; +} + +fn disown(gpa: std.mem.Allocator, xs: []Example) void { + for (xs) |x| gpa.free(x.ids); + gpa.free(xs); +} diff --git a/zig/src/families/nemotron/slide.zig b/zig/src/families/nemotron/slide.zig index fca7a47fd78..dbce006bb7e 100644 --- a/zig/src/families/nemotron/slide.zig +++ b/zig/src/families/nemotron/slide.zig @@ -1,403 +1,10 @@ -//! Nemotron's Sliding Weights learner: each lesson a new block of the low-rank change at every layer, learned live. -const std = @import("std"); +//! Nemotron's Sliding Weights learner on Metal: the backend-neutral learner over the Metal trainer. +const learner = @import("learner.zig"); const train = @import("train.zig"); -const adapters = @import("adapters.zig"); -const choice = @import("choice.zig"); -const learned = @import("learned.zig"); -const backend = @import("backend.zig"); -const mtl = @import("metal"); -const Metal = backend.Metal; - -/// Token ids whose answer starts at `start`: the rows from start - 1 on predict it. -pub const Example = struct { ids: []const u32, start: u32 }; - -/// One fact's examples; `more` another round, `undo` one back, `commit` a weight change, `save` it into the shards. -pub const Lesson = struct { - train: []const Example = &.{}, - held: []const Example = &.{}, - near: []const Example = &.{}, - keep: []const Example = &.{}, - undo: bool = false, - steps: u32 = max_steps, - more: bool = false, - commit: bool = false, - save: bool = false, -}; - -pub const Report = union(enum) { - learned: struct { recalled: bool, steps: u32, loss: f32 }, - failed: []const u8, -}; - -pub const Step = struct { done: bool, changed: bool = false, report: ?Report = null }; - -const max_steps = 400; -const check_every = 20; -const plain_steps = 60; // steps a lesson takes once it is a plain weight change, before its near misses are mined -const replay_cap = 64; // earlier lessons' answers kept steady at most, the oldest giving way - -/// How far above every steady row's cosine with the gate's direction a row's must be for the block to act on it. -const gate_margin: f32 = 0.02; - -/// How much each steady row weighs against the fact's rows when a lesson becomes a plain weight change. -const hold: f64 = 1; - -/// A new lesson first sketches and measures what its block must avoid and read (build), then learns (steps). -const Phase = enum { idle, build, steps, undo, commit, save }; - -/// An example's turn: a fact answer or a twin kept as it is, and whether Adam steps after it. -const Turn = struct { ex: Example, fact: bool, last: bool }; - -pub const Learner = struct { - gpa: std.mem.Allocator, - io: std.Io, - b: *Metal, - trainer: ?*train.Trainer = null, - lesson: Lesson = .{}, - phase: Phase = .idle, - plan: std.ArrayList(Turn) = .empty, // this round's examples in order - at: usize = 0, // the plan's next example - taken: u32 = 0, // Adam steps this round - loss: f32 = 0, // the round's fact answers' summed loss - replay: std.ArrayList(Example) = .empty, // earlier lessons' answers, owned - last: []Example = &.{}, // the last lesson's answers, owned, joining replay when the next lesson begins - kept_rounds: u32 = 0, // the last lesson's rounds still in the weights - opened: bool = false, // the last lesson opened the block now last in the change - built: usize = 0, // examples a new lesson has sketched or projected so far - choice: ?choice.Choice = null, // the new block's directions and gates, as its examples are projected - answers: u32 = 0, // fact answer rows projected - can_undo: bool = false, - plain: bool = false, // the last lesson is a plain weight change, which an undo takes out whole - rounds: u64 = 0, // rounds begun, which seeds each round's order - - pub fn init(gpa: std.mem.Allocator, io: std.Io, b: *Metal) Learner { - return .{ .gpa = gpa, .io = io, .b = b }; - } - - pub fn deinit(l: *Learner) void { - if (l.trainer) |t| t.deinit(l.gpa); - if (l.choice) |*c| c.deinit(); - l.plan.deinit(l.gpa); - disown(l.gpa, l.last); - for (l.replay.items) |ex| l.gpa.free(ex.ids); - l.replay.deinit(l.gpa); - } - - /// Start a lesson's round; its examples must stay valid until its last step. - pub fn begin(l: *Learner, lesson: Lesson) !void { - std.debug.assert(l.phase == .idle); - l.lesson = lesson; - if (lesson.undo) { - l.phase = .undo; - return; - } - if (lesson.commit or lesson.save) { - l.phase = if (lesson.save) .save else .commit; - return; - } - if (lesson.train.len == 0) return; - for ([_][]const Example{ lesson.train, lesson.held, lesson.near, lesson.keep }) |xs| for (xs) |ex| { - if (ex.start < 1 or ex.start >= ex.ids.len or ex.ids.len - 1 > train.max_rows) return error.ExampleTooLong; - }; - if (l.trainer == null) { - l.choice = try choice.Choice.init(l.gpa, l.b.m.config.layers); - l.trainer = try train.Trainer.init(l.gpa, l.b); - } - if (lesson.more) { - if (!l.opened) return error.NothingToContinue; - return l.start(); - } - try l.settleLast(lesson.train); - if (l.trainer.?.sites.rank + adapters.block > adapters.max_rank) return error.LearnedChangeFull; - l.trainer.?.sites.clear(); - l.trainer.?.sketched = 0; - l.built = 0; - l.phase = .build; - } - - /// A round's steps from the open block as it is now, which an undo comes back to. - fn start(l: *Learner) !void { - const steps = @max(@min(l.lesson.steps, max_steps), 1); - if (l.plain) try l.schedulePlain(steps) else try l.schedule(steps); - l.trainer.?.sites.keep(); - l.can_undo = true; - l.at = 0; - l.taken = 0; - l.loss = 0; - l.phase = .steps; - } - - pub fn abort(l: *Learner) void { - l.phase = .idle; - } - - /// One bounded unit: one example sketched, one step of learning (with the held-out check every few), or the undo. - pub fn step(l: *Learner) Step { - return l.advance() catch |e| { - if (l.phase == .steps) l.trainer.?.sites.restore(); - l.phase = .idle; - return .{ .done = true, .changed = true, .report = .{ .failed = @errorName(e) } }; - }; - } - - fn advance(l: *Learner) !Step { - switch (l.phase) { - .idle => return .{ .done = true }, - .undo => { - l.phase = .idle; - if (l.plain) { - l.trainer.?.sites.close(); - l.trainer.?.sites.attach(&l.b.m.weights, true); - l.plain = false; - l.opened = false; - l.kept_rounds = 0; - return .{ .done = true, .changed = true }; - } - if (!l.can_undo) return .{ .done = true }; - l.trainer.?.sites.restore(); - l.can_undo = false; - l.kept_rounds -|= 1; - return .{ .done = true, .changed = true }; - }, - .build => return l.buildOnce(), - .steps => return l.stepOnce(), - .commit => return l.commitOnce(), - .save => return l.saveOnce(), - } - } - - /// Every lesson made a weight change, folded into its layers' output projections and written into the shards. - fn saveOnce(l: *Learner) !Step { - l.phase = .idle; - const t = l.trainer orelse return .{ .done = true }; - const ranks = t.sites.rank - @as(usize, if (l.opened and !l.plain) adapters.block else 0); - if (ranks == 0) return .{ .done = true }; - const m = l.b.m; - const t0 = mtl.clock.seconds(); - const bytes = try learned.write(l.gpa, l.io, m.dir, &m.checkpoint, &m.weights, m.config, &t.sites, ranks); - std.log.info("slide: {d} lessons written into the model's weights: {d} MB of output projections into its shards in {d:.1} s", .{ ranks / adapters.block, bytes >> 20, mtl.clock.seconds() - t0 }); - return .{ .done = true }; - } - - /// The kept lesson made a plain change of the weights: each layer's directions refit to hold steady rows still. - fn commitOnce(l: *Learner) !Step { - l.phase = .idle; - if (!l.opened or l.kept_rounds == 0) return .{ .done = true }; - const t = l.trainer.?; - const c = &l.choice.?; - for (0..t.sites.list.len) |k| try c.refit(k, hold); - t.sites.plain(c.coef); - t.sites.attach(&l.b.m.weights, true); - l.plain = true; - std.log.info("slide: lesson {d} is now a plain weight change; it learns on beside the answers it must keep", .{t.sites.first() / adapters.block + 1}); - try l.schedulePlain(plain_steps); - t.sites.keep(); - l.can_undo = false; - l.at = 0; - l.taken = 0; - l.loss = 0; - l.phase = .steps; - return .{ .done = false, .changed = true }; - } - - /// One example at a time: what must stay and the fact sketched, then projected; then the block chosen and opened. - fn buildOnce(l: *Learner) !Step { - const t = l.trainer.?; - const c = &l.choice.?; - const facts = l.lesson.train; - const stay = [_][]const Example{ l.lesson.keep, l.lesson.near, l.replay.items }; - const steady = l.lesson.keep.len + l.lesson.near.len + l.replay.items.len; - var i = l.built; - l.built += 1; - if (i < steady) return l.sketch(pick(&stay, i), .avoid); - i -= steady; - if (i < facts.len) return l.sketch(facts[i], .seek); - i -= facts.len; - if (i == 0) { - t.sites.frame(); - c.reset(); - l.answers = 0; - } - if (i < steady) { - const ex = pick(&stay, i); - _ = try t.step(ex.ids, ex.start, .project); - for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1), false, ex.start - 1, true); - return .{ .done = false }; - } - i -= steady; - if (i < facts.len) { - const ex = facts[i]; - _ = try t.step(ex.ids, ex.start, .project); - l.answers += @intCast(ex.ids.len - ex.start); - try c.head(); - for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1)[(ex.start - 1) * adapters.candidates ..], true, 0, false); - return .{ .done = false }; - } - try c.choose(gate_margin); - try t.sites.open(c.coef); - t.sites.attach(&l.b.m.weights, true); - l.opened = true; - l.gate(); - try l.start(); - return .{ .done = false }; - } - - fn sketch(l: *Learner, ex: Example, mode: train.Mode) !Step { - _ = try l.trainer.?.step(ex.ids, ex.start, mode); - return .{ .done = false }; - } - - /// The new block's gate at each layer: above every steady row's share there, shut where no fact row clears it. - fn gate(l: *Learner) void { - const sites = &l.trainer.?.sites; - const c = &l.choice.?; - const k = sites.first() / adapters.block; - var open: usize = 0; - var reach: u64 = 0; - var firsts: u64 = 0; - for (sites.list, c.tau, c.hits, c.opens) |*site, tau, hits, opens| { - site.gate(k).* = tau; - open += @intFromBool(hits > 0); - reach += hits; - firsts += opens; - } - const mean = 100 * @as(f64, @floatFromInt(reach)) / @as(f64, @floatFromInt(@max(open * l.answers, 1))); - const first = @as(f64, @floatFromInt(firsts)) / @as(f64, @floatFromInt(@max(c.heads.items.len, 1))); - std.log.info("slide: block {d} acts at {d} of {d} layers, on {d:.0}% of the fact's answer rows there; first rows at {d:.1}", .{ k + 1, open, sites.list.len, mean, first }); - } - - /// One example's gradients, Adam after each fact answer and its twin; every few steps the held-out answers are read - fn stepOnce(l: *Learner) !Step { - const t = l.trainer.?; - const turn = l.plan.items[l.at]; - const got = try t.step(turn.ex.ids, turn.ex.start, if (turn.last) .learn else .grad); - if (!std.math.isFinite(got.loss)) return error.NonfiniteStep; - l.at += 1; - if (turn.fact) l.loss += got.loss; - if (!turn.last) return .{ .done = false }; - l.taken += 1; - const end = l.at == l.plan.items.len; - if (l.plain and !end) return .{ .done = false, .changed = true }; - const back = (l.taken % check_every == 0 or end) and try l.recalled(); - if (!back and !end) return .{ .done = false, .changed = true }; - l.phase = .idle; - l.kept_rounds += 1; - const loss = l.loss / @as(f32, @floatFromInt(l.taken)); - return .{ .done = true, .changed = true, .report = .{ .learned = .{ .recalled = back, .steps = l.taken, .loss = loss } } }; - } - - /// Whether every held-out answer comes back token for token (each its row's likeliest). - fn recalled(l: *Learner) !bool { - if (l.lesson.held.len == 0) return false; - for (l.lesson.held) |ex| if (!(try l.trainer.?.step(ex.ids, ex.start, .loss)).recalled) return false; - return true; - } - - /// The last lesson's answers into replay if a round of it stayed (else its block out); this lesson's are last. - fn settleLast(l: *Learner, answers: []const Example) !void { - const now = try own(l.gpa, answers); - if (l.opened and l.kept_rounds == 0) { - l.trainer.?.sites.close(); - l.trainer.?.sites.attach(&l.b.m.weights, true); - } - l.opened = false; - l.plain = false; - if (l.kept_rounds > 0) { - for (l.last) |ex| { - if (l.replay.items.len == replay_cap) l.gpa.free(l.replay.orderedRemove(0).ids); - try l.replay.append(l.gpa, ex); - } - l.gpa.free(l.last); - } else disown(l.gpa, l.last); - l.last = now; - l.kept_rounds = 0; - } - - /// A plain change's steps: a fact answer, then two steady ones as they were (twins twice as often), Adam after. - fn schedulePlain(l: *Learner, steps: u32) !void { - l.rounds += 1; - var prng = std.Random.DefaultPrng.init(l.rounds); - var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); - defer facts.deinit(l.gpa); - var steady: Deck = try .init(l.gpa, &.{ l.lesson.keep, l.lesson.near, l.lesson.near, l.replay.items }); - defer steady.deinit(l.gpa); - l.plan.clearRetainingCapacity(); - for (0..steps) |_| { - const alone = steady.cards.len == 0; - try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = alone }); - if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = false }); - if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = true }); - } - } - - /// The round's steps: the fact's answers in fresh orders. - fn schedule(l: *Learner, steps: u32) !void { - l.rounds += 1; - var prng = std.Random.DefaultPrng.init(l.rounds); - var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); - defer facts.deinit(l.gpa); - l.plan.clearRetainingCapacity(); - for (0..steps) |_| try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = true }); - } -}; - -/// Example i of the lists in turn. -fn pick(lists: []const []const Example, i: usize) Example { - var at = i; - for (lists) |xs| { - if (at < xs.len) return xs[at]; - at -= xs.len; - } - unreachable; -} - -/// Examples dealt in shuffled passes: every one once before any comes again. -const Deck = struct { - cards: []Example, - next: usize, - - fn init(gpa: std.mem.Allocator, parts: []const []const Example) !Deck { - var n: usize = 0; - for (parts) |p| n += p.len; - const cards = try gpa.alloc(Example, n); - var at: usize = 0; - for (parts) |p| { - @memcpy(cards[at..][0..p.len], p); - at += p.len; - } - return .{ .cards = cards, .next = n }; - } - - fn deinit(d: *Deck, gpa: std.mem.Allocator) void { - gpa.free(d.cards); - } - - fn draw(d: *Deck, r: std.Random) Example { - if (d.next == d.cards.len) { - r.shuffle(Example, d.cards); - d.next = 0; - } - d.next += 1; - return d.cards[d.next - 1]; - } -}; - -fn own(gpa: std.mem.Allocator, xs: []const Example) ![]Example { - const out = try gpa.alloc(Example, xs.len); - var made: usize = 0; - errdefer { - for (out[0..made]) |x| gpa.free(x.ids); - gpa.free(out); - } - for (xs, out) |x, *o| { - o.* = .{ .ids = try gpa.dupe(u32, x.ids), .start = x.start }; - made += 1; - } - return out; -} - -fn disown(gpa: std.mem.Allocator, xs: []Example) void { - for (xs) |x| gpa.free(x.ids); - gpa.free(xs); -} +pub const Backend = train.Backend; +pub const Example = learner.Example; +pub const Lesson = learner.Lesson; +pub const Report = learner.Report; +pub const Step = learner.Step; +pub const Learner = learner.Of(train); diff --git a/zig/src/families/nemotron/slide_dims.zig b/zig/src/families/nemotron/slide_dims.zig new file mode 100644 index 00000000000..d8e2116eadf --- /dev/null +++ b/zig/src/families/nemotron/slide_dims.zig @@ -0,0 +1,20 @@ +//! The learned change's sizes and settings, the same on every backend: a block of ranks a lesson, its sketches, Adam. + +pub const block = 16; // ranks a lesson adds at each layer +pub const max_rank = 512; // thirty-two lessons' blocks +pub const max_blocks = max_rank / block; +pub const scale: f32 = 10; +pub const avoid_dims = 192; // directions sketched from the inputs a new block must leave alone +pub const candidates = 64; // directions sketched from the fact's inputs, which a new block's are chosen among + +/// Adam's settings for a block's outputs (its gate keeps them off what must stay): rate, moments' decays, epsilon. +pub const hyper = [4]f32{ 3e-4, 0.9, 0.999, 1e-8 }; + +/// Each new input direction's length, as MLX's LoRA draws its down factor's columns (uniform within 1 / sqrt(in)). +pub const a_norm: f32 = 0.577; + +/// A block's directions' squared length: a row's cosine with one is (x . a) / sqrt(unit |x|^2). +pub const unit = a_norm * a_norm; + +/// A block's gate before its lesson sets one: above any cosine, so the block stays shut. +pub const shut: f32 = 2; diff --git a/zig/src/families/nemotron/train.zig b/zig/src/families/nemotron/train.zig index e4faa2f7445..2fbf23113bd 100644 --- a/zig/src/families/nemotron/train.zig +++ b/zig/src/families/nemotron/train.zig @@ -9,6 +9,7 @@ const pl = @import("prefill_launch.zig"); const ops = @import("train_ops.zig"); const back = @import("train_back.zig"); const adapters = @import("adapters.zig"); +const learned = @import("learned.zig"); const backend = @import("backend.zig"); const Metal = backend.Metal; @@ -16,6 +17,9 @@ const At = pl.At; const Buffer = mtl.Buffer; const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; +/// What the learner runs on: the Metal engine. +pub const Backend = Metal; + /// Rows a step learns from at most: a question and its answer (attention's backward reads at most 256). pub const max_rows = 256; @@ -148,6 +152,17 @@ pub const Trainer = struct { return out; } + /// Every layer's forward applies the change's blocks in use (off: none of them). + pub fn attach(t: *Trainer, on: bool) void { + t.sites.attach(&t.b.m.weights, on); + } + + /// The first `ranks` of the change folded into the output projections and written into the model's shards. + pub fn save(t: *Trainer, gpa: std.mem.Allocator, io: std.Io, ranks: usize) !usize { + const m = t.b.m; + return learned.write(gpa, io, m.dir, &m.checkpoint, &m.weights, m.config, &t.sites, ranks); + } + /// Each row along layer l's candidate directions ([rows, candidates]), as the last project step left them. pub fn projected(t: *const Trainer, l: usize, rows: usize) []const f32 { const k = adapters.candidates; diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 12275297433..16e7b08c1dd 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -6,6 +6,7 @@ const lanes = @import("lanes"); const nemotron = @import("nemotron"); const Allocator = std.mem.Allocator; const budget = @import("cuda_memory.zig"); +const nemotron_slide = @import("nemotron_slide.zig"); const Pool = budget.Pool; /// CUDA families provide metadata, open their lane backend and explain their refusals. @@ -158,6 +159,9 @@ const Host = struct { startup: []u8 = &.{}, lone: ?LoneRun = null, // the family's driver for a lone drafted stream, called with `family` store: ?*api.prompt_cache.Store = null, // kept Nemotron states; null when the budget is 0 + learn: ?api.Learner = null, // the family's Sliding Weights learner (--slide), called with the context current + slide: ?*anyopaque = null, // that learner's adapter, freed by slide_free before the family + slide_free: ?*const fn (Allocator, *anyopaque) void = null, fn close(p: *anyopaque) void { const h: *Host = @ptrCast(@alignCast(p)); @@ -169,6 +173,7 @@ const Host = struct { s.deinit(); h.gpa.destroy(s); } + if (h.slide) |s| h.slide_free.?(h.gpa, s); h.release(h.family); if (h.gpu) |g| { g.ctx.deinit(); @@ -200,9 +205,35 @@ const Host = struct { h.host.explain = explain; h.host.cache = h.store; if (h.lone != null) h.host.lone = .{ .ctx = h, .run = loneRun, .sampled = true }; + if (h.learn != null) h.host.learner = h.learner(); try h.host.start(); } + /// The family's learner, each call made with the context current on the lane thread. + fn learner(h: *Host) api.Learner { + return .{ + .ctx = h, + .begin = struct { + fn f(p: *anyopaque, request: *const api.LearnRequest, sink: api.LearnSink) anyerror!void { + const l = bind(p).learn.?; + return l.begin(l.ctx, request, sink); + } + }.f, + .step = struct { + fn f(p: *anyopaque) api.Learner.Step { + const l = bind(p).learn.?; + return l.step(l.ctx); + } + }.f, + .abort = struct { + fn f(p: *anyopaque) void { + const l = bind(p).learn.?; + l.abort(l.ctx); + } + }.f, + }; + } + /// The family's lone driver with the context current on the lane thread. fn loneRun(p: *anyopaque, s: *lanes.Stream, hooks: api.LoneHooks) anyerror!bool { const x = bind(p); @@ -315,6 +346,16 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O }; return null; }; + if (o.slide) { + if (!@hasDecl(F, "slide")) { + problem.* = try std.fmt.allocPrint(a, "--slide: {s} checkpoints do not learn on CUDA yet", .{o.model_type}); + return null; + } + if (try F.linked(a, io, o.dir)) |name| { + problem.* = try std.fmt.allocPrint(a, "--slide rewrites the model's own files, and {s} in {s} is a link to data another file shares (a Hugging Face cache's blob, or a hard link), so learning would change that file too: serve a copy made with `cp -RL` (a copy that follows links)", .{ name, o.dir }); + return null; + } + } const device = try setting(a, o.device, "TF_CUDA_DEVICE", 0, problem) orelse return null; const segments = try setting(a, o.segments, "TF_CUDA_SEGMENTS", 1, problem) orelse return null; if (segments < 1 or segments > F.max_segments) { @@ -322,6 +363,10 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O problem.* = try std.fmt.allocPrint(a, "{s}{d}: whole prompt chunks a call, 1 to {d}", .{ named, segments, F.max_segments }); return null; } + if (o.slide and segments > 1) { + problem.* = "--slide runs a prompt one chunk at a time, its change's scratch shared by every layer: serve it without --segments or TF_CUDA_SEGMENTS"; + return null; + } const g = try gpa.create(Gpu); var opened = false; defer if (!opened) gpa.destroy(g); @@ -342,6 +387,10 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O const capability = try g.ctx.capability(); var name_buf: [256]u8 = undefined; const name = g.ctx.name(&name_buf) catch "GPU"; + if (o.slide and capability != 121) { + problem.* = try std.fmt.allocPrint(a, "--slide learns on a GB10 (sm_121) so far, and this {s} is sm_{d}: serve it without --slide", .{ name, capability }); + return null; + } const kernels: ?[]const u8 = switch (try cuda.aot.pick(a, io, getenv("TENSORFOLD_CUDA_KERNELS"), capability)) { .native => null, .captured => |dir| dir, @@ -357,7 +406,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O problem.* = try std.fmt.allocPrint(a, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the CUDA memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", .{ toGib(weights), toGib(before.room(held0)), toGib(before.free), toGib(before.reserve), if (before.limit != null) ", under TENSORFOLD_CUDA_MEMORY_LIMIT_GB" else "" }); return null; } - const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments }) catch |e| { + const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments, .slide = o.slide }) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot load {s} with {s} glue kernels ({s})", .{ o.dir, kernels orelse "its own", @errorName(e) }); return null; }; @@ -394,6 +443,21 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O store.deinit(); gpa.destroy(store); }; + if (loaded.learns) |e| { + const Slide = nemotron_slide.Adapter(F.slide); + const s = try gpa.create(Slide); + s.* = Slide.init(gpa, io, e); + h.slide = s; + h.slide_free = struct { + fn f(al: Allocator, p: *anyopaque) void { + const x: *Slide = @ptrCast(@alignCast(p)); + x.deinit(); + al.destroy(x); + } + }.f; + h.learn = s.hook(); + } + errdefer if (h.slide) |s| h.slide_free.?(gpa, s); // the family cuts its own prompt grid from position 0, as `tensorfold run` does: prefill_step 0 try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .logprobs = loaded.backend.vtable.first_row != null }, .{ .ctx = loaded.ctx, .text = F.explain }); opened = true; diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 369b7b5dbd8..59e2659cd9e 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -10,6 +10,7 @@ const qwen27 = @import("qwen27_host.zig"); const flashnext = @import("flashnext_host.zig"); const glm = @import("glm_host.zig"); const nemotron_slide = @import("nemotron_slide.zig"); +const Slide = nemotron_slide.Adapter(nemotron.slide); const cache_fit = @import("cache_fit.zig"); pub const backends: []const []const u8 = &.{"metal"}; @@ -68,7 +69,7 @@ const Host = struct { cache: ?api.prompt_cache.Store = null, // kept prompt states (engine thread only); null: a zero budget learned: ?api.prompt_imprint.Imprint = null, // --learn: shared states on disk, read back by later servers round: nemotron.gpu_round.Options = .{ .depth = 8 }, // a lone greedy stream's GPU-side rounds, as the CLI runs them - slide: ?*nemotron_slide.Adapter = null, // Sliding Weights' learner, with --slide + slide: ?*Slide = null, // Sliding Weights' learner, with --slide /// A lone greedy stream's rounds on the GPU until it finishes, or a hand-over to the lane core (true). fn lone(ctx: *anyopaque, s: *lanes.Stream, hooks: api.LoneHooks) anyerror!bool { @@ -180,9 +181,9 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; h.slide = null; if (o.slide) { - const s = try gpa.create(nemotron_slide.Adapter); + const s = try gpa.create(Slide); errdefer gpa.destroy(s); - s.* = nemotron_slide.Adapter.init(gpa, io, h.metal); + s.* = Slide.init(gpa, io, h.metal); h.slide = s; h.host.learner = s.hook(); } diff --git a/zig/src/native/nemotron_slide.zig b/zig/src/native/nemotron_slide.zig index 93b5f10bdbd..3400b7744c5 100644 --- a/zig/src/native/nemotron_slide.zig +++ b/zig/src/native/nemotron_slide.zig @@ -1,62 +1,65 @@ //! Nemotron's Sliding Weights learner behind the lane host's learn hook: lessons in, learn events out. const std = @import("std"); const api = @import("engine_api"); -const tf = @import("tensorfold"); -const slide = tf.nemotron.slide; const Allocator = std.mem.Allocator; -pub const Adapter = struct { - learner: slide.Learner, - arena: std.heap.ArenaAllocator, - sink: ?api.LearnSink = null, - - pub fn init(gpa: Allocator, io: std.Io, b: *tf.nemotron.backend.Metal) Adapter { - return .{ .learner = slide.Learner.init(gpa, io, b), .arena = .init(gpa) }; - } - - pub fn deinit(a: *Adapter) void { - a.learner.deinit(); - a.arena.deinit(); - } - - pub fn hook(a: *Adapter) api.Learner { - return .{ .ctx = a, .begin = begin, .step = step, .abort = abort }; - } - - fn begin(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.LearnSink) anyerror!void { - const a: *Adapter = @ptrCast(@alignCast(ctx)); - _ = a.arena.reset(.retain_capacity); - const al = a.arena.allocator(); - try a.learner.begin(.{ .train = try examples(al, request.train), .held = try examples(al, request.held), .near = try examples(al, request.near), .keep = try examples(al, request.keep), .undo = request.undo, .steps = request.steps, .more = request.more, .commit = request.commit, .save = request.save }); - a.sink = sink; - } - - fn step(ctx: *anyopaque) api.Learner.Step { - const a: *Adapter = @ptrCast(@alignCast(ctx)); - const s = a.learner.step(); - const failed = if (s.report) |r| r == .failed else false; - if (s.report) |r| a.emit(switch (r) { - .learned => |x| .{ .learned = .{ .recalled = x.recalled, .steps = x.steps, .loss = x.loss } }, - .failed => |message| .{ .done = .{ .message = message } }, - }); - if (s.done and !failed) a.emit(.{ .done = .{} }); - return .{ .done = s.done, .changed = s.changed }; - } - - fn abort(ctx: *anyopaque) void { - const a: *Adapter = @ptrCast(@alignCast(ctx)); - a.learner.abort(); - a.emit(.{ .done = .{ .message = "the engine closed" } }); - } - - fn emit(a: *Adapter, event: api.LearnEvent) void { - const sink = a.sink orelse return; - sink.event(sink.ctx, &event); - } -}; - -fn examples(al: Allocator, xs: []const api.Example) ![]slide.Example { - const out = try al.alloc(slide.Example, xs.len); - for (xs, out) |x, *o| o.* = .{ .ids = x.ids, .start = x.start }; - return out; +/// The hook over `slide`, a backend's learner file (its Learner, Example and Backend: Metal's or CUDA's). +pub fn Adapter(comptime slide: type) type { + return struct { + const Self = @This(); + + learner: slide.Learner, + arena: std.heap.ArenaAllocator, + sink: ?api.LearnSink = null, + + pub fn init(gpa: Allocator, io: std.Io, b: *slide.Backend) Self { + return .{ .learner = slide.Learner.init(gpa, io, b), .arena = .init(gpa) }; + } + + pub fn deinit(a: *Self) void { + a.learner.deinit(); + a.arena.deinit(); + } + + pub fn hook(a: *Self) api.Learner { + return .{ .ctx = a, .begin = begin, .step = step, .abort = abort }; + } + + fn begin(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.LearnSink) anyerror!void { + const a: *Self = @ptrCast(@alignCast(ctx)); + _ = a.arena.reset(.retain_capacity); + const al = a.arena.allocator(); + try a.learner.begin(.{ .train = try examples(al, request.train), .held = try examples(al, request.held), .near = try examples(al, request.near), .keep = try examples(al, request.keep), .undo = request.undo, .steps = request.steps, .more = request.more, .commit = request.commit, .save = request.save }); + a.sink = sink; + } + + fn step(ctx: *anyopaque) api.Learner.Step { + const a: *Self = @ptrCast(@alignCast(ctx)); + const s = a.learner.step(); + const failed = if (s.report) |r| r == .failed else false; + if (s.report) |r| a.emit(switch (r) { + .learned => |x| .{ .learned = .{ .recalled = x.recalled, .steps = x.steps, .loss = x.loss } }, + .failed => |message| .{ .done = .{ .message = message } }, + }); + if (s.done and !failed) a.emit(.{ .done = .{} }); + return .{ .done = s.done, .changed = s.changed }; + } + + fn abort(ctx: *anyopaque) void { + const a: *Self = @ptrCast(@alignCast(ctx)); + a.learner.abort(); + a.emit(.{ .done = .{ .message = "the engine closed" } }); + } + + fn emit(a: *Self, event: api.LearnEvent) void { + const sink = a.sink orelse return; + sink.event(sink.ctx, &event); + } + + fn examples(al: Allocator, xs: []const api.Example) ![]slide.Example { + const out = try al.alloc(slide.Example, xs.len); + for (xs, out) |x, *o| o.* = .{ .ids = x.ids, .start = x.start }; + return out; + } + }; } diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 9451db61fa5..9294d2603cd 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -15,6 +15,11 @@ const chunk_costs = @import("chunk_costs.zig"); const grouped_tests = @import("grouped_tests.zig"); const fp8_tests = @import("fp8_tests.zig"); const carveout_tests = @import("carveout_tests.zig"); +const slide_grad = @import("slide_grad.zig"); +const slide_bench = @import("slide_bench.zig"); +const slide_decode = @import("slide_decode.zig"); +const train_mixer_tests = @import("train_mixer_tests.zig"); +const train_tests = @import("train_tests.zig"); const usage = \\usage: tf-cuda-test @@ -39,6 +44,12 @@ const usage = \\ grouped-plan the shared expert plan against experts.route's bytes (oracle/grouped_plan.py) \\ fp8-lane block-FP8 projections against the Python lane matmul's bytes (oracle/fp8_lane.py) \\ carveout [MiB] [card] GB10 display memory: round trips and bandwidth (SKIP without the card) + \\ train Sliding Weights' training kernels against f64 references (synthetic rows) + \\ train-mixers Sliding Weights' mixer gradients against f64 references (synthetic rows) + \\ slide-decode MODEL IDS_FILE a decode token's milliseconds without --slide and with 0 to 512 ranks + \\ slide-kernels the change's window kernels at 512 ranks, a and b in mapped host or device memory + \\ slide-bench MODEL IDS_FILE START Sliding Weights' step milliseconds in each mode + \\ slide-grad MODEL IDS_FILE START [REACH [STARTS]] Sliding Weights' gradient against a cubic fit of the loss \\ ; @@ -99,6 +110,12 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { const mib = if (rest.len > 0) try std.fmt.parseInt(usize, rest[0], 10) else cuda.carveout.default_bytes >> 20; return carveout_tests.run(gpu, if (rest.len > 1) rest[1] else cuda.carveout.default_card, mib); } + if (std.mem.eql(u8, cmd, "train")) return train_tests.run(gpu); + if (std.mem.eql(u8, cmd, "train-mixers")) return train_mixer_tests.run(gpu); + if (std.mem.eql(u8, cmd, "slide-decode")) return slide_decode.run(gpu, try arg(rest, 0), try arg(rest, 1)); + if (std.mem.eql(u8, cmd, "slide-kernels")) return slide_decode.kernels(gpu); + if (std.mem.eql(u8, cmd, "slide-bench")) return slide_bench.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "slide-grad")) return slide_grad.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), if (rest.len > 3) rest[3] else null, if (rest.len > 4) rest[4] else null); std.debug.print("{s}", .{usage}); return error.UnknownCommand; } diff --git a/zig/tests/cuda/slide_bench.zig b/zig/tests/cuda/slide_bench.zig new file mode 100644 index 00000000000..20ff8f0b4c0 --- /dev/null +++ b/zig/tests/cuda/slide_bench.zig @@ -0,0 +1,42 @@ +//! Sliding Weights on CUDA: one step's milliseconds in each mode, for a tokenized example, with one block open. + +const std = @import("std"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); + +const dims = nemotron.slide_dims; +const reps = 10; + +/// MODEL with IDS_FILE's tokens (the answer from START): the median of ten steps in each mode. +pub fn run(gpu: check.Gpu, model: []const u8, ids_path: []const u8, start_text: []const u8) !void { + const gpa = gpu.gpa; + const io = gpu.io; + const text = try std.Io.Dir.cwd().readFileAlloc(io, ids_path, gpa, .limited(1 << 20)); + defer gpa.free(text); + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n"); + while (it.next()) |w| try ids.append(gpa, try std.fmt.parseInt(u32, w, 10)); + const start = try std.fmt.parseInt(usize, start_text, 10); + const e = try nemotron.Engine.init(gpa, io, gpu.ctx, model, null, .{ .context = 2048, .mtp = false, .graphs = false, .sampling = null, .segments = 1, .slide = true }); + defer e.deinit(); + const t = try nemotron.train.Trainer.init(gpa, e); + defer t.deinit(gpa); + var prng = std.Random.DefaultPrng.init(3); + const r = prng.random(); + for (t.sites.list) |*site| { + for (site.a.slice(f32, dims.block * site.in)) |*v| v.* = (r.float(f32) - 0.5) * 0.02; + site.gate(0).* = -std.math.inf(f32); + } + t.sites.rank = dims.block; + t.attach(true); + for ([_]nemotron.train.Mode{ .loss, .grad, .learn, .project, .seek }) |mode| { + var ms: [reps]f64 = undefined; + for (&ms) |*m| { + const t0 = check.now(io); + _ = try t.step(ids.items, start, mode); + m.* = @as(f64, @floatFromInt(check.now(io) - t0)) / 1e6; + } + std.debug.print("RESULT {t} step, {d} rows: {d:.1} ms (median of {d})\n", .{ mode, ids.items.len - 1, check.median(&ms), reps }); + } +} diff --git a/zig/tests/cuda/slide_decode.zig b/zig/tests/cuda/slide_decode.zig new file mode 100644 index 00000000000..549b164ea38 --- /dev/null +++ b/zig/tests/cuda/slide_decode.zig @@ -0,0 +1,100 @@ +//! Sliding Weights' cost to serving on CUDA: a decode token's milliseconds without --slide, and with 0 to 512 ranks. + +const std = @import("std"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); + +const dims = nemotron.slide_dims; +const tokens = 96; + +/// MODEL from IDS_FILE's prompt: one serial decode token's mean milliseconds in each case, through the captured graphs. +pub fn run(gpu: check.Gpu, model: []const u8, ids_path: []const u8) !void { + const gpa = gpu.gpa; + const io = gpu.io; + const text = try std.Io.Dir.cwd().readFileAlloc(io, ids_path, gpa, .limited(1 << 20)); + defer gpa.free(text); + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n"); + while (it.next()) |w| try ids.append(gpa, try std.fmt.parseInt(u32, w, 10)); + var base: f64 = 0; + for ([_]bool{ false, true }) |slide| { + const e = try nemotron.Engine.init(gpa, io, gpu.ctx, model, null, .{ .context = 2048, .mtp = false, .graphs = true, .sampling = null, .segments = 1, .slide = slide }); + defer e.deinit(); + try e.captureWindows(); // the one-row window's graph, as the server captures it without drafts + if (!slide) { + base = try decode(e, ids.items); + std.debug.print("RESULT without --slide: {d:.3} ms a token\n", .{base}); + continue; + } + var prng = std.Random.DefaultPrng.init(9); + const r = prng.random(); + const s = &e.slide.?; + for (s.list) |*site| { + for (site.a.slice(f32, dims.max_rank * site.in)) |*v| v.* = (r.float(f32) - 0.5) * 1e-3; + for (site.b.slice(f32, dims.max_rank * site.out)) |*v| v.* = (r.float(f32) - 0.5) * 1e-4; + for (site.tau.slice(f32, dims.max_blocks)) |*v| v.* = -std.math.inf(f32); + } + for ([_]usize{ 0, dims.block, 4 * dims.block, dims.max_rank }) |rank| { + s.rank = rank; + s.attach(&e.w, true); + const ms = try decode(e, ids.items); + std.debug.print("RESULT --slide with {d} ranks: {d:.3} ms a token ({d:.1}% over none)\n", .{ rank, ms, 100 * (ms / base - 1) }); + } + } +} + +/// The change's two window kernels alone at 512 ranks on one row: a and b in mapped host memory, then on the device. +pub fn kernels(gpu: check.Gpu) !void { + const cuda = @import("cuda"); + var k = try nemotron.kernels.Kernels.load(gpu.gpa, gpu.io, gpu.ctx, null); + try k.loadTrain(); + defer k.deinit(); + var st = try cuda.Stream.init(gpu.d, true); + defer st.deinit(); + const t: nemotron.train_ops.Train = .{ .f = &k.train, .s = st, .d = gpu.d }; + const in = 4096; + const out = 2688; + var word = try nemotron.sites.Shared.init(gpu.d, u32, 1); + defer word.free(); + word.slice(u32, 1)[0] = dims.max_rank; + var ha = try nemotron.sites.Shared.init(gpu.d, f32, dims.max_rank * in); + defer ha.free(); + var hb = try nemotron.sites.Shared.init(gpu.d, f32, dims.max_rank * out); + defer hb.free(); + var tau = try nemotron.sites.Shared.init(gpu.d, f32, dims.max_blocks); + defer tau.free(); + for (tau.slice(f32, dims.max_blocks)) |*v| v.* = -std.math.inf(f32); + var da = try cuda.DeviceBuffer.alloc(gpu.d, dims.max_rank * in * 4); + defer da.free(); + var db = try cuda.DeviceBuffer.alloc(gpu.d, dims.max_rank * out * 4); + defer db.free(); + var x = try cuda.DeviceBuffer.alloc(gpu.d, in * 2); + defer x.free(); + var y = try cuda.DeviceBuffer.alloc(gpu.d, out * 4); + defer y.free(); + var xa = try cuda.DeviceBuffer.alloc(gpu.d, 16 * dims.max_rank * 4); + defer xa.free(); + var xn = try cuda.DeviceBuffer.alloc(gpu.d, 16 * 4); + defer xn.free(); + for ([2][2]u64{ .{ ha.dev, hb.dev }, .{ da.ptr, db.ptr } }, [2][]const u8{ "mapped host", "device" }) |ab, where| { + const ad: nemotron.weights.Adapter = .{ .a = ab[0], .b = ab[1], .tau = tau.dev, .rank = word.dev, .xa = xa.ptr, .xn = xn.ptr, .in = in, .out = out }; + for (0..20) |_| try t.adapt(ad, x.ptr, in, y.ptr, true, out, 1, 0, 1); + try st.synchronize(); + const t0 = check.now(gpu.io); + for (0..1000) |_| try t.adapt(ad, x.ptr, in, y.ptr, true, out, 1, 0, 1); + try st.synchronize(); + const us = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e3 / 1000; + const gbs = @as(f64, @floatFromInt(dims.max_rank * (in + out) * 4)) / us / 1e3; + std.debug.print("RESULT the change's window kernels, 512 ranks, a and b in {s} memory: {d:.1} us ({d:.0} GB/s)\n", .{ where, us, gbs }); + } +} + +/// The prompt, then `tokens` serial rounds of the graph: their mean milliseconds. +fn decode(e: *nemotron.Engine, prompt: []const u32) !f64 { + var tok = try e.prefill(prompt, null, null); + for (0..8) |_| tok = try e.step(tok, null); + const t0 = check.now(e.io); + for (0..tokens) |_| tok = try e.step(tok, null); + return @as(f64, @floatFromInt(check.now(e.io) - t0)) / 1e6 / tokens; +} diff --git a/zig/tests/cuda/slide_grad.zig b/zig/tests/cuda/slide_grad.zig new file mode 100644 index 00000000000..915a1a16560 --- /dev/null +++ b/zig/tests/cuda/slide_grad.zig @@ -0,0 +1,167 @@ +//! Sliding Weights on CUDA: the change's gradient against the loss's slope along it, where no expert choice moves. + +const std = @import("std"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); + +const dims = nemotron.slide_dims; +const block = dims.block; + +/// MODEL with IDS_FILE's tokens (the answer from START): each probe's analytic slope against its central differences. +pub fn run(gpu: check.Gpu, model: []const u8, ids_path: []const u8, start_text: []const u8, reach_text: ?[]const u8, restarts_text: ?[]const u8) !void { + const gpa = gpu.gpa; + const io = gpu.io; + const text = try std.Io.Dir.cwd().readFileAlloc(io, ids_path, gpa, .limited(1 << 20)); + defer gpa.free(text); + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n"); + while (it.next()) |w| try ids.append(gpa, try std.fmt.parseInt(u32, w, 10)); + const start = try std.fmt.parseInt(usize, start_text, 10); + // the loss change the furthest step predicts + const reach: f64 = if (reach_text) |x| try std.fmt.parseFloat(f64, x) else 0.16; + const e = try nemotron.Engine.init(gpa, io, gpu.ctx, model, null, .{ .context = 2048, .mtp = false, .graphs = false, .sampling = null, .segments = 1, .slide = true }); + defer e.deinit(); + const t = try nemotron.train.Trainer.init(gpa, e); + defer t.deinit(gpa); + const s = &t.sites; + const restarts: usize = if (restarts_text) |x| try std.fmt.parseInt(usize, x, 10) else 1; + // the top layers: below them a step in the change moves expert choices downstream, each a step in the loss + const spans = [_][2]usize{ .{ 51, 52 }, .{ 50, 51 }, .{ 49, 50 } }; + var sum: [spans.len]f64 = @splat(0); + var sq: [spans.len]f64 = @splat(0); + var fits: [spans.len]usize = @splat(0); + for (0..restarts) |restart| { + var prng = std.Random.DefaultPrng.init(7 + restart); + const r = prng.random(); + // one block at every layer: random directions a_norm long, open on every row, small random outputs + for (s.list) |*site| { + const a = site.a.slice(f32, block * site.in); + for (0..block) |q| { + const row = a[q * site.in ..][0..site.in]; + var n: f32 = 0; + for (row) |*v| { + v.* = r.floatNorm(f32); + n += v.* * v.*; + } + for (row) |*v| v.* *= dims.a_norm / @sqrt(n); + } + site.gate(0).* = -std.math.inf(f32); + for (site.b.slice(f32, block * site.out)) |*v| v.* = 1e-3 * r.floatNorm(f32); + } + s.rank = block; + t.attach(true); + const base = try t.step(ids.items, start, .loss); + for (s.list) |*site| @memset(site.gb.slice(f32, block * site.out), 0); + const graded = try t.step(ids.items, start, .grad); + try check.expect(@abs(base.loss - graded.loss) < 1e-4 * @max(1, base.loss), "a grad step's loss {d} equals the loss step's {d}", .{ graded.loss, base.loss }); + // the probes' grad steps add into the gradients: each probe starts from the base's, and its expert choices + const was = try picks(t, ids.items.len - 1); + defer std.heap.page_allocator.free(was); + var grads: std.ArrayList(f32) = .empty; + defer grads.deinit(gpa); + for (s.list) |*site| try grads.appendSlice(gpa, site.gb.slice(f32, block * site.out)); + for (spans, 0..) |span, si| { + var at: usize = 0; + for (s.list) |*site| { + const g = site.gb.slice(f32, block * site.out); + @memcpy(g, grads.items[at..][0..g.len]); + at += g.len; + } + const rel = try probe(t, ids.items, start, span, reach, base.loss, was) orelse continue; + sum[si] += rel; + sq[si] += rel * rel; + fits[si] += 1; + } + } + var worst: f64 = 0; + for (spans, sum, sq, fits) |span, x, x2, count| { + if (count == 0) continue; + const n: f64 = @floatFromInt(count); + const mean = x / n; + const sd = @sqrt(@max(x2 / n - mean * mean, 0)); + worst = @max(worst, @abs(mean)); + std.debug.print("RESULT layer {d} ({t}): fitted over analytic slope {d:.4} (sd {d:.4} over {d} starts)\n", .{ span[0], e.c.kinds[span[0]], 1 + mean, sd, count }); + } + try check.expect(worst < 0.05, "every probe's mean fitted slope within 5% of its analytic slope (worst {d:.4})", .{worst}); + check.pass("slide-grad: every probe's mean within {d:.2}% of its analytic slope", .{100 * worst}); +} + +/// The slope along the span's gradient, fitted where no expert choice moved, over its length less 1 (null: no fit). +fn probe(t: *nemotron.train.Trainer, ids: []const u32, start: usize, span: [2]usize, reach: f64, base: f32, was: []const i32) !?f64 { + const gpa = std.heap.page_allocator; + const s = &t.sites; + var dirs: std.ArrayList(f32) = .empty; + defer dirs.deinit(gpa); + var keep: std.ArrayList(f32) = .empty; + defer keep.deinit(gpa); + var norm: f64 = 0; + for (s.list[span[0]..span[1]]) |*site| for (site.gb.slice(f32, block * site.out)) |g| { + try dirs.append(gpa, g); + norm += g * g; + }; + const slope = @sqrt(norm); + for (dirs.items) |*v| v.* /= @floatCast(slope); + for (s.list[span[0]..span[1]]) |*site| try keep.appendSlice(gpa, site.b.slice(f32, block * site.out)); + const eps: f64 = reach / 8 / @max(slope, 1e-12); + var xs: [17]f64 = undefined; + var ys: [17]f64 = undefined; + var moved: [17]usize = @splat(0); + for (0..17) |i| { + const k = @as(f64, @floatFromInt(i)) - 8; + xs[i] = k * eps; + if (k == 0) { + ys[i] = base; + continue; + } + place(s, span, keep.items, dirs.items, @floatCast(xs[i])); + ys[i] = (try t.step(ids, start, .grad)).loss; + const now = try picks(t, ids.len - 1); + defer gpa.free(now); + for (was, now) |a, b| moved[i] += @intFromBool(a != b); + } + place(s, span, keep.items, dirs.items, 0); + var lo: usize = 8; + var hi: usize = 8; + while (lo > 0 and moved[lo - 1] == 0) lo -= 1; + while (hi < 16 and moved[hi + 1] == 0) hi += 1; + const clean = @min(8 - lo, hi - 8); + // the odd part's least-squares slope over the clean steps: sum k (y(+k) - y(-k)) / (2 eps sum k^2) + var num: f64 = 0; + var den: f64 = 0; + for (1..clean + 1) |kk| { + const kf: f64 = @floatFromInt(kk); + num += kf * (ys[8 + kk] - ys[8 - kk]); + den += 2 * eps * kf * kf; + } + var all: usize = 0; + for (moved) |m| all += m; + std.debug.print("INFO layers {d}..{d}: {d} expert choices moved across the steps; {d} clean steps each side\n", .{ span[0], span[1] - 1, all, clean }); + if (clean < 2) return null; + return num / den / @max(slope, 1e-12) - 1; +} + +/// Every MoE layer's expert choices as the last grad step kept them. +fn picks(t: *nemotron.train.Trainer, rows: usize) ![]i32 { + const gpa = std.heap.page_allocator; + const c = t.e.c; + var out: std.ArrayList(i32) = .empty; + for (0..c.layers) |l| if (c.kinds[l] == .moe) { + const n = rows * c.slots(); + const at = out.items.len; + try out.resize(gpa, at + n); + try t.e.stream.synchronize(); + try t.e.ctx.d.check(t.e.ctx.d.api.cuMemcpyDtoH_v2(out.items[at..].ptr, t.parts(l)[0], n * 4), "cuMemcpyDtoH"); + }; + return out.toOwnedSlice(gpa); +} + +/// The span's open block outputs at keep + x dirs. +fn place(s: *nemotron.sites.Sites, span: [2]usize, keep: []const f32, dirs: []const f32, x: f32) void { + var at: usize = 0; + for (s.list[span[0]..span[1]]) |*site| { + const b = site.b.slice(f32, block * site.out); + for (b, keep[at..][0..b.len], dirs[at..][0..b.len]) |*v, k0, d| v.* = k0 + x * d; + at += b.len; + } +} diff --git a/zig/tests/cuda/train_mixer_tests.zig b/zig/tests/cuda/train_mixer_tests.zig new file mode 100644 index 00000000000..3e46253d48c --- /dev/null +++ b/zig/tests/cuda/train_mixer_tests.zig @@ -0,0 +1,336 @@ +//! Sliding Weights' mixer gradients (train_mixers.cu, train.cu's routing) at Nemotron's shapes against f64 references. + +const std = @import("std"); +const cuda = @import("cuda"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); +const Gpu = check.Gpu; +const ops = nemotron.train_ops; +const gm = nemotron.glue_math; + +const D = 2688; +const E = 128; +const top_k = 6; +const NS = 8; +const H = 32; // attention heads +const KV = 2; +const HD = 128; +const QD = H * HD; +const NQKV = QD + 2 * KV * HD; +const MH = 64; // Mamba heads +const DH = 64; +const G = 8; +const N = 128; +const XD = MH * DH; +const CD = XD + 2 * G * N; +const PW = XD + CD + MH; +const eps: f32 = 1e-5; + +pub const Rig = struct { + gpu: Gpu, + a: std.mem.Allocator, + s: cuda.Stream, + t: ops.Train, + rng: std.Random, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + worst: f64 = 0, + + pub fn dev(r: *Rig, comptime T: type, host: []const T) !u64 { + const b = try cuda.DeviceBuffer.fromHost(r.gpu.d, std.mem.sliceAsBytes(host)); + try r.bufs.append(r.gpu.gpa, b); + return b.ptr; + } + + pub fn zeros(r: *Rig, comptime T: type, n: usize) !u64 { + const host = try r.a.alloc(T, n); + @memset(std.mem.sliceAsBytes(host), 0); + return r.dev(T, host); + } + + pub fn bfs(r: *Rig, n: usize, scale: f32) ![]u16 { + const out = try r.a.alloc(u16, n); + for (out) |*v| v.* = gm.f32ToBf16((r.rng.float(f32) * 2 - 1) * scale); + return out; + } + + pub fn f32s(r: *Rig, n: usize, lo: f32, hi: f32) ![]f32 { + const out = try r.a.alloc(f32, n); + for (out) |*v| v.* = lo + r.rng.float(f32) * (hi - lo); + return out; + } + + pub fn back(r: *Rig, comptime T: type, ptr: u64, n: usize) ![]T { + try r.s.synchronize(); + const out = try r.a.alloc(T, n); + try r.gpu.d.check(r.gpu.d.api.cuMemcpyDtoH_v2(out.ptr, ptr, n * @sizeOf(T)), "cuMemcpyDtoH"); + return out; + } + + /// The f32 device values at `ptr` against `want`: the largest difference over the largest reference value. + pub fn close(r: *Rig, what: []const u8, ptr: u64, want: []const f64, tol: f64) !void { + const got = try r.back(f32, ptr, want.len); + var diff: f64 = 0; + var top: f64 = 0; + for (got, want) |x, y| { + diff = @max(diff, @abs(x - y)); + top = @max(top, @abs(y)); + } + const rel = diff / @max(top, 1e-30); + r.worst = @max(r.worst, rel); + std.debug.print("RESULT {s}: largest difference {e:.3} of the largest value {e:.3} ({e:.2})\n", .{ what, diff, top, rel }); + try check.expect(rel < tol, "{s} within {e:.0} of its f64 reference ({e:.2})", .{ what, tol, rel }); + } +}; + +pub fn bf(v: u16) f64 { + return gm.bf16ToF32(v); +} + +pub fn run(gpu: Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var k = try nemotron.kernels.Kernels.load(gpu.gpa, gpu.io, gpu.ctx, null); + try k.loadTrain(); + defer k.deinit(); + var s = try cuda.Stream.init(gpu.d, true); + defer s.deinit(); + var prng = std.Random.DefaultPrng.init(11); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = s, .t = .{ .f = &k.train, .s = s, .d = gpu.d }, .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + } + try attention(&r, 37); + try route(&r, 37); + try mamba(&r, 21); + check.pass("train-mixers: every gradient within {e:.2} of its f64 reference", .{r.worst}); +} + +/// Causal attention's backward with shared kv heads, q, k and v read from one qkv row. +fn attention(r: *Rig, rows: usize) !void { + const qkv = try r.bfs(rows * NQKV, 1.0); + const dout = try r.f32s(rows * QD, -1, 1); + const scale: f64 = 1 / @sqrt(@as(f64, HD)); + const want = try r.a.alloc(f64, rows * NQKV); + @memset(want, 0); + const p = try r.a.alloc(f64, rows); + const dp = try r.a.alloc(f64, rows); + for (0..H) |h| { + const kv = h / (H / KV); + for (0..rows) |i| { + var top: f64 = -std.math.inf(f64); + for (0..i + 1) |j| { + var sc: f64 = 0; + var dv: f64 = 0; + for (0..HD) |d| { + sc += bf(qkv[i * NQKV + h * HD + d]) * bf(qkv[j * NQKV + QD + kv * HD + d]); + dv += dout[i * QD + h * HD + d] * bf(qkv[j * NQKV + QD + KV * HD + kv * HD + d]); + } + p[j] = sc * scale; + dp[j] = dv; + top = @max(top, p[j]); + } + var total: f64 = 0; + for (p[0 .. i + 1]) |*x| { + x.* = @exp(x.* - top); + total += x.*; + } + var mix: f64 = 0; + for (p[0 .. i + 1], dp[0 .. i + 1]) |*x, y| { + x.* /= total; + mix += x.* * y; + } + for (0..i + 1) |j| { + const ds = p[j] * (dp[j] - mix); + for (0..HD) |d| { + want[i * NQKV + h * HD + d] += scale * ds * bf(qkv[j * NQKV + QD + kv * HD + d]); + want[j * NQKV + QD + kv * HD + d] += scale * ds * bf(qkv[i * NQKV + h * HD + d]); + want[j * NQKV + QD + KV * HD + kv * HD + d] += p[j] * dout[i * QD + h * HD + d]; + } + } + } + } + const hs: ops.Heads = .{ .rows = @intCast(rows), .heads = H, .kv_heads = KV, .dim = HD, .nqkv = NQKV, .scale = @floatCast(scale) }; + const qd = try r.dev(u16, qkv); + const od = try r.dev(f32, dout); + const probs = try r.zeros(f32, H * rows * rows); + const dsc = try r.zeros(f32, H * rows * rows); + const out = try r.zeros(f32, rows * NQKV); + try r.t.attnQ(qd, od, probs, dsc, out, hs); + try r.t.attnKv(qd, od, probs, dsc, out, hs); + try r.close("attention dq, dk, dv", out, want, 1e-4); +} + +/// The routing weights' gradient through normalized sigmoid scores into the router's input, added to dx. +fn route(r: *Rig, rows: usize) !void { + const sk = 6; + const part = try r.f32s(sk * rows * E, -0.5, 0.5); + const ids = try r.a.alloc(i32, rows * NS); + for (0..rows) |t| { + var used: [E]bool = @splat(false); + for (0..top_k) |j| { + var e = r.rng.uintLessThan(usize, E); + while (used[e]) e = r.rng.uintLessThan(usize, E); + used[e] = true; + ids[t * NS + j] = @intCast(e); + } + ids[t * NS + top_k] = E; + ids[t * NS + top_k + 1] = E + 1; + } + const ys = try r.bfs(rows * NS * D, 1.0); + const g = try r.f32s(rows * D, -1, 1); + const gate = try r.bfs(E * D, 0.05); + const dx0 = try r.f32s(rows * D, -1, 1); + const want = try r.a.alloc(f64, rows * D); + for (0..rows) |t| { + var a: [top_k]f64 = undefined; + var p: [top_k]f64 = undefined; + var total: f64 = 0; + for (0..top_k) |j| { + a[j] = 0; + for (0..D) |i| a[j] += g[t * D + i] * bf(ys[(t * NS + j) * D + i]); + var z: f64 = 0; + for (0..sk) |sl| z += part[(sl * rows + t) * E + @as(usize, @intCast(ids[t * NS + j]))]; + p[j] = 1 / (1 + @exp(-z)); + total += p[j]; + } + var mix: f64 = 0; + for (0..top_k) |j| mix += a[j] * p[j] / total; + for (0..D) |i| { + var sum: f64 = dx0[t * D + i]; + for (0..top_k) |j| sum += 2.5 / total * (a[j] - mix) * p[j] * (1 - p[j]) * bf(gate[@as(usize, @intCast(ids[t * NS + j])) * D + i]); + want[t * D + i] = sum; + } + } + const dx = try r.dev(f32, dx0); + try r.t.routeBack(try r.dev(f32, part), sk, try r.dev(i32, ids), try r.dev(u16, ys), try r.dev(f32, g), try r.dev(u16, gate), dx, rows, E, top_k, NS, D, 2.5); + try r.close("route back", dx, want, 1e-4); +} + +/// The Mamba-2 mixer from its in-projection's rows to its gated norm, in f64: the objective sum(dn * out). +const Mixer = struct { + rows: usize, + cw: []const f32, + cb: []const f32, + dtb: []const f32, + a: []const f32, + d: []const f32, + w: []const u16, + dn: []const f32, + + fn loss(m: Mixer, al: std.mem.Allocator, proj: []const f64, act_out: ?[]u16) !f64 { + const rows = m.rows; + const act = try al.alloc(f64, rows * CD); + defer al.free(act); + for (0..rows) |t| for (0..CD) |c| { + var pre: f64 = m.cb[c]; + for (0..4) |j| if (t + j >= 3) { + pre += m.cw[j * CD + c] * proj[(t + j - 3) * PW + XD + c]; + }; + act[t * CD + c] = pre / (1 + @exp(-pre)); + if (act_out) |o| o[t * CD + c] = gm.f32ToBf16(@floatCast(act[t * CD + c])); + }; + const y = try al.alloc(f64, rows * XD); + defer al.free(y); + const st = try al.alloc(f64, DH * N); + defer al.free(st); + for (0..MH) |h| { + const g = h / (MH / G); + @memset(st, 0); + for (0..rows) |t| { + const v = proj[t * PW + XD + CD + h] + m.dtb[h]; + const dt = @max(v, 0) + @log(1 + @exp(-@abs(v))); + const decay = @exp(dt * m.a[h]); + for (0..DH) |p| { + const x = act[t * CD + h * DH + p]; + var out: f64 = 0; + for (0..N) |n| { + const at = p * N + n; + st[at] = decay * st[at] + dt * x * act[t * CD + XD + g * N + n]; + out += st[at] * act[t * CD + XD + G * N + g * N + n]; + } + y[t * XD + h * DH + p] = out + m.d[h] * x; + } + } + } + var total: f64 = 0; + const width = XD / G; + for (0..rows) |t| for (0..G) |g| { + var sq: f64 = 0; + for (0..width) |j| { + const i = g * width + j; + const z = proj[t * PW + i]; + const gated = y[t * XD + i] * z / (1 + @exp(-z)); + sq += gated * gated; + } + const inv = 1 / @sqrt(sq / @as(f64, @floatFromInt(width)) + eps); + for (0..width) |j| { + const i = g * width + j; + const z = proj[t * PW + i]; + total += m.dn[t * XD + i] * bf(m.w[i]) * inv * y[t * XD + i] * z / (1 + @exp(-z)); + } + }; + return total; + } +}; + +/// The Mamba-2 backward (dt, scan, gate, conv, raw dt) against the f64 mixer's central differences at sampled columns. +fn mamba(r: *Rig, rows: usize) !void { + const proj16 = try r.bfs(rows * PW, 1.0); + const proj = try r.a.alloc(f64, rows * PW); + for (proj, proj16) |*x, v| x.* = bf(v); + for (0..rows) |t| for (0..MH) |h| { + proj[t * PW + XD + CD + h] = -2 + 2 * r.rng.float(f64); // raw dt near the softplus knee + proj16[t * PW + XD + CD + h] = gm.f32ToBf16(@floatCast(proj[t * PW + XD + CD + h])); + proj[t * PW + XD + CD + h] = bf(proj16[t * PW + XD + CD + h]); + }; + const m: Mixer = .{ .rows = rows, .cw = try r.f32s(4 * CD, -0.5, 0.5), .cb = try r.f32s(CD, -0.1, 0.1), .dtb = try r.f32s(MH, -1, 0), .a = try r.f32s(MH, -2, -0.2), .d = try r.f32s(MH, 0.5, 1.5), .w = try r.bfs(XD, 1.0), .dn = try r.f32s(rows * XD, -1, 1) }; + const act16 = try r.a.alloc(u16, rows * CD); + _ = try m.loss(r.a, proj, act16); + const shape: ops.Shape = .{ .rows = @intCast(rows), .heads = MH, .dh = DH, .groups = G, .n = N, .inner = XD, .conv = CD, .proj = PW, .lo = 0, .hi = std.math.inf(f32) }; + const pd = try r.dev(u16, proj16); + const actd = try r.dev(u16, act16); + const dtb = try r.dev(f32, m.dtb); + const ad = try r.dev(f32, m.a); + const dd = try r.dev(f32, m.d); + const dt = try r.zeros(f32, rows * MH); + const ytot = try r.zeros(f32, rows * XD); + const ckpt = try r.zeros(f32, MH * (rows / 16 + 1) * DH * N); + const states = try r.zeros(f32, MH * 16 * DH * N); + const dytot = try r.zeros(f32, rows * XD); + const dproj = try r.zeros(f32, rows * PW); + const dact = try r.zeros(f32, rows * CD); + const dbp = try r.zeros(f32, rows * MH * N); + const dcp = try r.zeros(f32, rows * MH * N); + const ddt = try r.zeros(f32, rows * MH); + try r.t.dt(pd, dtb, dt, shape); + try r.t.ssmFwd(actd, dt, ad, dd, ytot, ckpt, shape); + try r.t.gateBack(ytot, pd, try r.dev(u16, m.w), try r.dev(f32, m.dn), dytot, dproj, shape, eps); + try r.t.ssmBack(actd, dt, ad, dd, dytot, ckpt, states, dact, dbp, dcp, ddt, shape); + try r.t.ssmBc(dbp, dcp, dact, shape); + try r.t.convBack(dact, pd, try r.dev(f32, m.cw), try r.dev(f32, m.cb), dproj, shape); + try r.t.dtBack(pd, dtb, ddt, dproj, shape); + const got = try r.back(f32, dproj, rows * PW); + // central differences at columns of z, x, B, C and dt, early and late rows + const cols = [_]usize{ 5, 1500, XD + 7, XD + 2000, XD + XD + 3, XD + XD + G * N + 9, XD + CD + 2, XD + CD + 40 }; + var diff: f64 = 0; + var top: f64 = 0; + for (cols) |col| for ([_]usize{ 0, rows / 2, rows - 1 }) |t| { + const at = t * PW + col; + const h = 1e-4 * @max(1, @abs(proj[at])); + const keep = proj[at]; + proj[at] = keep + h; + const up = try m.loss(r.a, proj, null); + proj[at] = keep - h; + const down = try m.loss(r.a, proj, null); + proj[at] = keep; + const want = (up - down) / (2 * h); + diff = @max(diff, @abs(got[at] - want)); + top = @max(top, @abs(want)); + std.debug.print("RESULT mamba dproj row {d} col {d}: {e:.5} against central {e:.5}\n", .{ t, col, got[at], want }); + }; + const rel = diff / @max(top, 1e-30); + r.worst = @max(r.worst, rel); + std.debug.print("RESULT mamba backward: largest difference {e:.3} of the largest value {e:.3} ({e:.2})\n", .{ diff, top, rel }); + try check.expect(rel < 2e-2, "the Mamba backward within 2% of the f64 mixer's central differences ({e:.2})", .{rel}); +} diff --git a/zig/tests/cuda/train_tests.zig b/zig/tests/cuda/train_tests.zig new file mode 100644 index 00000000000..78671f80f33 --- /dev/null +++ b/zig/tests/cuda/train_tests.zig @@ -0,0 +1,397 @@ +//! Sliding Weights' training kernels (train.cu) against f64 references: products, packed weights, the change, the loss. + +const std = @import("std"); +const cuda = @import("cuda"); +const nemotron = @import("nemotron"); +const check = @import("check.zig"); +const mixers = @import("train_mixer_tests.zig"); +const Gpu = check.Gpu; +const Rig = mixers.Rig; +const bf = mixers.bf; +const gm = nemotron.glue_math; +const dims = nemotron.slide_dims; +const kern = nemotron.kernels; + +pub fn run(gpu: Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var k = try kern.Kernels.load(gpu.gpa, gpu.io, gpu.ctx, null); + try k.loadTrain(); + defer k.deinit(); + var s = try cuda.Stream.init(gpu.d, true); + defer s.deinit(); + var prng = std.Random.DefaultPrng.init(5); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = s, .t = .{ .f = &k.train, .s = s, .d = gpu.d }, .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + } + for ([_][4]usize{ .{ 37, 192, 96, 1 }, .{ 130, 2688, 2688, 3 }, .{ 5, 64, 8192, 4 } }) |shape| try gemm(&r, shape); + try dequant(&r, &k, 200, 128); + try experts(&r, &k); + try adapter(&r, 23); + try adapter(&r, 5); + try lora(&r, 19); + try loss(&r, 7, 5000); + try rmsBack(&r, 9); + try sketches(&r, 11); + try small(&r); + check.pass("train: every kernel within {e:.2} of its f64 reference", .{r.worst}); +} + +/// C (+)= A B^T on the tensor cores, its K cut into slices that add in. +fn gemm(r: *Rig, shape: [4]usize) !void { + const m, const n, const kk, const split = shape; + const a = try r.bfs(m * kk, 1.0); + const b = try r.bfs(n * kk, 1.0); + const c0 = try r.f32s(m * n, -1, 1); + const want = try r.a.alloc(f64, m * n); + for (0..m) |i| for (0..n) |j| { + var sum: f64 = c0[i * n + j]; + for (0..kk) |x| sum += bf(a[i * kk + x]) * bf(b[j * kk + x]); + want[i * n + j] = sum; + }; + const c = try r.dev(f32, c0); + try r.t.gemm(try r.dev(u16, a), kk, try r.dev(u16, b), kk, c, n, m, n, kk, split); + var name: [64]u8 = undefined; + try r.close(try std.fmt.bufPrint(&name, "gemm {d}x{d}x{d} in {d} slices", .{ m, n, kk, split }), c, want, 1e-5); +} + +/// MLX 4-bit words, scales and biases for `rows` rows of `cols` inputs. +fn mlx(r: *Rig, rows: usize, cols: usize) ![3][]const u8 { + const words = try r.a.alloc(u32, rows * cols / 8); + for (words) |*w| w.* = r.rng.int(u32); + return .{ std.mem.sliceAsBytes(words), std.mem.sliceAsBytes(try r.bfs(rows * cols / 64, 0.05)), std.mem.sliceAsBytes(try r.bfs(rows * cols / 64, 0.05)) }; +} + +fn value(w: [3][]const u8, cols: usize, row: usize, i: usize) f64 { + const words = std.mem.bytesAsSlice(u32, @as([]align(4) const u8, @alignCast(w[0]))); + const sb = [2][]align(1) const u16{ std.mem.bytesAsSlice(u16, w[1]), std.mem.bytesAsSlice(u16, w[2]) }; + const q: f64 = @floatFromInt((words[(row * cols + i) / 8] >> @intCast(4 * (i % 8))) & 0xF); + const g = (row * cols + i) / 64; + return bf(sb[0][g]) * q + bf(sb[1][g]); +} + +/// A projection packed as the loader tiles it (tf_pack_dense, tf_transpose_pad16), dequantized transposed. +fn dequant(r: *Rig, k: *const kern.Kernels, n: usize, kk: usize) !void { + const w = try mlx(r, n, kk); + const kg = kk / 64; + const npad = (n + 127) / 128 * 128; + const q: nemotron.weights.QLinear = .{ .w = try r.zeros(u32, npad * kk / 8), .s = try r.zeros(u16, kg * npad), .b = try r.zeros(u16, kg * npad), .n = n, .k = kk, .npad = npad }; + const total: u64 = @as(u64, npad / 64) * kg * 512; + var a: cuda.Args = .{}; + a.add(try r.dev(u8, w[0])); + for ([_]usize{ n, kk / 8, kg }) |v| a.add(@as(c_int, @intCast(v))); + a.add(q.w); + a.add(@as(c_longlong, @intCast(total))); + try cuda.launch.launch(k.pack_dense, .{ .grid = .{ .x = @intCast((total + 255) / 256) }, .block = .{ .x = 256 } }, r.s, &a); + for ([_]u64{ q.s, q.b }, [_]usize{ 1, 2 }) |out, part| { + var t: cuda.Args = .{}; + t.add(try r.dev(u8, w[part])); + for ([_]usize{ n, kg, npad }) |v| t.add(@as(c_int, @intCast(v))); + t.add(out); + try cuda.launch.launch(k.transpose16, .{ .grid = .{ .x = @intCast((kg * npad + 255) / 256) }, .block = .{ .x = 256 } }, r.s, &t); + } + const out = try r.zeros(u16, kk * n); + try r.t.dequantT(q, out); + const got = try r.back(u16, out, kk * n); + var bad: usize = 0; + for (0..kk) |i| for (0..n) |j| { + bad += @intFromBool(got[i * n + j] != gm.f32ToBf16(@floatCast(value(w, kk, j, i)))); + }; + std.debug.print("RESULT dequant_t {d}x{d}: {d} of {d} values differ from the MLX dequantization\n", .{ n, kk, bad, n * kk }); + try check.expect(bad == 0, "dequant_t reads the tiled layout as MLX's codes", .{}); +} + +/// Pairs' input gradients through packed experts (tf_experts_pack's blocks), plan item by plan item. +fn experts(r: *Rig, k: *const kern.Kernels) !void { + const count = 3; + const n = 64; + const kk = 128; + const w = try mlx(r, count * n, kk); + const nb = n / 32; + const kg = kk / 64; + const packed_w = try r.zeros(u32, count * nb * kg * 288); + var a: cuda.Args = .{}; + for ([_]u64{ try r.dev(u8, w[0]), try r.dev(u8, w[1]), try r.dev(u8, w[2]), packed_w }) |v| a.add(v); + for ([_]usize{ n, kk / 8, kg, nb }) |v| a.add(@as(c_int, @intCast(v))); + try cuda.launch.launch(k.pack_experts, .{ .grid = .{ .x = kg, .y = nb, .z = count }, .block = .{ .x = 288 } }, r.s, &a); + const pick = [_]usize{ 0, 2, 2, 1, 0, 2, 1 }; + const items = [_]i32{ 0, 0, 2, 1, 2, 2, 2, 4, 3 }; + const members = [_]i32{ 0, 4, 3, 6, 1, 2, 5 }; + const x = try r.f32s(pick.len * n, -1, 1); + const want = try r.a.alloc(f64, pick.len * kk); + for (pick, 0..) |e, p| for (0..kk) |i| { + var sum: f64 = 0; + for (0..n) |j| sum += x[p * n + j] * value(w, kk, e * n + j, i); + want[p * kk + i] = sum; + }; + const out = try r.zeros(f32, pick.len * kk); + try r.t.expertsBack(try r.dev(f32, x), n, packed_w, try r.dev(i32, &items), try r.dev(i32, &[_]i32{3}), try r.dev(i32, &members), out, kk, n, kk, 3); + try r.close("experts back", out, want, 1e-5); +} + +/// The forward's change: xa over every block in use, then y += scale xa b where each block is open on the row. +fn adapter(r: *Rig, rows: usize) !void { + const in = 3712; + const out = 2688; + const stride = 8 * 1856; + const rank = 48; + const x = try r.bfs(rows * stride, 1.0); + const a = try r.f32s(dims.max_rank * in, -0.02, 0.02); + const b = try r.f32s(dims.max_rank * out, -0.01, 0.01); + var tau: [dims.max_blocks]f32 = @splat(dims.shut); + tau[0] = -std.math.inf(f32); + tau[1] = 0; + const xa = try r.a.alloc(f64, rows * rank); + for (0..rows) |t| for (0..rank) |q| { + var sum: f64 = 0; + var n: f64 = 0; + for (0..in) |i| { + sum += bf(x[t * stride + 6 * 1856 + i]) * a[q * in + i]; + n += bf(x[t * stride + 6 * 1856 + i]) * bf(x[t * stride + 6 * 1856 + i]); + } + xa[t * rank + q] = sum; + if (q % 16 == 15) { + const bl = q / 16; + const open = n * dims.unit > 0 and xa[t * rank + bl * 16] >= tau[bl] * @sqrt(n * dims.unit); + if (!open) for (xa[t * rank + bl * 16 ..][0..16]) |*v| { + v.* = 0; + }; + } + }; + const want = try r.a.alloc(f64, rows * out); + for (0..rows) |t| for (0..out) |j| { + var sum: f64 = 0; + for (0..rank) |q| sum += xa[t * rank + q] * b[q * out + j]; + want[t * out + j] = dims.scale * sum; + }; + var word = try nemotron.sites.Shared.init(r.gpu.d, u32, 1); + defer word.free(); + word.slice(u32, 1)[0] = rank; + const ad: nemotron.weights.Adapter = .{ .a = try r.dev(f32, a), .b = try r.dev(f32, b), .tau = try r.dev(f32, &tau), .rank = word.dev, .xa = try r.zeros(f32, rows * dims.max_rank), .xn = try r.zeros(f32, rows), .in = in, .out = out }; + const y = try r.zeros(f32, rows * 8 * out); + try r.t.adapt(ad, try r.dev(u16, x) + 6 * 1856 * 2, stride, y, true, out, 8, 6, rows); + const got = try r.back(f32, y, rows * 8 * out); + const rowsd = try r.a.alloc(f64, rows * out); + for (0..rows) |t| for (0..out) |j| { + rowsd[t * out + j] = got[(t * 8 + 6) * out + j]; + }; + const picked = try r.dev(f32, try toF32(r, rowsd)); + var name: [64]u8 = undefined; + try r.close(try std.fmt.bufPrint(&name, "the change's forward at {d} rows", .{rows}), picked, want, 1e-4); +} + +fn toF32(r: *Rig, xs: []const f64) ![]f32 { + const out = try r.a.alloc(f32, xs.len); + for (out, xs) |*o, x| o.* = @floatCast(x); + return out; +} + +/// The change's backward: gates, the open block's gradient, and every block's part of its site's input gradient. +fn lora(r: *Rig, rows: usize) !void { + const in = 4096; + const out = 2688; + const rank = 48; + const first = 32; + const a = try r.f32s(dims.max_rank * in, -0.02, 0.02); + const b = try r.f32s(dims.max_rank * out, -0.01, 0.01); + const xa0 = try r.f32s(rows * dims.max_rank, -1, 1); + const xn = try r.f32s(rows, 0.5, 2); + var tau: [dims.max_blocks]f32 = @splat(dims.shut); + tau[0] = -std.math.inf(f32); + tau[1] = 0; + tau[2] = -std.math.inf(f32); + const g = try r.f32s(rows * out, -1, 1); + const db0 = try r.f32s(16 * out, -1, 1); + const dx0 = try r.f32s(rows * in, -1, 1); + const xa = try r.a.alloc(f64, rows * rank); + const gates = try r.a.alloc(f64, rows * 3); + for (0..rows) |t| for (0..3) |bl| { + const open = xn[t] * dims.unit > 0 and xa0[t * dims.max_rank + bl * 16] >= tau[bl] * @sqrt(xn[t] * dims.unit); + gates[t * 3 + bl] = if (open) 1 else 0; + for (0..16) |q| xa[t * rank + bl * 16 + q] = if (open) xa0[t * dims.max_rank + bl * 16 + q] else 0; + }; + const db = try r.a.alloc(f64, 16 * out); + for (0..16) |q| for (0..out) |j| { + var sum: f64 = 0; + for (0..rows) |t| sum += xa[t * rank + first + q] * g[t * out + j]; + db[q * out + j] = db0[q * out + j] + dims.scale * sum; + }; + const dx = try r.a.alloc(f64, rows * in); + for (0..rows) |t| { + var dxa: [rank]f64 = undefined; + for (0..rank) |q| { + var sum: f64 = 0; + for (0..out) |j| sum += g[t * out + j] * b[q * out + j]; + dxa[q] = dims.scale * sum * gates[t * 3 + q / 16]; + } + for (0..in) |i| { + var sum: f64 = dx0[t * in + i]; + for (0..rank) |q| sum += dxa[q] * a[q * in + i]; + dx[t * in + i] = sum; + } + } + var word = try nemotron.sites.Shared.init(r.gpu.d, u32, 1); + defer word.free(); + const ad: nemotron.weights.Adapter = .{ .a = try r.dev(f32, a), .b = try r.dev(f32, b), .tau = try r.dev(f32, &tau), .rank = word.dev, .xa = 0, .xn = 0, .in = in, .out = out }; + const xad = try r.dev(f32, xa0); + const gated = try r.zeros(f32, rows * dims.max_blocks); + const gd = try r.dev(f32, g); + const dbd = try r.dev(f32, db0); + const dxa = try r.zeros(f32, rows * dims.max_rank); + const dxd = try r.dev(f32, dx0); + try r.t.gate(ad, xad, try r.dev(f32, xn), gated, rows, rank); + try r.t.loraDb(xad, gd, dbd, rows, out, first); + try r.t.loraDxa(gd, ad.b, gated, dxa, rows, out, rank); + try r.t.loraDx(dxa, ad.a, dxd, in, rows, in, rank); + try r.close("the open block's gradient", dbd, db, 1e-5); + try r.close("the change's input gradient", dxd, dx, 1e-5); +} + +/// Each row's loss and target probability, and its logits replaced by (p - onehot) weight. +fn loss(r: *Rig, rows: usize, vocab: usize) !void { + const logits = try r.bfs(rows * vocab, 6.0); + const targets = try r.a.alloc(u32, rows); + for (targets) |*t| t.* = r.rng.uintLessThan(u32, @intCast(vocab)); + const wts = try r.f32s(rows, 0, 1); + const stats = try r.a.alloc(f64, rows * 2); + const grad = try r.a.alloc(f64, rows * vocab); + for (0..rows) |t| { + var top: f64 = -std.math.inf(f64); + for (logits[t * vocab ..][0..vocab]) |v| top = @max(top, bf(v)); + var sum: f64 = 0; + for (logits[t * vocab ..][0..vocab]) |v| sum += @exp(bf(v) - top); + const lt = bf(logits[t * vocab + targets[t]]); + stats[2 * t] = @log(sum) + top - lt; + stats[2 * t + 1] = @exp(lt - top) / sum; + for (0..vocab) |v| grad[t * vocab + v] = (@exp(bf(logits[t * vocab + v]) - top) / sum - @as(f64, if (v == targets[t]) 1 else 0)) * wts[t]; + } + const ld = try r.dev(u16, logits); + const sd = try r.zeros(f32, rows * 2); + try r.t.softmax(ld, try r.dev(u32, targets), try r.dev(f32, wts), sd, rows, vocab); + try r.close("softmax loss and probability", sd, stats, 1e-5); + const got = try r.back(u16, ld, rows * vocab); + var diff: f64 = 0; + for (got, grad) |x, y| diff = @max(diff, @abs(bf(x) - y)); + std.debug.print("RESULT softmax gradient: largest difference {e:.3} (bf16 grain at 1: 3.9e-3)\n", .{diff}); + try check.expect(diff < 4e-3, "the logits' gradient within bf16's grain", .{}); +} + +/// The input RMS norm undone onto the residual's gradient. +fn rmsBack(r: *Rig, rows: usize) !void { + const dim = 2688; + const h = try r.bfs(rows * dim, 2.0); + const w = try r.bfs(dim, 1.0); + const dx = try r.f32s(rows * dim, -1, 1); + const g0 = try r.f32s(rows * dim, -1, 1); + const want = try r.a.alloc(f64, rows * dim); + for (0..rows) |t| { + var sq: f64 = 0; + var dot: f64 = 0; + for (0..dim) |j| { + sq += bf(h[t * dim + j]) * bf(h[t * dim + j]); + dot += bf(w[j]) * dx[t * dim + j] * bf(h[t * dim + j]); + } + const s = 1 / @sqrt(sq / dim + 1e-5); + for (0..dim) |j| want[t * dim + j] = g0[t * dim + j] + s * bf(w[j]) * dx[t * dim + j] - s * s * s * dot / dim * bf(h[t * dim + j]); + } + const g = try r.dev(f32, g0); + try r.t.rmsBack(try r.dev(u16, h), try r.dev(u16, w), try r.dev(f32, dx), g, rows, dim, 1e-5); + try r.close("rms norm back", g, want, 1e-5); +} + +fn coin(row: u32, j: u32, seed: u32) f64 { + var h = row *% 0x9E3779B9 +% j *% 0x7FEB352D +% seed; + h ^= h >> 16; + h *%= 0x7FEB352D; + h ^= h >> 15; + h *%= 0x846CA68B; + h ^= h >> 16; + return if (h & 1 == 1) 1 else -1; +} + +/// Site inputs into random sketches, and their unit rows along candidate directions. +fn sketches(r: *Rig, rows: usize) !void { + const in = 3712; + const stride = 8 * 1856; + const k = 64; + const x = try r.bfs(rows * stride, 1.0); + const y0 = try r.f32s(k * in, -1, 1); + const first = 1000; + const want = try r.a.alloc(f64, k * in); + for (0..k) |j| for (0..in) |i| { + var sum: f64 = 0; + for (0..rows) |t| sum += coin(@intCast(first + t), @intCast(j), 2) * bf(x[t * stride + i]); + want[j * in + i] = y0[j * in + i] + 1.5 * sum; + }; + const y = try r.dev(f32, y0); + const xd = try r.dev(u16, x); + try r.t.sketch(xd, stride, y, rows, in, k, first, 2, 1.5); + try r.close("sketch", y, want, 1e-5); + const f = try r.f32s(k * in, -1, 1); + const proj = try r.a.alloc(f64, rows * k); + for (0..rows) |t| for (0..k) |j| { + var sum: f64 = 0; + var n: f64 = 0; + for (0..in) |i| { + sum += f[j * in + i] * bf(x[t * stride + i]); + n += bf(x[t * stride + i]) * bf(x[t * stride + i]); + } + proj[t * k + j] = sum / @sqrt(n); + }; + const p = try r.zeros(f32, rows * k); + try r.t.project(xd, stride, try r.dev(f32, f), p, rows, in, k); + try r.close("project", p, proj, 1e-5); +} + +/// relu^2 undone from its output, the pairs' gradients in and out, and Adam. +fn small(r: *Rig) !void { + const rows = 5; + const slots = 8; + const dim = 2688; + const act = try r.a.alloc(u16, rows * slots * 64); + for (act) |*v| v.* = gm.f32ToBf16(@max(0, r.rng.float(f32) * 2 - 0.5)); + const da = try r.f32s(act.len, -1, 1); + const du = try r.a.alloc(f64, act.len); + for (du, act, da) |*o, v, d| o.* = d * 2 * @sqrt(bf(v)); + const dud = try r.zeros(f32, act.len); + try r.t.relu2Back(try r.dev(u16, act), try r.dev(f32, da), dud, act.len); + try r.close("relu^2 back", dud, du, 1e-6); + const wt = try r.f32s(rows * slots, 0, 1); + const g = try r.f32s(rows * dim, -1, 1); + const dy = try r.a.alloc(f64, rows * slots * dim); + for (0..rows * slots) |p| for (0..dim) |j| { + dy[p * dim + j] = wt[p] * g[p / slots * dim + j]; + }; + const dyd = try r.zeros(f32, dy.len); + try r.t.pairsIn(try r.dev(f32, wt), try r.dev(f32, g), dyd, rows * slots, slots, dim); + try r.close("pairs in", dyd, dy, 1e-6); + const dxp = try r.f32s(rows * slots * dim, -1, 1); + const dx0 = try r.f32s(rows * dim, -1, 1); + const dx = try r.a.alloc(f64, rows * dim); + for (0..rows) |t| for (0..dim) |j| { + var sum: f64 = dx0[t * dim + j]; + for (0..slots) |q| sum += dxp[(t * slots + q) * dim + j]; + dx[t * dim + j] = sum; + }; + const dxd = try r.dev(f32, dx0); + try r.t.pairsOut(try r.dev(f32, dxp), dxd, rows, slots, dim); + try r.close("pairs out", dxd, dx, 1e-6); + const n = 1000; + const p0 = try r.f32s(n, -1, 1); + const g0 = try r.f32s(n, -1, 1); + const m0 = try r.f32s(n, -0.1, 0.1); + const v0 = try r.f32s(n, 0, 0.1); + const h = dims.hyper; + const corr = [2]f32{ 2, 3 }; + const want = try r.a.alloc(f64, n); + for (want, p0, g0, m0, v0) |*o, p, gg, m, v| { + const mi = h[1] * m + (1 - h[1]) * gg; + const vi = h[2] * v + (1 - h[2]) * gg * gg; + o.* = p - h[0] * (mi * corr[0]) / (@sqrt(vi * corr[1]) + h[3]); + } + const pd = try r.dev(f32, p0); + try r.t.adam(pd, try r.dev(f32, g0), try r.dev(f32, m0), try r.dev(f32, v0), n, h, corr); + try r.close("adam", pd, want, 1e-5); +}