Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f9fc1a7
glm: group-limited top-k routing (Ling's 8 groups, keep 4) and a per-…
jschmied Oct 15, 2026
a655957
ling: Ling-3.1-flash's config loader and weight map, its routing and …
jschmied Oct 15, 2026
d46e372
ling: weights in the checkpoint's own format (bf16, FP8 blocks, Model…
jschmied Oct 15, 2026
faf7af1
docs: Ling-3.1-flash recipe: what exists, what is missing, testing wi…
jschmied Oct 15, 2026
7d184cb
glm: MLA kernels take Ling-3.1's shape: 64 roped key columns, 128-wid…
jschmied Oct 15, 2026
ef8f12f
glm: KDA serves Ling-3.1 as is (real layer 0 vs fla and float64); an …
jschmied Oct 15, 2026
6f583ba
ling: the TP=1 layer graph in any loaded format: KDA and MLA mixers, …
jschmied Oct 15, 2026
bfb44dd
ling: SwiGLU clamp in Ling's order, min(silu(g), L) * clip(u, -L, L)
jschmied Oct 15, 2026
2a5e1b6
tests: zig fmt ling_mla_real.zig
jschmied Oct 15, 2026
a3f14d3
ling: served through the lane core at TP=1: engine, lane backend, ser…
jschmied Oct 15, 2026
577436b
ling: the MTP layer (model.layers.72) drafts: enorm | hnorm through e…
jschmied Oct 15, 2026
7bd7a40
tests: ling-pack times one MoE layer's expert load (read, pack, cold)…
jschmied Oct 15, 2026
bbe360f
ling: routed experts staged in batches through pinned memory and pack…
jschmied Oct 15, 2026
412f66f
tests: ling-layer-speed times one real layer whole and op by op per p…
jschmied Oct 15, 2026
99652ba
ling: row copies 16 bytes a thread on aligned rows (prompt KDA and ML…
jschmied Oct 15, 2026
b3faea6
ling: a single decode row's projections write their columns in place,…
jschmied Oct 15, 2026
5b00637
ling: FP8 prompt chunks under 16 routed pairs an expert run the decod…
jschmied Oct 15, 2026
e78d23b
glm: group-limited select without divisions where groups are whole la…
jschmied Oct 15, 2026
0ffce4f
tests: ling-layer-speed takes a rows list, times prompt ops from an i…
jschmied Oct 15, 2026
bd7c23e
tests: ling-layer-speed starts each rep after a random spin (tf_probe…
jschmied Oct 15, 2026
32055e9
glm: swiglu keeps GLM's limit as given; only Ling's swigluWith maps 0…
jschmied Oct 15, 2026
991383f
glm: swigluWith's doc comment within 120 columns
jschmied Oct 15, 2026
03171bf
glm: drop the opt-in 16-row chunked KDA prompt path; GLM's cuda_kda.z…
jschmied Oct 15, 2026
66579cb
ling: config refuses every geometry the kernels don't take, at load, …
jschmied Oct 16, 2026
92afed6
ling: routing groups of one and a single pick refused at load; one gr…
jschmied Oct 16, 2026
674163f
ling: Store.alloc owns a buffer only once it is in both lists; a fake…
jschmied Oct 16, 2026
0ba510a
ling: a new stream's slot is chosen before its map entry exists (lane…
jschmied Oct 16, 2026
82b3817
ling: rows past a sequence's capacity are refused before any layer ru…
jschmied Oct 16, 2026
0ba2adf
ling: Engine.init frees its sequences when binding slot 0 or the last…
jschmied Oct 16, 2026
5649c63
ling: every tensor of the full checkpoint checked against the loader'…
jschmied Oct 16, 2026
e4c9bcc
oracle: the Ling oracles check their HF source against inclusionAI/Li…
jschmied Oct 16, 2026
5e931c3
ling: a segment the scratch cannot hold is refused before any layer r…
jschmied Oct 16, 2026
1395e26
ling: staging and loaded weights freed only after the stream drains; …
jschmied Oct 16, 2026
e99e650
docs/recipes/ling-3.1: file names for hashes the rebase changed, curr…
jschmied Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
ling: the TP=1 layer graph in any loaded format: KDA and MLA mixers, …
…dense and MoE MLPs, head, windows and commits

Every projection runs as the qlinear.Weight and every routed-expert layer as the experts.Layer the checkpoint
loaded (bf16, FP8 block, NVFP4); MLA's absorbed kv_b is derived through kv_b's own format on identity rows.
ling_glue.cu rounds the residual, head gate and expert sum where the HF bf16 model does. Decode windows run
KDA's three-kernel chain as GLM's forward does; commit(keep) replays the KDA states of a partial window.

ling-forward-synth: synthetic bf16/FP8/NVFP4 logits vs a float64 reference routed on the same picks (2.1-2.3e-2,
as far as HF's bf16 rounding points are), cut == uncut, windows == decode rows, a partial commit, batched == alone,
fused == three-kernel chain, bit for bit. ling-layer-real: real FP8 layers 0, 4, 7, 71 vs HF 3.0-3.7e-3 without
routing flips. GLM files untouched.
  • Loading branch information
jschmied committed Oct 16, 2026
commit 6f583baf91ab3bf06ae20045ef32fa95f604d382
107 changes: 84 additions & 23 deletions docs/recipes/ling-3.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,67 @@ block FP8 (e4m3 in 128 x 128 blocks with `weight_scale_inv`).
| Part | Where | Checked by |
| --- | --- | --- |
| Group-limited top-k routing, per-layer shared SwiGLU limit (GLM's bytes unchanged) | `ling-family`, commit 51c01573 | `glm-ref`, `glm-route-old`, `glm-route-ling` |
| MLA at Ling's shape: 64 roped key columns, 128-wide heads, GPT-J rope, head-wise gate | branch `ling-mla`, f8e594f6 | `ling-mla`, `ling-mla-real`, `glm-mla-same` |
| KDA on Ling's layer 0 (q/k/v convs as one q\|k\|v conv), opt-in chunked prompt path | branch `ling-kda`, b55aa13d | `glm-kda-ling`, `glm-kda-chunk` |
| MLA at Ling's shape: 64 roped key columns, 128-wide heads, GPT-J rope, head-wise gate | f8e594f6, merged | `ling-mla`, `ling-mla-real`, `glm-mla-same` |
| KDA on Ling's layer 0 (q/k/v convs as one q\|k\|v conv), opt-in chunked prompt path | b55aa13d, merged | `glm-kda-ling`, `glm-kda-chunk` |
| Config loader and weight map (all 214,025 names of the real index) | `zig/src/families/ling/config.zig`, `names.zig` | `zig build test-ling` |
| Weight loader at TP=1: bf16, FP8 block, ModelOpt NVFP4 | `zig/src/families/ling/weights.zig`, `weights_proj.zig` | `ling-weights`, `ling-weights-real` |
| Synthetic checkpoints in all three formats | `tf-cuda-test ling-synth` | its own name check |

The MLA and KDA commits live on their own branches and are not merged into `ling-family`.
| The TP=1 layer graph: embedding, KDA/MLA mixers, dense MLP and MoE, final norm, head; windows and commits | `zig/src/families/ling/forward.zig`, `graph.zig`, `state.zig`, `block_*.zig`, `kernels/cuda/ling_glue.cu` | `ling-forward-synth`, `ling-layer-real` |

## The layer graph

`forward.Forward` runs rows of one or more sequences (`Seg`: a `State`, its first row, its row count) through the
embedding, every loaded layer and the head; `stack()` runs the layers alone on `Buffers.x`, `layer()` one of them.
`Buffers` are prompt rows or decode rows; each sequence's rows stay pending until `commit(state, keep)`. A prompt
keeps every row; a decode window (at most `window_rows`, 16) keeps any prefix: the KDA states are replayed from the
window's saves (`replay_layers`) and the conv windows shifted, as #804's GLM commit does. The API follows GLM's
`cuda_forward.zig` (`Rank`/`Seg`, `Buffers`/`State`, `commit`) so lanes hooks can follow.

Every projection is a `qlinear.Weight` and every routed-expert layer an `experts.Layer` in the format the checkpoint
stored; the graph only calls `qlinear.Linear.decode`/`prompt` and `experts.Grouped.decode`/`prompt`. MLA's absorbed
`kv_b` (bf16 `wk`/`wv` per head) is derived at load by running `kv_b` in its own format on identity rows, so any format
`qlinear` serves works. bf16 routed experts (no grouped bf16 kernel) run every expert on every row and the combine
reads each row's picks: correct, for tests, not for speed.

Per layer, in the HF model's order: input RMSNorm; KDA (q, k, v, beta into one `[q|k|v|b]` row, f and g rows, GLM's
chain with the safe gate, gated output norm, `o_proj`) or MLA (`q_a`, `q_a_layernorm`, `q_b`; `kv_a_proj_with_mqa`,
`kv_a_layernorm` on the 512 latent, the 64 key columns roped into the cache row; absorbed queries, roped attention
over the 576-wide cache, `expand_v`, sigmoid head gate from `g_proj`, `dense`); residual; post-attention RMSNorm;
dense SwiGLU (layers 0-3) or MoE (bf16 router dot in fp32, sigmoid + `expert_bias` with 8 groups keeping 4,
normalized weights x 2.5, grouped experts with the layer's limit, shared expert with its own limit); residual. The
residual stream, every linear's output and the MoE sums are bf16 at the points where the HF bf16 model rounds them
(`ling_glue.cu`: residual add, head gate, expert sum + shared). Decode windows run KDA's three-kernel chain, as
GLM's forward does by default (bit-equal to the fused chain, checked).

Measured on synthetic checkpoints (4 layers: KDA dense, MLA MoE, KDA MoE, MLA MoE; 80 prompt rows, 8 decode rows),
logits against `oracle/ling_forward.py` routed on the graph's own picks (with free routing, 15-21 of 264 picks
differ from float64's: group near-ties, the worst group sums 0.0014-0.008 apart):

| Format | vs float64 | vs the bf16 rounding points | bf16 points vs float64 | argmax vs float64 |
| --- | --- | --- | --- | --- |
| bf16 | 2.17e-2 | 1.31e-2 | 2.18e-2 | 86/88 |
| FP8 block | 2.12e-2 | 1.22e-2 | 2.12e-2 | 85/88 |
| NVFP4 | 2.29e-2 | 1.40e-2 | 2.25e-2 | 85/88 |

(relative L2 of the logits). The graph is as far from float64 as the HF model's own bf16 rounding is. Bit for bit, in
every format: a prompt cut at 48 equals the uncut prompt; an 8-row verify window equals 8 decode rows; keeping 3 of 8
and running the next 5 leaves every KDA state, conv window and MLA cache row equal to 8 decode rows; two sequences in
one prompt chunk and in one decode window equal each alone; the fused and three-kernel KDA chains agree.

Real layers of the FP8 release (`ling-layer-real`, the HF bf16 chain's captured input and output, 512 tokens):

| Layer | Kind | rel L2 vs HF | rows with a different top-8 | rel L2 without them | decode rows vs HF | device peak |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | KDA, dense | 3.27e-3 | - | 3.27e-3 | 3.12e-3 | 0.9 GB |
| 4 | KDA, MoE | 5.88e-3 | 21 | 3.13e-3 | 4.28e-3 | 8.5 GB |
| 7 | MLA, MoE | 4.89e-3 | 17 | 3.05e-3 | 3.57e-3 | 8.3 GB |
| 71 | MLA, MoE, limits 10 | 4.13e-3 | 7 | 3.75e-3 | 3.89e-3 | 8.3 GB |

exllamav3's port measured 0.4-1.1e-3 without flips (4 flips each on layers 4 and 7) on the same chain: it keeps fp16
activations, the captured HF chain carries an fp32 residual from layer 3's output on, and this graph rounds the stream
to bf16 as the bf16 model does. On every
real layer a prompt cut at 300 equals the uncut prompt and a 16-row window equals 16 decode rows; for FP8 decode rows
equal the prompt's rows (both run the lane). Loading one MoE layer's 512 experts from the sshfs mount takes ~150 s.

### Formats

Expand All @@ -42,11 +96,15 @@ per projection. The router must be bf16 (GLM's router kernel reads bf16); a quan

## What is missing

- The layer graph: `weights.Layer` holds one `qlinear.Weight` per projection, while #804's GLM blocks read raw bf16
pointers (KDA's fused `[q | k | v | f_a | g_a | b]`, MLA's latent projections). Ling's blocks have to call
`qlinear.Linear` per projection, or fuse same-format rows.
- Lanes hooks (drafted, concurrent and cut-prompt windows) for Ling.
- MTP drafting: the MTP layer's tensors load (`weights.Mtp`), nothing drafts with them.
- Lanes hooks (drafted, concurrent and cut-prompt windows) for Ling: the graph has the pieces (segments, windows,
`commit(keep)`), nothing schedules them yet. Sampling, the server and a full-checkpoint run are not wired.
- MTP drafting: the MTP layer's tensors load (`weights.Mtp`); the graph leaves it unwired. It would be
`enorm(embed(next)) | hnorm(hidden)` through `eh_proj`, one MLA + MoE layer on its own cache, the final norm and
the shared head.
- The SwiGLU limit clamps the gate before SiLU (`silu(min(g, 10))`, the grouped expert kernels' and GLM's rule);
the Ling reference clamps after (`min(silu(g), 10)`). They differ by at most 4.5e-4 on a clamped element.
- Speed: nothing is tuned. Projections land in their columns through a byte copy, bf16 routed experts run densely,
and the RMS norms take hidden and `q_lora_rank` widths 512, 1536 and 4096 only (`glue.rmsnorm`).
- EXL3, through ashhart's EXL3 module (tracker #832).
- Tensor parallelism: the loader is TP=1; shares and transport would come from #804's `cuda_shard.zig` and #855.

Expand All @@ -58,18 +116,23 @@ TF_LING_INDEX=/path/to/model.safetensors.index.json zig build test-ling # adds
zig build -Doptimize=ReleaseFast -Dnvcc=/usr/local/cuda/bin/nvcc
zig-out/bin/tf-cuda-test ling-synth /tmp/ling-fp8 --format fp8 # bf16 | fp8 | nvfp4, --layers N (default 4)
zig-out/bin/tf-cuda-test ling-weights /tmp/ling-fp8
python zig/tests/cuda/oracle/ling_forward.py /tmp/ling-fp8 /tmp/ref # float64 reference, free routing
zig-out/bin/tf-cuda-test ling-forward-synth /tmp/ling-fp8 /tmp/ref /tmp/picks # exactness; writes the picks
python zig/tests/cuda/oracle/ling_forward.py /tmp/ling-fp8 /tmp/fref --picks /tmp/picks
zig-out/bin/tf-cuda-test ling-forward-synth /tmp/ling-fp8 /tmp/fref # same picks: logits bounded
```

`ling-synth` writes `config.json` (the real file's schema) and `model.safetensors` with the real key names: hidden 512,
4 heads, 16 experts in 4 groups keeping 2, `q_lora_rank` 256, vocabulary 1,024, layer groups of 2 (KDA, MLA, KDA,
MLA), layer 0 dense, the last layer clamped, plus the MTP layer. KDA's head dim 128 and MLA's 512 latent, 64 rope and
128-wide heads stay as the kernels take them. The FP8 file carries the real exception list's pattern; the NVFP4 file
uses globs and leaves layer 0's dense MLP in bf16, so one checkpoint mixes formats. It checks its names against the
weight map before it passes. Sizes: bf16 282 tensors, 43 MiB; FP8 517, 23 MiB; NVFP4 978, 15 MiB.
4 heads, 16 experts in 4 groups keeping 2, `q_lora_rank` 512 (a width the norm kernel takes), vocabulary 1,024, layer
groups of 2 (KDA, MLA, KDA, MLA), layer 0 dense, the last layer clamped, plus the MTP layer. KDA's head dim 128 and
MLA's 512 latent, 64 rope and 128-wide heads stay as the kernels take them. The FP8 file carries the real exception
list's pattern; the NVFP4 file uses globs and leaves layer 0's dense MLP in bf16, so one checkpoint mixes formats. It
checks its names against the weight map before it passes. FP8 codes stay within 2^-3 to 3.75 so a forward stays in
range. Sizes: bf16 282 tensors, 45 MiB; FP8 517, 24 MiB; NVFP4 978, 16 MiB.

`ling-weights` loads every layer and checks every projection (decode and prompt rows, 3 rows) against float64 from
the file, the grouped experts' gate-up (SwiGLU) and down, and each small tensor (norms, convs as fp32 q|k|v, `A_log`,
`dt_bias`, router, bias) byte for byte. Measured: bf16 85 projections, FP8 and NVFP4 61 each, worst 0.456 of the bound
`dt_bias`, router, bias) byte for byte. Measured: bf16 85 projections, FP8 and NVFP4 61 each, worst 0.433 of the bound
(2^-7 of |y| plus 2^-12 of the sum of |x w|); 37 small tensors equal.

With the real checkpoint:
Expand All @@ -79,7 +142,8 @@ python zig/tests/cuda/oracle/ling_weights.py /path/to/Ling-3.1-flash /tmp/ling-r
zig-out/bin/tf-cuda-test ling-weights-real /path/to/Ling-3.1-flash /tmp/ling-ref
```

It loads layers 0, 4 and 7 with experts 0-3 (769 MiB on the device) and compares 35 products with torch's float64
`ling-layer-real DIR FIXTURE` runs one whole layer (fixture from `oracle/ling_layer.py CHAIN L OUT`, the captured
HF chain's `h<L>.pt`, `h<L+1>.pt`, `r<L>.pt`). `ling-weights-real` loads layers 0, 4 and 7 with experts 0-3 (769 MiB on the device) and compares 35 products with torch's float64
on the same 8 rows: worst 0.414 of the bound, relative L2 at most 1.7e-3 for bf16 outputs and 6.9e-8 for the
experts' fp32 down rows.

Expand All @@ -105,13 +169,10 @@ size.

Each item stands alone.

1. **KDA block on `qlinear`.** Write Ling's KDA block over `weights.Kda`: seven `qlinear.Linear` calls (or one fused
`[q | k | v]` per format) feeding #804's chain with `conv`, `a_log`, `dt_bias`, `o_norm` as loaded. Check it with
`ling-synth` plus `glm-kda-ling`'s fixture.
2. **MLA block on `qlinear`.** The same for `weights.Mla` on `ling-mla`'s kernels (`q_a`, `q_b`, `kv_a`, `kv_b`,
head gate, `dense`).
3. **MoE block.** Route with GLM's `moe.Layer` (`ling.route()` fills top-k, groups and limits), run `experts.Grouped`
on `Moe.routed`, the shared expert as three projections.
1. **Lanes hooks.** Drive `Forward` from #804's `cuda_lanes.zig` pattern: drafted windows, concurrent streams as
segments, cut prompts; `ling-forward-synth` already checks the exactness each needs.
2. **MTP.** Wire `weights.Mtp` as a drafter (see "What is missing").
3. **Fused projections.** Same-format q|k|v (and gate|up) rows as one weight per format, without the column copies.
4. **Bf16 routed experts.** Add a grouped bf16 expert kernel, or quantize at load, and drop the per-expert lanes.
5. **TP.** Cut `weights.load` by heads and widths as `glm/cuda_shard.zig` does; FP8 scale blocks span 128 rows and
128 inputs, so FP8 cuts fall on multiples of 128.
Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const kernels = [_]Kernel{
.{ .name = "glm_glue", .flags = &.{"-O3"} }, // ours: the Python family's Triton glue by hand, its PTX op for op
.{ .name = "glm_ops", .flags = &.{"-O3"} }, // ours: GLM's integer work the Python family did in torch (the DSA token lists)
.{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family
.{ .name = "ling_glue", .flags = glue }, // ours: Ling-3.1's bf16 glue at the HF model's rounding points
.{ .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 },
Expand Down
39 changes: 39 additions & 0 deletions zig/kernels/cuda/ling_glue.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Ling-3.1-flash's bf16 glue at the HF model's rounding points: the residual add, the head-wise gate, the MoE sum.
#include <cuda_bf16.h>
#include <stdint.h>

namespace ling_glue {
__device__ __forceinline__ float bf(__nv_bfloat16 x) { return __bfloat162float(x); }
__device__ __forceinline__ float rbf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); }
} // namespace ling_glue

// torch's bf16 x + y: the fp32 sum rounded once; out may alias x or y.
extern "C" __global__ void tf_ling_add(const __nv_bfloat16* x, const __nv_bfloat16* y, __nv_bfloat16* out, int64_t n) {
const int64_t i = static_cast<int64_t>(blockIdx.x) * blockDim.x + threadIdx.x;
if (i < n) out[i] = __float2bfloat16_rn(__fadd_rn(ling_glue::bf(x[i]), ling_glue::bf(y[i])));
}

// The head-wise gate: o [rows][heads][dv] times bf16(sigmoid(float(g [rows][gs], column h))), rounded to bf16.
extern "C" __global__ void tf_ling_gate(__nv_bfloat16* o, int64_t heads, const __nv_bfloat16* g, int64_t gs) {
const int64_t r = blockIdx.x, h = blockIdx.y, dv = blockDim.x;
const float z = ling_glue::bf(g[r * gs + h]);
const float s = ling_glue::rbf(__fdiv_rn(1.0f, __fadd_rn(1.0f, expf(0.0f - z))));
__nv_bfloat16* p = o + (r * heads + h) * dv + threadIdx.x;
*p = __float2bfloat16_rn(__fmul_rn(ling_glue::bf(*p), s));
}

// moe_infer's sum, bf16(sum of float(y) w over k < used) + shared, y [rows][slots][d] or by_pick [experts][rows][d].
extern "C" __global__ void tf_ling_combine(const __nv_bfloat16* y, const int* pick, const float* wts,
const __nv_bfloat16* shared, __nv_bfloat16* out, int64_t rows, int64_t d,
int slots, int used, int by_pick) {
const int64_t r = blockIdx.x, c = static_cast<int64_t>(blockIdx.y) * blockDim.x + threadIdx.x;
if (c >= d) return;
float a = 0.0f;
for (int k = 0; k < used; ++k) {
const int64_t at = by_pick ? (static_cast<int64_t>(pick[r * slots + k]) * rows + r) * d + c : (r * slots + k) * d + c;
a = __fadd_rn(a, __fmul_rn(ling_glue::bf(y[at]), wts[r * slots + k]));
}
float v = ling_glue::rbf(a);
if (shared != nullptr) v = __fadd_rn(v, ling_glue::bf(shared[r * d + c]));
out[r * d + c] = __float2bfloat16_rn(v);
}
1 change: 1 addition & 0 deletions zig/src/cuda/kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub const glm_glue: []const u8 = if (available) &Blob("fatbin_glm_glue").bytes e
pub const glm_ops: []const u8 = if (available) &Blob("fatbin_glm_ops").bytes else &.{};
pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{};
pub const glm_kda: []const u8 = if (available) &Blob("fatbin_glm_kda").bytes else &.{};
pub const ling_glue: []const u8 = if (available) &Blob("fatbin_ling_glue").bytes else &.{};
pub const glm_kda_chunk: []const u8 = if (available) &Blob("fatbin_glm_kda_chunk").bytes else &.{};
pub const torch_argmax: []const u8 = if (available) &Blob("fatbin_torch_argmax").bytes else &.{};
pub const torch_topk: []const u8 = if (available) &Blob("fatbin_torch_topk").bytes else &.{};
Expand Down
61 changes: 61 additions & 0 deletions zig/src/families/ling/block_ffn.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//! Ling's MLPs on CUDA: SwiGLU over projections in their loaded formats, and the MoE block (router, groups, experts).
const std = @import("std");
const cuda = @import("cuda");
const graph = @import("graph.zig");
const weights = @import("weights.zig");
const state = @import("state.zig");
const ling = @import("cuda.zig");

const glue = graph.glue;
const Ops = graph.Ops;
const Config = @import("config.zig").Config;

/// Gate and up into [gate | up] rows, SwiGLU clamped at `limit` (0: none), down into `out` [rows][hidden].
pub fn mlp(o: Ops, b: *const state.Buffers, m: weights.Mlp, x: u64, ldx: usize, rows: usize, limit: f32, out: u64) !void {
const w = m.gate.outputs();
try o.mmCols(m.gate, x, ldx, rows, b.tmp, b.gu, 2 * w, 0);
try o.mmCols(m.up, x, ldx, rows, b.tmp, b.gu, 2 * w, w);
try glue.swiglu(o.set(), o.s, b.gu, b.act, b.xs, limit, rows, w);
try o.mm(m.down, b.act, w, rows, out);
}

/// The MoE block on b.normed into b.y: routed experts' slots summed (weights fp32), plus the shared expert.
pub fn moe(o: Ops, b: *const state.Buffers, e: weights.Moe, g: *const graph.Graph, layer: u32, rows: usize, picks: ?u64) !void {
const c = &g.w.config;
const D: usize = c.hidden;
const E: usize = c.experts;
if (e.experts != E) return error.PartialExperts; // the router picks among every expert
const top: usize = c.topk;
const slots = top + 1;
const lim = ling.limits(c, layer);
try glue.router(o.set(), o.s, b.normed, D, e.router, b.mlog, b.rpart, rows, D, E);
try glue.select(o.set(), o.s, b.mlog, if (e.bias != 0) e.bias else g.zero_bias, b.pick, b.wts, rows, top, E, c.routed_scale, c.norm_topk, ling.groups(c));
if (picks) |p| try o.copy(b.pick, slots * 4, p, slots * 4, rows, slots * 4);
switch (e.routed) {
.grouped => |l| try grouped(o, b, l, rows, slots, E),
.lanes => |ls| for (ls, 0..) |x, j| try mlp(o, b, x, b.normed, D, rows, lim.routed, b.ey + j * rows * D * 2),
}
if (e.shared) |s| try mlp(o, b, s, b.normed, D, rows, e.shared_limit, b.sh);
var a: cuda.Args = .{};
inline for (.{ b.ey, b.pick, b.wts, if (e.shared != null) b.sh else @as(u64, 0), b.y, @as(i64, @intCast(rows)), @as(i64, @intCast(D)), @as(c_int, @intCast(slots)), @as(c_int, @intCast(top)), @as(c_int, @intFromBool(e.routed == .lanes)) }) |v| a.add(v);
try cuda.launch.launch(o.m.combine, .{ .grid = .{ .x = @intCast(rows), .y = @intCast((D + 255) / 256) }, .block = .{ .x = 256 } }, o.s, &a);
}

/// Grouped experts on every row's top-k slots (the shared slot skipped): gate-up SwiGLU, then down to bf16 slot rows.
fn grouped(o: Ops, b: *const state.Buffers, l: cuda.experts.Layer, rows: usize, slots: usize, count: usize) !void {
const pairs = rows * slots;
const tile: usize = if (o.prompt) cuda.experts.promptTile(l.format) else 16;
const skip: i32 = @intCast(count);
try o.m.router.route(o.s, b.pick, pairs, count + 1, tile, b.plan);
const items = cuda.grouped.maxItems(pairs, count + 1, tile);
const g = o.m.grouped();
const up: cuda.experts.Rows = .{ .x = b.normed, .stride = l.dims, .slots = slots };
const down: cuda.experts.Rows = .{ .x = b.eact, .stride = l.width };
if (o.prompt) {
try g.prompt(o.s, .up, up, l, b.plan, b.eact, items, skip);
try g.prompt(o.s, .down_bf16, down, l, b.plan, b.ey, items, skip);
} else {
try g.decode(o.s, .up, up, l, b.plan, b.eact, items, skip);
try g.decode(o.s, .down_bf16, down, l, b.plan, b.ey, items, skip);
}
}
Loading