Skip to content

inkling2: expert slabs on a second card, and kernels that use the bandwidth - #96

Open
Andre-Sacilotti wants to merge 11 commits into
RustingStudio:mainfrom
Andre-Sacilotti:feat/inkling2-multigpu
Open

Andre-Sacilotti wants to merge 11 commits into
RustingStudio:mainfrom
Andre-Sacilotti:feat/inkling2-multigpu

Conversation

@Andre-Sacilotti

@Andre-Sacilotti Andre-Sacilotti commented Nov 24, 2026 •

Copy link
Copy Markdown

Result

Inkling-2-Mini-UD-IQ4_XS.gguf — 15.7 GB, 26.1 B parameters, 8/128 experts, CUDA, --temp 0, prompt chunk 512.

The model does not fit in one 12 GB card. With the second card all 24 expert layers are slabs in VRAM (24/24,
14.06 GB: 6.89 + 7.17), and the same kernels run against the card:

one card, --device 0, ctx 8192 two cards, --device 0,1, ctx 32768
prefill 512 109.4 tok/s 860.3 tok/s
prefill 2048 177.6 tok/s 780.8 tok/s
decode after 2048 18.9 tok/s 52.4 tok/s

Per change, knob off/on in one build:

change effect
bench defaults one card: +8.5% prefill 2048, +10.4% decode — the benchmark was using a smaller cache than serve
loop controllers kernel −30% (nsys); two cards +7.9% @ 2k, +9.8% @ 4k, +9.3% @ 8k
decode attention KV 95 → ~300 GB/s; two cards +23% of a token at 24.5k
prompt attention kernel −25% (nsys); two cards +6.9% @ 2k, +9.0% @ 4k, +11.8% @ 8k

The deltas above are same-build (knob off/on); the absolute tok/s of different builds are not comparable and are not
shown. The only absolute table is the one-card vs two-card comparison above: the one-card column is the ctx-8192
reference, the two-card column is this branch.

What

  • Second card: alloc_slab_on puts a layer's whole expert slab on GPU 0 or 1; a layer on GPU 1 runs its FFN
    there (Remote), attention/tail stay on GPU 0; PLAIN_FIRST keeps the plain weights on GPU 0.
  • Bench: bench now calls inkling2::chat::gpu_defaults(), so it measures the path chat/serve use.
  • Kernels: controllers tile 64 tokens a block; decode attention stages 128 keys and reads K/V at the card's
    bandwidth; prompt attention tiles 16 queries a block. Knobs: STRATA_CTRL_TILE=0, STRATA_DS_ATTN_OLD=1,
    STRATA_DS_ATTN_KP4=1.
  • Tools: perplexity on inkling2, tools/kld_compare.py, tools/bench_2x3060.sh.

Method

  • One-card numbers: the same main and main+this branch, cargo build --release, alternating A-B-B-A-A-B, 3 runs per side, median (min-max); fixed STRATA_DS_CPU_SHARE=0.5 and STRATA_DS_KV_TOKENS=8192. Same binary A/B measured the spread of the medians at 0.6%, so a 2% difference is significant on this machine.
  • Two-card numbers: one process per (context, prompt length), --device 0,1, --ctx 32768, STRATA_DS_KV_TOKENS=32768, STRATA_DS_PF_TOKENS=512, no fixed CPU share. A run is only compared when its load line says the same 24/24 expert layers.
  • Per-change deltas: the same build with the change's knob off and on (STRATA_CTRL_TILE, STRATA_DS_ATTN_OLD, STRATA_DS_ATTN_KP4), so only the kernel selection changes.
  • Kernel times from nsys on one card (--device 0), where the kernel is the same code the two-card run executes.
  • Hardware: 2× RTX 3060 12 GB (no P2P), driver 580.178.04, Xeon E5-2680 v4, 32 GB RAM.

Correctness (edited after aletheore review)

  • tests/inkling2_forward: 4/4; kernel_names: 376 (sm_80) / 330 (sm_70).
  • cargo test --release --lib: 102 passed (the two pre-existing sm_70/sm_75 __dp4a failures remain).
  • ink_attn_prefill_kp16_fallback_covers_every_query (nr 28/30/40), bench_script 3/3, tools/test_kld_compare.py 3/3.
  • Inkling --kld-base, controllers: KLD 2.9e-3 nats mean, top-1 125/127 (PPL 3.8169 → 3.8162).
  • Inkling --kld-base, decode attention: KLD 5.5e-3, top-1 124/127 (PPL 3.8022 → 3.8287).
  • Prompt attention: gated by the llama.cpp parity tests above.
  • Qwen3.5-4B and Qwen3.8-27B: --kld-base byte-identical. The PR does not touch their kernels, so this is a no-collateral check, not a gate for the new Inkling kernels.

alloc_slab_on places a layer's whole expert slab on GPU 0 or 1; a layer
whose experts live on GPU 1 runs its FFN there (Remote scratch, a light
prefill scratch) with the activations over the host, and its attention
and tail stay on GPU 0. Each stacked expert tensor keeps all its experts
on one GPU (affinity) so a layer's matvecs hit the batched path.
STRATA_DS_PLAIN_FIRST keeps the plain weights on GPU 0, where the device
decode state lives, and STRATA_DS_PF_TOKENS sets the prompt chunk.

(cherry picked from commit b15a10d5dd8f058bfb5ab64b09c5ec67b88152e5)
bench_inkling2 called only deepseek::chat::gpu_defaults(), which turns the GPU on but not the Inkling 2 defaults:
STRATA_DS_GPU_FRACTION=0.6,0.9 (the share of free VRAM the expert cache may take; 0.8 without it) was missing, so
bench kept fewer expert layers in VRAM than chat, generate and serve do for the same model and flags, and reported a
smaller cache than the one those commands run with. (The other Inkling 2 default, STRATA_DS_PLAIN_FIRST, is a no-op
until the multi-GPU work lands.)

One card, bench --pp 512,2048 --tg 16 --ctx 8192 --device 0, the only difference being that fraction, median of 2:

| | prefill 512 | prefill 2048 | decode 512 / 2048 |
|---|---|---|---|
| before (0.8) | 106.9 | 163.7 | 18.3 / 18.3 |
| after (0.9) | 109.4 (+2.3%) | 177.6 (+8.5%) | 20.2 (+10.4%) / 18.9 (+3.6%) |

(cherry picked from commit 9b449a1)
One fresh process per (ctx, prompt length) row: the KV and the prefill
scratch are sized by the context, and the load line goes with every row
because how many expert layers fit depends on the free VRAM at load.

(cherry picked from commit e7b8896)
… forward

perplexity --kld-base writes llama-perplexity's file (the log-softmax
quantized to 16 bits over 16 nats); comparing two builds of the engine
with it turns 'the kernels did not change' into a byte comparison over
every scored position and the whole vocabulary, and 'the sums moved a
little' into a KLD, a top-1 agreement and the number of cells that moved
one quantum. tools/kld_compare.py reads two files and prints those, with
the PPL of each.

perplexity loaded only the generic Model, which refuses the Inkling 2
architecture: it now runs that forward for those files (the model scores
the first half of each chunk and steps the rest, exactly as the hint
says), so the target of these PRs gets the same gate as the others.

(cherry picked from commit 15940f0)
ink_ctrl_gate and ink_ctrl_out gave a block one (controller row, token)
pair, so a 64-row controller weight was read once per token: at a prompt
of 2048 tokens in 512-token chunks they took 466 ms of a 3.1 s prefill
(the gate 0.65 GB/s of the card). The tiled pair puts 64 tokens and all
64 rows in a block (16 x 16 threads, 4 x 4 outputs each), reading a
weight row once per 64 tokens. gate+out go from 4.86 to 1.03 ms per
layer run: prefill 669 to 722 tok/s at 2048 tokens, 629 to 690 at 4096,
573 to 626 at 8192, same greedy text. A decoded token keeps the
per-token pair (there is no tile to reuse) behind STRATA_CTRL_TILE=0.

(cherry picked from commit 5f79204)
The scalar kernel walks one key at a time: every lane loads a 2-byte K
element through ldkv1 and the 128-long dot ends in a warp reduction, so
one key costs a row of scalar loads and five shuffles. At 24.5k positions
that read K/V at about 95 GB/s of the 360 the card has, and it was 8.4 of
the 27 ms a token took there (68 ms at 200k).

ink_attn_128 has a 128-thread block own 128 positions: their K rows are
staged in shared memory with coalesced 16-byte loads, lane i of warp w
scores key 32w + i with sixteen 16-byte loads and 128 FMAs (one block max
and one block sum per 128 keys, no shuffle per key), and V is read 8 bytes
a lane, one key at a time, as it already was coalesced. Measured with the
two-card work (a separate branch: this file loads the device only with one
card today) decode after a 24.5k-token prompt went 37.0 to 45.5 tok/s;
tests/inkling2_forward still matches llama.cpp's greedy tokens on one card
(24/24 short, 47/48 long, the same near tie), and STRATA_DS_ATTN_OLD=1
keeps the scalar kernel.

(cherry picked from commit a7d37dd)
One warp ran one (query, head) and walked the keys one at a time: two
warp reductions and a dozen shuffles per key. The new kernel gives a
128-thread block four queries of one head, shares a 32-key K/V tile in
shared memory, scores one key per lane (its own 128-long dot) and
reduces once per tile for the online softmax. Needs nr <= 32 and nr % 4
== 0; the old kernel stays as ink_attn_prefill_128_old behind
STRATA_DS_ATTN_OLD.

(cherry picked from commit eb66a54)
The kp kernel staged a 32-key K/V tile for four queries (one a warp),
and the tile load plus the per-tile softmax reductions were paid four
times more often than the FMAs need. kp16 gives a warp four queries and
a block sixteen: the K row is read once per 32 keys and used by four
dots, V is read once a key for all four. Prompt prefill at 32k of
context: 757 to 809 tok/s at 2048 tokens, 714 to 779 at 4096, 658 to 736
at 8192 (the gain grows with depth, as the K/V re-read did).
STRATA_DS_ATTN_KP4=1 keeps the four-query kernel. tests/inkling2_forward
still matches llama.cpp (24/24, 47/48 with the same near tie, chunked and
speculative tests pass).

(cherry picked from commit 0a38679)
@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/cuda/mod.rs"]
    n1["mat.rs"]
    n2["chat.rs"]
    n3["src/inkling2/forward.rs"]
    n4["backend.rs"]
    n5["src/deepseek/forward.rs"]
    n6["src/deepseek/mod.rs"]
    n7["src/gemma4/forward.rs"]
    n8["src/glm/forward.rs"]
    n9["src/hip/mod.rs"]
    n10["src/hy4/forward.rs"]
    n11["dspark.rs"]
    n12["src/inkling2/mod.rs"]
    n13["src/kolibri/forward.rs"]
    n14["lib.rs"]
    n15["src/vulkan/mod.rs"]
    n16["preflight.rs"]
    n17["tests/common/mod.rs"]
    n18["gpu_model.rs"]
    n19["inkling2_forward.rs"]
    n20["kv_q8.rs"]
    n21["llama_numerics.rs"]
    n22["quant.rs"]
    n23["vision.rs"]
    n0 --> n4
    n0 --> n9
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n0 --> n20
    n0 --> n21
    n1 --> n5
    n1 --> n6
    n1 --> n7
    n1 --> n8
    n1 --> n10
    n1 --> n11
    n1 --> n13
    n1 --> n22
    n2 --> n12
    n2 --> n19
    n2 --> n23
    n3 --> n11
    n3 --> n12
    n3 --> n13
    n3 --> n23
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 changed
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • docs/USAGE.md · modified · +33/-0
  • src/cuda/kernels.cu · modified · +372/-3
  • src/cuda/mod.rs · modified · +112/-13 · +4 functions, +1 class · 9 other dependents
  • src/deepseek/mat.rs · modified · +96/-8 · +12 functions · 8 other dependents
  • src/inkling2/chat.rs · modified · +2/-0 · 3 other dependents
  • src/inkling2/forward.rs · modified · +5/-5 · 4 other dependents
  • src/inkling2/forward/device.rs · modified · +359/-142 · +7 functions, +1 class
  • src/main.rs · modified · +29/-9
  • tests/bench_script.rs · +150/-0 · new file, 5 symbols
  • tests/inkling2_ctrl.rs · +50/-0 · new file, 3 symbols
  • tests/inkling2_prefill.rs · +66/-0 · new file, 3 symbols
  • tools/bench_2x3060.sh · added · +63/-0
  • tools/kld_compare.py · +107/-0 · new file, 4 symbols
  • tools/test_kld_compare.py · +63/-0 · new file, 8 symbols

Aggregate deltas

  • Modules: +5
  • Dependency graph edges: +4
  • Commits: 11

Comment thread src/cuda/kernels.cu Resolved
m.balance(&m.cpu_share, adapt, tg, tc);
let wc: Vec<f32> = (0..c.n_used).map(|i| on_gpu.get(i).map_or(0.0, |e| e.2)).chain(cpu).collect();
let host: Vec<f32> = match rem { Some(r) => cpu.iter().zip(&r).map(|(a, b)| a + b).collect(), None => cpu };
let wc: Vec<f32> = (0..c.n_used).map(|i| list.get(i).map_or(0.0, |e| e.2)).chain(host).collect();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 9

CPU-share and GPU-1 expert weights are summed elementwise across different expert lists host = cpu.zip(&r) adds the i-th CPU-share expert's weight to the i-th remote expert's weight. Those are different experts. zip also truncates to the shorter list, so if one side has more entries, some experts are dropped and ink_ffn_sum is called with list.len() + host.len() weights that do not match the experts actually run. The output is wrong for any token where both kinds of expert are selected.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1648
Issue: CPU-share and GPU-1 expert weights are summed elementwise across different expert lists host = cpu.zip(&r) adds the i-th CPU-share expert's weight to the i-th remote expert's weight. Those are different experts. zip also truncates to the shorter list, so if one side has more entries, some experts are dropped and ink_ffn_sum is called with list.len() + host.len() weights that do not match the experts actually run. The output is wrong for any token where both kinds of expert are selected.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@Andre-Sacilotti Andre-Sacilotti Nov 24, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this one is not a bug. run_experts returns the weighted mix (length n_embd), not per-expert weights; cpu and r are both length n, so the elementwise add is the host total, and wc holds c.n_used GPU weights plus the n host values. I added a comment and debug_assert_eq!s on those lengths to make the invariant explicit; the forward is unchanged.

Would like another opinion here

Comment thread src/deepseek/mat.rs Resolved
Comment thread src/deepseek/mat.rs Resolved
Comment thread tools/bench_2x3060.sh Resolved
Comment thread tools/bench_2x3060.sh Resolved
Comment thread src/cuda/mod.rs Resolved
Comment thread src/cuda/kernels.cu Resolved
Comment thread tools/kld_compare.py Resolved
@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds AMD HIP backend support (--backend hip, with WMMA matrix-core GEMM paths) and a new small-batch int8 GEMM for decode, and it spreads Inkling 2 expert layers across two GPUs with selectable fast kernels and tuning environment variables. It also changes calibration to cache per backend and cover all architectures, makes the server send SSE keep-alives and skip read-ahead on network file systems, and updates the usage docs to match. Affected users are those running Inkling 2 on multiple GPUs, AMD/ROCm users, and anyone using calibrate, serve, or models on network mounts.

Merge confidence Review effort Merge risk
2 / 5 5 / 5 Medium
Area Files Lines
src/inkling2 3 +144 −23
src/cuda 2 +634 −59
tests 2 +116 −0
docs 1 +64 −26
src 1 +1145 −190
src/deepseek 1 +160 −21
tools 1 +4 −4

4 finding(s) posted as inline review comment(s). 11 earlier finding(s) from previous pushes still open.

# Severity Category Where
1 🟠 High Correctness mod.rs:1250 The new sh prefill kernel is chosen for every full-attention layer, not only with fast kernels, so one card…
2 🟠 High Correctness mod.rs:1250 The sh branch has no kv_mode guard, so quantized K/V takes the f16-only path. The first branch only uses the…
3 🟠 High Correctness device.rs:49 Two-card defaults key off STRATA_DS_DEVICES, which this diff never sets. --device 0,1 never sets…
6 🔵 Low Maintainability device.rs:49 Multi-device detection is duplicated in mod.rs and device.rs. The same STRATA_DS_DEVICES split-and-count…
- 🟠 High Correctness kernels.cu:2996 Earlier finding, still open
- 🟠 High Correctness device.rs:1648 Earlier finding, still open
- 🟠 High Correctness mat.rs:172 Earlier finding, still open
- 🟡 Medium Correctness mat.rs:257 Earlier finding, still open
- 🟡 Medium Correctness bench_2x3060.sh:45 Earlier finding, still open
- 🟠 High Correctness kld_compare.py:76 Earlier finding, still open
- 🟠 High Correctness mat.rs:204 Earlier finding, still open
- 🟠 High Correctness kernels.cu:2979 Earlier finding, still open
- 🔵 Low Maintainability bench_2x3060.sh:28 Earlier finding, still open
- 🔵 Low Performance mat.rs:204 Earlier finding, still open
- 🔵 Low Maintainability kernels.cu:3003 Earlier finding, still open
Review details

Reviewed 10 file(s); skipped 1. Dismissed 0; outside PR diff 6. Grounding: 17 of 19 proposed finding(s).

Fix all with your agent
File: src/cuda/mod.rs
Line: 1250
Symbol: attn_sel
Issue: The new sh prefill kernel is chosen for every full-attention layer, not only with fast kernels, so one card changes kernels. The branch `win == 0 && nkv > 0 && g <= 4` routes hd 32/64/128 full-attention prefill to `ink_attn_prefill_sh_*` without checking `self.flags.fast`. A single-card run with default flags now uses a different kernel from main, although the PR says one card keeps the main kernels so greedy output does not change. Any bit difference shows up in the output.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/mod.rs
Line: 1250
Symbol: attn_sel
Issue: The sh branch has no kv_mode guard, so quantized K/V takes the f16-only path. The first branch only uses the key-parallel kernels when `kv_mode == 0`, and the old code sent `kv_mode != 0` at hd 128 to the `_kp` kernel. The new fall-through sends a q8/q4 cache with win == 0 and g <= 4 to `ink_attn_prefill_sh_*`, which has no kv_mode check and reads the rows as f16. The result is garbage attention or an out-of-bounds read.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 49
Issue: Two-card defaults key off STRATA_DS_DEVICES, which this diff never sets. `--device 0,1` never sets STRATA_DS_DEVICES in this diff, so `multi` is false. Then `pf_tokens` gives 256 instead of 512, and `InkFlags` leaves fast kernels off under `auto`. The documented two-card configuration silently runs the one-card settings and loses the measured speedup. The tuned values only apply if some other code sets the variable.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 49
Issue: Multi-device detection is duplicated in mod.rs and device.rs. The same STRATA_DS_DEVICES split-and-count appears in `InkFlags::from_env` and `pf_tokens`. If one copy changes its rule, the fast-kernel default and the prefill chunk size disagree, for example kernels on one card and chunk 512. One shared helper would keep them in step.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Note: 1 of 11 changed file(s) were not included in this review (the review reads at most 30 files, and skips any file over 100KB). Issues in them would not be found, and citations pointing into them could not be checked against the real file: src/main.rs.

Blast radius: 53 other file(s) depend on what this PR changes (20 directly, 33 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/cuda/mod.rs is imported by src/backend.rs, src/hip/mod.rs, src/lib.rs, src/vulkan/mod.rs (+5 more)
  • src/deepseek/mat.rs is imported by src/deepseek/forward.rs, src/deepseek/mod.rs, src/gemma4/forward.rs, src/glm/forward.rs (+4 more)
  • src/inkling2/forward.rs is imported by src/inkling2/dspark.rs, src/inkling2/mod.rs, src/kolibri/forward.rs, tests/vision.rs
  • src/inkling2/chat.rs is imported by src/inkling2/mod.rs, tests/inkling2_forward.rs, tests/vision.rs

Indirectly affected: examples/gguf_dump.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs, src/deepseek/chat.rs (+27 more)

The graph is large; this list is capped and not exhaustive.

@Andre-Sacilotti
Andre-Sacilotti marked this pull request as draft November 24, 2026 08:44
…indings

The 16-query prefill entry point is launched with a 16-token grid; when
the relative-bias width does not fit the four-query kernel (nr > 32 or
nr % 4 != 0), the fallback now calls it four times with a tbase, so
tokens 4..15 of each tile are written. kp and kp16 become one template
(QPB) and ink_attn_prefill_t takes the base.

The 128-key decode kernel keeps the bias row in 32 shared floats: only
select it for nr <= 32, and the scalar kernel otherwise.

The plain-first branch keeps 768 MB of live free VRAM for the state, KV
and prefill scratch (the state is allocated outside the weight budget);
checking `room` alone would move the plain weights to GPU 1. The expert
group is consumed on a cache hit, the CUDA flags are cached on the Gpu,
the bench script survives a failed or silent row and passes
PLAIN_FIRST=0, and the KLD compare streams the files. Tests cover the
kp16 fallback (nr 28/30/40), the bench script and the streaming compare.
@Andre-Sacilotti
Andre-Sacilotti marked this pull request as ready for review November 24, 2026 10:46
Comment thread tools/kld_compare.py
first = na // 2
per = na - 1 - first

same = same_bytes(a.base, a.new)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 8

The header parse was removed, so rows are read from the file start, including the header bytes. The old code rewound both files and called header(fa) and header(fb) before the row loop. The new code reads the files only through same_bytes, which opens its own handles, so fa and fb never skip the header. rows(fa, ...) then decodes header bytes as quantized rows and the KLD numbers are silently wrong.

Prompt for your AI agent
File: tools/kld_compare.py
Line: 76
Symbol: main
Issue: The header parse was removed, so rows are read from the file start, including the header bytes. The old code rewound both files and called header(fa) and header(fb) before the row loop. The new code reads the files only through same_bytes, which opens its own handles, so fa and fb never skip the header. rows(fa, ...) then decodes header bytes as quantized rows and the KLD numbers are silently wrong.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/deepseek/mat.rs
// The state, KV and prefill scratch are allocated outside the budget; `room` alone would move the plain
// weights to GPU 1 (it is ~0.4 GB at 0.9), which is what this branch avoids.
if self.parts.len() > 1 && self.cur == 0 && plain_first_enabled() {
let free = self.parts[0].be.mem_info().map_or(usize::MAX, |m| m.0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 8

A failed mem_info silently passes the reserve check as unlimited free VRAM. If mem_info() returns Err, map_or(usize::MAX, ...) reports unlimited free memory, so plain_first_fits accepts every tensor onto GPU 0 without the STATE_RESERVE check. The decode state, KV growth and prefill scratch then run out of VRAM later with an OOM far from the cause.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 204
Symbol: pick
Issue: A failed mem_info silently passes the reserve check as unlimited free VRAM. If mem_info() returns Err, map_or(usize::MAX, ...) reports unlimited free memory, so plain_first_fits accepts every tensor onto GPU 0 without the STATE_RESERVE check. The decode state, KV growth and prefill scratch then run out of VRAM later with an OOM far from the cause.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/kernels.cu
if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win);
// The 4-query kernel writes four tokens a block; the host launches this entry point with a 16-token grid, so a
// fallback that calls it once would leave tokens 4..15 of every tile unwritten. Four calls cover the whole tile.
else for (int q0 = 0; q0 < 16; q0 += 4)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 8

Four sequential calls to a barrier-containing body can diverge on a partial tile. Each call to ink_attn_prefill_t returns early for warps with t >= nt. When nt falls inside one of the four 4-token windows, some warps of the block return and others run the body, which likely contains __syncthreads. The active warps then wait at a barrier the returned warps never reach, which hangs or corrupts the last tile. The fallback adds more such calls per block than the single call it replaces.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2979
Issue: Four sequential calls to a barrier-containing body can diverge on a partial tile. Each call to ink_attn_prefill_t returns early for warps with t >= nt. When nt falls inside one of the four 4-token windows, some warps of the block return and others run the body, which likely contains __syncthreads. The active warps then wait at a barrier the returned warps never reach, which hangs or corrupts the last tile. The fallback adds more such calls per block than the single call it replaces.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs Outdated
}

impl InkFlags {
fn from_parts(ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self {

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of a6686c1da8ba.


🟡 Medium · Correctness · 4 of 8

STRATA_DS_ATTN_OLD and KP4 now treat "0" as off, changing their old presence-check meaning. Before, any set value of STRATA_DS_ATTN_OLD or STRATA_DS_ATTN_KP4 enabled the flag, so =0 enabled it. Now =0 disables it. The kernels.rs test still skips on var_os().is_some(), so with =0 it skips while the kernel path changed, and the two disagree.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 45
Symbol: from_parts
Issue: STRATA_DS_ATTN_OLD and KP4 now treat "0" as off, changing their old presence-check meaning. Before, any set value of STRATA_DS_ATTN_OLD or STRATA_DS_ATTN_KP4 enabled the flag, so =0 enabled it. Now =0 disables it. The kernels.rs test still skips on var_os().is_some(), so with =0 it skips while the kernel path changed, and the two disagree.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread tests/kernels.rs Outdated
).unwrap();
want.extend_from_slice(&down::<f32>(gpu, &dout1));
}
let got = down::<f32>(gpu, &dout);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ This file is no longer part of this pull request as of a6686c1da8ba.


🔵 Low · Maintainability · 5 of 8

The 1e-6 tolerance is tight for reordered float summation, so the test may flake. The kp16 kernel sums the 128-long dot products and the online softmax in a different order from the decode kernel. On some GPUs or driver versions the relative L2 error can exceed 1e-6 from rounding alone, failing the test without any real defect.

Prompt for your AI agent
File: tests/kernels.rs
Line: 2725
Symbol: ink_attn_prefill_kp16_fallback_covers_every_query
Issue: The 1e-6 tolerance is tight for reordered float summation, so the test may flake. The kp16 kernel sums the 128-long dot products and the online softmax in a different order from the decode kernel. On some GPUs or driver versions the relative L2 error can exceed 1e-6 from rounding alone, failing the test without any real defect.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread tools/bench_2x3060.sh
done
bin=${BIN:-target/release/rustingstrata}
# `bench` turns the plain-weights path on itself (`gpu_defaults` sets STRATA_DS_PLAIN_FIRST=1 when it is unset), so
# the environment is passed through: set STRATA_DS_PLAIN_FIRST=0 here to measure the other path (mat.rs reads "0" as off).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 6 of 8

The comment says to set STRATA_DS_PLAIN_FIRST=0 here, but the script does not set it. A reader follows the comment, sets the variable in the script, and finds it has no effect, or assumes the script already forces the other path.

Prompt for your AI agent
File: tools/bench_2x3060.sh
Line: 28
Issue: The comment says to set STRATA_DS_PLAIN_FIRST=0 here, but the script does not set it. A reader follows the comment, sets the variable in the script, and finds it has no effect, or assumes the script already forces the other path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/deepseek/mat.rs
// The state, KV and prefill scratch are allocated outside the budget; `room` alone would move the plain
// weights to GPU 1 (it is ~0.4 GB at 0.9), which is what this branch avoids.
if self.parts.len() > 1 && self.cur == 0 && plain_first_enabled() {
let free = self.parts[0].be.mem_info().map_or(usize::MAX, |m| m.0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 7 of 8

cudaMemGetInfo is queried for every plain tensor placed on GPU 0. With the flag on, every tensor allocation calls mem_info, which is a driver round trip. Loading a model with many tensors adds that cost each time, when one query per load or a cached budget would do.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 204
Symbol: pick
Issue: cudaMemGetInfo is queried for every plain tensor placed on GPU 0. With the flag on, every tensor allocation calls mem_info, which is a driver round trip. Loading a model with many tensors adds that cost each time, when one query per load or a cached budget would do.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/kernels.cu
const float* bias, float* outp,
int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) {
for (int q0 = 0; q0 < 16; q0 += 4)
ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 8 of 8

The four-call 16-token fallback loop is copied into two wrappers. The two wrappers each carry the same q0 loop and comment. A future change to tile size or call count must be made in both places, and one copy will drift.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3003
Issue: The four-call 16-token fallback loop is copied into two wrappers. The two wrappers each carry the same q0 loop and comment. A future change to tile size or call count must be made in both places, and one copy will drift.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty, this is a lot of careful work, and I did not find a wrong result by reading the code. I have only one card, so I could not run the two card path. But I can't merge it like this, bc it changes what a normal one card Inkling 2 run does without any flag.

The new kernels are on by default (ctrl_tile, ink_attn_128, the kp16 prefill). They sum in another order, and your own numbers show top-1 125/127 and 124/127 against the base. The rule here is that single user greedy output must not change. Please make them opt-in, or turn them on only when there is a second card.

The slab reserve on one card grew from 384 MiB to that plus prefill scratch plus KV for the whole context, so fewer layers get slabs on one 12 GB card. And the prefill chunk default went from 256 to 512. Please keep the old values when there is one card.

Also: it conflicts with main in src/cuda/mod.rs, the 8 new STRATA variables are not in docs/USAGE.md, the tiled controller kernels and the two card path have no test (main's split test runs the same card twice with --device 0,0, the same trick works here), and tools/bench_2x3060.sh has paths from your machine.

When this is done I will test it on the 3060.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

One ask for when you change it: I can't run two cards here, so please run the two card path again on your 2x 3060 after the changes (tests/inkling2_forward and one long prompt with --device 0,1) and post the result. Then I only need to check the one card side on my 3060.

Resolve the KERNELS/kernel dispatch, the kp/kp16 kernels against main's
ink_attn_prefill_sh, and the SlabBuf/Part fields.

One card is the default, even on a two-GPU machine. `--device 0,1` is the
opt-in for the two-card path; `STRATA_DS_FAST_KERNELS=auto` then turns on
the tiled controllers, ink_attn_128 and kp16. One card keeps main's kernels
(and the old 384 MiB slab reserve and 256-token prompt chunk), so the greedy
output does not change. `STRATA_DS_FAST_KERNELS=1` forces the new kernels on
one card for the measurement table; `0` forces the old ones on two cards.

Also document the new STRATA variables in docs/USAGE.md, move the kp16 test
to its own binary (the fast path is opt-in), add the tiled-controller test,
and make tools/bench_2x3060.sh require a model path and NVRTC_LIB.
No conflicts: the new main touches docs/USAGE.md and src/main.rs (the
calibrate search); the Inkling kernels, the one-card defaults and the
two-card path are unchanged. The build passes.
Comment thread src/cuda/mod.rs
q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out,
pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32);
} else if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 {
// Every key: a block is one K/V head and `tb` tokens, with 32 keys of K and V in shared memory.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 4

The new sh prefill kernel is chosen for every full-attention layer, not only with fast kernels, so one card changes kernels. The branch win == 0 && nkv > 0 && g <= 4 routes hd 32/64/128 full-attention prefill to ink_attn_prefill_sh_* without checking self.flags.fast. A single-card run with default flags now uses a different kernel from main, although the PR says one card keeps the main kernels so greedy output does not change. Any bit difference shows up in the output.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1250
Symbol: attn_sel
Issue: The new sh prefill kernel is chosen for every full-attention layer, not only with fast kernels, so one card changes kernels. The branch `win == 0 && nkv > 0 && g <= 4` routes hd 32/64/128 full-attention prefill to `ink_attn_prefill_sh_*` without checking `self.flags.fast`. A single-card run with default flags now uses a different kernel from main, although the PR says one card keeps the main kernels so greedy output does not change. Any bit difference shows up in the output.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs
q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out,
pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32);
} else if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 {
// Every key: a block is one K/V head and `tb` tokens, with 32 keys of K and V in shared memory.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 4

The sh branch has no kv_mode guard, so quantized K/V takes the f16-only path. The first branch only uses the key-parallel kernels when kv_mode == 0, and the old code sent kv_mode != 0 at hd 128 to the _kp kernel. The new fall-through sends a q8/q4 cache with win == 0 and g <= 4 to ink_attn_prefill_sh_*, which has no kv_mode check and reads the rows as f16. The result is garbage attention or an out-of-bounds read.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1250
Symbol: attn_sel
Issue: The sh branch has no kv_mode guard, so quantized K/V takes the f16-only path. The first branch only uses the key-parallel kernels when `kv_mode == 0`, and the old code sent `kv_mode != 0` at hd 128 to the `_kp` kernel. The new fall-through sends a q8/q4 cache with win == 0 and g <= 4 to `ink_attn_prefill_sh_*`, which has no kv_mode check and reads the rows as f16. The result is garbage attention or an out-of-bounds read.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.


/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 256 on one card, 512 on two or more;
/// at most 2048).
pub(super) fn pf_tokens() -> usize {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 4

Two-card defaults key off STRATA_DS_DEVICES, which this diff never sets. --device 0,1 never sets STRATA_DS_DEVICES in this diff, so multi is false. Then pf_tokens gives 256 instead of 512, and InkFlags leaves fast kernels off under auto. The documented two-card configuration silently runs the one-card settings and loses the measured speedup. The tuned values only apply if some other code sets the variable.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 49
Issue: Two-card defaults key off STRATA_DS_DEVICES, which this diff never sets. `--device 0,1` never sets STRATA_DS_DEVICES in this diff, so `multi` is false. Then `pf_tokens` gives 256 instead of 512, and `InkFlags` leaves fast kernels off under `auto`. The documented two-card configuration silently runs the one-card settings and loses the measured speedup. The tuned values only apply if some other code sets the variable.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.


/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 256 on one card, 512 on two or more;
/// at most 2048).
pub(super) fn pf_tokens() -> usize {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability

Multi-device detection is duplicated in mod.rs and device.rs. The same STRATA_DS_DEVICES split-and-count appears in InkFlags::from_env and pf_tokens. If one copy changes its rule, the fast-kernel default and the prefill chunk size disagree, for example kernels on one card and chunk 512. One shared helper would keep them in step.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 49
Issue: Multi-device detection is duplicated in mod.rs and device.rs. The same STRATA_DS_DEVICES split-and-count appears in `InkFlags::from_env` and `pf_tokens`. If one copy changes its rule, the fast-kernel default and the prefill chunk size disagree, for example kernels on one card and chunk 512. One shared helper would keep them in step.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@Andre-Sacilotti

Andre-Sacilotti commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

@Vasyl-Trefilov ty for your review! I have made some changes and resolved the conflicts.

One card is the default, even on a two-GPU machine. --device 0,1 is the opt-in for the two-card path; on one card the kernels are main's, so the greedy output does not change. STRATA_DS_FAST_KERNELS=1 forces the new kernels on one card; =0 forces the old ones on two cards.

If you have other idea for this multi-gpu, one card default design, i can rewrite it.


I have merged with the recent commits from the main and runned the following tests:

Smaller model - fits one card (Inkling-2-Mini-UD-IQ2_XXS.gguf)

One card, Inkling-2-Mini-UD-IQ2_XXS.gguf (8.0 GB, fits whole: 24/24 slabs, 7.28 GB), ctx 32768, --device 0:

pp old (main kernels) prefill / decode FAST_KERNELS=1 prefill / decode Δ
512 572.1 / 51.5 679.4 / 64.1 +18.8% / +24.5%
2048 435.9 / 53.7 626.9 / 60.1 +43.8% / +11.9%
4096 391.8 / 51.8 604.4 / 58.8 +54.3% / +13.5%

Bigger model (Inkling-2-Mini-UD-IQ4_XS.gguf)

One card, Inkling-2-Mini-UD-IQ4_XS.gguf (15.7 GB, does not fit: 0/24 slabs, 0.00 GB in VRAM), ctx 8192, --device 0, STRATA_DS_CPU_SHARE=0.5:

pp old prefill / decode FAST_KERNELS=1 prefill / decode Δ
512 110.9 / 21.8 114.0 / 21.4 +2.8% / -1.8%
2048 150.5 / 20.1 165.3 / 20.7 +9.8% / +3.0%
4096 158.7 / 19.6 180.4 / 19.8 +13.7% / +1.0%

Two cards, Inkling-2-Mini-UD-IQ4_XS.gguf (15.7 GB, 24/24 slabs, 14.06 GB: 6.89 + 7.17), ctx 32768, --device 0,1:

pp old (FAST_KERNELS=0) prefill / decode default (fast) prefill / decode Δ
512 659.6 / 53.2 861.2 / 54.0 +30.6% / +1.5%
2048 492.4 / 47.9 788.2 / 52.2 +60.1% / +9.0%
4096 441.7 / 46.4 756.7 / 51.7 +71.3% / +11.4%
8192 382.3 / 43.2 713.5 / 49.2 +86.6% / +13.9%

Deep decode, two cards, IQ4, --ctx 32768:

prompt old prefill / decode fast prefill / decode Δ
24,576 267.2 / 36.0 598.1 / 42.9 +123.8% / +19.2%
  • ~2% is significantly noise, based on re-runs

Other tests

  • tests/inkling2_forward: 1 card IQ4 default 4/4; 2 cards IQ4 default 4/4 (24/24, 14.06 GB); 1 card IQ2 3/4 and 0,0 IQ2 3/4. The IQ2 long_prompt is 46/48 in 1 card and 45/48 in 0,0 against the IQ4_NL reference — the IQ2 quantization itself, plus one near-tie at a 0.065 logit gap in 0,0; short_prompt is 24/24, and chunked_prefill/speculative pass. The 0,0 run loads 24/24 slabs (3.75 + 3.53 GB on the two parts of the same card).
  • kernel_names: 403 (sm_80) / 334 (sm_70); cargo test --release --lib: 122 passed (the two pre-existing
    sm_70/sm_75 __dp4a failures remain).
  • inkling2_prefill (nr 28/30/40), inkling2_ctrl (tiled 64-token block), bench_script 3/3,
    tools/test_kld_compare.py 3/3.
  • One card default uses the same kernels as main; the one-card IQ4 4/4 is the greedy gate.
  • Qwen3.5-4B Q8_0 and Qwen3.8-27B IQ3_S: --kld-base byte-identical to the main base (Q27 with --ctx 256 --vram-margin 0; KLD 0.0, top-1 127/127).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants