Skip to content

inkling2: support mainline llama.cpp DSpark GGUF schema (markov_w2, ctx_mix, per-slot mask_embd) - #90

Merged
Vasyl-Trefilov merged 3 commits into
RustingStudio:mainfrom
ybenyedder:feat/dspark-mainline-schema
Nov 24, 2026
Merged

Vasyl-Trefilov merged 3 commits into
RustingStudio:mainfrom
ybenyedder:feat/dspark-mainline-schema

Conversation

@ybenyedder

Copy link
Copy Markdown
Contributor

Unsloth updated unsloth/Inkling-2-Mini-GGUF/dspark-Inkling-2-Mini-Q8_0.gguf today (2026-11-23) to match mainline llama.cpp tensor names and head layout, which caused DsparkDrafter::open to fail with dspark: missing tensor dspark_fuse.weight.

This PR adds support for the updated mainline DSpark schema while remaining backward-compatible with earlier Unsloth DSpark files:

  • Per-layer blk.{il}.ctx_mix.weight / blk.{il}.ctx_norm.weight and markov_ctx_mix.weight / markov_ctx_norm.weight (fallback for dspark_fuse.weight, blk.{il}.dflare_norm.weight, dspark_norm.weight).
  • Optional token_embd_norm.weight applied to raw target token embeddings via Inkling2Model::embed_raw.
  • Per-position mask_embd.weight ([n_embd, block_size - 1]) in addition to single-vector mask_embd.
  • markov_w2.weight + markov_w2.bias low-rank logit delta head added onto one batched Inkling2Model::lm_head_batch (Device::lm_head_batch) projection of hidden[1..=count].

Verification

  • cargo test --release --lib --locked (all tests pass)
  • rustingstrata bench on Radeon 890M Vulkan with updated Inkling-2-Mini-UD-IQ3_XXS.gguf + updated dspark-Inkling-2-Mini-Q8_0.gguf: 46/51 (90.2%) drafts accepted, pp 128: 128.9 tok/s, tg 64: 13.9 tok/s.

@aletheore

aletheore Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["dspark.rs"]
    n1["forward.rs"]
    n2["chat.rs"]
    n3["mod.rs"]
    n4["main.rs"]
    n5["vision.rs"]
    n0 --> n3
    n1 --> n2
    n1 --> n3
    n1 --> n4
    n1 --> n5
    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 dependent
    class n3 dependent
    class n4 dependent
    class n5 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/inkling2/dspark.rs · modified · +148/-26 · +2 classes · 1 other dependent
  • src/inkling2/forward.rs · modified · +51/-0 · +6 functions · 4 other dependents
  • src/inkling2/forward/device.rs · modified · +56/-0 · +3 functions

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +2
  • Commits: 3

Comment thread src/inkling2/dspark.rs Outdated
joint_in[r..2 * r].copy_from_slice(&prev_embd);
joint_in[2 * r..2 * r + n].copy_from_slice(h_row);

self.joint_proj.matvec(&joint_in, &mut joint);

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🟠 High · Correctness · 1 of 9

Logits-head argmax silently ignores vocab tokens past min(n_vocab, w2.rows, bias.len()) If markov_w2.bias or markov_w2.weight has fewer rows than cfg.n_vocab, nv is truncated and tokens at index >= nv can never be drafted. Nothing validates bias.len() or w2.rows against n_vocab at load time, so a malformed or differently sized GGUF yields silently wrong drafts instead of an error.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 470
Issue: Logits-head argmax silently ignores vocab tokens past min(n_vocab, w2.rows, bias.len()) If markov_w2.bias or markov_w2.weight has fewer rows than cfg.n_vocab, nv is truncated and tokens at index >= nv can never be drafted. Nothing validates bias.len() or w2.rows against n_vocab at load time, so a malformed or differently sized GGUF yields silently wrong drafts instead of an error.
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/inkling2/dspark.rs Outdated
for step in 0..count {
let h_row = &hidden[(step + 1) * n..(step + 2) * n];
self.markov_w1.row_into(prev as usize, &mut prev_embd);
joint_in[..r].copy_from_slice(&state);

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🟠 High · Correctness · 2 of 9

Markov delta added to pre-softcap logits may not match mainline's argmax lm_head_batch returns logits before softcap, and the code adds delta and bias to those. If mainline applies the markov delta after softcap, the argmax can differ on near-tied tokens, lowering draft acceptance without any error.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 466
Issue: Markov delta added to pre-softcap logits may not match mainline's argmax lm_head_batch returns logits before softcap, and the code adds delta and bias to those. If mainline applies the markov delta after softcap, the argmax can differ on near-tied tokens, lowering draft acceptance without any error.
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/inkling2/dspark.rs
};
let mask_embd = f32s(g_ref, "mask_embd.weight")?;
let output_norm = f32s(g_ref, "output_norm.weight")?;
let joint_proj = host_mat(g_ref, "joint_proj.weight")?;

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🟠 High · Correctness · 3 of 9

w2 column count is never checked against the latent rank w2.matvec(&latent, &mut delta) assumes w2.cols equals rank. A GGUF whose markov_w2.weight has a different inner dimension panics on a slice or shape assert during drafting rather than failing at load.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 160
Symbol: open
Issue: w2 column count is never checked against the latent rank w2.matvec(&latent, &mut delta) assumes w2.cols equals rank. A GGUF whose markov_w2.weight has a different inner dimension panics on a slice or shape assert during drafting rather than failing at load.
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/inkling2/dspark.rs
if let Some(norm_w) = &self.token_embd_norm {
let mut emb = vec![0.0f32; n];
target.embed_raw(anchor_tok, &mut emb);
rms_norm_w(&emb, norm_w, self.eps, &mut inp[..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.

🟡 Medium · Correctness · 4 of 9

Per-position mask fallback silently reuses row 0 when mask_embd is short mask_embd with length between n and (bs-1)*n fails the per_pos_mask check and every mask position copies mask_embd[..n]. The per-slot mask embeddings the PR is meant to support are ignored with no error, so draft quality silently degrades.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 320
Symbol: draft
Issue: Per-position mask fallback silently reuses row 0 when mask_embd is short mask_embd with length between n and (bs-1)*n fails the per_pos_mask check and every mask position copies mask_embd[..n]. The per-slot mask embeddings the PR is meant to support are ignored with no error, so draft quality silently degrades.
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.


/// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU in one batched matvec
/// and return `[nt, c.n_vocab]` logits (before softcap).
pub(super) fn lm_head_batch(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result<Vec<f32>> {

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🟡 Medium · Correctness · 5 of 9

Device lm_head_batch unwraps the device lock and global handle dev::get().unwrap().lock().unwrap() panics if the global device is absent or a previous holder panicked and poisoned the mutex. The panic propagates out of drafting rather than falling back to the CPU path that lm_head_batch otherwise provides.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 693
Symbol: record_dspark_visit
Issue: Device lm_head_batch unwraps the device lock and global handle dev::get().unwrap().lock().unwrap() panics if the global device is absent or a previous holder panicked and poisoned the mutex. The panic propagates out of drafting rather than falling back to the CPU path that lm_head_batch otherwise provides.
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/inkling2/forward.rs Outdated
/// `[nt, cfg.n_vocab]` logits before softcap.
pub fn lm_head_batch(&mut self, h_rows: &[f32], nt: usize) -> Vec<f32> {
if let Some(mut d) = self.device.take() {
let res = d.lm_head_batch(self, h_rows, nt);

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🟡 Medium · Correctness · 6 of 9

Silent GPU error swallowing in lm_head_batch fallback if let Ok(v) = res discards any GPU error and quietly recomputes on CPU. A broken GPU path shows up only as a large slowdown in drafting, with nothing logged to diagnose it.

Prompt for your AI agent
File: src/inkling2/forward.rs
Line: 596
Symbol: lm_head_argmax
Issue: Silent GPU error swallowing in lm_head_batch fallback if let Ok(v) = res discards any GPU error and quietly recomputes on CPU. A broken GPU path shows up only as a large slowdown in drafting, with nothing logged to diagnose it.
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/inkling2/forward.rs
/// Look up `tok` in `tok_embd` and RMS-normalize with `tok_norm` (`cfg.eps`), writing `out` (`[n_embd]`).
pub fn embed_raw(&self, tok: u32, out: &mut [f32]) {
assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary");
self.tok_embd.row_into(tok as usize, out);

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🔵 Low · Maintainability · 7 of 9

Doc comment now sits on embed_raw; embed_normed lost its doc The existing doc for embed_normed is now above the new embed_raw, so embed_raw documents RMS normalization it does not perform and embed_normed is undocumented. Readers and generated docs get the wrong contract.

Prompt for your AI agent
File: src/inkling2/forward.rs
Line: 582
Symbol: embed_normed
Issue: Doc comment now sits on embed_raw; embed_normed lost its doc The existing doc for embed_normed is now above the new embed_raw, so embed_raw documents RMS normalization it does not perform and embed_normed is undocumented. Readers and generated docs get the wrong contract.
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/inkling2/dspark.rs
weight.matvec(&latent, &mut corr);
for ((c, &b), &h_v) in corr.iter_mut().zip(bias).zip(h_row) {
*c = *c + b + h_v;
}

@aletheore aletheore Bot Nov 23, 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 64ded698e2cf.


🔵 Low · Maintainability · 8 of 9

Joint-state update loop is duplicated across both head arms The GRU-style state update and the joint projection are copied verbatim in both match arms. A future fix to one path, such as the gate or the bias, will be missed in the other and the two heads will diverge.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 453
Issue: Joint-state update loop is duplicated across both head arms The GRU-style state update and the joint projection are copied verbatim in both match arms. A future fix to one path, such as the gate or the bias, will be missed in the other and the two heads will diverge.
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/inkling2/forward.rs
}
}
let rows: Vec<&[f32]> = h_rows.chunks_exact(self.cfg.n_embd).take(nt).collect();
let raw = matvec_rows(&self.output, &rows);

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

Logit trimming duplicates logic in device.rs and the single-row head The chunks_exact plus n_vocab truncation is repeated in forward.rs and device.rs, and the batch CPU path does not reuse the existing single-row lm_head projection. Any change to the vocab-slicing rule has to be made in several places.

Prompt for your AI agent
File: src/inkling2/forward.rs
Line: 603
Symbol: lap
Issue: Logit trimming duplicates logic in device.rs and the single-row head The chunks_exact plus n_vocab truncation is repeated in forward.rs and device.rs, and the batch CPU path does not reuse the existing single-row lm_head projection. Any change to the vocab-slicing rule has to be made in several places.
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 23, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR refactors the DSpark drafter in the inkling2 model so the Markov step is shared between the CPU and GPU draft paths, and it adds bounds checks and error handling for the markov_w2 argmax and LM head GPU calls (replacing unwraps and lock panics with contextual errors). It also adds a bias_len parameter and clamps the vocabulary intersection to the bias length, which is meant to make the drafter accept GGUF files following mainline llama.cpp's DSpark schema.

Merge confidence Review effort Merge risk
3 / 5 2 / 5 Medium
Area Files Lines
src/inkling2 3 +70 −89

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

# Severity Category Where
1 🔵 Low Performance dspark.rs:509 CPU fallback now bypasses the device LM head, so the device path is never tried. Previously the non-GPU…
2 🔵 Low Performance dspark.rs:509 GPU failure mid-batch recomputes the full vocab projection on CPU and discards GPU logits. lm_head_batch_gpu…
3 🟠 High Correctness dspark.rs:507 GPU errors are swallowed and use_gpu latches off for the rest of the batch. markov_w2_argmax_gpu maps every…
4 🟡 Medium Correctness device.rs:712 ensure! on empty vocab is pointless because its error is discarded by .ok(). If bias is empty, bias_len is 0…
5 🟡 Medium Correctness dspark.rs:514 CPU argmax with nv == 0 silently returns token 0 for all drafts. When the bias or w2 is empty, the loop body…
6 🟡 Medium Correctness device.rs:712 ensure! may not be in scope in this module. The diff uses .context and anyhow::anyhow! but adds a bare…
- 🟡 Medium Correctness dspark.rs:320 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:603 Earlier finding, still open
- 🟠 High Correctness dspark.rs:465 Earlier finding, still open
- 🟡 Medium Correctness device.rs:713 Earlier finding, still open
- 🔵 Low Performance dspark.rs:483 Earlier finding, still open
Review details

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

Fix all with your agent
File: src/inkling2/dspark.rs
Line: 509
Issue: CPU fallback now bypasses the device LM head, so the device path is never tried. Previously the non-GPU branch called target.lm_head_batch, which tried the device first and fell back to CPU. Now cpu_base always calls lm_head_batch_cpu. When gpu_w2 is None or lm_head_batch_gpu returns false, the output projection runs entirely on CPU even when a GPU device exists, which is a large slowdown for a 128-token prefill and the per-step decode path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/dspark.rs
Line: 509
Issue: GPU failure mid-batch recomputes the full vocab projection on CPU and discards GPU logits. lm_head_batch_gpu succeeds and fills logits_buf, then markov_w2_argmax_gpu fails on step k. The code falls back to lm_head_batch_cpu over all count rows, duplicating a full [count, n_vocab] matmul that the GPU already performed. A transient GPU error therefore costs an extra full CPU LM-head pass per draft batch.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/dspark.rs
Line: 507
Issue: GPU errors are swallowed and use_gpu latches off for the rest of the batch. markov_w2_argmax_gpu maps every error (lock poisoning, missing pf, kernel failure) to None via .ok(). The first failure silently sets use_gpu = false for the whole batch, so the GPU is never retried and the cause is never logged. Benchmarks can then report CPU-speed numbers with no visible indication that the GPU path was abandoned.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 712
Symbol: prefill_chunk_seq
Issue: ensure! on empty vocab is pointless because its error is discarded by .ok(). If bias is empty, bias_len is 0 and nv becomes 0. The ensure! fails, the wrapper converts that to None, and the CPU loop runs with nv = 0. best_i stays 0, so every draft is token 0 with no error. The check adds nothing and the real problem is silent.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/dspark.rs
Line: 514
Issue: CPU argmax with nv == 0 silently returns token 0 for all drafts. When the bias or w2 is empty, the loop body never runs, best_i keeps its initial 0, and prev = 0 is pushed for every step. Downstream acceptance then fails silently, with no error signal pointing at the bad weights.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward/device.rs
Line: 712
Symbol: prefill_chunk_seq
Issue: ensure! may not be in scope in this module. The diff uses .context and anyhow::anyhow! but adds a bare ensure! macro. If the module does not import anyhow::ensure, the crate fails to compile, which the PR's green test claim would not reflect for this file.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 52 other file(s) depend on what this PR changes (4 directly, 48 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/inkling2/forward.rs is imported by src/inkling2/chat.rs, src/inkling2/mod.rs, src/main.rs, tests/vision.rs
  • src/inkling2/dspark.rs is imported by src/inkling2/mod.rs

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

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

Comment thread src/inkling2/dspark.rs Outdated
if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, bias_addr, &latent, step) {
prev = id;
drafts.push(prev);
} else {

@aletheore aletheore Bot Nov 23, 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 22467e5a95de.


🟠 High · Correctness · 1 of 7

A failed GPU argmax step silently truncates the draft instead of falling back to CPU for the remaining steps. If target.markov_w2_argmax_gpu returns None at step k (for example a transient Vulkan error), the loop breaks and returns only k drafts although count were requested. The caller gets fewer draft tokens than it expects, acceptance metrics are skewed, and no error is surfaced. Nothing falls back to the CPU path for the remaining steps.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 509
Issue: A failed GPU argmax step silently truncates the draft instead of falling back to CPU for the remaining steps. If target.markov_w2_argmax_gpu returns None at step k (for example a transient Vulkan error), the loop breaks and returns only k drafts although `count` were requested. The caller gets fewer draft tokens than it expects, acceptance metrics are skewed, and no error is surfaced. Nothing falls back to the CPU path for the remaining steps.
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/inkling2/forward/device.rs Outdated
) -> Result<u32> {
let c = &m.cfg;
let vrows = m.output.rows;
let nv = c.n_vocab.min(w2.rows);

@aletheore aletheore Bot Nov 23, 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 22467e5a95de.


🟠 High · Correctness · 2 of 7

nv is taken from vocab and w2.rows only, not bias.len(), so the GPU bias add can read past the uploaded bias buffer. The CPU path uses nv = min(n_vocab, w2.rows, bias.len()), but the GPU path uses min(n_vocab, w2.rows). If a GGUF has a bias tensor shorter than the vocabulary, be.add(s.logits, bias_addr, nv) reads beyond the bias allocation of bias.len()*4 bytes. The result is garbage logits or a device fault.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 712
Symbol: prefill_chunk_seq
Issue: nv is taken from vocab and w2.rows only, not bias.len(), so the GPU bias add can read past the uploaded bias buffer. The CPU path uses nv = min(n_vocab, w2.rows, bias.len()), but the GPU path uses min(n_vocab, w2.rows). If a GGUF has a bias tensor shorter than the vocabulary, be.add(s.logits, bias_addr, nv) reads beyond the bias allocation of bias.len()*4 bytes. The result is garbage logits or a device fault.
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/inkling2/dspark.rs
drafts.push(prev);
}
}
MarkovHead::Logits { w2, bias, gpu } => {

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

OnceLock caches a None from a transient init failure, permanently disabling the GPU markov head for this drafter. If the first call happens before the device is ready, or dev::get() or the mutex fails once, get_or_init stores None forever. Every later draft then silently uses the slow CPU path with no retry or warning, and the GPU speedup is lost for the drafter's lifetime.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 465
Issue: OnceLock caches a None from a transient init failure, permanently disabling the GPU markov head for this drafter. If the first call happens before the device is ready, or dev::get() or the mutex fails once, get_or_init stores None forever. Every later draft then silently uses the slow CPU path with no retry or warning, and the GPU speedup is lost for the drafter's lifetime.
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 c = &m.cfg;
let vrows = m.output.rows;
let nv = c.n_vocab.min(w2.rows);
let pf = self.pf.as_ref().context("lm_head_batch_gpu not called")?;

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

markov_w2_argmax_gpu uses unwrap on dev::get and the mutex, unlike the closure which uses ok()?, so it can panic on the hot path. If the device mutex is poisoned or the device is gone, dev::get().unwrap().lock().unwrap() panics inside draft generation. The OnceLock initializer handles the same condition by returning None, so the two paths disagree and a recoverable device error crashes the process.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 713
Symbol: prefill_chunk_seq
Issue: markov_w2_argmax_gpu uses unwrap on dev::get and the mutex, unlike the closure which uses ok()?, so it can panic on the hot path. If the device mutex is poisoned or the device is gone, dev::get().unwrap().lock().unwrap() panics inside draft generation. The OnceLock initializer handles the same condition by returning None, so the two paths disagree and a recoverable device error crashes the process.
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/inkling2/dspark.rs Outdated
});
let use_gpu = gpu_w2.is_some()
&& target.lm_head_batch_gpu(&hidden[n..(1 + count) * n], count);
if use_gpu {

@aletheore aletheore Bot Nov 23, 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 22467e5a95de.


🔵 Low · Maintainability · 5 of 7

The CPU and GPU branches duplicate the full markov step loop almost verbatim. The joint_proj, gate and state update is copied into both branches, so any future fix to the recurrence (e.g. the bias or clamp logic) must be applied twice or the two paths will diverge silently. Factoring out a per-step function that takes a closure for the argmax would remove the duplication.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 486
Issue: The CPU and GPU branches duplicate the full markov step loop almost verbatim. The joint_proj, gate and state update is copied into both branches, so any future fix to the recurrence (e.g. the bias or clamp logic) must be applied twice or the two paths will diverge silently. Factoring out a per-step function that takes a closure for the argmax would remove the duplication.
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/inkling2/dspark.rs Outdated
state[k] = cand + gate * (state[k] - cand);
latent[k] = joint[2 * r + k].tanh();
}

@aletheore aletheore Bot Nov 23, 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 22467e5a95de.


🔵 Low · Performance · 6 of 7

Each draft step does a synchronous upload, GEMV, add, argmax and readback, so the GPU path pays per-token round-trips. For count draft tokens, the code issues count separate put, gemvq, add, argmax and get sequences, each with a host-device sync. The batched lm_head already runs once, but the low-rank head is not batched, so the GPU path can end up slower than expected for larger draft counts.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 505
Issue: Each draft step does a synchronous upload, GEMV, add, argmax and readback, so the GPU path pays per-token round-trips. For count draft tokens, the code issues count separate put, gemvq, add, argmax and get sequences, each with a host-device sync. The batched lm_head already runs once, but the low-rank head is not batched, so the GPU path can end up slower than expected for larger draft counts.
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/inkling2/dspark.rs
let bias_buf = be.alloc(bias.len() * 4).ok()?;
be.put(bias, &bias_buf, 0).ok()?;
Some(MarkovW2Gpu { w2: w2_gpu, bias: bias_buf })
});

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 7

When the GPU path is skipped after gpu_w2 is Some, the CPU branch calls target.lm_head_batch, which re-attempts the GPU projection. If lm_head_batch_gpu fails, use_gpu is false and the CPU branch calls target.lm_head_batch, which runs lm_head_batch_gpu again before any CPU work. The failing GPU projection is executed twice per draft, wasting device time on every call while the GPU is broken.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 483
Issue: When the GPU path is skipped after gpu_w2 is Some, the CPU branch calls target.lm_head_batch, which re-attempts the GPU projection. If lm_head_batch_gpu fails, use_gpu is false and the CPU branch calls target.lm_head_batch, which runs lm_head_batch_gpu again before any CPU work. The failing GPU projection is executed twice per draft, wasting device time on every call while the GPU is broken.
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/inkling2/dspark.rs
}
use_gpu = false;
}
let base_all = cpu_base.get_or_insert_with(|| target.lm_head_batch_cpu(&hidden[n..(1 + count) * n], count));

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

CPU fallback now bypasses the device LM head, so the device path is never tried. Previously the non-GPU branch called target.lm_head_batch, which tried the device first and fell back to CPU. Now cpu_base always calls lm_head_batch_cpu. When gpu_w2 is None or lm_head_batch_gpu returns false, the output projection runs entirely on CPU even when a GPU device exists, which is a large slowdown for a 128-token prefill and the per-step decode path.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 509
Issue: CPU fallback now bypasses the device LM head, so the device path is never tried. Previously the non-GPU branch called target.lm_head_batch, which tried the device first and fell back to CPU. Now cpu_base always calls lm_head_batch_cpu. When gpu_w2 is None or lm_head_batch_gpu returns false, the output projection runs entirely on CPU even when a GPU device exists, which is a large slowdown for a 128-token prefill and the per-step decode 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/inkling2/dspark.rs
}
use_gpu = false;
}
let base_all = cpu_base.get_or_insert_with(|| target.lm_head_batch_cpu(&hidden[n..(1 + count) * n], count));

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

GPU failure mid-batch recomputes the full vocab projection on CPU and discards GPU logits. lm_head_batch_gpu succeeds and fills logits_buf, then markov_w2_argmax_gpu fails on step k. The code falls back to lm_head_batch_cpu over all count rows, duplicating a full [count, n_vocab] matmul that the GPU already performed. A transient GPU error therefore costs an extra full CPU LM-head pass per draft batch.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 509
Issue: GPU failure mid-batch recomputes the full vocab projection on CPU and discards GPU logits. lm_head_batch_gpu succeeds and fills logits_buf, then markov_w2_argmax_gpu fails on step k. The code falls back to lm_head_batch_cpu over all count rows, duplicating a full [count, n_vocab] matmul that the GPU already performed. A transient GPU error therefore costs an extra full CPU LM-head pass per draft batch.
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/inkling2/dspark.rs
drafts.push(prev);
continue;
}
use_gpu = false;

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 6

GPU errors are swallowed and use_gpu latches off for the rest of the batch. markov_w2_argmax_gpu maps every error (lock poisoning, missing pf, kernel failure) to None via .ok(). The first failure silently sets use_gpu = false for the whole batch, so the GPU is never retried and the cause is never logged. Benchmarks can then report CPU-speed numbers with no visible indication that the GPU path was abandoned.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 507
Issue: GPU errors are swallowed and use_gpu latches off for the rest of the batch. markov_w2_argmax_gpu maps every error (lock poisoning, missing pf, kernel failure) to None via .ok(). The first failure silently sets use_gpu = false for the whole batch, so the GPU is never retried and the cause is never logged. Benchmarks can then report CPU-speed numbers with no visible indication that the GPU path was abandoned.
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.

) -> Result<u32> {
let c = &m.cfg;
let vrows = m.output.rows;
let nv = c.n_vocab.min(w2.rows).min(bias_len);

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 6

ensure! on empty vocab is pointless because its error is discarded by .ok(). If bias is empty, bias_len is 0 and nv becomes 0. The ensure! fails, the wrapper converts that to None, and the CPU loop runs with nv = 0. best_i stays 0, so every draft is token 0 with no error. The check adds nothing and the real problem is silent.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 712
Symbol: prefill_chunk_seq
Issue: ensure! on empty vocab is pointless because its error is discarded by .ok(). If bias is empty, bias_len is 0 and nv becomes 0. The ensure! fails, the wrapper converts that to None, and the CPU loop runs with nv = 0. best_i stays 0, so every draft is token 0 with no error. The check adds nothing and the real problem is silent.
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/inkling2/dspark.rs
w2.matvec(&latent, &mut delta);
let base = &base_all[step * n_vocab..(step + 1) * n_vocab];
let (mut best_i, mut best_v) = (0usize, f32::NEG_INFINITY);
for i in 0..nv {

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

CPU argmax with nv == 0 silently returns token 0 for all drafts. When the bias or w2 is empty, the loop body never runs, best_i keeps its initial 0, and prev = 0 is pushed for every step. Downstream acceptance then fails silently, with no error signal pointing at the bad weights.

Prompt for your AI agent
File: src/inkling2/dspark.rs
Line: 514
Issue: CPU argmax with nv == 0 silently returns token 0 for all drafts. When the bias or w2 is empty, the loop body never runs, best_i keeps its initial 0, and prev = 0 is pushed for every step. Downstream acceptance then fails silently, with no error signal pointing at the bad weights.
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.

) -> Result<u32> {
let c = &m.cfg;
let vrows = m.output.rows;
let nv = c.n_vocab.min(w2.rows).min(bias_len);

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

ensure! may not be in scope in this module. The diff uses .context and anyhow::anyhow! but adds a bare ensure! macro. If the module does not import anyhow::ensure, the crate fails to compile, which the PR's green test claim would not reflect for this file.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 712
Symbol: prefill_chunk_seq
Issue: ensure! may not be in scope in this module. The diff uses .context and anyhow::anyhow! but adds a bare ensure! macro. If the module does not import anyhow::ensure, the crate fails to compile, which the PR's green test claim would not reflect for this file.
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
Vasyl-Trefilov merged commit 80a6911 into RustingStudio:main Nov 24, 2026
5 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Merged, ty for the PR! I tested it on the 3060 with Inkling 2 Mini IQ4_NL: the old draft file accepts 19 of 33 drafts like before, the new one 18 of 39, and the output matches greedy (up to near ties).

After the merge I added a few checks at load (size of markov_w2, its bias and mask_embd) and removed the two lm_head_batch functions that nothing called (d8d681b).

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