[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.
This commit is contained in:
adm committed 2026-12-01 17:18:27 +01:00
1 parent 1df8342f96
commit 0a46c4dd7b
6 files changed
+288

No files matched your search

Generated
+1
View File
@@ -700,6 +700,7 @@ dependencies = [
name = "vetta-infer-gw" name = "vetta-infer-gw"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"tokenizers",
"vetta-infer-abi", "vetta-infer-abi",
"vetta-infer-hip", "vetta-infer-hip",
"vetta-infer-ld", "vetta-infer-ld",
+1
View File
@@ -12,6 +12,7 @@ path = "src/main.rs"
vetta-infer-abi = { path = "../vetta-infer-abi" } vetta-infer-abi = { path = "../vetta-infer-abi" }
vetta-infer-ld = { path = "../vetta-infer-ld" } vetta-infer-ld = { path = "../vetta-infer-ld" }
vetta-infer-hip = { path = "../vetta-infer-hip", optional = true } vetta-infer-hip = { path = "../vetta-infer-hip", optional = true }
tokenizers = { version = "0.23.2", default-features = false, features = ["fancy-regex"] }
[features] [features]
# Real GPU `serve`/`gen` (links the HIP backend via ld). Default OFF keeps the # 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 session;
pub mod chat_template;
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub mod serve; pub mod serve;
#[cfg(feature = "hip")]
pub mod chat;
/// Python-repr float spelling (always a decimal point), as `strata-ctl` emits. /// Python-repr float spelling (always a decimal point), as `strata-ctl` emits.
fn fmt_float(v: f64) -> String { fn fmt_float(v: f64) -> String {
let s = format!("{v}"); 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 info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)"); 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 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"); eprintln!(" vetta-infer version Print version & build info");
} }
@@ -116,6 +117,31 @@ fn main() -> ExitCode {
ExitCode::from(2) 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(); usage();
ExitCode::from(2) ExitCode::from(2)