Skip to content

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

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

Andre-Sacilotti wants to merge 9 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/hy4/forward.rs"]
    n10["dspark.rs"]
    n11["src/inkling2/mod.rs"]
    n12["lib.rs"]
    n13["src/vulkan/mod.rs"]
    n14["preflight.rs"]
    n15["tests/common/mod.rs"]
    n16["gpu_model.rs"]
    n17["inkling2_forward.rs"]
    n18["kv_q8.rs"]
    n19["llama_numerics.rs"]
    n20["quant.rs"]
    n21["vision.rs"]
    n0 --> n4
    n0 --> n12
    n0 --> n13
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n18
    n0 --> n19
    n1 --> n5
    n1 --> n6
    n1 --> n7
    n1 --> n8
    n1 --> n9
    n1 --> n10
    n1 --> n20
    n2 --> n11
    n2 --> n17
    n2 --> n21
    n3 --> n10
    n3 --> n11
    n3 --> n21
    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
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.

  • src/cuda/kernels.cu · modified · +372/-3
  • src/cuda/mod.rs · modified · +91/-17 · +4 functions, +1 class · 8 other dependents
  • src/deepseek/mat.rs · modified · +96/-8 · +12 functions, -1 function · 7 other dependents
  • src/inkling2/chat.rs · modified · +2/-0 · 3 other dependents
  • src/inkling2/forward.rs · modified · +5/-5 · 3 other dependents
  • src/inkling2/forward/device.rs · modified · +353/-142 · +7 functions, +1 class
  • src/main.rs · modified · +29/-9
  • tests/bench_script.rs · +150/-0 · new file, 5 symbols
  • tests/kernels.rs · modified · +52/-0 · +1 function
  • 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: +3
  • Dependency graph edges: -1
  • Commits: 6

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 refactors the CUDA prefill attention kernels into a templated four-or-sixteen-query-per-block variant, with a token-base offset so the fallback paths cover the full tile. It also caches the STRATA_CTRL_TILE, STRATA_DS_ATTN_OLD, and STRATA_DS_ATTN_KP4 environment flags at Gpu creation, adds a free-VRAM reserve check for keeping plain weights on GPU 0, and adds unit tests for these pieces. The changes mainly affect GPU inference for the DeepSeek/Inkling 2 model on multi-GPU setups and anyone who sets these environment variables.

Merge confidence Review effort Merge risk
2 / 5 4 / 5 Medium
Area Files Lines
tools 3 +91 −9
src/cuda 2 +97 −138
tests 2 +202 −0
src/deepseek 1 +41 −4
src/inkling2 1 +8 −1

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

# Severity Category Where
1 🟠 High Correctness kld_compare.py:76 The header parse was removed, so rows are read from the file start, including the header bytes. The old code…
2 🟠 High Correctness mat.rs:204 A failed mem_info silently passes the reserve check as unlimited free VRAM. If mem_info() returns Err…
3 🟠 High Correctness kernels.cu:2979 Four sequential calls to a barrier-containing body can diverge on a partial tile. Each call to…
4 🟡 Medium Correctness mod.rs:45 STRATA_DS_ATTN_OLD and KP4 now treat "0" as off, changing their old presence-check meaning. Before, any set…
5 🔵 Low Maintainability kernels.rs:2725 The 1e-6 tolerance is tight for reordered float summation, so the test may flake. The kp16 kernel sums the…
6 🔵 Low Maintainability bench_2x3060.sh:28 The comment says to set STRATA_DS_PLAIN_FIRST=0 here, but the script does not set it. A reader follows the…
7 🔵 Low Performance mat.rs:204 cudaMemGetInfo is queried for every plain tensor placed on GPU 0. With the flag on, every tensor allocation…
8 🔵 Low Maintainability kernels.cu:3003 The four-call 16-token fallback loop is copied into two wrappers. The two wrappers each carry the same q0…
- 🟠 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
Review details

Reviewed 9 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 8 of 8 proposed finding(s).

Fix all with your 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.

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.

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.

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.

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.

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.

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.

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.
Blast radius: 51 other file(s) depend on what this PR changes (17 directly, 34 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/deepseek/mat.rs is imported by src/deepseek/forward.rs, src/deepseek/mod.rs, src/gemma4/forward.rs, src/glm/forward.rs (+5 more)
  • src/cuda/mod.rs is imported by src/backend.rs, src/lib.rs, src/vulkan/mod.rs, src/vulkan/preflight.rs (+4 more)
  • src/inkling2/forward/device.rs is imported by src/inkling2/forward.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 (+28 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
}

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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
).unwrap();
want.extend_from_slice(&down::<f32>(gpu, &dout1));
}
let got = down::<f32>(gpu, &dout);

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 · 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.

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