Repository navigation
Living Weights learns on CUDA (GB10): the training step, its kernels checked against float64 - #591
Conversation
The Metal learner's policy moves from slide.zig into learner.zig, generic over the training file it drives: its Backend, Mode, max_rows and Trainer, which now attaches the change to the forward and saves it itself. slide.zig instantiates it for Metal, nemotron_slide's Adapter takes the learner's file the same way, and the sizes the learner, its choice and its sites share live in slide_dims.zig. Lessons, rounds, checks, the plain change, undo and save are the same code; each round now logs its steps, its loss and whether the held-out answers came back.
…against float64, --slide served --slide on the native CUDA server runs learner.zig over cuda_train.zig: a step runs the prompt-chunk forward on the trainer's own sequence, keeping each layer's parts, then the head, the final norm and every layer backward to its change (MoE with routes frozen and the packed experts' 4-bit tables, Mamba, attention), and Adam on the open block. train.cu and train_mixers.cu hold the change's forward (tiled for prompt chunks, a window kernel for decode rows) and every training kernel; tf-cuda-test train and train-mixers check each against float64, and slide-grad checks the whole model's gradient against measured loss slopes. The change's sites live in mapped memory and the forward reads a rank word, so graphs captured at load stay valid as lessons open and close; with nothing attached, the forward's hooks launch nothing, and the training modules load only with --slide, after the weights. Save folds the change into bf16 shards as Metal's does, so a folder taught on either backend serves on the other. --slide refuses a folder of links, GPUs other than the GB10 and staggered prompt segments. slide-bench and slide-decode time a step and the change's decode cost.
|
Thanks, @ZackSample. The plan is on #590: we'll bring this up to date with main ourselves, rerun your six facts on a GB10, and run the Metal gate and a whole-model gradient check before it lands. |
|
Thank you, @ZackSample. This is merged into main (47158cd) with your two commits as they were, and it ships in the next release, 1.0.6. What we checked on a GB10 and an M3 Ultra:
The six facts from #590 found one bug, fixed in 25d3d27 with a host test that fails on the old code. Every learn request ends with a save, and the CUDA save re-read each projection from the shards while folding in every lesson since the server started, so each later request wrote the earlier lessons in again. After a restart the model answered "Your sister's name is lasagna." Each save now folds onto the projections as first loaded, as Metal's save does. With the fix, 1 or 2 of the 6 facts were kept and recalled per run (lasagna both times), against 0 of 6 in #590. Two smaller commits went in with it. 5557e44 puts the measured decode cost in the guide: about 1% with no lessons, 6% with one kept lesson and 11% with four. 36141c5 keeps the trainer's 1.78 GiB out of the CUDA memory budget at load; with a capped budget and a full prompt cache, the first lesson went 0.53 GiB over the cap. Two follow-ups, if you'd like them:
Thanks again. Living Weights on a GB10 is a big piece of work. |
|
Kernels on sm_120: two gates fail here — and we may well be holding it wrong We want Passing:
Failing, 3 of 3 runs each:
What a local bisect suggests (our harness, not your test):
Where we could be wrong, plainly: this is a laptop card on a different driver than your receipts, with other processes on it, and we never ran your gates on a GB10 to compare against. It could be our harness ordering, an sm_120 codegen difference, or something the So the useful question for us is whether |
…s.pack, where ashhart#602 moved the repack
|
Thanks for landing it, and for the careful gate. The double fold was a real bug of ours; good catch on the lasagna. Yes to follow-up 1. I'll make On the bleed question from #590: is there anything you've tried, or a direction you're heading, for keeping a plain change specific? We have a lead we're testing and would rather line it up with where you're going than work in parallel. |
|
@zweck thanks for the careful report. On our GB10 (sm_121, driver 580.178.04, CUDA 13.0, nvcc 13.0.88, Zig 0.17.0), current main (9041e20) is reproducibly green:
Those are the numbers your passing runs printed, so your build and harness reproduce ours when it works. That points at sm_120 or its driver rather than your setup. What I checked in
The only thing split-K adds over your always-clean I'm taking ashhart's follow-up 1, which makes that reduction deterministic: each slice writes its own partial with plain stores, and one pass adds them into |
|
Update from the same card: main is green here, the PR-built binary is not — so our first report was build-specific, not arch-specific ZackSample's 50-of-50 result on a GB10 sent us back to re-run, and the picture changed. Same machine, same session, same command (
What we can do: the moment the deterministic per-slice reduction is up, we will rerun both builds here. If the failures go with Here is the harness, as asked. It drops into //! sm_120 diagnosis for tf_train_gemm: which part of the split-K path the 0.6 relative error is in.
//! Not part of the PR: a local bisect (c0 zero or not, one split at a time, per-slice coverage).
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 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);
}
// The failing shape from the PR's own test, then the same with a zero C, then split by split.
_ = try one(&r, 130, 2688, 2688, 3, false);
_ = try one(&r, 130, 2688, 2688, 3, true);
for ([_]usize{ 1, 2, 3, 4, 6 }) |split| _ = try one(&r, 130, 2688, 2688, split, false);
_ = try one(&r, 130, 2688, 2688, 3, false);
// Flakiness: the same configuration eight times, then whole tiles (m a multiple of 64) eight times.
var bad_odd: usize = 0;
var bad_even: usize = 0;
for (0..8) |i| {
if (!try one(&r, 130, 2688, 2688, 3, false)) bad_odd += 1;
if (!try one(&r, 128, 2688, 2688, 3, false)) bad_even += 1;
if (i == 3) _ = try one(&r, 5, 64, 8192, 4, false); // the PR's third case, never reached
}
std.debug.print("DIAG repeats: m=130 split=3 wrong {d}/8, m=128 split=3 wrong {d}/8\n", .{ bad_odd, bad_even });
// The failing case, and the same slices run one at a time (no two blocks adding to one element).
for (0..4) |_| _ = try one(&r, 5, 64, 8192, 4, false);
for (0..4) |_| try sequentialSlices(&r, 5, 64, 8192, 4);
}
/// The PR's third case run as `split` separate single-slice calls: the slice compute alone, no concurrent adds.
/// Always clean means the K-slice math is fine and the concurrent accumulation into C is what breaks.
fn sequentialSlices(r: *Rig, m: usize, n: usize, kk: usize, split: usize) !void {
const per = (kk / 32 + split - 1) / split * 32;
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);
// Each slice packed into contiguous rows and added by its own call: same K arithmetic, no two blocks on one element.
for (0..split) |sl| {
const lo = sl * per;
const kk_i = @min(per, kk - lo);
const ai = try r.a.alloc(u16, m * kk_i);
const bi = try r.a.alloc(u16, n * kk_i);
for (0..m) |i| @memcpy(ai[i * kk_i ..][0..kk_i], a[i * kk + lo ..][0..kk_i]);
for (0..n) |j| @memcpy(bi[j * kk_i ..][0..kk_i], b[j * kk + lo ..][0..kk_i]);
try r.t.gemm(try r.dev(u16, ai), kk_i, try r.dev(u16, bi), kk_i, c, n, m, n, kk_i, 1);
}
try r.s.synchronize();
const got = try r.a.alloc(f32, m * n);
try r.gpu.d.check(r.gpu.d.api.cuMemcpyDtoH_v2(got.ptr, c, m * n * 4), "cuMemcpyDtoH");
var worst: f64 = 0;
var off: usize = 0;
for (got, want) |g, w| {
const d = @abs(@as(f64, g) - w);
if (d > 1e-3 * @max(@abs(w), 1.0)) off += 1;
worst = @max(worst, d / @max(@abs(w), 1.0));
}
std.debug.print("DIAG sequential slices m={d} n={d} k={d} split={d} (k per call {d}): worst rel {e:.3}, {d} of {d} off\n", .{ m, n, kk, split, per, worst, off, got.len });
}
/// One GEMM at m x n x k with `split` slices, `zero` for an all-zero C: the largest relative error, and its position.
fn one(r: *Rig, m: usize, n: usize, kk: usize, split: usize, zero: bool) !bool {
const a = try r.bfs(m * kk, 1.0);
const b = try r.bfs(n * kk, 1.0);
const c0 = if (zero) try r.a.alloc(f32, m * n) else try r.f32s(m * n, -1, 1);
if (zero) @memset(c0, 0);
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);
try r.s.synchronize();
const got = try r.a.alloc(f32, m * n);
try r.gpu.d.check(r.gpu.d.api.cuMemcpyDtoH_v2(got.ptr, c, m * n * 4), "cuMemcpyDtoH");
var worst: f64 = 0;
var at: usize = 0;
var exact: usize = 0;
var off: usize = 0;
for (got, want, 0..) |g, w, i| {
const d = @abs(@as(f64, g) - w);
if (d == 0) exact += 1;
if (d > 1e-3 * @max(@abs(w), 1.0)) off += 1;
if (d / @max(@abs(w), 1.0) > worst) {
worst = d / @max(@abs(w), 1.0);
at = i;
}
}
std.debug.print("DIAG m={d} n={d} k={d} split={d} zeroC={} : worst rel {e:.3} at {d} (got {d:.4}, want {d:.4}), {d} of {d} off, {d} exact\n", .{ m, n, kk, split, zero, worst, at, got[at], want[at], off, got.len, exact });
return off == 0;
} |
… came back, else takes it out whole Thanks @ThinkOffApp. Fixes ashhart#589. ashhart#591 moved the learner from slide.zig into learner.zig, so the merge makes the PR's undo change there.
…der, so a lesson repeats run to run tf_train_gemm cut K into slices that each added their part into C with atomicAdd, so the adds landed in a different order on every run and every gradient differed in its last bits; ashhart#591's six facts kept Lisbon in one run and took it out in the next. One slice now adds into C as the only writer of its elements. More slices each write their part to the backward's new parts buffer (f32 [split, m, n]: split() keeps slices times 64 x 64 tiles within its 192 blocks, so 3 MiB, counted in Trainer.memory through Bufs.total), and tf_train_gemm_sum adds them into C in slice order. tf-cuda-test train runs each product twice and requires the same bits. On a GB10, each fact taught twice through /v1/slide/learn on a fresh copy of the folder: - "My sister is called Ana." (taken out both times): main's losses differ between the runs (0.529 and 0.526 after the first round); this branch's logs are the same line for line. - "My favorite food is lasagna." (kept both times): main saved different bytes into all four shards; this branch saved the same bytes. The kernels' accuracy (8.42e-7 and 2.40e-6 for the split cases), train-mixers, slide-grad (1.0267 at layer 51) and the step times (223 ms at 26 rows, 490 ms at 87) are unchanged.
The pocket's learner replaces the earlier change-and-fold learner on both backends: its CUDA trainer, sites and kernels stand in for ashhart#591's (cuda_learned.zig, slide_dims.zig, train_mixers.cu and their tf-cuda-test commands go), and slide_test.zig's take-out checks for the earlier rounds go with them. Main's prompt reuse, carveout, heat bands, ModelOpt checkpoints, logprobs and grouped experts stay as they are; the CUDA trainer's memory bound feeds main's --slide budget.
…ct, and the CHANGELOG The guide explains the pocket (64 neurons beside each shared expert, keyed on the reply or the subject), the /slide 3D view, the GB10's trainer memory, what was measured (personal facts on three machines, short and long documents, time a fact, serving cost) and the startup refusal of folders taught by 1.0.3 to 1.0.5. The README mentions documents and the 3D view. The CHANGELOG's Unreleased entries replace ashhart#591, ashhart#599 and ashhart#632's with the pocket learner, the speed work and the view, crediting them.
… step and its kernels checked against float64 Thanks @ZackSample. Closes ashhart#590.
…s.pack, where ashhart#602 moved the repack
… came back, else takes it out whole Thanks @ThinkOffApp. Fixes ashhart#589. ashhart#591 moved the learner from slide.zig into learner.zig, so the merge makes the PR's undo change there.
…der, so a lesson repeats run to run tf_train_gemm cut K into slices that each added their part into C with atomicAdd, so the adds landed in a different order on every run and every gradient differed in its last bits; ashhart#591's six facts kept Lisbon in one run and took it out in the next. One slice now adds into C as the only writer of its elements. More slices each write their part to the backward's new parts buffer (f32 [split, m, n]: split() keeps slices times 64 x 64 tiles within its 192 blocks, so 3 MiB, counted in Trainer.memory through Bufs.total), and tf_train_gemm_sum adds them into C in slice order. tf-cuda-test train runs each product twice and requires the same bits. On a GB10, each fact taught twice through /v1/slide/learn on a fresh copy of the folder: - "My sister is called Ana." (taken out both times): main's losses differ between the runs (0.529 and 0.526 after the first round); this branch's logs are the same line for line. - "My favorite food is lasagna." (kept both times): main saved different bytes into all four shards; this branch saved the same bytes. The kernels' accuracy (8.42e-7 and 2.40e-6 for the split cases), train-mixers, slide-grad (1.0267 at layer 51) and the step times (223 ms at 26 rows, 490 ms at 87) are unchanged.
The pocket's learner replaces the earlier change-and-fold learner on both backends: its CUDA trainer, sites and kernels stand in for ashhart#591's (cuda_learned.zig, slide_dims.zig, train_mixers.cu and their tf-cuda-test commands go), and slide_test.zig's take-out checks for the earlier rounds go with them. Main's prompt reuse, carveout, heat bands, ModelOpt checkpoints, logprobs and grouped experts stay as they are; the CUDA trainer's memory bound feeds main's --slide budget.
…ct, and the CHANGELOG The guide explains the pocket (64 neurons beside each shared expert, keyed on the reply or the subject), the /slide 3D view, the GB10's trainer memory, what was measured (personal facts on three machines, short and long documents, time a fact, serving cost) and the startup refusal of folders taught by 1.0.3 to 1.0.5. The README mentions documents and the 3D view. The CHANGELOG's Unreleased entries replace ashhart#591, ashhart#599 and ashhart#632's with the pocket learner, the speed work and the view, crediting them.
What this changes
tensorfold serve --slidelearns on a GB10 (DGX Spark). The native CUDA server runs the same Living Weights learneras Metal, with our own CUDA training kernels. Lessons, rounds, the held-out, near and keep checks, the plain change,
mining, undo and save are the Metal code itself, so a folder taught on either backend serves on the other. Draft until
we agree on the gate in #590.
Two commits:
slide.zigintolearner.zig, generic over a backend'straining file (
learner.Of(train): itsBackend,Mode,max_rowsandTrainer, which now attaches and savesthe change).
slide.ziginstantiates it for Metal, andnemotron_slide.Adapteris generic the same way. Theshared sizes are in
slide_dims.zig.git diff -w main:zig/src/families/nemotron/slide.zig HEAD:zig/src/families/nemotron/learner.zigis 56 lines, covering:attachandsavethrough the trainer;cuda_train.zig,cuda_train_back.zig,cuda_train_ops.zig: a step runs the prompt-chunk forward on thetrainer's own 512-key sequence, keeping each layer's parts. It then runs backward through the head, the final
norm and every layer to its change: MoE with routes frozen as on Metal (the packed experts' backward reads their
4-bit tables), Mamba (scan, conv, dt, gated norm) and attention. Adam runs on the open block. Sketch and project
modes feed the block's choice.
train.cu,train_mixers.cuhold the CUDA kernels:cuda_sites.zig: each layer's a, b, gate and Adam state in mapped memory. The forward reads a rank word, sographs captured at load stay valid as lessons open and close.
cuda_forward.zigapplies the change after every output projection on every path: windows, prompt chunks, andthe shared expert's halves. With nothing attached its hooks launch nothing. The training modules load only with
--slide, after the weights and buffers, so nothing else moves.cuda_learned.zig: save folds the change into each touched output projection as bf16 throughshard_edit.bake, as Metal'slearned.zigdoes.native/cuda.zigwires--slide; the learn hook runs with the CUDA context current. It refuses:cp -RL);cache stays correct under learning.
Receipt
Environment
One DGX Spark: GB10, sm_121, driver 580.178.04, CUDA 13.0, the only model process on the machine for speed runs.
Checkpoint
TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit@d9d758fb. This branch on4ebf52a, builtwith
zig build native -Dnvcc=…(Zig 0.17.0) and the built-in kernels.Correctness against float64
tf-cuda-test train, synthetic rows): every kernel within 2.4e-6 relative of its float64reference. The tiled 4-bit dequantization equals MLX's in all 25,600 values; the packed experts' backward is within
2.0e-7.
tf-cuda-test train-mixers): Mamba and attention within 1.8e-3 of float64 central differences.tf-cuda-test slide-grad MODEL IDS 24 0.16 8): layer 51's analytic gradient against a cubic fit ofthe measured loss gives slope 1.0015 (sd 0.0061 over 8 starts). Deeper layers can't be checked this way: one step
there changes thousands of downstream expert choices (counted), each a step in the loss, since routes are frozen by
design.
Exactness and speed without
--slide, againstmainServed with
bench_openai.pyandbench_concurrent.py --levels 1,4 --alone --serial: 256 tokens, greedy, drafts on,--parallel 4 --context 4096 --prompt-cache-gib 0.--slide, no lessonstoken_sha)Both builds read the same window-cost table for these runs. Each build times its windows once, at its first start,
and keeps that table. On this machine, tables timed at different moments differed by 2 to 5% as it warmed. That alone
moved 4-stream code between 311 and 437 tok/s on unchanged kernels, by changing the draft depth.
The change's cost while serving
Decode (
tf-cuda-test slide-decode, the one-row graph): 10.06 ms a token without--slide.At 512 ranks the change's window kernels take 83 µs with a and b in mapped memory, against 44 µs in device memory
(
slide-kernels). Device-resident a and b is a follow-up.A step (
tf-cuda-test slide-bench):A fact through the server took 110 to 263 s, most of it the model writing its lesson.
Learning
Through
/v1/slide/learn, six facts told one at a time: none came back on its held-out questions.The model writes some lessons differently on a GB10 than on a Mac, where its greedy picks nearly tie. These failures
are in the written lessons and the checks, not the step; details are in #590.
With a hand-written lesson for "My favorite color is blue." through the same rounds, checks, plain change, mining
and save, using a debug hook that is not in this branch:
--slide: "39 output projections carry what lessons taught this model". 8 of 8 recall questionsanswered blue, including British spellings and two phrasings it never saw. 19 of 20 eval replies and 14 of 16 probe
replies were identical to the live change's.
now get invented facts where the original declines: "Do you remember where I live?" became "Yes, you live in New
York."
Metal
I have no Mac. The Metal learner's diff is commit 1. A macOS cross build of the server stopped only at linking Apple's
frameworks, and its object holds
nemotron_slide.Adapter(families.nemotron.slide)and the learner. It needs yourMetal gate.
Host checks
zig build testpasses. The lean checker reports 510 problems, the same asmain.🤖 Generated with Claude Code