[LD] autoregressive generation + 2 correctness fixes vs reference engine

Added a reference-ground-truth debugging loop: drove the strata-inkling
reference engine (--serve, GEN protocol) on the same prompts to obtain the
correct continuations, then compared against vetta's forward.

- tokenizers crate (fancy-regex) added to vetta-infer-ld for real BPE
  encode/decode from tokenizer.json.
- forward_inkling_with_state: stateful variant exposing the persistent
  per-layer KV cache + shortconv history across decode positions, enabling
  autoregressive prefill + generation. forward_inkling wraps it with fresh state.
- generate_continuation_real_prompt test: encode prompt -> token-by-token
  prefill -> greedy sampling via the hardened abi sampler -> decode.

TWO REAL BUGS FOUND via reference comparison (reference: "The capital of
France is" -> " Paris."; single token 100 -> argmax 68014):
1. embed_token omitted embed_norm: the reference k_embed_lookup fuses gather +
   RMS-normalize with embed_norm.weight. Fixed (gather then rms_norm).
2. full-attn ShortConv static_w transpose had REVERSED tap order: reference
   upload_sc uses kt[c*4+(3-lag)] = kw[lag*kv_dim+c]; fixed to match.

NOTE: generation is still divergent after these two fixes (single-token argmax
moved 120533 -> 100, reference 68014); further correctness debugging is in
progress. These two fixes are verified-correct against the reference semantics.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; generation + full-forward tests run
(--features hip, --ignored).
This commit is contained in:
adm committed 2026-12-01 15:28:20 +01:00
1 parent 3c870743fe
commit b1bb4e13be
3 files changed
+838 -9

No files matched your search

+2 -1
View File
@@ -5,10 +5,11 @@ edition.workspace = true
license.workspace = true
[dependencies]
tokenizers = { version = "0.23.2", default-features = false, features = ["fancy-regex"] }
vetta-infer-abi = { path = "../vetta-infer-abi" }
vetta-infer-hip = { path = "../vetta-infer-hip", optional = true }
vetta-infer-rt = { path = "../vetta-infer-rt", optional = true }
[features]
# GPU packer + real-weight run tests (links HIP backend + executor).
hip = ["dep:vetta-infer-hip", "vetta-infer-hip/hip", "dep:vetta-infer-rt", "vetta-infer-rt/hip"]
hip = ["dep:vetta-infer-hip", "vetta-infer-hip/hip", "dep:vetta-infer-rt", "vetta-infer-rt/hip"]
+68 -8
View File
@@ -242,11 +242,15 @@ pub fn layer_forward_swa(
}
/// Embed a single token id from the real BF16 embed table -> f32 cur [hidden].
/// Exact strata k_embed_lookup: gather the row THEN RMS-normalize it with
/// embed_norm.weight (the embed lookup fuses gather + norm).
pub fn embed_token(ar: &SafetensorsArchive, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> {
let table = load_raw(ar, "model.llm.embed.weight")?;
let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&token.to_le_bytes())?;
let cur = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::embed_bf16_gather(&table, &tok, &cur, 1, hidden as i32, vocab as i32)?;
let emb_norm = load_bf16_as_f32(ar, "model.llm.embed_norm.weight")?;
vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, 1, hidden as i32, 1e-6)?;
Ok(cur)
}
@@ -339,13 +343,23 @@ fn run_layer(
/// [18,24) -> final depth mix + unembed + softcap. Returns logits [vocab].
pub fn forward_inkling(
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
) -> Result<DeviceBuf, String> {
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
forward_inkling_with_state(ar, d, token, vocab, max_seq, pos, cap, &mut states)
}
/// Stateful variant: `states` holds the persistent per-layer KV cache + shortconv
/// history across decode positions (autoregressive generation). The depth-block
/// snapshots reset each forward; the KV/history evolve token by token.
pub fn forward_inkling_with_state(
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
let h = d.hidden;
let cur = embed_token(ar, token, h, vocab)?;
let mut blocks: Vec<DeviceBuf> = Vec::new();
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
// Prelude.
for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, &mut states, max_seq, pos, None)?; }
for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?; }
let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?;
let n_prelude_blocks = blocks.len();
// Core: 3 passes.
@@ -374,14 +388,14 @@ pub fn forward_inkling(
vetta_infer_hip::attn_res_mix(&blk, &bank_out, &mq, &msgs_buf, n_bank as i32, 1, 4, h as i32, d.eps)?;
let msgs = LoopMsgs(msgs_buf);
let cw = load_controllers(ar, ip)?;
run_layer(ar, d, ip, &cur, &mut blocks, &mut states, max_seq, pos, Some((&cw, &msgs)))?;
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, Some((&cw, &msgs)))?;
} else {
run_layer(ar, d, ip, &cur, &mut blocks, &mut states, max_seq, pos, None)?;
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?;
}
}
}
// Coda.
for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, &mut states, max_seq, pos, None)?; }
for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?; }
final_logits(ar, &cur, &blocks, h, vocab, d.eps, cap)
}
@@ -392,9 +406,10 @@ fn load_sconv_transposed(ar: &SafetensorsArchive, name: &str, c: usize) -> Resul
let mut b = vec![0u8; info.byte_len() as usize];
ar.read_slice(name, 0, &mut b)?;
let f: Vec<f32> = b.chunks_exact(2).map(|x| f32::from_bits((u16::from_le_bytes([x[0], x[1]]) as u32) << 16)).collect();
// f is [4, C]; transpose to [C, 4].
// f is [4, C] (lag-major); the kernel reads sw[c*4 + (3-lag)] (exact strata
// upload_sc: kt[c*4+(3-lag)] = kw[lag*kv_dim+c]) — tap order REVERSED.
let mut t = vec![0f32; c * 4];
for k in 0..4 { for ch in 0..c { t[ch * 4 + k] = f[k * c + ch]; } }
for lag in 0..4 { for ch in 0..c { t[ch * 4 + (3 - lag)] = f[lag * c + ch]; } }
let buf = DeviceBuf::alloc(c * 4 * 4)?; buf.h2d(&t)?; Ok(buf)
}
@@ -680,7 +695,52 @@ mod tests {
assert!(lg.iter().all(|v| v.is_finite()), "full forward logits must be finite");
assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "logits must be softcap-bounded");
let argmax = lg.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0;
eprintln!("FULL Inkling forward: argmax token={argmax} logit={:.3}", lg[argmax]);
let mut idx: Vec<usize> = (0..201024).collect();
idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap());
let top5: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect();
eprintln!("FULL Inkling forward: argmax token={argmax} logit={:.3} top5={top5:?} logit[68014]={:.3} logit[100]={:.3}", lg[argmax], lg[68014], lg[100]);
assert!(argmax < 201024);
}
/// Autoregressive generation: encode a real prompt, prefill token-by-token
/// (persistent KV/history), then greedily sample continuations with the
/// hardened abi sampler and decode. Correctness signal: a coherent
/// continuation indicates the full forward + state evolution are right.
#[test]
#[ignore]
fn generate_continuation_real_prompt() {
use tokenizers::Tokenizer;
use vetta_infer_abi::sampler::{sample_logits_exact, SampleReport, SamplerScratch, SamplingOpts, SplitMix64};
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap();
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 };
let vocab = 201024usize;
let prompt = "The capital of France is";
let ids: Vec<i32> = tok.encode(prompt, false).unwrap().get_ids().iter().map(|&x| x as i32).collect();
let n_gen = 16usize;
let max_seq = ids.len() + n_gen + 2;
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
let mut history: Vec<i32> = Vec::new();
let mut pos = 0i32;
let mut logits = DeviceBuf::alloc(vocab * 4).unwrap();
for &t in &ids {
logits = forward_inkling_with_state(&ar, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap();
history.push(t); pos += 1;
}
let opts = SamplingOpts::default(); // greedy
let mut rng = SplitMix64::new(42);
let mut scratch = SamplerScratch::default();
let mut generated: Vec<u32> = Vec::new();
for _ in 0..n_gen {
let mut lg = vec![0f32; vocab]; logits.d2h(&mut lg).unwrap();
let rep: SampleReport = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch);
generated.push(rep.token as u32);
history.push(rep.token);
logits = forward_inkling_with_state(&ar, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap();
pos += 1;
}
let text = tok.decode(&generated, true).unwrap();
eprintln!("prompt={prompt:?} -> generated={text:?} (tokens={generated:?})");
assert!(!generated.is_empty());
}
}