Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 148 additions & 26 deletions src/inkling2/dspark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ struct DsparkLayer {
ffn_down: Mat<'static>,
}

struct MarkovW2Gpu {
w2: crate::backend::GpuTensor,
bias: crate::backend::Buf,
}

enum MarkovHead {
/// Legacy Unsloth DSpark: projects `latent` (`[rank]`) to hidden space (`[n_embd]`), adds `h_row`, then runs target LM head.
HiddenOut { weight: Mat<'static>, bias: Vec<f32> },
/// Mainline llama.cpp DSpark: adds low-rank logit delta `markov_w2 @ latent + bias` onto batched target LM head logits.
Logits { w2: Mat<'static>, bias: Vec<f32>, gpu: std::sync::OnceLock<Option<MarkovW2Gpu>> },
}

pub struct DsparkDrafter {
pub n_layer: usize,
pub n_embd: usize,
Expand All @@ -52,13 +64,13 @@ pub struct DsparkDrafter {
pub target_layers: [usize; 4],
fuse: Vec<f32>,
dspark_norm: Vec<f32>,
token_embd_norm: Option<Vec<f32>>,
mask_embd: Vec<f32>,
output_norm: Vec<f32>,
markov_w1: Mat<'static>,
joint_proj: Mat<'static>,
joint_proj_b: Vec<f32>,
hidden_out: Mat<'static>,
hidden_out_b: Vec<f32>,
markov_head: MarkovHead,
layers: Vec<DsparkLayer>,
k_cache: Vec<Vec<f32>>,
v_cache: Vec<Vec<f32>>,
Expand Down Expand Up @@ -122,24 +134,62 @@ impl DsparkDrafter {

let markov_w1 = host_mat(g_ref, "markov_w1.weight")?;
let rank = markov_w1.cols;
let fuse = f32s(g_ref, "dspark_fuse.weight")?;
ensure!(fuse.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", fuse.len(), 4 * (n_layer + 1));
let dspark_norm = f32s(g_ref, "dspark_norm.weight")?;
let fuse = if g_ref.tensors.contains_key("dspark_fuse.weight") {
let f = f32s(g_ref, "dspark_fuse.weight")?;
ensure!(f.len() == 4 * (n_layer + 1), "dspark_fuse.weight len {} != {}", f.len(), 4 * (n_layer + 1));
f
} else {
let mut f = Vec::with_capacity(4 * (n_layer + 1));
for il in 0..n_layer {
let row = f32s(g_ref, &format!("blk.{il}.ctx_mix.weight"))?;
ensure!(row.len() == 4, "blk.{il}.ctx_mix.weight len {} != 4", row.len());
f.extend_from_slice(&row);
}
let row = f32s(g_ref, "markov_ctx_mix.weight")?;
ensure!(row.len() == 4, "markov_ctx_mix.weight len {} != 4", row.len());
f.extend_from_slice(&row);
f
};
let dspark_norm = if g_ref.tensors.contains_key("dspark_norm.weight") {
f32s(g_ref, "dspark_norm.weight")?
} else {
f32s(g_ref, "markov_ctx_norm.weight")?
};
let token_embd_norm = if g_ref.tensors.contains_key("token_embd_norm.weight") {
Some(f32s(g_ref, "token_embd_norm.weight")?)
} else {
None
};
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.

let joint_proj_b = f32s(g_ref, "joint_proj.bias")?;
let hidden_out = host_mat(g_ref, "dspark_hidden_out.weight")?;
let hidden_out_b = f32s(g_ref, "dspark_hidden_out.bias")?;
let markov_head = if g_ref.tensors.contains_key("markov_w2.weight") {
MarkovHead::Logits {
w2: host_mat(g_ref, "markov_w2.weight")?,
bias: f32s(g_ref, "markov_w2.bias")?,
gpu: std::sync::OnceLock::new(),
}
} else {
MarkovHead::HiddenOut {
weight: host_mat(g_ref, "dspark_hidden_out.weight")?,
bias: f32s(g_ref, "dspark_hidden_out.bias")?,
}
};

let mut layers = Vec::with_capacity(n_layer);
for il in 0..n_layer {
let p = |s: &str| format!("blk.{il}.{s}");
let m = |s: &str| Mat::load(g_ref, &p(s));
let v = |s: &str| f32s(g_ref, &p(s));
let dflare_norm = if g_ref.tensors.contains_key(&p("dflare_norm.weight")) {
v("dflare_norm.weight")?
} else {
v("ctx_norm.weight")?
};
layers.push(DsparkLayer {
swa: swa[il],
dflare_norm: v("dflare_norm.weight")?,
dflare_norm,
attn_k_ctx: m("attn_k_ctx.weight")?,
attn_v_ctx: m("attn_v_ctx.weight")?,
attn_k_ctx_norm: v("attn_k_ctx_norm.weight")?,
Expand Down Expand Up @@ -172,13 +222,13 @@ impl DsparkDrafter {
target_layers,
fuse,
dspark_norm,
token_embd_norm,
mask_embd,
output_norm,
markov_w1,
joint_proj,
joint_proj_b,
hidden_out,
hidden_out_b,
markov_head,
layers,
k_cache: vec![Vec::new(); n_layer],
v_cache: vec![Vec::new(); n_layer],
Expand Down Expand Up @@ -270,9 +320,17 @@ impl DsparkDrafter {

// 1. Build 8-token input: slot 0 is normed target token embedding of `anchor_tok`, slots 1..8 are `mask_embd`.
let mut inp = vec![0.0f32; bs * n];
target.embed_normed(anchor_tok, &mut inp[..n]);
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.

} else {
target.embed_normed(anchor_tok, &mut inp[..n]);
}
let per_pos_mask = self.mask_embd.len() >= (bs - 1) * n;
for i in 1..bs {
inp[i * n..(i + 1) * n].copy_from_slice(&self.mask_embd);
let src = if per_pos_mask { &self.mask_embd[(i - 1) * n..i * n] } else { &self.mask_embd[..n] };
inp[i * n..(i + 1) * n].copy_from_slice(src);
}

// 2. Run the 3 non-causal DSpark transformer layers over the 8-token block.
Expand Down Expand Up @@ -372,34 +430,98 @@ impl DsparkDrafter {
joint_in[2 * r + n..].copy_from_slice(ctx_feat);
let mut joint = vec![0.0f32; 3 * r];
let mut latent = vec![0.0f32; r];
let mut corr = vec![0.0f32; n];
let mut prev = anchor_tok;
let mut drafts = Vec::with_capacity(count);

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);
joint_in[r..2 * r].copy_from_slice(&prev_embd);
let markov_step = |prev_tok: u32,
h_row: &[f32],
state: &mut [f32],
prev_embd: &mut [f32],
joint_in: &mut [f32],
joint: &mut [f32],
latent: &mut [f32]| {
self.markov_w1.row_into(prev_tok as usize, prev_embd);
joint_in[..r].copy_from_slice(state);
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);
self.joint_proj.matvec(joint_in, joint);
for (v, &b) in joint.iter_mut().zip(&self.joint_proj_b) { *v += b; }

for k in 0..r {
let gate = crate::ops::sigmoid(joint[k]);
let cand = joint[r + k].tanh();
state[k] = cand + gate * (state[k] - cand);
latent[k] = joint[2 * r + k].tanh();
}
};

self.hidden_out.matvec(&latent, &mut corr);
for ((c, &b), &h_v) in corr.iter_mut().zip(&self.hidden_out_b).zip(h_row) {
*c = *c + b + h_v;
match &self.markov_head {
MarkovHead::HiddenOut { weight, bias } => {
let mut corr = vec![0.0f32; n];
for step in 0..count {
let h_row = &hidden[(step + 1) * n..(step + 2) * n];
markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent);
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.

prev = target.lm_head_argmax(&corr);
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 gpu_w2 = gpu.get_or_init(|| {
if w2.rows > target.output_rows() || w2.cols > n {
return None;
}
let dm = crate::deepseek::mat::dev::get()?;
let d = dm.lock().ok()?;
let be = &*d.parts[0].be;
let w2_gpu = be.upload(&crate::weights::Tensor {
ty: w2.ty,
rows: w2.rows,
cols: w2.cols,
data: w2.data,
scale: w2.scale,
}).ok()?;
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.

let mut use_gpu = gpu_w2.is_some()
&& target.lm_head_batch_gpu(&hidden[n..(1 + count) * n], count);
let mut cpu_base: Option<Vec<f32>> = None;
let mut delta = Vec::new();
let n_vocab = target.cfg.n_vocab;
let nv = n_vocab.min(w2.rows).min(bias.len());

prev = target.lm_head_argmax(&corr);
drafts.push(prev);
for step in 0..count {
let h_row = &hidden[(step + 1) * n..(step + 2) * n];
markov_step(prev, h_row, &mut state, &mut prev_embd, &mut joint_in, &mut joint, &mut latent);
if use_gpu {
let g = gpu_w2.as_ref().unwrap();
if let Some(id) = target.markov_w2_argmax_gpu(&g.w2, g.bias.addr(), bias.len(), &latent, step) {
prev = id;
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.

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

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.

if delta.is_empty() { delta.resize(w2.rows, 0.0); }
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.

let v = base[i] + delta[i] + bias[i];
if v > best_v {
best_v = v;
best_i = i;
}
}
prev = best_i as u32;
drafts.push(prev);
}
}
}
drafts
}
Expand Down
51 changes: 51 additions & 0 deletions src/inkling2/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,13 +577,64 @@ impl<'a> Inkling2Model<'a> {
}

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

}

pub fn embed_normed(&self, tok: u32, out: &mut [f32]) {
assert!((tok as usize) < self.tok_embd.rows, "token {tok} is outside the vocabulary");
let mut emb = vec![0.0f32; self.cfg.n_embd];
self.tok_embd.row_into(tok as usize, &mut emb);
rms_norm_w(&emb, &self.tok_norm, self.cfg.eps, out);
}

/// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on GPU, keeping the logits on device.
pub(super) fn lm_head_batch_gpu(&mut self, h_rows: &[f32], nt: usize) -> bool {
if let Some(mut d) = self.device.take() {
let ok = d.lm_head_batch_gpu(self, h_rows, nt).is_ok();
self.device = Some(d);
return ok;
}
false
}

/// Add `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID.
pub(super) fn markov_w2_argmax_gpu(
&self, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize,
) -> Option<u32> {
self.device.as_ref()?.markov_w2_argmax_gpu(self, w2, bias_addr, bias_len, latent, step).ok()
}

pub(super) fn output_rows(&self) -> usize { self.output.rows }

/// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head on CPU only.
pub(super) fn lm_head_batch_cpu(&self, h_rows: &[f32], nt: usize) -> Vec<f32> {
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.

if self.output.rows == self.cfg.n_vocab {
return raw;
}
let mut out = Vec::with_capacity(nt * self.cfg.n_vocab);
for row in raw.chunks_exact(self.output.rows) {
out.extend_from_slice(&row[..self.cfg.n_vocab]);
}
out
}

/// Project `nt` hidden states (`[nt, n_embd]`) through the target LM head (`output.weight`) and return
/// `[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);
self.device = Some(d);
if let Ok(v) = res {
return v;
}
}
self.lm_head_batch_cpu(h_rows, nt)
}

/// Project a single hidden state `h` (`[n_embd]`) through the target LM head (`output.weight`) and return the
/// greedy argmax token ID (`0..cfg.n_vocab`) of the logits before the softcap. For drafts.
pub fn lm_head_argmax(&self, h: &[f32]) -> u32 {
Expand Down
56 changes: 56 additions & 0 deletions src/inkling2/forward/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,62 @@ impl Device {
Ok(id)
}

/// Project `nt` hidden vectors (`[nt, n_embd]`) through the target's LM head on GPU into `pf.logits_buf`
/// (`[nt, m.output.rows]`), keeping the logits on device for `markov_w2_argmax_gpu`.
pub(super) fn lm_head_batch_gpu(&mut self, m: &Inkling2Model, h_rows: &[f32], nt: usize) -> Result<()> {
let c = &m.cfg;
let vrows = m.output.rows;
let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?;
let be = &*d.parts[0].be;
self.ensure_pf(be, c, vrows, nt)?;
let pf = self.pf.as_ref().unwrap();
let o = pf.buf.addr();
be.put(h_rows, &pf.buf, ((pf.p.hn - o) / 4) as usize)?;
be.gemvq(d.tensor(m.output.gpu.context("output.weight not on GPU")?), pf.p.hn, c.n_embd, 0, pf.logits_buf.addr(), vrows, nt)?;
Ok(())
}

/// Add low-rank `w2 @ latent + bias` onto `pf.logits_buf[step]` on GPU and return the argmax token ID.
pub(super) fn markov_w2_argmax_gpu(
&self, m: &Inkling2Model, w2: &crate::backend::GpuTensor, bias_addr: u64, bias_len: usize, latent: &[f32], step: usize,
) -> 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.

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.

ensure!(nv > 0, "markov_w2: empty vocabulary intersection");
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.

let (s, o) = (self.s, self.scr.addr());
let d = dev::get().context("no GPU device")?.lock().map_err(|_| anyhow::anyhow!("GPU device lock poisoned"))?;
let be = &*d.parts[0].be;
be.put(latent, &self.scr, ((s.hn - o) / 4) as usize)?;
be.gemvq(w2, s.hn, w2.cols, 0, s.logits, w2.rows, 1)?;
be.add(s.logits, pf.logits_buf.addr() + (step * vrows * 4) as u64, nv)?;
be.add(s.logits, bias_addr, nv)?;
be.argmax_rows(s.logits, nv, 1, s.amax)?;
let id = be.get::<i32>(&self.scr, ((s.amax - o) / 4) as usize, 1)?[0] as u32;
Ok(id)
}

/// 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>> {
let c = &m.cfg;
let vrows = m.output.rows;
self.lm_head_batch_gpu(m, h_rows, nt)?;
let d = dev::get().unwrap().lock().unwrap();
let be = &*d.parts[0].be;
let pf = self.pf.as_ref().unwrap();
let raw = be.get::<f32>(&pf.logits_buf, 0, nt * vrows)?;
if vrows == c.n_vocab {
return Ok(raw);
}
let mut out = Vec::with_capacity(nt * c.n_vocab);
for row in raw.chunks_exact(vrows) {
out.extend_from_slice(&row[..c.n_vocab]);
}
Ok(out)
}

fn record_dspark_visit(&self, visit: usize, cur_a: u64, nt: usize, n: usize) -> Result<()> {
let Some(k) = DSPARK_VISITS.iter().position(|&v| v == visit) else { return Ok(()) };
let d = dev::get().unwrap().lock().unwrap();
Expand Down
Loading