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.
123 lines
4.6 KiB
Rust
123 lines
4.6 KiB
Rust
//! 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:?}");
|
|
}
|
|
} |