Skip to content

inkling2: batch non-resident verify and capture step_fast graph - #72

Merged
Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
ybenyedder:feat/inkling2-dspark-graph-opt
Nov 22, 2026
Merged

Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
ybenyedder:feat/inkling2-dspark-graph-opt

Conversation

@ybenyedder

Copy link
Copy Markdown
Contributor

Follow-up to #65 / #66 addressing the two remaining Inkling 2 decode bottlenecks:

  1. Batched DSpark / N-gram verify on non-FullExps layers (src/inkling2/forward/device.rs):

    • prefill_chunk_seq (!has_full_exps) previously looped for t in 0..nt in verify_mode, executing nt individual be.get, m.plan, moe_gemv, and run_experts calls per layer.
    • Unified it onto the already-batched m.ffn_batch(ip, &hn_rows) path, which deduplicates shared experts across all nt drafted tokens and runs GPU + CPU in parallel.
  2. GPU graph capture on Device::step_fast (src/inkling2/forward/device.rs, src/backend.rs, CUDA + Vulkan kernels):

    • Added ink_clip_pos and ink_attn_pos reading pos from a device i32 pointer (s.pos) with max_rows = ((pos / 64 + 1) * 64).min(ring) and safe i0 < rows ? min(64, rows - i0) : 0 bounds in ink_attn (avoiding unsigned underflow on padded chunks).
    • Wrapped Device::step_fast in be.graph(...) keyed on (argmax, pos / 64, sc_buf, cur, slot k addrs), allowing 64 consecutive full-resident decode steps per recorded GPU graph.

Verification

  • ./tools/gen_spirv.sh + cargo test --release --test backend --locked (spirv_is_fresh + all 10 tests pass)
  • cargo test --release --lib --locked (99/99 pass)
  • cargo test --release --test kernels --locked (37/37 active pass, including new ink_pos_kernels_match_fixed_pos across pos = 0, 65, 137)
  • STRATA_INKLING2_MODEL=... STRATA_INKLING2_DSPARK=... STRATA_DS_GPU=1 STRATA_DS_BACKEND=vulkan cargo test --release --test inkling2_forward --locked (4/4 pass)
  • rustingstrata bench on Radeon 890M (Vulkan, Inkling-2-Mini-IQ4_NL.gguf, --pp 128 --tg 64 --reps 1):
    • Plain decode: 9.0 tok/s
    • DSpark (dspark-Inkling-2-Mini-Q8_0.gguf): 11.5 tok/s (+27.8%, 46/54 = 85.2% drafts accepted)

@aletheore

aletheore Bot commented Nov 22, 2026

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["device.rs"]
    n3["src/vulkan/mod.rs"]
    n4["cpu_worker.rs"]
    n5["mat.rs"]
    n6["expert_cache.rs"]
    n7["src/gpu_model.rs"]
    n8["prefill.rs"]
    n9["forward.rs"]
    n10["lib.rs"]
    n11["main.rs"]
    n12["model.rs"]
    n13["preflight.rs"]
    n14["tests/backend.rs"]
    n15["tests/common/mod.rs"]
    n16["tests/gpu_model.rs"]
    n17["kv_q8.rs"]
    n18["llama_numerics.rs"]
    n0 --> n4
    n0 --> n5
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n10
    n0 --> n11
    n0 --> n12
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n1 --> n10
    n1 --> n13
    n1 --> n15
    n1 --> n16
    n1 --> n17
    n1 --> n18
    n2 --> n9
    n3 --> n10
    n3 --> n13
    n3 --> n14
    n3 --> n15
    n3 --> n16
    n3 --> n17
    n3 --> n18
    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
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/backend.rs · modified · +12/-0 · +2 functions · 13 other dependents
  • src/cuda/kernels.cu · modified · +12/-5
  • src/cuda/mod.rs · modified · +22/-2 · +2 functions · 6 other dependents
  • src/inkling2/forward/device.rs · modified · +72/-102 · 1 other dependent
  • src/vulkan/mod.rs · modified · +22/-2 · +2 functions · 7 other dependents
  • src/vulkan/shaders/ink_attn.comp · modified · +10/-4
  • src/vulkan/shaders/ink_clip.comp · modified · +6/-3
  • src/vulkan/spv/ink_attn.spv · modified
  • src/vulkan/spv/ink_clip.spv · modified
  • tests/kernels.rs · modified · +43/-0 · +1 function

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +0
  • Commits: 1

if graph {
let max_rows = ((pos / 64 + 1) * 64).min(ring);
be.batch(&mut || {
be.ink_clip_pos(s.q, l.q_clip.addr(), hd, nh, 1, c.qk_clip, 0.0, 1.0, 0, 1, s.pos, log_alpha, c.log_floor)?;

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 7

Graph path uses ring (ds.cap) for SWA layers, while the eager path caps at c.n_swa The eager path computes SWA rows as min(pos+1, c.n_swa) and at as pos % c.n_swa. The graph path uses rows = min(pos+1, ring) and at = pos % ring, with ring = ds.cap. If ds.cap differs from c.n_swa, SWA attention reads a different window than the eager path. Output then depends on whether the step was captured, and K/V writes and attention reads can disagree on the ring slot.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1297
Symbol: layer_attn
Issue: Graph path uses ring (ds.cap) for SWA layers, while the eager path caps at c.n_swa The eager path computes SWA rows as min(pos+1, c.n_swa) and at as pos % c.n_swa. The graph path uses rows = min(pos+1, ring) and at = pos % ring, with ring = ds.cap. If ds.cap differs from c.n_swa, SWA attention reads a different window than the eager path. Output then depends on whether the step was captured, and K/V writes and attention reads can disagree on the ring slot.
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.

be.put(&y_flat, &pf.acc_buf, 0)?;
}
d.parts[0].be.get(&pf.buf, ((p.hn - buf_o) / 4) as usize, nt * n)?
};

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 7

verify_mode GPU-resident expert path deleted; verify now shares the batch FFN path The removed block computed per-token resident GPU experts, combined them with CPU experts using router weights, and wrote per-token results at acc_buf offset t*n. The new code writes one ffn_batch result at offset 0 for all verify tokens. If anything after the remaining 'if verify_mode' block still expects per-token accumulation, verify logits diverge from decode, or resident experts stop being used and verify slows down.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1222
Symbol: prefill_layer
Issue: verify_mode GPU-resident expert path deleted; verify now shares the batch FFN path The removed block computed per-token resident GPU experts, combined them with CPU experts using router weights, and wrote per-token results at acc_buf offset t*n. The new code writes one ffn_batch result at offset 0 for all verify tokens. If anything after the remaining 'if verify_mode' block still expects per-token accumulation, verify logits diverge from decode, or resident experts stop being used and verify slows down.
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.

let mut h = std::hash::DefaultHasher::new();
(argmax, pos / 64, self.sc_buf.addr(), self.s.cur).hash(&mut h);
for sl in &self.slots { sl.k.addr().hash(&mut h); }
0x494E_4B32_0000_0000u64 | (h.finish() & 0x0000_FFFF_FFFF_FFFF)

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 7

Graph key omits inputs the captured closure depends on beyond pos/64 The key hashes argmax, pos/64, sc_buf, cur and slot K addresses. The closure captures pos for every layer_attn call, and the layer_ffn_gpu routing it records is data-dependent. If any captured value depends on pos outside the 64-token chunk, or on routing that changes between steps, a replayed graph computes with stale values. The 48-bit hash truncation also allows collisions that replay the wrong graph.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 496
Symbol: step_fast
Issue: Graph key omits inputs the captured closure depends on beyond pos/64 The key hashes argmax, pos/64, sc_buf, cur and slot K addresses. The closure captures pos for every layer_attn call, and the layer_ffn_gpu routing it records is data-dependent. If any captured value depends on pos outside the 64-token chunk, or on routing that changes between steps, a replayed graph computes with stale values. The 48-bit hash truncation also allows collisions that replay the wrong graph.
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.

}
for ip in c.loop_start..c.loop_end {
let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start };
if pass > 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.

🟡 Medium · Correctness · 4 of 7

layer_ffn_gpu return value ignored inside the captured closure The decode loop branches on layer_ffn_gpu's return value, but the graph closure discards it with '?'. If that bool records a host-side fallback decision, the captured graph freezes whichever path ran during capture, and every later replay repeats it even when the decision would change.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 519
Symbol: step_fast
Issue: layer_ffn_gpu return value ignored inside the captured closure The decode loop branches on layer_ffn_gpu's return value, but the graph closure discards it with '?'. If that bool records a host-side fallback decision, the captured graph freezes whichever path ran during capture, and every later replay repeats it even when the decision would change.
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.

be.ink_clip_pos(s.q, l.q_clip.addr(), hd, nh, 1, c.qk_clip, 0.0, 1.0, 0, 1, s.pos, log_alpha, c.log_floor)?;
be.ink_clip_pos(s.k, 0, hd, nkv, 1, c.qk_clip, 0.0, 1.0, ds.k.addr(), ring, s.pos, 0.0, 1.0)?;
be.ink_clip_pos(s.v, 0, hd, nkv, 1, 0.0, c.eps, 1.0, ds.v.addr(), ring, s.pos, 0.0, 1.0)?;
be.ink_clip_pos(s.r, l.rel_clip.addr(), nr, nh, 1, c.rel_clip, 0.0, 1.0, 0, 1, s.pos, log_alpha, c.log_floor)

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 7

layer_attn duplicates the four ink_clip calls in graph and eager branches Both branches repeat the same four-step clip sequence with only the _pos or _n variant and the position source changed. A future change to one branch, such as a new clip parameter, can be missed in the other, causing the two paths to diverge silently. Factoring out a helper that takes the position source would keep them in sync.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1300
Symbol: layer_attn
Issue: layer_attn duplicates the four ink_clip calls in graph and eager branches Both branches repeat the same four-step clip sequence with only the _pos or _n variant and the position source changed. A future change to one branch, such as a new clip parameter, can be missed in the other, causing the two paths to diverge silently. Factoring out a helper that takes the position source would keep them in sync.
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.

let key = {
use std::hash::{Hash, Hasher};
let mut h = std::hash::DefaultHasher::new();
(argmax, pos / 64, self.sc_buf.addr(), self.s.cur).hash(&mut h);

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 · 6 of 7

Graph key rehashes per step and recaptures every 64 tokens The DefaultHasher runs over all slot addresses on every decode step. Because the key includes pos/64, a new graph is captured every 64 positions. Each capture re-records the whole layer stack, which adds latency and build cost, while the stable pos buffer alone would have let one graph serve every position up to the ring size.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 494
Symbol: step_fast
Issue: Graph key rehashes per step and recaptures every 64 tokens The DefaultHasher runs over all slot addresses on every decode step. Because the key includes pos/64, a new graph is captured every 64 positions. Each capture re-records the whole layer stack, which adds latency and build cost, while the stable pos buffer alone would have let one graph serve every position up to the ring size.
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
let (ring, nh, nkv, hd, nr, ext) = (100usize, 6usize, 2usize, 64usize, 4usize, 32usize);
let q = xs(nh * hd);
let k_init = xs(nkv * hd);
let (r, sink, g) = (xs(nh * nr + 1)[1..].to_vec(), xs(nh + 2)[2..].to_vec(), xs(nh * hd + 3)[3..].to_vec());

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

Pos-kernel test covers only one ring size and no SWA cap mismatch The new test fixes ring=100 and checks only K/V clip and attention. It never exercises an SWA layer whose cap differs from n_swa, never runs the Device graph replay across a 64-token boundary, and never covers quantized KV through ink_clip_pos. The SWA mismatch above would pass CI undetected.

Prompt for your AI agent
File: tests/kernels.rs
Line: 2232
Symbol: tensor_scale_applies_to_all_gpu_ops
Issue: Pos-kernel test covers only one ring size and no SWA cap mismatch The new test fixes ring=100 and checks only K/V clip and attention. It never exercises an SWA layer whose cap differs from n_swa, never runs the Device graph replay across a 64-token boundary, and never covers quantized KV through ink_clip_pos. The SWA mismatch above would pass CI undetected.
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.

@aletheore

aletheore Bot commented Nov 22, 2026

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds graph-capturable variants of the Inkling 2 clip and attention kernels (ink_clip_pos, ink_attn_pos) that read the position from a device pointer, and it wraps the decode step in a CUDA graph keyed on position and buffer addresses.

Merge confidence Review effort Merge risk
2 / 5 3 / 5 Medium
Area Files Lines
src/vulkan 3 +38 −9
src/cuda 2 +34 −7
src 1 +12 −0
src/inkling2 1 +72 −102
tests 1 +43 −0

7 finding(s) posted as inline review comment(s).

# Severity Category Where
1 🟠 High Correctness device.rs:1297 Graph path uses ring (ds.cap) for SWA layers, while the eager path caps at c.n_swa The eager path computes…
2 🟠 High Correctness device.rs:1222 verify_mode GPU-resident expert path deleted; verify now shares the batch FFN path The removed block computed…
3 🟠 High Correctness device.rs:496 Graph key omits inputs the captured closure depends on beyond pos/64 The key hashes argmax, pos/64, sc_buf…
4 🟡 Medium Correctness device.rs:519 layer_ffn_gpu return value ignored inside the captured closure The decode loop branches on layer_ffn_gpu's…
5 🔵 Low Maintainability device.rs:1300 layer_attn duplicates the four ink_clip calls in graph and eager branches Both branches repeat the same…
6 🔵 Low Performance device.rs:494 Graph key rehashes per step and recaptures every 64 tokens The DefaultHasher runs over all slot addresses on…
7 🔵 Low Maintainability kernels.rs:2232 Pos-kernel test covers only one ring size and no SWA cap mismatch The new test fixes ring=100 and checks only…
Review details

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

Fix all with your agent
File: src/inkling2/forward/device.rs
Line: 1297
Symbol: layer_attn
Issue: Graph path uses ring (ds.cap) for SWA layers, while the eager path caps at c.n_swa The eager path computes SWA rows as min(pos+1, c.n_swa) and at as pos % c.n_swa. The graph path uses rows = min(pos+1, ring) and at = pos % ring, with ring = ds.cap. If ds.cap differs from c.n_swa, SWA attention reads a different window than the eager path. Output then depends on whether the step was captured, and K/V writes and attention reads can disagree on the ring slot.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 1222
Symbol: prefill_layer
Issue: verify_mode GPU-resident expert path deleted; verify now shares the batch FFN path The removed block computed per-token resident GPU experts, combined them with CPU experts using router weights, and wrote per-token results at acc_buf offset t*n. The new code writes one ffn_batch result at offset 0 for all verify tokens. If anything after the remaining 'if verify_mode' block still expects per-token accumulation, verify logits diverge from decode, or resident experts stop being used and verify slows down.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 496
Symbol: step_fast
Issue: Graph key omits inputs the captured closure depends on beyond pos/64 The key hashes argmax, pos/64, sc_buf, cur and slot K addresses. The closure captures pos for every layer_attn call, and the layer_ffn_gpu routing it records is data-dependent. If any captured value depends on pos outside the 64-token chunk, or on routing that changes between steps, a replayed graph computes with stale values. The 48-bit hash truncation also allows collisions that replay the wrong graph.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 519
Symbol: step_fast
Issue: layer_ffn_gpu return value ignored inside the captured closure The decode loop branches on layer_ffn_gpu's return value, but the graph closure discards it with '?'. If that bool records a host-side fallback decision, the captured graph freezes whichever path ran during capture, and every later replay repeats it even when the decision would change.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 1300
Symbol: layer_attn
Issue: layer_attn duplicates the four ink_clip calls in graph and eager branches Both branches repeat the same four-step clip sequence with only the _pos or _n variant and the position source changed. A future change to one branch, such as a new clip parameter, can be missed in the other, causing the two paths to diverge silently. Factoring out a helper that takes the position source would keep them in sync.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 494
Symbol: step_fast
Issue: Graph key rehashes per step and recaptures every 64 tokens The DefaultHasher runs over all slot addresses on every decode step. Because the key includes pos/64, a new graph is captured every 64 positions. Each capture re-records the whole layer stack, which adds latency and build cost, while the stable pos buffer alone would have let one graph serve every position up to the ring size.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: tests/kernels.rs
Line: 2232
Symbol: tensor_scale_applies_to_all_gpu_ops
Issue: Pos-kernel test covers only one ring size and no SWA cap mismatch The new test fixes ring=100 and checks only K/V clip and attention. It never exercises an SWA layer whose cap differs from n_swa, never runs the Device graph replay across a 64-token boundary, and never covers quantized KV through ink_clip_pos. The SWA mismatch above would pass CI undetected.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Note: 2 of 10 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/vulkan/spv/ink_attn.spv, src/vulkan/spv/ink_clip.spv.

Blast radius: 46 other file(s) depend on what this PR changes (15 directly, 31 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/backend.rs is imported by src/cpu_worker.rs, src/deepseek/mat.rs, src/expert_cache.rs, src/gpu_model.rs (+9 more)
  • src/vulkan/mod.rs is imported by src/lib.rs, src/vulkan/preflight.rs, tests/backend.rs, tests/common/mod.rs (+3 more)
  • src/cuda/mod.rs is imported by src/lib.rs, src/vulkan/preflight.rs, tests/common/mod.rs, tests/gpu_model.rs (+2 more)
  • src/inkling2/forward/device.rs is imported by src/inkling2/forward.rs

Indirectly affected: examples/gguf_dump.rs, src/config.rs, src/cpu_moe.rs, src/deepseek/chat.rs, src/deepseek/forward.rs, src/deepseek/mod.rs (+25 more)

@Vasyl-Trefilov
Vasyl-Trefilov merged commit 0359cc2 into RustingStudio:main Nov 22, 2026
6 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

@ybenyedder Merged, ty. Two notes:

  • Part 1 (batched draft check of the layers outside VRAM) was on main already (44e63c5, one commit after your base), so the merge keeps main's version there.
  • Part 2 (graph for step_fast): one fix on top. A new graph was recorded every 64 positions and none was freed. On CUDA a graph holds about 17 MiB of VRAM and the backend stops recording at 32, so after position 2048 the decode ran without graphs. Now one graph per kind of step stays (Backend::graph_drop).

RTX 3060 12 GB, Inkling-2-Mini-UD-IQ2_XXS.gguf (whole model in VRAM), decode tok/s without / with the graph:

  • CUDA, 3000 tokens: 46.2 / 52.6 (your branch as sent: 46.1, and 0.5 GB more VRAM).
  • Vulkan, 1000 tokens: 50.5 / 54.9.

The text of a greedy run is identical with and without the graph on both backends. A file that does not fit in VRAM does not take this path, so its speed is unchanged.

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