Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/e5fb0ed9772d5f0c # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#248 (code only) closed derived `e5fb0ed9772d5f0c` #248 Imported from GitHub aien-dev/aien-sovereign-core-mv#248 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `08a24536aac83215b448488acabf59f52041702b` · Head `b2e0892fe0640372d8ea42eb6e83f49adc373db3` ### Fetch it A git bundle of the pull request's head, 11225 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/e5fb0ed9772d5f0c.bundle -o e5fb0ed9772d5f0c.bundle git fetch e5fb0ed9772d5f0c.bundle refs/pull/248/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 248 b2e0892fe0640372d8ea42eb6e83f49adc373db3 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":248,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/248","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:31Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 44ec25dd..e5bb5905 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:009593670dc7accc2b442a6a8c6f3b848ab73de4d6e61df57401bf4bf00b294a", - "compiled_at": "2026-10-06T23:42:37Z", + "compiled_at": "2026-10-06T23:54:32Z", "compiler": "crumb-compile/1", - "digest": "sha256:895beb9623c0f2f3f110ee49ecd6c9a8d00f06f17a9447327c3dd8076b3304eb", + "digest": "sha256:4ed9d62b3cff270611467090a1efaa16acea64916f49361d8fdab17d260409d6", "evidence_files": 90, "evidence_root": "sha256:913405b594470a9dfda6998ea0386eba372f438bce4e9d05c062369a9f7b1e22", - "files": 952, - "generated_at_commit": "9632b10920f7238d3c681f38882d858a346a3977", - "source_tree": "sha256:c5af629fb13f833c34efb0aa8d48de22727a50bc8f98e9342224fe4171f39ffd" + "files": 954, + "generated_at_commit": "e68f200ff7f60ea821590a06901ea534ccc52279", + "source_tree": "sha256:ccae4fb70742224a69ab9e1db58e8e02abd0f07f09f3972c6555b0d5ddec07ae" } }, "history": [], diff --git a/crates/aien-inference-abi/src/tokenizer.rs b/crates/aien-inference-abi/src/tokenizer.rs index 06202cca..2590bfb7 100644 --- a/crates/aien-inference-abi/src/tokenizer.rs +++ b/crates/aien-inference-abi/src/tokenizer.rs @@ -57,6 +57,12 @@ pub enum ChatTemplate { /// The default system message read from the model's own template, if it has one. default_system: Option>, }, + /// The model directory has no chat template at all (a base model). Plain text encode + /// and decode work; every chat render is refused (`try_render` errors with + /// "no chat template"). Chosen only when neither `tokenizer_config.json` `chat_template` + /// nor `chat_template.jinja` exists; a template that exists but is unrecognized is + /// refused at load. + None, } /// The ChatML layouts this engine renders, as the exact Jinja text a model ships in @@ -137,12 +143,19 @@ fn ends_in_assistant(turns: &[(&str, &str)]) -> bool { }) } +fn no_chat_template_error() -> TokenizerError { + TokenizerError::LoadError( + "no chat template: this is a plain (base) model, chat rendering is refused".to_string(), + ) +} + impl ChatTemplate { pub fn name(&self) -> &'static str { match self { Self::Zephyr => "zephyr (TinyLlama chat)", Self::Llama3 => "llama3 (Llama 3 instruct)", Self::ChatMl { .. } => "chatml (<|im_start|> / <|im_end|>)", + Self::None => "none (plain text model)", } } @@ -178,8 +191,17 @@ impl ChatTemplate { /// skipped, and the BOS token is not part of the text (`encode` adds exactly one /// through the tokenizer's post-processor). ChatML: see [`ChatTemplate::ChatMl`]. pub fn render(&self, turns: &[(&str, &str)]) -> String { + self.try_render(turns).expect("no chat template") + } + + /// Like [`ChatTemplate::render`], but a plain model (no chat template) is refused with + /// an error containing "no chat template" instead of a layout being invented. + pub fn try_render(&self, turns: &[(&str, &str)]) -> Result { + if let Self::None = self { + return Err(no_chat_template_error()); + } if let Self::ChatMl { default_system } = self { - return render_chatml(default_system.as_deref(), turns); + return Ok(render_chatml(default_system.as_deref(), turns)); } let mut out = String::new(); for (role, content) in turns { @@ -198,6 +220,7 @@ impl ChatTemplate { "<|start_header_id|>{role}<|end_header_id|>\n\n{body}<|eot_id|>" )), Self::ChatMl { .. } => unreachable!("ChatML returned above"), + Self::None => unreachable!("plain model refused above"), } } if !ends_in_assistant(turns) { @@ -205,9 +228,10 @@ impl ChatTemplate { Self::Zephyr => "<|assistant|>\n", Self::Llama3 => "<|start_header_id|>assistant<|end_header_id|>\n\n", Self::ChatMl { .. } => unreachable!("ChatML returned above"), + Self::None => unreachable!("plain model refused above"), }); } - out + Ok(out) } } @@ -299,19 +323,47 @@ impl ChatTokenizer { ) -> Result { let default_json = dir.join("tokenizer.json"); let mut tokenizer = Self::from_file(tokenizer_json.unwrap_or(&default_json))?; - let template_text = match read_json(&dir.join("tokenizer_config.json"))? - .and_then(|c| c.get("chat_template").and_then(|t| t.as_str()).map(str::to_string)) + // A present `chat_template` key must be a string; any other form (the HF list + // form, null, an object) is an unrecognized template and never falls back to plain. + let config_template = match read_json(&dir.join("tokenizer_config.json"))? + .as_ref() + .and_then(|c| c.get("chat_template")) { - Some(text) => text, - None => std::fs::read_to_string(dir.join("chat_template.jinja")).map_err(|e| { - TokenizerError::LoadError(format!( - "no chat template in {} (tokenizer_config.json chat_template or chat_template.jinja): {}", - dir.display(), - e - )) - })?, + None => None, + Some(serde_json::Value::String(text)) => Some(text.clone()), + Some(other) => { + let found = match other { + serde_json::Value::Array(_) => "a list", + serde_json::Value::Object(_) => "an object", + serde_json::Value::Null => "null", + _ => "a non-string value", + }; + return Err(TokenizerError::LoadError(format!( + "unrecognized chat template form in {}: expected a string, found {}", + dir.join("tokenizer_config.json").display(), + found + ))); + } + }; + let jinja_path = dir.join("chat_template.jinja"); + let template_text = match config_template { + Some(text) => Some(text), + None if jinja_path.exists() => { + Some(std::fs::read_to_string(&jinja_path).map_err(|e| { + TokenizerError::LoadError(format!( + "unreadable chat template {}: {}", + jinja_path.display(), + e + )) + })?) + } + None => None, + }; + // Plain state only when neither source exists; an existing template must be recognized. + tokenizer.template = match template_text { + Some(text) => ChatTemplate::detect(&text)?, + None => ChatTemplate::None, }; - tokenizer.template = ChatTemplate::detect(&template_text)?; let config = read_json(&dir.join("config.json"))?; let stop = read_json(&dir.join("generation_config.json"))? .as_ref() @@ -355,6 +407,11 @@ impl ChatTokenizer { self.template.render(turns) } + /// Fallible [`ChatTokenizer::format_chat`]: refuses a plain model ("no chat template"). + pub fn try_format_chat(&self, turns: &[(&str, &str)]) -> Result { + self.template.try_render(turns) + } + /// Formats a conversation according to the canonical TinyLlama chat template: /// `<|system|>\n{system}\n<|user|>\n{user}\n<|assistant|>\n` pub fn format_chat_prompt(&self, system: Option<&str>, user: &str) -> String { diff --git a/crates/aien-inference-abi/tests/chat_prompt_pin.rs b/crates/aien-inference-abi/tests/chat_prompt_pin.rs new file mode 100644 index 00000000..c3772990 --- /dev/null +++ b/crates/aien-inference-abi/tests/chat_prompt_pin.rs @@ -0,0 +1,51 @@ +//! Pins the composed chat prompt token ids for a fixed chat input, so the plain-model +//! change cannot alter how chat-template models build prompts. Ids were computed on +//! origin/main (86841ba) before the change. + +use aien_inference_abi::tokenizer::{ChatTemplate, ChatTokenizer}; +use std::path::Path; + +const TURNS: &[(&str, &str)] = &[("system", "You are terse."), ("user", " What is 2+2?\n")]; + +fn ids(dir: &Path) -> (ChatTemplate, String, Vec) { + let tok = ChatTokenizer::from_model_dir(dir, None).expect("load"); + let text = tok.template().render(TURNS); + let ids = tok.encode(&text).expect("encode"); + (tok.template(), text, ids) +} + +#[test] +fn pin_tinyllama_zephyr_fixture_prompt_ids() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures"); + let (t, text, ids) = ids(&dir); + println!("PIN zephyr text={text:?} ids={ids:?}"); + assert_eq!(t, ChatTemplate::Zephyr); + assert_eq!( + text, + "<|system|>\nYou are terse.\n<|user|>\nWhat is 2+2?\n<|assistant|>\n" + ); + assert_eq!(ids, PIN_ZEPHYR); +} + +/// CAND-4 model (Llama-3.2-1B-Instruct): set `AIEN_LLAMA3_DIR` to its model directory. +#[test] +fn pin_llama32_1b_prompt_ids() { + let Ok(dir) = std::env::var("AIEN_LLAMA3_DIR") else { + eprintln!("AIEN_LLAMA3_DIR not set: Llama 3.2 pin skipped"); + return; + }; + let (t, text, ids) = ids(Path::new(&dir)); + println!("PIN llama3 text={text:?} ids={ids:?}"); + assert_eq!(t, ChatTemplate::Llama3); + assert_eq!(ids, PIN_LLAMA32); +} + +const PIN_ZEPHYR: &[u32] = &[ + 1, 529, 29989, 5205, 29989, 29958, 13, 3492, 526, 1935, 344, 29889, 2, 29871, 13, 29966, 29989, + 1792, 29989, 29958, 13, 5618, 338, 29871, 29906, 29974, 29906, 29973, 2, 29871, 13, 29966, + 29989, 465, 22137, 29989, 29958, 13, +]; +const PIN_LLAMA32: &[u32] = &[ + 128000, 128006, 9125, 128007, 271, 2675, 527, 51637, 13, 128009, 128006, 882, 128007, 271, + 3923, 374, 220, 17, 10, 17, 30, 128009, 128006, 78191, 128007, 271, +]; diff --git a/crates/aien-inference-abi/tests/plain_model_load.rs b/crates/aien-inference-abi/tests/plain_model_load.rs new file mode 100644 index 00000000..27028534 --- /dev/null +++ b/crates/aien-inference-abi/tests/plain_model_load.rs @@ -0,0 +1,101 @@ +//! A base (non-chat) model directory has no chat template: it loads with an explicit +//! "no chat template" state, plain encode/decode work, and chat rendering is refused. +//! An existing but unrecognized template is still refused at load. + +use aien_inference_abi::tokenizer::{ChatTemplate, ChatTokenizer}; +use std::path::{Path, PathBuf}; + +const DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/openwaldo-byte"); + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("aien-plain-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for f in ["tokenizer.json", "config.json", "generation_config.json"] { + std::fs::copy(Path::new(DIR).join(f), dir.join(f)).unwrap(); + } + dir +} + +#[test] +fn model_dir_without_template_loads_as_plain() { + let tok = ChatTokenizer::from_model_dir(Path::new(DIR), None).expect("plain model loads"); + assert_eq!(tok.template(), ChatTemplate::None); + assert!(tok.stop_token_ids().contains(&2)); + let ids = tok.encode("hi").expect("plain encode"); + assert!(!ids.is_empty()); + assert!(tok + .decode_opts(&ids, true) + .expect("plain decode") + .contains("hi")); +} + +#[test] +fn chat_render_on_plain_model_is_refused() { + let tok = ChatTokenizer::from_model_dir(Path::new(DIR), None).unwrap(); + let err = tok + .try_format_chat(&[("user", "hello")]) + .unwrap_err() + .to_string(); + assert!(err.contains("no chat template"), "{err}"); + let err = ChatTemplate::None + .try_render(&[("user", "hello")]) + .unwrap_err() + .to_string(); + assert!(err.contains("no chat template"), "{err}"); +} + +#[test] +fn unrecognized_template_still_refused_at_load() { + let dir = scratch("unrec"); + std::fs::write( + dir.join("tokenizer_config.json"), + r#"{"chat_template": "{{ messages }}"}"#, + ) + .unwrap(); + let err = ChatTokenizer::from_model_dir(&dir, None) + .err() + .expect("refused") + .to_string(); + assert!(err.contains("unsupported chat template"), "{err}"); + std::fs::write(dir.join("tokenizer_config.json"), "{}").unwrap(); + std::fs::write(dir.join("chat_template.jinja"), "{{ messages }}").unwrap(); + assert!(ChatTokenizer::from_model_dir(&dir, None).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Plain prompt format: the text is passed to the tokenizer as-is, nothing is wrapped +/// around it. Whatever the model's own tokenizer.json adds (BOS via its post-processor) +/// is added, exactly as `from_file` + `encode` does; the OpenWALDO byte tokenizer has +/// none, so "hi" is its two bytes (h=104, i=105, ids = byte + 3). +#[test] +fn plain_prompt_is_text_encoded_as_is() { + let tok = ChatTokenizer::from_model_dir(Path::new(DIR), None).unwrap(); + let direct = ChatTokenizer::from_file(format!("{DIR}/tokenizer.json")).unwrap(); + assert_eq!(tok.encode("hi").unwrap(), direct.encode("hi").unwrap()); + assert_eq!(tok.encode("hi").unwrap(), vec![107, 108]); +} + +/// A `chat_template` key that is present but not a string (Hugging Face's list form +/// `[{name, template}, ...]`, `null`, or an object) is an unrecognized template, not +/// "no template": it is refused at load and never falls back to the plain state. +#[test] +fn non_string_template_key_is_refused_not_plain() { + let dir = scratch("nonstring"); + for form in [ + r#"{"chat_template": [{"name": "default", "template": "{{ messages }}"}]}"#, + r#"{"chat_template": null}"#, + r#"{"chat_template": {"template": "{{ messages }}"}}"#, + ] { + std::fs::write(dir.join("tokenizer_config.json"), form).unwrap(); + let err = ChatTokenizer::from_model_dir(&dir, None) + .err() + .unwrap_or_else(|| panic!("loaded as plain: {form}")) + .to_string(); + assert!( + err.contains("unrecognized chat template form"), + "{form}: {err}" + ); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 61bf8059..003c4a3b 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -31,6 +31,18 @@ pub fn format_chat(template: aien_inference_abi::ChatTemplate, messages: &[ChatT template.render(&turns) } +/// Fallible [`format_chat`]: a plain model (no chat template) is refused. +pub fn try_format_chat( + template: aien_inference_abi::ChatTemplate, + messages: &[ChatTurn], +) -> Result { + let turns: Vec<(&str, &str)> = messages + .iter() + .map(|m| (m.role.as_str(), m.content.as_str())) + .collect(); + template.try_render(&turns) +} + /// TinyLlama chat template. Generation always continues from an assistant header. pub fn format_tinyllama_chat(messages: &[ChatTurn]) -> String { format_chat(aien_inference_abi::ChatTemplate::Zephyr, messages) diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index d3e6a23b..c2c337cf 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -280,8 +280,9 @@ impl AienRuntimeServer { let prompt_tokens = { let guard = self.tokenizer.read().expect("tokenizer lock"); guard.as_ref().and_then(|t| { - t.encode(&crate::control::format_chat(t.template(), &messages)) + crate::control::try_format_chat(t.template(), &messages) .ok() + .and_then(|text| t.encode(&text).ok()) .map(|ids| ids.len()) }) }; @@ -337,7 +338,8 @@ async fn submit_turn( // tokenizer adds the one BOS token. let prompt = format!( "{}{assistant_prefix}", - crate::control::format_chat(tokenizer.template(), &messages) + crate::control::try_format_chat(tokenizer.template(), &messages) + .map_err(|error| format!("{error}"))? ); let tokens = tokenizer .encode(&prompt) diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 45908df8..3dc72e0b 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -757,6 +757,8 @@ pub fn compose_assistant_prefix(template: &aien_inference_abi::ChatTemplate) -> use aien_inference_abi::ChatTemplate; match template { ChatTemplate::Zephyr | ChatTemplate::Llama3 => COMPOSE_ASSISTANT_PREFIX, + // A plain model never reaches generation (chat render is refused first). + ChatTemplate::None => COMPOSE_ASSISTANT_PREFIX, ChatTemplate::ChatMl { .. } => "filename:", } } ```