Compare commits

...
2 Commits
Author SHA1 Message Date
adm 0a46c4dd7b [GW] Real multi-turn chat: Inkling template + streaming REPL
chat_template renders the plain-text subset of chat_template.jinja (effort
header before first non-system message, role/content_text/end_message tags,
assistant turns closed with content_model_end_sampling, effort-0 model opener);
4 CPU tests. chat::chat_turn tokenizes the rendered prompt and drives the
Lean-proven serve_gen FSM, streaming decoded text; run_chat is an interactive
multi-turn REPL. CLI: vetta-infer chat <dir> [effort] [max_new].

MEASURED live (release, gfx1150): 3-turn Italian chat answers correctly and
keeps context ('La capitale della Francia e Parigi.' / '...del Giappone e
Tokyo.'). GPU test chat_turn_paris green. Workspace -D warnings green.
2026-12-01 17:18:27 +01:00
adm 1df8342f96 [LD] Resident WeightCache: memoize device uploads across decode tokens
Per-token forward re-read ~3 GiB of NVFP4/MXFP8 expert blobs from NVMe and
re-uploaded every layer/norm/query tensor. WeightCache borrows the archive and
memoizes raw tensors, BF16->F32 norms, per-layer weights, controllers and expert
matrices (Arc, interior mutability) so autoregressive decode reuses GPU-resident
weights. The forward path now takes &WeightCache; serve_gen creates one cache
per request shared across prefill + decode.

MEASURED (gfx1150, debug): 21 forwards 36s -> 8.8s (~4x); parity unchanged
(first tokens [152717,13,68014,32,13] exact). Release steady decode ~3.8 tok/s
(DONE 64: decode_ms 16909 over 64 tokens). Suite green: 18 ld GPU + 17 hip GPU.
2026-12-01 17:18:21 +01:00
9 changed files with 440 additions and 55 deletions

No files matched your search

Generated
+1
View File
@@ -700,6 +700,7 @@ dependencies = [
name = "vetta-infer-gw"
version = "0.1.0"
dependencies = [
"tokenizers",
"vetta-infer-abi",
"vetta-infer-hip",
"vetta-infer-ld",
+1
View File
@@ -12,6 +12,7 @@ path = "src/main.rs"
vetta-infer-abi = { path = "../vetta-infer-abi" }
vetta-infer-ld = { path = "../vetta-infer-ld" }
vetta-infer-hip = { path = "../vetta-infer-hip", optional = true }
tokenizers = { version = "0.23.2", default-features = false, features = ["fancy-regex"] }
[features]
# Real GPU `serve`/`gen` (links the HIP backend via ld). Default OFF keeps the
+123
View File
@@ -0,0 +1,123 @@
//! Real multi-turn chat over the GPU engine (feature `hip`).
//!
//! Renders the Inkling chat template, tokenizes, and drives the Lean-proven
//! `serve_gen` FSM per turn, streaming decoded text. The resident weight cache
//! lives inside each `serve_gen` request; the KV/history are re-prefilled per
//! turn (prefix-cache reuse is a later performance refinement).
use std::io::{self, Write};
use std::path::Path;
use std::sync::atomic::AtomicBool;
use tokenizers::Tokenizer;
use vetta_infer_abi::sampler::SamplingOpts;
use vetta_infer_abi::serve::ParsedGen;
use crate::chat_template::{render_prompt, ChatMessage};
use crate::serve::{serve_gen, InklingEngine};
/// Run one assistant turn: render `history` (which must end with the latest user
/// message), generate up to `max_new` tokens greedily, and stream decoded text
/// through `on_text`. Returns the full reply (special tokens stripped).
pub fn chat_turn(
eng: &InklingEngine,
tok: &Tokenizer,
history: &[ChatMessage],
effort: &str,
max_new: usize,
on_text: &mut dyn FnMut(&str),
) -> Result<String, String> {
let prompt = render_prompt(history, effort)?;
let enc = tok.encode(prompt, false).map_err(|e| e.to_string())?;
let ids: Vec<i32> = enc.get_ids().iter().map(|&x| x as i32).collect();
let g = ParsedGen {
max_new,
sampling: SamplingOpts::default(), // greedy, deterministic
spec_mode: None,
draft_top_k: None,
domain_hint: None,
images: Vec::new(),
ids,
};
let stop = AtomicBool::new(false);
let mut generated: Vec<u32> = Vec::new();
let mut printed = 0usize;
let mut full = String::new();
{
let mut emit = |line: String| {
let Some(idstr) = line.strip_prefix("T ") else { return };
let Ok(id) = idstr.trim().parse::<u32>() else { return };
generated.push(id);
if let Ok(txt) = tok.decode(&generated, true) {
if let Some(delta) = txt.get(printed..) {
if !delta.is_empty() {
on_text(delta);
printed = txt.len();
}
}
full = txt;
}
};
serve_gen(eng, &g, &stop, &mut emit);
}
Ok(full)
}
/// Interactive REPL: read user lines from stdin, stream the model's reply,
/// accumulate history. `quit` / `exit` (or EOF) ends the session.
pub fn run_chat(dir: &str, effort: &str, max_new: usize) -> Result<(), String> {
let eng = InklingEngine::new(dir)?;
let tok_path = Path::new(dir).join("tokenizer.json");
let tok = Tokenizer::from_file(&tok_path).map_err(|e| format!("{}: {e}", tok_path.display()))?;
let mut history: Vec<ChatMessage> = Vec::new();
eprintln!("Inkling chat ready (vocab {}, effort {effort}). Type a message; 'quit' to exit.", eng.vocab());
let stdin = io::stdin();
loop {
eprint!("> ");
let _ = io::stderr().flush();
let mut line = String::new();
let n = stdin.read_line(&mut line).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
let text = line.trim();
if text.is_empty() {
continue;
}
if text == "quit" || text == "exit" {
break;
}
history.push(ChatMessage::new("user", text));
let t0 = std::time::Instant::now();
let reply = chat_turn(&eng, &tok, &history, effort, max_new, &mut |chunk| {
print!("{chunk}");
let _ = io::stdout().flush();
})?;
let dt = t0.elapsed().as_secs_f64();
println!();
eprintln!("[{dt:.1}s]");
history.push(ChatMessage::new("assistant", &reply));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// GPU integration: a real chat turn over the wire. Asks the canonical
/// capital question through the chat template and checks the reply mentions
/// Paris. Requires GPU + /mnt/models/Inkling.
#[test]
#[ignore]
fn chat_turn_paris() {
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap();
let history = [ChatMessage::new("user", "What is the capital of France? Answer in one word.")];
let mut streamed = String::new();
let reply = chat_turn(&eng, &tok, &history, "none", 32, &mut |c| streamed.push_str(c)).unwrap();
eprintln!("[chat] reply={reply:?} streamed={streamed:?}");
assert_eq!(reply, streamed, "streamed text must equal the full reply");
assert!(reply.to_lowercase().contains("paris"), "reply should name Paris: {reply:?}");
}
}
+132
View File
@@ -0,0 +1,132 @@
//! Inkling chat template (plain-text subset of `chat_template.jinja`).
//!
//! Renders OpenAI-shaped messages to the prompt string the tokenizer encodes,
//! mirroring the model's Jinja template for the no-tools / no-thinking path:
//! a `Thinking effort level` system header emitted before the first non-system
//! message, each message wrapped in its role token + `<|content_text|>` …
//! `<|end_message|>`, assistant turns closed with `<|content_model_end_sampling|>`,
//! and (effort 0) the `<|message_model|><|content_text|>` generation opener.
//!
//! Special-token ids (tokenizer.json added_tokens): message_user=200000,
//! message_model=200001, message_system=200002, content_text=200004,
//! content_model_end_sampling=200006 (EOS), end_message=200010.
/// One conversation turn. `role` is `user` / `assistant` / `system`.
#[derive(Debug, Clone, PartialEq)]
pub struct ChatMessage {
pub role: String,
pub content: String,
}
impl ChatMessage {
pub fn new(role: &str, content: &str) -> Self {
Self { role: role.to_string(), content: content.to_string() }
}
}
const MSG_USER: &str = "<|message_user|>";
const MSG_MODEL: &str = "<|message_model|>";
const MSG_SYSTEM: &str = "<|message_system|>";
const CONTENT_TEXT: &str = "<|content_text|>";
const END_MSG: &str = "<|end_message|>";
const END_SAMPLING: &str = "<|content_model_end_sampling|>";
/// Map a reasoning-effort name to the template's numeric level (effort_map).
fn effort_num(effort: &str) -> Result<&'static str, String> {
match effort.trim() {
"none" => Ok("0"),
"minimal" => Ok("0.1"),
"low" => Ok("0.2"),
"medium" => Ok("0.7"),
"high" => Ok("0.9"),
"xhigh" | "max" => Ok("0.99"),
other => Err(format!("unknown reasoning_effort: {other}")),
}
}
fn role_token(role: &str) -> Result<&'static str, String> {
match role {
"user" => Ok(MSG_USER),
"assistant" => Ok(MSG_MODEL),
"system" => Ok(MSG_SYSTEM),
other => Err(format!("unknown message role: {other}")),
}
}
/// Render the prompt for `history` plus the generation opener for the next
/// assistant reply. `effort` selects the thinking level; `"none"` (0) makes the
/// model answer directly via the `<|message_model|><|content_text|>` opener.
pub fn render_prompt(history: &[ChatMessage], effort: &str) -> Result<String, String> {
let num = effort_num(effort)?;
let header = format!("{MSG_SYSTEM}{CONTENT_TEXT}Thinking effort level: {num}{END_MSG}");
let mut s = String::new();
let mut effort_emitted = false;
for m in history {
let rtok = role_token(&m.role)?;
if !effort_emitted && m.role != "system" {
s.push_str(&header);
effort_emitted = true;
}
s.push_str(rtok);
s.push_str(CONTENT_TEXT);
s.push_str(&m.content);
s.push_str(END_MSG);
if m.role == "assistant" {
s.push_str(END_SAMPLING);
}
}
if !effort_emitted {
s.push_str(&header);
}
// Generation opener (effort 0, no tools): the model opens content_text.
s.push_str(MSG_MODEL);
s.push_str(CONTENT_TEXT);
Ok(s)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn single_user_turn_exact() {
let h = [ChatMessage::new("user", "Ciao")];
let p = render_prompt(&h, "none").unwrap();
assert_eq!(
p,
"<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>\
<|message_user|><|content_text|>Ciao<|end_message|>\
<|message_model|><|content_text|>"
);
}
#[test]
fn multi_turn_history_closes_assistant_with_end_sampling() {
let h = [
ChatMessage::new("user", "Hi"),
ChatMessage::new("assistant", "Hello!"),
ChatMessage::new("user", "How are you?"),
];
let p = render_prompt(&h, "none").unwrap();
assert!(p.contains("<|message_model|><|content_text|>Hello!<|end_message|><|content_model_end_sampling|>"));
assert!(p.ends_with("<|message_user|><|content_text|>How are you?<|end_message|><|message_model|><|content_text|>"));
// Exactly one effort header, before the first user message.
assert_eq!(p.matches("Thinking effort level: 0").count(), 1);
}
#[test]
fn system_message_precedes_effort_header() {
let h = [ChatMessage::new("system", "Be brief."), ChatMessage::new("user", "Go")];
let p = render_prompt(&h, "none").unwrap();
let sys = p.find("<|message_system|><|content_text|>Be brief.").unwrap();
let eff = p.find("Thinking effort level: 0").unwrap();
assert!(sys < eff, "system message renders before the effort header");
}
#[test]
fn effort_levels_map() {
assert!(render_prompt(&[], "high").unwrap().contains("Thinking effort level: 0.9"));
assert!(render_prompt(&[], "none").unwrap().contains("Thinking effort level: 0"));
assert!(render_prompt(&[], "bogus").is_err());
}
}
+5
View File
@@ -12,9 +12,14 @@
pub mod session;
pub mod chat_template;
#[cfg(feature = "hip")]
pub mod serve;
#[cfg(feature = "hip")]
pub mod chat;
/// Python-repr float spelling (always a decimal point), as `strata-ctl` emits.
fn fmt_float(v: f64) -> String {
let s = format!("{v}");
+26
View File
@@ -11,6 +11,7 @@ fn usage() {
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
eprintln!(" vetta-infer version Print version & build info");
}
@@ -116,6 +117,31 @@ fn main() -> ExitCode {
ExitCode::from(2)
}
}
Some("chat") => {
let Some(dir) = args.get(1) else {
eprintln!("error: missing <safetensors-dir>");
usage();
return ExitCode::from(2);
};
let effort = args.get(2).map(|s| s.as_str()).unwrap_or("none");
let max_new: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(512);
#[cfg(feature = "hip")]
{
match vetta_infer_gw::chat::run_chat(dir, effort, max_new) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
#[cfg(not(feature = "hip"))]
{
let _ = (dir, effort, max_new);
eprintln!("error: 'chat' requires the GPU backend; rebuild with --features hip");
ExitCode::from(2)
}
}
_ => {
usage();
ExitCode::from(2)
+9 -4
View File
@@ -26,7 +26,7 @@ use vetta_infer_abi::sampler::{
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config;
use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState};
use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState, WeightCache};
use vetta_infer_ld::SafetensorsArchive;
use crate::session::ServeSession;
@@ -105,12 +105,13 @@ impl InklingEngine {
fn forward(
&self,
cache: &WeightCache,
token: i32,
pos: i32,
max_seq: usize,
states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_inkling_with_state(&self.ar, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
forward_inkling_with_state(cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
}
}
@@ -152,6 +153,10 @@ pub fn serve_gen(
}
};
// Resident weight cache for this request: weights upload once and stay on
// the GPU across prefill + decode (no per-token NVMe expert re-reads).
let cache = WeightCache::new(&eng.ar);
// --- Prefill: run the forward over every prompt token, growing KV/history. ---
let t0 = Instant::now();
let mut pos = 0i32;
@@ -165,7 +170,7 @@ pub fn serve_gen(
stop.store(false, Ordering::Relaxed);
return;
}
match eng.forward(tok, pos, max_seq, &mut states) {
match eng.forward(&cache, tok, pos, max_seq, &mut states) {
Ok(lg) => logits = Some(lg),
Err(e) => {
emit_all(emit, sess.on_error(&e));
@@ -245,7 +250,7 @@ pub fn serve_gen(
finish = "length";
break;
}
match eng.forward(rep.token, pos, max_seq, &mut states) {
match eng.forward(&cache, rep.token, pos, max_seq, &mut states) {
Ok(l) => logits = l,
Err(e) => {
emit_all(emit, sess.on_error(&e));
+139 -49
View File
@@ -10,8 +10,11 @@
//! layers (3-query split), loop controllers (gain/forget/down) and the
//! multi-pass bank rollback are layered on next.
use crate::packer::{expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw};
use crate::packer::{expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw, ExpertMatrix};
use crate::SafetensorsArchive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use vetta_infer_hip::DeviceBuf;
/// Resident weights for one physical layer step `ip`.
@@ -59,6 +62,89 @@ impl Dims {
pub fn scale(&self) -> f32 { 1.0 / (self.hd as f32).sqrt() }
}
/// Resident weight cache: memoizes every device upload (raw tensors, BF16->F32
/// norms, per-layer weights, controllers and the NVFP4/MXFP8 expert matrices)
/// so autoregressive decode reuses GPU-resident weights instead of re-reading
/// ~3 GiB of expert blobs from NVMe per token. Borrows the archive; the maps
/// use interior mutability so the forward can hold shared `&WeightCache` while
/// loading lazily. Single-threaded forward (serve decodes on one thread).
pub struct WeightCache<'a> {
pub ar: &'a SafetensorsArchive,
raw: RefCell<HashMap<String, Arc<DeviceBuf>>>,
bf16: RefCell<HashMap<String, Arc<DeviceBuf>>>,
sconv: RefCell<HashMap<(String, usize), Arc<DeviceBuf>>>,
swa: RefCell<HashMap<usize, Arc<LayerWeights>>>,
full: RefCell<HashMap<usize, Arc<FullLayerWeights>>>,
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
}
impl<'a> WeightCache<'a> {
pub fn new(ar: &'a SafetensorsArchive) -> Self {
Self {
ar,
raw: RefCell::new(HashMap::new()),
bf16: RefCell::new(HashMap::new()),
sconv: RefCell::new(HashMap::new()),
swa: RefCell::new(HashMap::new()),
full: RefCell::new(HashMap::new()),
experts: RefCell::new(HashMap::new()),
ctrl: RefCell::new(HashMap::new()),
}
}
pub fn raw(&self, name: &str) -> Result<Arc<DeviceBuf>, String> {
if let Some(v) = self.raw.borrow().get(name) { return Ok(v.clone()); }
let v = Arc::new(load_raw(self.ar, name)?);
self.raw.borrow_mut().insert(name.to_string(), v.clone());
Ok(v)
}
pub fn bf16_f32(&self, name: &str) -> Result<Arc<DeviceBuf>, String> {
if let Some(v) = self.bf16.borrow().get(name) { return Ok(v.clone()); }
let v = Arc::new(load_bf16_as_f32(self.ar, name)?);
self.bf16.borrow_mut().insert(name.to_string(), v.clone());
Ok(v)
}
pub fn sconv_t(&self, name: &str, c: usize) -> Result<Arc<DeviceBuf>, String> {
let key = (name.to_string(), c);
if let Some(v) = self.sconv.borrow().get(&key) { return Ok(v.clone()); }
let v = Arc::new(load_sconv_transposed(self.ar, name, c)?);
self.sconv.borrow_mut().insert(key, v.clone());
Ok(v)
}
pub fn swa_layer(&self, ip: usize) -> Result<Arc<LayerWeights>, String> {
if let Some(v) = self.swa.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_layer(self.ar, ip, true)?);
self.swa.borrow_mut().insert(ip, v.clone());
Ok(v)
}
pub fn full_layer(&self, ip: usize, d: &Dims) -> Result<Arc<FullLayerWeights>, String> {
if let Some(v) = self.full.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_full_layer(self.ar, ip, d)?);
self.full.borrow_mut().insert(ip, v.clone());
Ok(v)
}
pub fn expert(&self, ip: usize, e: usize, mat: &str) -> Result<Arc<ExpertMatrix>, String> {
let key = (ip, e, mat.to_string());
if let Some(v) = self.experts.borrow().get(&key) { return Ok(v.clone()); }
let v = Arc::new(load_expert_matrix(self.ar, ip, e, mat)?);
self.experts.borrow_mut().insert(key, v.clone());
Ok(v)
}
pub fn controllers(&self, ip: usize) -> Result<Arc<ControllerWeights>, String> {
if let Some(v) = self.ctrl.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_controllers(self.ar, ip)?);
self.ctrl.borrow_mut().insert(ip, v.clone());
Ok(v)
}
}
pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<LayerWeights, String> {
let p = format!("model.llm.layers.{ip}.attn");
let attn_query = if ip > 0 {
@@ -106,7 +192,7 @@ pub fn new_state(d: &Dims, max_seq: usize) -> Result<LayerState, String> {
/// to `blocks` when `ip % block_size == 0`. `pos` is the decode position.
/// Experts are loaded on demand from `ar` (zero requantization).
pub fn layer_forward_swa(
ar: &SafetensorsArchive, w: &LayerWeights, st: &mut LayerState, d: &Dims,
cache: &WeightCache, w: &LayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
@@ -227,7 +313,7 @@ pub fn layer_forward_swa(
vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?;
let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>() };
if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); }
let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?;
let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?;
let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?;
let moeout = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?;
@@ -243,20 +329,20 @@ 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")?;
pub fn embed_token(cache: &WeightCache, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> {
let table = cache.raw("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")?;
let emb_norm = cache.bf16_f32("model.llm.embed_norm.weight")?;
vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, 1, hidden as i32, 1e-6)?;
Ok(cur)
}
/// Final norm + cast + unembed GEMM -> f32 logits [vocab].
pub fn unembed_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result<DeviceBuf, String> {
let norm = load_bf16_as_f32(ar, "model.llm.norm.weight")?;
let unembed = load_raw(ar, "model.llm.unembed.weight")?;
pub fn unembed_logits(cache: &WeightCache, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result<DeviceBuf, String> {
let norm = cache.bf16_f32("model.llm.norm.weight")?;
let unembed = cache.raw("model.llm.unembed.weight")?;
let n = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::rms_norm_f32(cur, Some(&norm), &n, 1, hidden as i32, eps)?;
let nb = DeviceBuf::alloc(hidden * 2)?;
@@ -269,8 +355,8 @@ pub fn unembed_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, hidden: usize, v
/// Correct final output path: the final norm is itself an AttnRes depth mix
/// (output_query over blocks + cur), then norm + unembed + logit softcap.
/// h_norm = norm(attn_res_mix(blocks, cur, output_query)); logits = softcap(unembed(h_norm)).
pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result<DeviceBuf, String> {
let oq = load_raw(ar, "model.llm.attn_res.output_query")?;
pub fn final_logits(cache: &WeightCache, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result<DeviceBuf, String> {
let oq = cache.raw("model.llm.attn_res.output_query")?;
let n_blocks = blocks.len();
let blk = DeviceBuf::alloc(n_blocks.max(1) * hidden * 4)?;
let mut bh = vec![0f32; n_blocks.max(1) * hidden];
@@ -278,7 +364,7 @@ pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBu
blk.h2d(&bh)?;
let mix = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::attn_res_mix(&blk, cur, &oq, &mix, n_blocks as i32, 1, 1, hidden as i32, eps)?;
let logits = unembed_logits(ar, &mix, hidden, vocab, eps)?;
let logits = unembed_logits(cache, &mix, hidden, vocab, eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
Ok(logits)
}
@@ -287,14 +373,14 @@ pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBu
/// final residual stream + the accumulated depth-block snapshots. (Prelude /
/// single-pass; full-attn layers + loop controllers + bank rollback come next.)
pub fn forward_swa_layers(
ar: &SafetensorsArchive, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32,
cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32,
) -> Result<(DeviceBuf, Vec<DeviceBuf>), String> {
let cur = embed_token(ar, token, d.hidden, /*vocab*/ 201024)?;
let cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?;
let mut blocks: Vec<DeviceBuf> = Vec::new();
for &ip in schedule {
let w = load_layer(ar, ip, true)?;
let w = cache.swa_layer(ip)?;
let mut st = new_state(d, max_seq)?;
layer_forward_swa(ar, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?;
layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?;
}
Ok((cur, blocks))
}
@@ -304,10 +390,10 @@ pub fn is_swa(ip: usize) -> bool { !matches!(ip, 5 | 11 | 17 | 23) }
/// Build the stacked cross-pass msg_queries [4, hidden] for a core layer ip:
/// [q_cp[2i], kv_cp[2i], kv_cp[2i+1], q_cp[2i+1]] with i = ip - core_start.
fn load_msg_queries(ar: &SafetensorsArchive, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
let i = ip - 6;
let q_cp = load_raw(ar, "model.llm.middle_cycle_cross_pass_queries")?;
let kv_cp = load_raw(ar, "model.llm.middle_cycle_cross_pass_kv_queries")?;
let q_cp = cache.raw("model.llm.middle_cycle_cross_pass_queries")?;
let kv_cp = cache.raw("model.llm.middle_cycle_cross_pass_kv_queries")?;
let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?;
let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?;
let mut mq = vec![0f32; 4 * hidden];
@@ -335,7 +421,7 @@ fn dbg_norm(name: &str, buf: &DeviceBuf, n: usize) {
/// shifts tok100 logits by ~0.01 but does NOT flip the near-tie argmax (220 vs
/// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision.
fn run_experts(
ar: &SafetensorsArchive, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize,
cache: &WeightCache, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize,
) -> Result<Vec<f32>, String> {
let gu = DeviceBuf::alloc(2 * d.inter * 4)?;
let mut y_part_h = vec![0f32; d.top_k * h];
@@ -345,10 +431,10 @@ fn run_experts(
let act16 = DeviceBuf::alloc(d.inter * 2)?;
for kk in 0..d.top_k {
let e = ids_h[kk] as usize;
let w13 = load_expert_matrix(ar, ip, e, "w13")?;
let w13 = cache.expert(ip, e, "w13")?;
expert_gemv_f16(&w13, &mlpin16, &gu)?;
vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?;
let w2 = load_expert_matrix(ar, ip, e, "w2")?;
let w2 = cache.expert(ip, e, "w2")?;
let ye = DeviceBuf::alloc(h * 4)?;
expert_gemv_f16(&w2, &act16, &ye)?;
ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?;
@@ -357,10 +443,10 @@ fn run_experts(
let act = DeviceBuf::alloc(d.inter * 4)?;
for kk in 0..d.top_k {
let e = ids_h[kk] as usize;
let w13 = load_expert_matrix(ar, ip, e, "w13")?;
let w13 = cache.expert(ip, e, "w13")?;
expert_gemv(&w13, mlpin, &gu)?;
vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?;
let w2 = load_expert_matrix(ar, ip, e, "w2")?;
let w2 = cache.expert(ip, e, "w2")?;
let ye = DeviceBuf::alloc(h * 4)?;
expert_gemv(&w2, &act, &ye)?;
ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?;
@@ -372,18 +458,18 @@ fn run_experts(
/// Run one physical layer step (SWA or full-attn dispatch), reusing its
/// persistent state (KV cache + shortconv history) across loop passes.
fn run_layer(
ar: &SafetensorsArchive, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>,
cache: &WeightCache, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>,
states: &mut [Option<LayerState>], max_seq: usize, pos: i32, pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
) -> Result<(), String> {
if states[ip].is_none() { states[ip] = Some(new_state(d, max_seq)?); }
let st = states[ip].as_mut().unwrap();
let r = if is_swa(ip) {
let w = load_layer(ar, ip, true)?;
layer_forward_swa(ar, &w, st, d, cur, blocks, pos, pass, ctrl)
let w = cache.swa_layer(ip)?;
layer_forward_swa(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
} else {
let w = load_full_layer(ar, ip, d)?;
layer_forward_full(ar, &w, st, d, cur, blocks, pos, pass, ctrl)
let w = cache.full_layer(ip, d)?;
layer_forward_full(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
};
if std::env::var("VETTA_DBG_NORM").is_ok() {
let visit = if ip < 6 { ip } else if ip < 18 { 6 + pass * 12 + (ip - 6) } else { 42 + (ip - 18) };
@@ -399,21 +485,21 @@ fn run_layer(
/// (bank rollback + cross-pass msgs + controllers on passes 1,2) -> coda
/// [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,
cache: &WeightCache, 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)
forward_inkling_with_state(cache, 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,
cache: &WeightCache, 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 cur = embed_token(cache, token, h, vocab)?;
if std::env::var("VETTA_DBG_NORM").is_ok() {
let mut eh = vec![0f32; h]; cur.d2h(&mut eh).unwrap();
let n = eh.iter().map(|v| v * v).sum::<f32>().sqrt();
@@ -421,7 +507,7 @@ pub fn forward_inkling_with_state(
}
let mut blocks: Vec<DeviceBuf> = Vec::new();
// Prelude.
for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
for ip in 0..6 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?;
let n_prelude_blocks = blocks.len();
if std::env::var("VETTA_DBG_NORM").is_ok() {
@@ -444,7 +530,7 @@ pub fn forward_inkling_with_state(
}
for ip in 6..18 {
if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() {
let mq = load_msg_queries(ar, ip, h)?;
let mq = load_msg_queries(cache, ip, h)?;
let n_bank = bank.len();
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
let mut bh = vec![0f32; n_bank.max(1) * h];
@@ -453,22 +539,22 @@ pub fn forward_inkling_with_state(
let msgs_buf = DeviceBuf::alloc(4 * h * 4)?;
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, states, max_seq, pos, p, Some((&cw, &msgs)))?;
let cw = cache.controllers(ip)?;
run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, Some((&cw, &msgs)))?;
} else {
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, p, None)?;
run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, None)?;
}
}
}
// Coda.
for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
for ip in 18..24 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
if std::env::var("VETTA_DBG_NORM").is_ok() {
let mut ch = vec![0f32; h]; cur.d2h(&mut ch).unwrap();
let n = ch.iter().map(|v| v * v).sum::<f32>().sqrt();
eprintln!("[dbg] after coda: cur_norm={n:.3} blocks={}", blocks.len());
for (i, b) in blocks.iter().enumerate() { let mut bh = vec![0f32; h]; b.d2h(&mut bh).unwrap(); let bn = bh.iter().map(|v| v * v).sum::<f32>().sqrt(); eprintln!("[dbg] block[{i}]_norm={bn:.3}"); }
}
final_logits(ar, &cur, &blocks, h, vocab, d.eps, cap)
final_logits(cache, &cur, &blocks, h, vocab, d.eps, cap)
}
/// Load a full-attn ShortConv static weight tensor [4, C] transposed to the
@@ -536,7 +622,7 @@ pub fn load_full_layer(ar: &SafetensorsArchive, ip: usize, d: &Dims) -> Result<F
/// split into in0/in1/in2, separate q/k/v norms, projections from distinct
/// inputs, dynamic ShortConv K/V, tau on Q/R, global (window=0) flash attention.
pub fn layer_forward_full(
ar: &SafetensorsArchive, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
@@ -633,7 +719,7 @@ pub fn layer_forward_full(
vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?;
let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>() };
if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); }
let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?;
let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?;
let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?;
let moeout = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?;
@@ -708,10 +794,11 @@ mod tests {
#[ignore]
fn multi_layer_prelude_forward() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
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 (cur, blocks) = forward_swa_layers(&ar, &[0, 1, 2, 3, 4], &d, 100, 1, 0).unwrap();
let (cur, blocks) = forward_swa_layers(&cache, &[0, 1, 2, 3, 4], &d, 100, 1, 0).unwrap();
assert_eq!(blocks.len(), 1, "prelude 0..4 snapshots only at ip=0");
let logits = final_logits(&ar, &cur, &blocks, d.hidden, 201024, d.eps, 30.0).unwrap();
let logits = final_logits(&cache, &cur, &blocks, d.hidden, 201024, d.eps, 30.0).unwrap();
let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap();
assert!(lg.iter().all(|v| v.is_finite()), "logits must be finite");
assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "softcap must bound logits");
@@ -729,14 +816,15 @@ mod tests {
#[ignore]
fn full_attn_layer_end_to_end() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
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 cur = embed_token(&ar, 100, d.hidden, 201024).unwrap();
let cur = embed_token(&cache, 100, d.hidden, 201024).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
let mut seed = vec![0f32; d.hidden]; cur.d2h(&mut seed).unwrap();
let b0 = DeviceBuf::alloc(d.hidden * 4).unwrap(); b0.h2d(&seed).unwrap(); blocks.push(b0);
let w = load_full_layer(&ar, 5, &d).unwrap();
let mut st = new_state(&d, 1).unwrap();
layer_forward_full(&ar, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap();
layer_forward_full(&cache, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=5 does not snapshot (5%6!=0)");
let mut out = vec![0f32; d.hidden]; cur.d2h(&mut out).unwrap();
assert!(out.iter().all(|v| v.is_finite()), "full-attn residual must be finite");
@@ -752,8 +840,9 @@ mod tests {
#[ignore]
fn full_inkling_forward_logits() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
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 logits = forward_inkling(&ar, &d, 100, 201024, 1, 0, 30.0).unwrap();
let logits = forward_inkling(&cache, &d, 100, 201024, 1, 0, 30.0).unwrap();
let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap();
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");
@@ -775,6 +864,7 @@ mod tests {
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 cache = WeightCache::new(&ar);
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;
@@ -788,7 +878,7 @@ mod tests {
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();
logits = forward_inkling_with_state(&cache, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap();
history.push(t); pos += 1;
}
let opts = SamplingOpts::default(); // greedy
@@ -800,7 +890,7 @@ mod tests {
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();
logits = forward_inkling_with_state(&cache, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap();
pos += 1;
}
let text = tok.decode(&generated, true).unwrap();
+4 -2
View File
@@ -716,7 +716,8 @@ mod tests {
let mut st = crate::layer::new_state(&dims, steps).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
let cache = crate::layer::WeightCache::new(&ar);
crate::layer::layer_forward_swa(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
@@ -838,7 +839,8 @@ mod tests {
let mut st = crate::layer::new_state(&dims, 1).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
crate::layer::layer_forward_full(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
let cache = crate::layer::WeightCache::new(&ar);
crate::layer::layer_forward_full(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// CPU oracle
let qn_f = read_bf16_f32(&ar, &format!("{l}.q_input_norm.weight"));