spec_accept_greedy + committed_prefix mirror strata ink_serve.h block-verify: row i feeds anchor (i=0) / draft[i-1] at cur_pos+i, greedy[i] predicts cur_pos+1+i; accept while argmax==draft[i], else emit correction (or bonus at i==nd); accepted=emit.len(); rollback keeps cur_pos+accepted; the correction's KV is deferred to the next round (becomes its anchor). Stop/length cap end the request mid-round. Lossless per proofs/speculative_draft.lean spec_lossless. CPU tests: all-accept+bonus, mid/first mismatch, stop, length cap, prefix. CPU -D warnings green.
746 lines
38 KiB
Rust
746 lines
38 KiB
Rust
//! DSpark drafter (MTP head) weight manifest, layout check and loader.
|
||
//!
|
||
//! Step 1 of the reviewer's drafter guide (review/2026-12-02-…): load
|
||
//! `mtp.safetensors` and validate its layout BEFORE any speculative kernel runs
|
||
//! (mirrors the reference `ink_dspark_layout_check`); a missing/mismatched file
|
||
//! disables the drafter gracefully instead of corrupting generation.
|
||
//!
|
||
//! The manifest/layout check is CPU-only (safe Rust, checked shapes); the GPU
|
||
//! upload (`load`) is behind the `hip` feature. QKV and gate/up are fused at
|
||
//! load time (reviewer tip) so the draft step issues one GEMM each.
|
||
|
||
use crate::SafetensorsArchive;
|
||
|
||
/// DSpark geometry (config.json `mtp_config`), validated against the manifest.
|
||
pub const DS_LAYERS: usize = 3;
|
||
pub const DS_HIDDEN: usize = 2304;
|
||
pub const DS_HEADS: usize = 24;
|
||
pub const DS_KV: usize = 8;
|
||
pub const DS_HD: usize = 128;
|
||
pub const DS_INTER: usize = 9216;
|
||
pub const DS_BLOCK: usize = 8;
|
||
pub const DS_MARKOV_RANK: usize = 256;
|
||
pub const DS_VOCAB_PAD: usize = 201024;
|
||
/// Target-layer taps [5, 23, 41, 48] (48 = post depth-mix + final norm).
|
||
pub const DS_TAPS: [usize; 4] = [5, 23, 41, 48];
|
||
/// Which drafter layers are SWA (local_layer_ids); the rest are global.
|
||
pub const DS_SWA_LAYERS: [usize; 2] = [0, 2];
|
||
|
||
/// Expected (name, shape) pairs for `mtp.safetensors` (all BF16).
|
||
pub fn expected_tensors() -> Vec<(String, Vec<u64>)> {
|
||
let mut v = vec![
|
||
("fuse_weight".to_string(), vec![4, 4]),
|
||
("markov_head.dflare_norm.weight".to_string(), vec![DS_HIDDEN as u64]),
|
||
("markov_head.markov_w1.weight".to_string(), vec![DS_VOCAB_PAD as u64, DS_MARKOV_RANK as u64]),
|
||
("markov_head.rnn_proj.weight".to_string(), vec![768, 5120]),
|
||
("markov_head.rnn_proj.bias".to_string(), vec![768]),
|
||
("markov_head.hidden_out.weight".to_string(), vec![DS_HIDDEN as u64, DS_MARKOV_RANK as u64]),
|
||
("markov_head.hidden_out.bias".to_string(), vec![DS_HIDDEN as u64]),
|
||
("mask_embed".to_string(), vec![DS_HIDDEN as u64]),
|
||
("norm.weight".to_string(), vec![DS_HIDDEN as u64]),
|
||
];
|
||
for il in 0..DS_LAYERS {
|
||
let p = format!("layers.{il}.");
|
||
let q = DS_HEADS * DS_HD; // 3072
|
||
let kv = DS_KV * DS_HD; // 1024
|
||
for (suf, shape) in [
|
||
("dflare_norm.weight", vec![DS_HIDDEN as u64]),
|
||
("input_layernorm.weight", vec![DS_HIDDEN as u64]),
|
||
("post_attention_layernorm.weight", vec![DS_HIDDEN as u64]),
|
||
("self_attn.q_norm.weight", vec![DS_HD as u64]),
|
||
("self_attn.k_norm.weight", vec![DS_HD as u64]),
|
||
("self_attn.k_norm_ctx.weight", vec![DS_HD as u64]),
|
||
("self_attn.q_proj.weight", vec![q as u64, DS_HIDDEN as u64]),
|
||
("self_attn.k_proj.weight", vec![kv as u64, DS_HIDDEN as u64]),
|
||
("self_attn.v_proj.weight", vec![kv as u64, DS_HIDDEN as u64]),
|
||
("self_attn.k_proj_ctx.weight", vec![kv as u64, DS_HIDDEN as u64]),
|
||
("self_attn.v_proj_ctx.weight", vec![kv as u64, DS_HIDDEN as u64]),
|
||
("self_attn.o_proj.weight", vec![DS_HIDDEN as u64, q as u64]),
|
||
("mlp.gate_proj.weight", vec![DS_INTER as u64, DS_HIDDEN as u64]),
|
||
("mlp.up_proj.weight", vec![DS_INTER as u64, DS_HIDDEN as u64]),
|
||
("mlp.down_proj.weight", vec![DS_HIDDEN as u64, DS_INTER as u64]),
|
||
] {
|
||
v.push((format!("{p}{suf}"), shape));
|
||
}
|
||
}
|
||
v
|
||
}
|
||
|
||
/// Validate that `ar` (opened on mtp.safetensors) carries exactly the expected
|
||
/// BF16 tensors with the expected shapes. Err => disable the drafter.
|
||
pub fn layout_check(ar: &SafetensorsArchive) -> Result<(), String> {
|
||
for (name, shape) in expected_tensors() {
|
||
let info = ar
|
||
.tensors
|
||
.get(&name)
|
||
.ok_or_else(|| format!("dspark layout: missing tensor '{name}'"))?;
|
||
if info.dtype != "BF16" {
|
||
return Err(format!("dspark layout: '{name}' dtype {} != BF16", info.dtype));
|
||
}
|
||
if info.shape != shape {
|
||
return Err(format!(
|
||
"dspark layout: '{name}' shape {:?} != {:?}",
|
||
info.shape, shape
|
||
));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(feature = "hip")]
|
||
mod gpu {
|
||
use super::*;
|
||
use crate::packer;
|
||
use vetta_infer_hip::DeviceBuf;
|
||
|
||
pub struct DsparkLayer {
|
||
pub dflare_norm: DeviceBuf,
|
||
pub input_ln: DeviceBuf,
|
||
pub post_ln: DeviceBuf,
|
||
pub q_norm: DeviceBuf,
|
||
pub k_norm: DeviceBuf,
|
||
pub k_norm_ctx: DeviceBuf,
|
||
/// fused [q;k;v] = [(24+8+8)*128, 2304] BF16 (f32 act × bf16 w GEMM)
|
||
pub qkv_w: DeviceBuf,
|
||
pub o_w: DeviceBuf,
|
||
/// fused [gate;up] = [2*9216, 2304] BF16
|
||
pub gate_up_w: DeviceBuf,
|
||
pub down_w: DeviceBuf,
|
||
pub k_ctx: DeviceBuf,
|
||
pub v_ctx: DeviceBuf,
|
||
}
|
||
|
||
pub struct DsparkWeights {
|
||
pub fuse_w: DeviceBuf,
|
||
pub layers: Vec<DsparkLayer>,
|
||
pub markov_dflare_norm: DeviceBuf,
|
||
pub markov_w1: DeviceBuf,
|
||
pub rnn_proj_w: DeviceBuf,
|
||
pub rnn_proj_b: DeviceBuf,
|
||
pub hidden_out_w: DeviceBuf,
|
||
pub hidden_out_b: DeviceBuf,
|
||
pub mask_embed: DeviceBuf,
|
||
pub norm: DeviceBuf,
|
||
}
|
||
|
||
/// Concatenate row-major BF16 matrices [rows_i, k] into one BF16 DeviceBuf
|
||
/// (raw byte concat; weights stay bf16 so f32-act × bf16-w GEMM is exact).
|
||
fn fuse_rows(ar: &SafetensorsArchive, names: &[&str]) -> Result<DeviceBuf, String> {
|
||
let mut raw = Vec::new();
|
||
for n in names {
|
||
let info = ar.tensors.get(*n).ok_or_else(|| format!("missing '{n}'"))?;
|
||
let mut b = vec![0u8; info.byte_len() as usize];
|
||
ar.read_slice(n, 0, &mut b)?;
|
||
raw.extend_from_slice(&b);
|
||
}
|
||
let buf = DeviceBuf::alloc_unpooled(raw.len())?;
|
||
buf.h2d_bytes(&raw)?;
|
||
Ok(buf)
|
||
}
|
||
|
||
impl DsparkWeights {
|
||
/// Load + fuse all drafter weights (resident, unpooled). Caller must
|
||
/// have passed `layout_check` first.
|
||
pub fn load(ar: &SafetensorsArchive) -> Result<Self, String> {
|
||
layout_check(ar)?;
|
||
let f = |n: &str| packer::load_bf16_as_f32(ar, n);
|
||
let r = |n: &str| packer::load_raw(ar, n);
|
||
let mut layers = Vec::with_capacity(DS_LAYERS);
|
||
for il in 0..DS_LAYERS {
|
||
let p = format!("layers.{il}.");
|
||
let qkv = fuse_rows(
|
||
ar,
|
||
&[
|
||
&format!("{p}self_attn.q_proj.weight"),
|
||
&format!("{p}self_attn.k_proj.weight"),
|
||
&format!("{p}self_attn.v_proj.weight"),
|
||
],
|
||
)?;
|
||
let gate_up = fuse_rows(
|
||
ar,
|
||
&[
|
||
&format!("{p}mlp.gate_proj.weight"),
|
||
&format!("{p}mlp.up_proj.weight"),
|
||
],
|
||
)?;
|
||
layers.push(DsparkLayer {
|
||
dflare_norm: f(&format!("{p}dflare_norm.weight"))?,
|
||
input_ln: f(&format!("{p}input_layernorm.weight"))?,
|
||
post_ln: f(&format!("{p}post_attention_layernorm.weight"))?,
|
||
q_norm: f(&format!("{p}self_attn.q_norm.weight"))?,
|
||
k_norm: f(&format!("{p}self_attn.k_norm.weight"))?,
|
||
k_norm_ctx: f(&format!("{p}self_attn.k_norm_ctx.weight"))?,
|
||
qkv_w: qkv,
|
||
o_w: r(&format!("{p}self_attn.o_proj.weight"))?,
|
||
gate_up_w: gate_up,
|
||
down_w: r(&format!("{p}mlp.down_proj.weight"))?,
|
||
k_ctx: r(&format!("{p}self_attn.k_proj_ctx.weight"))?,
|
||
v_ctx: r(&format!("{p}self_attn.v_proj_ctx.weight"))?,
|
||
});
|
||
}
|
||
Ok(Self {
|
||
fuse_w: f("fuse_weight")?,
|
||
layers,
|
||
markov_dflare_norm: f("markov_head.dflare_norm.weight")?,
|
||
markov_w1: r("markov_head.markov_w1.weight")?,
|
||
rnn_proj_w: r("markov_head.rnn_proj.weight")?,
|
||
rnn_proj_b: f("markov_head.rnn_proj.bias")?,
|
||
hidden_out_w: r("markov_head.hidden_out.weight")?,
|
||
hidden_out_b: f("markov_head.hidden_out.bias")?,
|
||
mask_embed: f("mask_embed")?,
|
||
norm: f("norm.weight")?,
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Build the DSpark context for M committed tokens from the 4 target taps.
|
||
/// Per drafter layer il: mix(row=il, dflare_norm_il) -> k/v_proj_ctx ->
|
||
/// per-head k_norm_ctx + NeoX half-RoPE -> k_out[il]/v_out[il] [M,kv_dim] f32.
|
||
/// Plus frnn = mix(row=3, markov_head.dflare_norm) -> frnn_out [M,D] f32.
|
||
/// (bf16 ring scatter is the caller's job; this produces the f32 values.)
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub fn dspark_context(
|
||
w: &DsparkWeights, taps: [&DeviceBuf; 4], pos: &DeviceBuf, m: i32,
|
||
k_out: [&DeviceBuf; 3], v_out: [&DeviceBuf; 3], frnn_out: &DeviceBuf,
|
||
eps: f32, theta: f32,
|
||
) -> Result<(), String> {
|
||
use vetta_infer_hip::{copy_f32, dspark_mix_taps, dspark_rmsnorm_rope, router_gemv_batched};
|
||
let d = DS_HIDDEN as i32;
|
||
let kv_dim = (DS_KV * DS_HD) as i32;
|
||
let ctx = DeviceBuf::alloc(m as usize * DS_HIDDEN * 4)?;
|
||
let kc = DeviceBuf::alloc(m as usize * kv_dim as usize * 4)?;
|
||
let vc = DeviceBuf::alloc(m as usize * kv_dim as usize * 4)?;
|
||
for il in 0..DS_LAYERS {
|
||
dspark_mix_taps(taps, &w.fuse_w, il as i32, &w.layers[il].dflare_norm, &ctx, m, d, eps)?;
|
||
router_gemv_batched(&ctx, &w.layers[il].k_ctx, &kc, kv_dim, d, m)?;
|
||
router_gemv_batched(&ctx, &w.layers[il].v_ctx, &vc, kv_dim, d, m)?;
|
||
dspark_rmsnorm_rope(&kc, &w.layers[il].k_norm_ctx, pos, theta, m, DS_KV as i32, DS_HD as i32, eps)?;
|
||
copy_f32(&kc, k_out[il], m as usize * kv_dim as usize)?;
|
||
copy_f32(&vc, v_out[il], m as usize * kv_dim as usize)?;
|
||
}
|
||
dspark_mix_taps(taps, &w.fuse_w, DS_LAYERS as i32, &w.markov_dflare_norm, frnn_out, m, d, eps)?;
|
||
Ok(())
|
||
}
|
||
|
||
/// Full DSpark block-8 draft (Step 1, linear). Given the committed context
|
||
/// rings (bf16) + frnn, produce `n_draft` speculative token ids after
|
||
/// `anchor_tok` at `anchor_pos`. Trunk embed/unembed are passed in (bf16).
|
||
/// Lossless by construction (proofs/speculative_draft.lean): the trunk verify
|
||
/// step (b5) accepts/rejects; this only proposes.
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub fn dspark_draft(
|
||
w: &DsparkWeights, embed: &DeviceBuf, embed_norm: &DeviceBuf, unembed: &DeviceBuf,
|
||
ctx_k: [&DeviceBuf; 3], ctx_v: [&DeviceBuf; 3], frnn: &DeviceBuf,
|
||
anchor_tok: i32, anchor_pos: i32, n_draft: i32, ctx_cap: i32, frnn_cap: i32,
|
||
swa_win: i32, eps: f32, theta: f32, vocab: i32, out_ids: &mut [i32],
|
||
) -> Result<(), String> {
|
||
use vetta_infer_hip as hip;
|
||
let d = DS_HIDDEN; let hd = DS_HD; let h = DS_HEADS; let kv = DS_KV;
|
||
let q_dim = h * hd; let kv_dim = kv * hd; let inter = DS_INTER; let rank = DS_MARKOV_RANK;
|
||
let b = DS_BLOCK as i32;
|
||
let scale = 1.0f32 / (hd as f32).sqrt();
|
||
let al = |n: usize| DeviceBuf::alloc(n * 4);
|
||
// cur[B,D]: slot0 = rms(embed(anchor)), slots 1..B-1 = mask_embed.
|
||
let cur = al(b as usize * d)?;
|
||
let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&anchor_tok.to_le_bytes())?;
|
||
let emb0 = al(d)?;
|
||
hip::embed_bf16_gather(embed, &tok, &emb0, 1, d as i32, vocab)?;
|
||
hip::rms_norm_f32(&emb0, Some(embed_norm), &emb0, 1, d as i32, eps)?;
|
||
hip::copy_f32_at(&emb0, &cur, 0, d)?;
|
||
for i in 1..b as usize { hip::copy_f32_at(&w.mask_embed, &cur, i * d, d)?; }
|
||
let pos: Vec<i32> = (0..b).map(|i| anchor_pos + i).collect();
|
||
let dpos = DeviceBuf::alloc(pos.len() * 4)?;
|
||
dpos.h2d_bytes(&pos.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
|
||
let res = al(b as usize * d)?; let hn = al(b as usize * d)?;
|
||
let qkv = al(b as usize * (q_dim + 2 * kv_dim))?;
|
||
let q = al(b as usize * q_dim)?; let kd = al(b as usize * kv_dim)?; let vd = al(b as usize * kv_dim)?;
|
||
let attn = al(b as usize * q_dim)?; let o = al(b as usize * d)?;
|
||
let gu = al(b as usize * 2 * inter)?; let g = al(b as usize * inter)?; let u = al(b as usize * inter)?; let mg = al(b as usize * inter)?;
|
||
for il in 0..DS_LAYERS {
|
||
let lw = &w.layers[il];
|
||
hip::copy_f32(&cur, &res, b as usize * d)?;
|
||
hip::rms_norm_f32(&cur, Some(&lw.input_ln), &hn, b, d as i32, eps)?;
|
||
hip::router_gemv_batched(&hn, &lw.qkv_w, &qkv, (q_dim + 2 * kv_dim) as i32, d as i32, b)?;
|
||
hip::dspark_split3(&qkv, &q, &kd, Some(&vd), b, q_dim as i32, kv_dim as i32, kv_dim as i32)?;
|
||
hip::dspark_rmsnorm_rope(&q, &lw.q_norm, &dpos, theta, b, h as i32, hd as i32, eps)?;
|
||
hip::dspark_rmsnorm_rope(&kd, &lw.k_norm, &dpos, theta, b, kv as i32, hd as i32, eps)?;
|
||
let is_swa = DS_SWA_LAYERS.contains(&il);
|
||
let c0 = if is_swa { (anchor_pos - swa_win + 1).max(0) } else { 0 };
|
||
let c_len = anchor_pos - c0;
|
||
hip::dspark_block_attn(&q, &kd, &vd, ctx_k[il], ctx_v[il], &attn, b, h as i32, kv as i32, hd as i32, c0, c_len, ctx_cap, scale)?;
|
||
hip::router_gemv_batched(&attn, &lw.o_w, &o, d as i32, q_dim as i32, b)?;
|
||
hip::vec_add(&res, &o, &cur, b as usize * d)?;
|
||
hip::copy_f32(&cur, &res, b as usize * d)?;
|
||
hip::rms_norm_f32(&cur, Some(&lw.post_ln), &hn, b, d as i32, eps)?;
|
||
hip::router_gemv_batched(&hn, &lw.gate_up_w, &gu, (2 * inter) as i32, d as i32, b)?;
|
||
hip::dspark_split3(&gu, &g, &u, None, b, inter as i32, inter as i32, 0)?;
|
||
hip::dspark_swiglu(&g, &u, &mg, b as usize * inter)?;
|
||
hip::router_gemv_batched(&mg, &lw.down_w, &o, d as i32, inter as i32, b)?;
|
||
hip::vec_add(&res, &o, &cur, b as usize * d)?;
|
||
}
|
||
hip::rms_norm_f32(&cur, Some(&w.norm), &cur, b, d as i32, eps)?;
|
||
let mut cur_h = vec![0f32; b as usize * d]; cur.d2h(&mut cur_h)?;
|
||
// context = frnn[anchor_pos-1] (bf16 ring row -> f32).
|
||
let fr_slot = (anchor_pos - 1).rem_euclid(frnn_cap);
|
||
let fr_tok = DeviceBuf::alloc(4)?; fr_tok.h2d_bytes(&fr_slot.to_le_bytes())?;
|
||
let ctx = al(d)?;
|
||
hip::embed_bf16_gather(frnn, &fr_tok, &ctx, 1, d as i32, frnn_cap)?;
|
||
let mut ctx_h = vec![0f32; d]; ctx.d2h(&mut ctx_h)?;
|
||
// Recurrent Markov head.
|
||
let state = al(rank)?; state.h2d(&vec![0f32; rank])?;
|
||
let latent = al(rank)?; let joint = al(2 * rank + 2 * d)?; let proj = al(3 * rank)?;
|
||
let mw1_row = al(rank)?; let corr = al(d)?; let cur_step = al(d)?; let combined = al(d)?;
|
||
let logits = al(vocab as usize)?;
|
||
let mut prev = anchor_tok;
|
||
let nd = n_draft.min(b - 1) as usize;
|
||
for step in 1..=nd {
|
||
let mut state_h = vec![0f32; rank]; state.d2h(&mut state_h)?;
|
||
let pt = DeviceBuf::alloc(4)?; pt.h2d_bytes(&prev.to_le_bytes())?;
|
||
hip::embed_bf16_gather(&w.markov_w1, &pt, &mw1_row, 1, rank as i32, DS_VOCAB_PAD as i32)?;
|
||
let mut mw1_h = vec![0f32; rank]; mw1_row.d2h(&mut mw1_h)?;
|
||
let mut jh = Vec::with_capacity(2 * rank + 2 * d);
|
||
jh.extend_from_slice(&state_h);
|
||
jh.extend_from_slice(&mw1_h);
|
||
jh.extend_from_slice(&cur_h[step * d..(step + 1) * d]);
|
||
jh.extend_from_slice(&ctx_h);
|
||
joint.h2d(&jh)?;
|
||
hip::router_gemv(&joint, &w.rnn_proj_w, &proj, (3 * rank) as i32, (2 * rank + 2 * d) as i32)?;
|
||
hip::dspark_markov_gru(&proj, &w.rnn_proj_b, &state, &latent, rank as i32)?;
|
||
hip::router_gemv(&latent, &w.hidden_out_w, &corr, d as i32, rank as i32)?;
|
||
hip::copy_f32_sub(&cur, step * d, &cur_step, d)?;
|
||
hip::dspark_corr_combine(&cur_step, &corr, &w.hidden_out_b, &combined, d as i32)?;
|
||
hip::router_gemv(&combined, unembed, &logits, vocab, d as i32)?;
|
||
let mut lh = vec![0f32; vocab as usize]; logits.d2h(&mut lh)?;
|
||
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
|
||
for (v, &z) in lh.iter().enumerate() { if z > bz { bz = z; best = v; } }
|
||
out_ids[step - 1] = best as i32;
|
||
prev = best as i32;
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[cfg(feature = "hip")]
|
||
pub use gpu::{DsparkLayer, DsparkWeights, dspark_context, dspark_draft};
|
||
|
||
/// Outcome of one greedy speculative round (mirrors strata ink_serve.h block
|
||
/// verify loop). `greedy[i]` is the trunk argmax from feeding row i (anchor for
|
||
/// i=0, draft[i-1] for i>0); it predicts the token at position cur_pos+1+i.
|
||
/// Lossless by proofs/speculative_draft.lean `spec_lossless`.
|
||
pub struct SpecRound {
|
||
/// Tokens to emit this round (accepted drafts + one correction/bonus).
|
||
pub emit: Vec<i32>,
|
||
/// Number of tokens committed to the KV prefix = emit.len(); rollback keeps
|
||
/// cur_pos + accepted (anchor + accepted drafts; the correction's KV is
|
||
/// deferred to the next round, becoming its anchor).
|
||
pub accepted: usize,
|
||
/// Anchor token for the next round (the correction/bonus), unless done.
|
||
pub next_tok: i32,
|
||
/// Request finished (stop token or length cap hit mid-round).
|
||
pub done: bool,
|
||
}
|
||
|
||
/// Greedy accept loop. `draft` = nd proposed ids; `greedy` = nd+1 trunk argmax
|
||
/// (row i predicts position cur_pos+1+i). `max_left` = remaining token budget;
|
||
/// `is_stop` flags end-of-sequence ids. Exact reference indexing.
|
||
pub fn spec_accept_greedy(
|
||
draft: &[i32], greedy: &[i32], anchor_tok: i32, max_left: usize,
|
||
is_stop: impl Fn(i32) -> bool,
|
||
) -> SpecRound {
|
||
let nd = draft.len();
|
||
debug_assert_eq!(greedy.len(), nd + 1);
|
||
let mut emit = Vec::with_capacity(nd + 1);
|
||
let mut next_tok = anchor_tok;
|
||
let mut done = false;
|
||
for i in 0..=nd {
|
||
let tok = greedy[i];
|
||
emit.push(tok);
|
||
if is_stop(tok) || emit.len() >= max_left {
|
||
done = true;
|
||
break;
|
||
}
|
||
if i < nd && tok == draft[i] {
|
||
continue; // accept draft[i], verify next position
|
||
}
|
||
next_tok = tok; // correction (mismatch) or bonus (i == nd)
|
||
break;
|
||
}
|
||
let accepted = emit.len();
|
||
SpecRound { emit, accepted, next_tok, done }
|
||
}
|
||
|
||
/// The KV-prefix tokens committed by a round (the fed inputs of the accepted
|
||
/// rows): anchor then draft[0..accepted-1]. Used to advance the cached prefix.
|
||
pub fn committed_prefix(anchor_tok: i32, draft: &[i32], accepted: usize) -> Vec<i32> {
|
||
let mut v = Vec::with_capacity(accepted);
|
||
v.push(anchor_tok);
|
||
for i in 0..accepted.saturating_sub(1) {
|
||
v.push(draft[i]);
|
||
}
|
||
v
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// CPU-only: the real mtp.safetensors must pass the layout check.
|
||
#[test]
|
||
fn mtp_layout_check_real_file() {
|
||
let path = "/mnt/models/Inkling/safetensors/mtp.safetensors";
|
||
if !std::path::Path::new(path).exists() {
|
||
eprintln!("skip: mtp.safetensors not present");
|
||
return;
|
||
}
|
||
let ar = SafetensorsArchive::open_file(path).unwrap();
|
||
layout_check(&ar).unwrap();
|
||
assert_eq!(ar.tensors.len(), expected_tensors().len());
|
||
}
|
||
|
||
/// Greedy accept loop: all drafts accepted + bonus.
|
||
#[test]
|
||
fn spec_accept_all_then_bonus() {
|
||
let r = spec_accept_greedy(&[10, 20, 30], &[10, 20, 30, 99], 5, 10, |_| false);
|
||
assert_eq!(r.emit, vec![10, 20, 30, 99]);
|
||
assert_eq!(r.accepted, 4);
|
||
assert_eq!(r.next_tok, 99);
|
||
assert!(!r.done);
|
||
assert_eq!(committed_prefix(5, &[10, 20, 30], r.accepted), vec![5, 10, 20, 30]);
|
||
}
|
||
|
||
/// Mismatch at i=1: accept draft[0], emit correction, rollback keeps 2.
|
||
#[test]
|
||
fn spec_accept_mid_mismatch() {
|
||
let r = spec_accept_greedy(&[10, 20, 30], &[10, 77, 0, 0], 5, 10, |_| false);
|
||
assert_eq!(r.emit, vec![10, 77]);
|
||
assert_eq!(r.accepted, 2);
|
||
assert_eq!(r.next_tok, 77);
|
||
assert!(!r.done);
|
||
assert_eq!(committed_prefix(5, &[10, 20, 30], r.accepted), vec![5, 10]);
|
||
}
|
||
|
||
/// Mismatch at i=0: only the correction is emitted/committed.
|
||
#[test]
|
||
fn spec_accept_first_mismatch() {
|
||
let r = spec_accept_greedy(&[10, 20], &[88, 0, 0], 5, 10, |_| false);
|
||
assert_eq!(r.emit, vec![88]);
|
||
assert_eq!(r.accepted, 1);
|
||
assert_eq!(r.next_tok, 88);
|
||
assert_eq!(committed_prefix(5, &[10, 20], r.accepted), vec![5]);
|
||
}
|
||
|
||
/// Stop token mid-round ends the request.
|
||
#[test]
|
||
fn spec_accept_stop() {
|
||
let r = spec_accept_greedy(&[10, 20, 30], &[10, 20, 99, 0], 5, 10, |t| t == 99);
|
||
assert_eq!(r.emit, vec![10, 20, 99]);
|
||
assert_eq!(r.accepted, 3);
|
||
assert!(r.done);
|
||
}
|
||
|
||
/// Length cap mid-round ends the request (accepted == budget).
|
||
#[test]
|
||
fn spec_accept_length_cap() {
|
||
let r = spec_accept_greedy(&[10, 20, 30], &[10, 20, 30, 99], 5, 2, |_| false);
|
||
assert_eq!(r.emit, vec![10, 20]);
|
||
assert_eq!(r.accepted, 2);
|
||
assert!(r.done);
|
||
}
|
||
|
||
/// A wrong shape must be rejected (drafter disabled), not silently accepted.
|
||
#[test]
|
||
fn layout_check_rejects_wrong_shape() {
|
||
let mut ar = SafetensorsArchive {
|
||
dir: std::path::PathBuf::from("."),
|
||
shards: vec![],
|
||
tensors: std::collections::HashMap::new(),
|
||
};
|
||
for (name, mut shape) in expected_tensors() {
|
||
if name == "fuse_weight" {
|
||
shape = vec![4, 5]; // corrupt
|
||
}
|
||
ar.tensors.insert(
|
||
name,
|
||
crate::TensorInfo { shard_idx: 0, dtype: "BF16".into(), shape, begin: 0, end: 0 },
|
||
);
|
||
}
|
||
assert!(layout_check(&ar).is_err());
|
||
}
|
||
|
||
/// GPU: load + fuse the real drafter weights; check resident buffer sizes.
|
||
#[test]
|
||
#[cfg(feature = "hip")]
|
||
fn dspark_load_real_weights() {
|
||
let path = "/mnt/models/Inkling/safetensors/mtp.safetensors";
|
||
if !std::path::Path::new(path).exists() {
|
||
eprintln!("skip: mtp.safetensors not present");
|
||
return;
|
||
}
|
||
let ar = SafetensorsArchive::open_file(path).unwrap();
|
||
let w = DsparkWeights::load(&ar).unwrap();
|
||
assert_eq!(w.layers.len(), DS_LAYERS);
|
||
assert_eq!(w.fuse_w.bytes, 4 * 4 * 4);
|
||
let qkv_rows = (DS_HEADS + 2 * DS_KV) * DS_HD; // 5120
|
||
assert_eq!(w.layers[0].qkv_w.bytes, qkv_rows * DS_HIDDEN * 2);
|
||
assert_eq!(w.layers[0].gate_up_w.bytes, 2 * DS_INTER * DS_HIDDEN * 2);
|
||
assert_eq!(w.markov_w1.bytes, DS_VOCAB_PAD * DS_MARKOV_RANK * 2);
|
||
assert_eq!(w.rnn_proj_w.bytes, 768 * 5120 * 2);
|
||
}
|
||
|
||
/// GPU dspark_context vs a CPU oracle on the REAL mtp weights (mix -> ctx
|
||
/// proj -> per-head k_norm + NeoX half-RoPE; frnn = row-3 mix).
|
||
#[test]
|
||
#[cfg(feature = "hip")]
|
||
fn dspark_context_parity_real_weights() {
|
||
use vetta_infer_hip::DeviceBuf;
|
||
let path = "/mnt/models/Inkling/safetensors/mtp.safetensors";
|
||
if !std::path::Path::new(path).exists() { eprintln!("skip: no mtp"); return; }
|
||
let ar = SafetensorsArchive::open_file(path).unwrap();
|
||
let w = DsparkWeights::load(&ar).unwrap();
|
||
let (m, d, hd, kv) = (2usize, DS_HIDDEN, DS_HD, DS_KV);
|
||
let kv_dim = kv * hd;
|
||
let (eps, theta) = (1e-6f32, 1e6f32);
|
||
let pos: Vec<i32> = vec![5, 1024];
|
||
let taps: Vec<Vec<f32>> = (0..4)
|
||
.map(|t| (0..m * d).map(|i| ((i % 41) as f32 - 20.0) * 0.05 + t as f32 * 0.1).collect())
|
||
.collect();
|
||
let bf = |name: &str| -> Vec<f32> {
|
||
let info = ar.tensors.get(name).unwrap();
|
||
let mut raw = vec![0u8; info.byte_len() as usize];
|
||
ar.read_slice(name, 0, &mut raw).unwrap();
|
||
raw.chunks_exact(2).map(|c| f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16)).collect()
|
||
};
|
||
let fuse = bf("fuse_weight");
|
||
let mix = |row: usize, norm: &[f32]| -> Vec<f32> {
|
||
let fw = &fuse[row * 4..row * 4 + 4];
|
||
let mx = fw.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
|
||
let e: Vec<f32> = fw.iter().map(|v| (v - mx).exp()).collect();
|
||
let es: f32 = e.iter().sum();
|
||
let sw: Vec<f32> = e.iter().map(|v| v / es).collect();
|
||
let mut out = vec![0f32; m * d];
|
||
for mi in 0..m {
|
||
let mut ss = 0f32;
|
||
for i in 0..d {
|
||
let mut v = 0f32;
|
||
for t in 0..4 { v += sw[t] * taps[t][mi * d + i]; }
|
||
out[mi * d + i] = v; ss += v * v;
|
||
}
|
||
let inv = 1f32 / (ss / d as f32 + eps).sqrt();
|
||
for i in 0..d { out[mi * d + i] *= inv * norm[i]; }
|
||
}
|
||
out
|
||
};
|
||
let dt: Vec<DeviceBuf> = taps.iter().map(|t| { let b = DeviceBuf::alloc(t.len() * 4).unwrap(); b.h2d(t).unwrap(); b }).collect();
|
||
let dp = DeviceBuf::alloc(pos.len() * 4).unwrap();
|
||
dp.h2d_bytes(&pos.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
|
||
let ko: Vec<DeviceBuf> = (0..3).map(|_| DeviceBuf::alloc(m * kv_dim * 4).unwrap()).collect();
|
||
let vo: Vec<DeviceBuf> = (0..3).map(|_| DeviceBuf::alloc(m * kv_dim * 4).unwrap()).collect();
|
||
let fr = DeviceBuf::alloc(m * d * 4).unwrap();
|
||
dspark_context(&w, [&dt[0], &dt[1], &dt[2], &dt[3]], &dp, m as i32,
|
||
[&ko[0], &ko[1], &ko[2]], [&vo[0], &vo[1], &vo[2]], &fr, eps, theta).unwrap();
|
||
let mut max_rel = 0f32;
|
||
for il in 0..3 {
|
||
let p = format!("layers.{il}.");
|
||
let ctx = mix(il, &bf(&format!("{p}dflare_norm.weight")));
|
||
let wk = bf(&format!("{p}self_attn.k_proj_ctx.weight"));
|
||
let wv = bf(&format!("{p}self_attn.v_proj_ctx.weight"));
|
||
let kn = bf(&format!("{p}self_attn.k_norm_ctx.weight"));
|
||
let mut kc = vec![0f32; m * kv_dim];
|
||
let mut vc = vec![0f32; m * kv_dim];
|
||
for mi in 0..m {
|
||
for j in 0..kv_dim {
|
||
let (mut ak, mut av) = (0f32, 0f32);
|
||
for dd in 0..d { ak += ctx[mi * d + dd] * wk[j * d + dd]; av += ctx[mi * d + dd] * wv[j * d + dd]; }
|
||
kc[mi * kv_dim + j] = ak; vc[mi * kv_dim + j] = av;
|
||
}
|
||
}
|
||
for mi in 0..m {
|
||
for kh in 0..kv {
|
||
let base = (mi * kv + kh) * hd;
|
||
let ss: f32 = (0..hd).map(|i| kc[base + i] * kc[base + i]).sum();
|
||
let inv = 1f32 / (ss / hd as f32 + eps).sqrt();
|
||
let t: Vec<f32> = (0..hd).map(|i| kc[base + i] * inv * kn[i]).collect();
|
||
for i in 0..hd / 2 {
|
||
let freq = (1f64 / (theta as f64).powf((2 * i) as f64 / hd as f64)) as f32;
|
||
let ang = pos[mi] as f32 * freq;
|
||
let s = (ang as f64).sin() as f32;
|
||
let c = (ang as f64).cos() as f32;
|
||
kc[base + i] = t[i] * c - t[i + hd / 2] * s;
|
||
kc[base + i + hd / 2] = t[i] * s + t[i + hd / 2] * c;
|
||
}
|
||
}
|
||
}
|
||
let (mut gk, mut gv) = (vec![0f32; m * kv_dim], vec![0f32; m * kv_dim]);
|
||
ko[il].d2h(&mut gk).unwrap(); vo[il].d2h(&mut gv).unwrap();
|
||
let sk = kc.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||
let sv = vc.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||
for (g, wnt) in gk.iter().zip(kc.iter()) { max_rel = max_rel.max((g - wnt).abs() / sk); }
|
||
for (g, wnt) in gv.iter().zip(vc.iter()) { max_rel = max_rel.max((g - wnt).abs() / sv); }
|
||
}
|
||
let frnn = mix(3, &bf("markov_head.dflare_norm.weight"));
|
||
let mut gf = vec![0f32; m * d];
|
||
fr.d2h(&mut gf).unwrap();
|
||
let sf = frnn.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||
for (g, wnt) in gf.iter().zip(frnn.iter()) { max_rel = max_rel.max((g - wnt).abs() / sf); }
|
||
eprintln!("dspark_context max_rel_err={max_rel:.3e}");
|
||
assert!(max_rel < 1e-4, "dspark_context parity failed: {max_rel}");
|
||
}
|
||
|
||
/// Full dspark_draft composition vs a complete CPU oracle. Real mtp drafter
|
||
/// weights + small synthetic trunk embed/unembed (V=512) + synthetic ctx
|
||
/// rings. Gate: the 7 drafted token ids match EXACTLY (discrete argmax).
|
||
#[test]
|
||
#[cfg(feature = "hip")]
|
||
fn dspark_draft_parity() {
|
||
use vetta_infer_hip::DeviceBuf;
|
||
let path = "/mnt/models/Inkling/safetensors/mtp.safetensors";
|
||
if !std::path::Path::new(path).exists() { eprintln!("skip: no mtp"); return; }
|
||
let ar = SafetensorsArchive::open_file(path).unwrap();
|
||
let w = DsparkWeights::load(&ar).unwrap();
|
||
let f2b = |v: f32| -> u16 { let u = v.to_bits(); ((u + 0x7FFFu32 + ((u >> 16) & 1)) >> 16) as u16 };
|
||
let b2f = |h: u16| -> f32 { f32::from_bits((h as u32) << 16) };
|
||
let bf = |name: &str| -> Vec<f32> {
|
||
let info = ar.tensors.get(name).unwrap();
|
||
let mut raw = vec![0u8; info.byte_len() as usize];
|
||
ar.read_slice(name, 0, &mut raw).unwrap();
|
||
raw.chunks_exact(2).map(|c| b2f(u16::from_le_bytes([c[0], c[1]]))).collect()
|
||
};
|
||
let (d, hd, hh, kv, inter, rank, b) = (DS_HIDDEN, DS_HD, DS_HEADS, DS_KV, DS_INTER, DS_MARKOV_RANK, DS_BLOCK);
|
||
let (q_dim, kv_dim) = (hh * hd, kv * hd);
|
||
let (eps, theta) = (1e-6f32, 1e6f32);
|
||
let vocab = 512usize; let cap = 64usize; let frnn_cap = 64usize;
|
||
let (anchor_tok, anchor_pos, n_draft, swa_win) = (7i32, 100i32, 7i32, 32i32);
|
||
// synthetic trunk tables (bf16) + norm
|
||
let embed_h: Vec<f32> = (0..vocab * d).map(|i| ((i % 43) as f32 - 21.0) * 0.04).collect();
|
||
let unemb_h: Vec<f32> = (0..vocab * d).map(|i| (((i * 7919 + 13) % 251) as f32 - 125.0) * 0.02).collect();
|
||
let enorm_h: Vec<f32> = (0..d).map(|i| 0.5 + (i % 13) as f32 * 0.05).collect();
|
||
let up = |v: &[f32]| -> DeviceBuf { let u: Vec<u16> = v.iter().map(|x| f2b(*x)).collect(); let bb = DeviceBuf::alloc(u.len() * 2).unwrap(); bb.h2d_bytes(&u.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()).unwrap(); bb };
|
||
let embed = up(&embed_h); let unembed = up(&unemb_h);
|
||
let enorm = DeviceBuf::alloc(d * 4).unwrap(); enorm.h2d(&enorm_h).unwrap();
|
||
// synthetic ctx rings + frnn (bf16)
|
||
let mut ck_h = vec![vec![0f32; cap * kv_dim]; 3];
|
||
let mut cv_h = vec![vec![0f32; cap * kv_dim]; 3];
|
||
for il in 0..3 {
|
||
for i in 0..cap * kv_dim { ck_h[il][i] = b2f(f2b(((i % 29 + il * 5) as f32 - 14.0) * 0.03)); cv_h[il][i] = b2f(f2b(((i % 17 + il * 3) as f32 - 8.0) * 0.05)); }
|
||
}
|
||
let frnn_h: Vec<f32> = (0..frnn_cap * d).map(|i| b2f(f2b(((i % 31) as f32 - 15.0) * 0.02))).collect();
|
||
let ck: Vec<DeviceBuf> = ck_h.iter().map(|v| up(v)).collect();
|
||
let cv: Vec<DeviceBuf> = cv_h.iter().map(|v| up(v)).collect();
|
||
let frnn = up(&frnn_h);
|
||
let mut ids = [0i32; 7];
|
||
dspark_draft(&w, &embed, &enorm, &unembed, [&ck[0], &ck[1], &ck[2]], [&cv[0], &cv[1], &cv[2]], &frnn,
|
||
anchor_tok, anchor_pos, n_draft, cap as i32, frnn_cap as i32, swa_win, eps, theta, vocab as i32, &mut ids).unwrap();
|
||
// ---- CPU oracle ----
|
||
let rms = |x: &[f32], nw: &[f32]| -> Vec<f32> {
|
||
let ss: f32 = x.iter().map(|v| v * v).sum();
|
||
let inv = 1f32 / (ss / x.len() as f32 + eps).sqrt();
|
||
x.iter().zip(nw.iter()).map(|(v, w)| v * inv * w).collect()
|
||
};
|
||
let mm = |x: &[f32], wt: &[f32], rows: usize, n: usize, k: usize| -> Vec<f32> {
|
||
let mut y = vec![0f32; rows * n];
|
||
for r in 0..rows { for j in 0..n { let mut a = 0f32; for t in 0..k { a += x[r * k + t] * wt[j * k + t]; } y[r * n + j] = a; } }
|
||
y
|
||
};
|
||
let rope = |x: &mut [f32], heads: usize, pos: i32| {
|
||
for h in 0..heads { let base = h * hd;
|
||
for i in 0..hd / 2 {
|
||
let freq = (1f64 / (theta as f64).powf((2 * i) as f64 / hd as f64)) as f32;
|
||
let ang = pos as f32 * freq; let s = (ang as f64).sin() as f32; let c = (ang as f64).cos() as f32;
|
||
let x0 = x[base + i]; let x1 = x[base + i + hd / 2];
|
||
x[base + i] = x0 * c - x1 * s; x[base + i + hd / 2] = x0 * s + x1 * c;
|
||
}
|
||
}
|
||
};
|
||
let mask = bf("mask_embed");
|
||
let mut cur = vec![0f32; b * d];
|
||
let e0 = rms(&embed_h[anchor_tok as usize * d..(anchor_tok as usize + 1) * d], &enorm_h);
|
||
cur[..d].copy_from_slice(&e0);
|
||
for i in 1..b { cur[i * d..(i + 1) * d].copy_from_slice(&mask); }
|
||
let scale = 1f32 / (hd as f32).sqrt(); let n_rep = hh / kv;
|
||
for il in 0..3 {
|
||
let p = format!("layers.{il}.");
|
||
let in_ln = bf(&format!("{p}input_layernorm.weight"));
|
||
let qnw = bf(&format!("{p}self_attn.q_norm.weight"));
|
||
let knw = bf(&format!("{p}self_attn.k_norm.weight"));
|
||
let qw = bf(&format!("{p}self_attn.q_proj.weight"));
|
||
let kw = bf(&format!("{p}self_attn.k_proj.weight"));
|
||
let vw = bf(&format!("{p}self_attn.v_proj.weight"));
|
||
let ow = bf(&format!("{p}self_attn.o_proj.weight"));
|
||
let res = cur.clone();
|
||
let mut h = vec![0f32; b * d];
|
||
for i in 0..b { h[i * d..(i + 1) * d].copy_from_slice(&rms(&cur[i * d..(i + 1) * d], &in_ln)); }
|
||
let mut q = mm(&h, &qw, b, q_dim, d);
|
||
let mut kd = mm(&h, &kw, b, kv_dim, d);
|
||
let vd = mm(&h, &vw, b, kv_dim, d);
|
||
for i in 0..b {
|
||
for hdi in 0..hh { let base = (i * hh + hdi) * hd; let t = rms(&q[base..base + hd], &qnw); q[base..base + hd].copy_from_slice(&t); }
|
||
for kdi in 0..kv { let base = (i * kv + kdi) * hd; let t = rms(&kd[base..base + hd], &knw); kd[base..base + hd].copy_from_slice(&t); }
|
||
rope(&mut q[i * q_dim..(i + 1) * q_dim], hh, anchor_pos + i as i32);
|
||
rope(&mut kd[i * kv_dim..(i + 1) * kv_dim], kv, anchor_pos + i as i32);
|
||
}
|
||
let is_swa = DS_SWA_LAYERS.contains(&il);
|
||
let c0 = if is_swa { (anchor_pos - swa_win + 1).max(0) } else { 0 };
|
||
let c_len = (anchor_pos - c0) as usize; let tot_k = c_len + b;
|
||
let mut attn = vec![0f32; b * q_dim];
|
||
for qi in 0..b { for hdi in 0..hh { let kvh = hdi / n_rep;
|
||
let qv = &q[(qi * hh + hdi) * hd..(qi * hh + hdi + 1) * hd];
|
||
let mut sc = vec![0f32; tot_k]; let mut mx = f32::NEG_INFINITY;
|
||
for t in 0..tot_k { let mut dot = 0f32;
|
||
if t < c_len { let slot = ((c0 + t as i32) as usize) % cap; for j in 0..hd { dot += qv[j] * ck_h[il][(slot * kv + kvh) * hd + j]; } }
|
||
else { let di = t - c_len; for j in 0..hd { dot += qv[j] * kd[(di * kv + kvh) * hd + j]; } }
|
||
dot *= scale; sc[t] = dot; mx = mx.max(dot); }
|
||
let mut sum = 0f32; for t in 0..tot_k { sc[t] = (sc[t] - mx).exp(); sum += sc[t]; }
|
||
let inv = 1f32 / sum;
|
||
for j in 0..hd { let mut a = 0f32;
|
||
for t in 0..c_len { let slot = ((c0 + t as i32) as usize) % cap; a += sc[t] * inv * cv_h[il][(slot * kv + kvh) * hd + j]; }
|
||
for di in 0..b { a += sc[c_len + di] * inv * vd[(di * kv + kvh) * hd + j]; }
|
||
attn[(qi * hh + hdi) * hd + j] = a; }
|
||
} }
|
||
let o = mm(&attn, &ow, b, d, q_dim);
|
||
for i in 0..b * d { cur[i] = res[i] + o[i]; }
|
||
let res = cur.clone();
|
||
let post = bf(&format!("{p}post_attention_layernorm.weight"));
|
||
let gw = bf(&format!("{p}mlp.gate_proj.weight"));
|
||
let uw = bf(&format!("{p}mlp.up_proj.weight"));
|
||
let dw = bf(&format!("{p}mlp.down_proj.weight"));
|
||
let mut h2 = vec![0f32; b * d];
|
||
for i in 0..b { h2[i * d..(i + 1) * d].copy_from_slice(&rms(&cur[i * d..(i + 1) * d], &post)); }
|
||
let g = mm(&h2, &gw, b, inter, d); let u2 = mm(&h2, &uw, b, inter, d);
|
||
let mg: Vec<f32> = (0..b * inter).map(|i| (g[i] / (1f32 + (-g[i]).exp())) * u2[i]).collect();
|
||
let o2 = mm(&mg, &dw, b, d, inter);
|
||
for i in 0..b * d { cur[i] = res[i] + o2[i]; }
|
||
}
|
||
let nw = bf("norm.weight");
|
||
for i in 0..b { let t = rms(&cur[i * d..(i + 1) * d], &nw); cur[i * d..(i + 1) * d].copy_from_slice(&t); }
|
||
let context = frnn_h[((anchor_pos - 1).rem_euclid(frnn_cap as i32)) as usize * d..((anchor_pos - 1).rem_euclid(frnn_cap as i32)) as usize * d + d].to_vec();
|
||
let mw1 = bf("markov_head.markov_w1.weight");
|
||
let rpw = bf("markov_head.rnn_proj.weight"); let rpb = bf("markov_head.rnn_proj.bias");
|
||
let how = bf("markov_head.hidden_out.weight"); let hob = bf("markov_head.hidden_out.bias");
|
||
let mut state = vec![0f32; rank]; let mut prev = anchor_tok as usize;
|
||
let mut want = [0i32; 7];
|
||
for step in 1..=n_draft as usize {
|
||
let mut joint = Vec::with_capacity(2 * rank + 2 * d);
|
||
joint.extend_from_slice(&state);
|
||
joint.extend_from_slice(&mw1[prev * rank..(prev + 1) * rank]);
|
||
joint.extend_from_slice(&cur[step * d..(step + 1) * d]);
|
||
joint.extend_from_slice(&context);
|
||
let jk = 2 * rank + 2 * d;
|
||
let mut proj = vec![0f32; 3 * rank];
|
||
for r in 0..3 * rank { let mut a = rpb[r]; for t in 0..jk { a += rpw[r * jk + t] * joint[t]; } proj[r] = a; }
|
||
let mut latent = vec![0f32; rank];
|
||
for r in 0..rank {
|
||
let gg = 1f32 / (1f32 + (-proj[r]).exp());
|
||
let cand = proj[rank + r].tanh();
|
||
state[r] = cand + gg * (state[r] - cand);
|
||
latent[r] = proj[2 * rank + r].tanh();
|
||
}
|
||
let mut combined = vec![0f32; d];
|
||
for dd in 0..d { let mut a = hob[dd]; for r in 0..rank { a += how[dd * rank + r] * latent[r]; } combined[dd] = cur[step * d + dd] + a; }
|
||
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
|
||
for v in 0..vocab { let mut z = 0f32; for t in 0..d { z += unemb_h[v * d + t] * combined[t]; } if z > bz { bz = z; best = v; } }
|
||
want[step - 1] = best as i32; prev = best;
|
||
}
|
||
eprintln!("dspark_draft ids gpu={ids:?} oracle={want:?}");
|
||
assert_eq!(ids, want, "dspark_draft token ids must match the CPU oracle exactly");
|
||
}
|
||
} |