From 58fd3b1bfd0b5682a3b45905348ce31c8046e6cc Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Tue, 6 Oct 2026 14:19:42 -0500 Subject: [PATCH 1/2] inference: ChatML template from the model's own files (SmolLM2-1.7B-Instruct) + per-template compose prefix - ChatTemplate::ChatMl { default_system }: detected from tokenizer_config.json chat_template only when it is exactly the plain ChatML layout (SmolLM2's, optionally without its default system block); any other ChatML template (tools, trim, another layout) is refused with an error. Renders the publisher's bytes: verbatim contents, the template's default system message when the first turn is not a system turn, generation prompt <|im_start|>assistant\n. No BOS in the text; SmolLM2's tokenizer.json has no post-processor, so encode adds none (publisher behaviour). - ChatTemplate loses Copy (it now carries the default system text); ChatTokenizer::template() returns a clone. Zephyr and Llama 3 rendering unchanged. - spine::compose_assistant_prefix(template): Zephyr and Llama 3 return COMPOSE_ASSISTANT_PREFIX byte for byte; ChatML returns "filename:" (SmolLM2 BPE: [filename][:], the path keeps its own leading-space token). model_proposer reads it from the loaded tokenizer's template. proposal_prompt unchanged. Seam approved by the NEXT-PHASE-1 v6 owner. - Tests: SmolLM2 config.json/generation_config.json verbatim (24 layers, 32 heads, 32 KV heads, head_dim 64, tied, plain rope 130000, eos [2], 218-tensor catalog without lm_head); SmolLM2 template verbatim against transformers 5.17.0 apply_chat_template strings; refusals; prefix seam (Zephyr/Llama 3 byte-identical, ChatML value); with AIEN_SMOLLM2_DIR the prompt ids equal the transformers ids (40 ids) and the prefix adds [5805, 42]. - NOTICE + ATTRIBUTION.md: SmolLM2-1.7B-Instruct as a third-party Apache-2.0 model (revision 31b70e2e869a, weights sha256 f55217be...a0e8), licence text LICENSES/Apache-2.0.txt, citation from the model card. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Drake Stapleton --- ATTRIBUTION.md | 27 +++ NOTICE | 6 + crates/aien-inference-abi/src/model_dir.rs | 93 ++++++++ crates/aien-inference-abi/src/tokenizer.rs | 200 ++++++++++++++++-- crates/aien-runtime/src/server.rs | 14 +- crates/aien-runtime/src/spine.rs | 14 ++ .../aien-runtime/tests/chat_template_test.rs | 89 +++++++- 7 files changed, 423 insertions(+), 20 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index adbd62d2..1fdbcc4c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -17,3 +17,30 @@ We extend our deep gratitude to Chris Lattner, Tim Davis, and the entire Modular - **NVIDIA**: Blackwell GB10 architecture, TensorRT, NeMo/Nemotron models, and CUDA driver runtime. - **The Rust Community**: Tokio, Axum, Ort (ONNX Runtime C-API bindings), and HuggingFace Tokenizers. - **Radicle**: Sovereign peer-to-peer code collaboration and Heartwood git protocol. + +--- + +## Third-Party Model: SmolLM2-1.7B-Instruct (Hugging Face) + +The runtime can load and run **SmolLM2-1.7B-Instruct** by Hugging Face (HuggingFaceTB), +an open-weights instruction model. It is a separate third-party component, not part of +the AIEN source code, and it keeps its own licence. + +- **Source**: https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct, revision + `31b70e2e869a7173562077fd711b654946d38674`. Weights `model.safetensors` sha256 + `f55217be716b6a997b97b9d8d7eb6fad02e00858f5010ec24f64603c3a98a0e8` (equal to the + publisher's Git LFS object id). Used unmodified: no conversion, no quantization. +- **Licence**: Apache License 2.0 (`Apache-2.0`), as declared in the model card + (`license: apache-2.0`). Full text: `LICENSES/Apache-2.0.txt`. The repository at this + revision ships no separate LICENSE or NOTICE file; its model card (`README.md`) is the + publisher's attribution and is distributed unchanged with the weights. +- **Attribution** (the model card's citation): Loubna Ben Allal, Anton Lozhkov, Elie + Bakouch, Gabriel Martín Blázquez, Guilherme Penedo, Lewis Tunstall, Andrés Marafioti, + Hynek Kydlíček, Agustín Piqueres Lajarín, Vaibhav Srivastav, Joshua Lochner, Caleb + Fahlgren, Xuan-Son Nguyen, Clémentine Fourrier, Ben Burtenshaw, Hugo Larcher, Haojun + Zhao, Cyril Zakka, Mathieu Morlon, Colin Raffel, Leandro von Werra, Thomas Wolf, + "SmolLM2: When Smol Goes Big -- Data-Centric Training of a Small Language Model", + arXiv:2502.02737 (2025). +- **Boundary**: AIEN code stays under AGPL-3.0-or-later. The model files stay under + Apache-2.0 with their notices preserved. Running the model through AIEN, or storing it + under another directory or file name, does not change either licence. diff --git a/NOTICE b/NOTICE index 8af76f76..606feb20 100644 --- a/NOTICE +++ b/NOTICE @@ -14,3 +14,9 @@ license text is in LICENSE, taken verbatim from https://www.gnu.org/licenses/agp Values and anti-enclosure principles live in the nonbinding COVENANT.md, which grants and restricts no legal rights. + +Third-party model (not part of this source tree): SmolLM2-1.7B-Instruct by +Hugging Face (HuggingFaceTB), revision 31b70e2e869a7173562077fd711b654946d38674, +licensed under the Apache License 2.0 (LICENSES/Apache-2.0.txt). Where AIEN +distributes these weights, the publisher's model card and this notice go with +them. Details and attribution: ATTRIBUTION.md. diff --git a/crates/aien-inference-abi/src/model_dir.rs b/crates/aien-inference-abi/src/model_dir.rs index 1061297e..77843a2f 100644 --- a/crates/aien-inference-abi/src/model_dir.rs +++ b/crates/aien-inference-abi/src/model_dir.rs @@ -380,6 +380,99 @@ mod tests { assert_eq!(c.rope_scaling, None); } + /// HuggingFaceTB/SmolLM2-1.7B-Instruct config.json at revision 31b70e2e869a, verbatim + /// (sha256 994f50b16abb4ae00880baefe03c10260b5bd608d2bf586f7056ca05a534feea), and its + /// generation_config.json (sha256 87b916ed...a013). + const SMOLLM2_17B_CONFIG: &str = r#"{ + "architectures": [ + "LlamaForCausalLM" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bos_token_id": 1, + "eos_token_id": 2, + "hidden_act": "silu", + "hidden_size": 2048, + "initializer_range": 0.02, + "intermediate_size": 8192, + "max_position_embeddings": 8192, + "mlp_bias": false, + "model_type": "llama", + "num_attention_heads": 32, + "num_hidden_layers": 24, + "num_key_value_heads": 32, + "pad_token_id": 2, + "pretraining_tp": 1, + "rms_norm_eps": 1e-05, + "rope_scaling": null, + "rope_theta": 130000, + "tie_word_embeddings": true, + "torch_dtype": "bfloat16", + "transformers_version": "4.42.3", + "transformers.js_config": { + "dtype": "q4", + "kv_cache_dtype": { + "q4f16": "float16", + "fp16": "float16" + }, + "use_external_data_format": { + "model.onnx": true, + "model_fp16.onnx": true + } + }, + "use_cache": true, + "vocab_size": 49152 +} +"#; + const SMOLLM2_17B_GENERATION: &str = r#"{ + "_from_model_config": true, + "bos_token_id": 1, + "eos_token_id": 2, + "pad_token_id": 2, + "transformers_version": "4.42.3" +} +"#; + + #[test] + fn smollm2_config_is_full_mha_tied_plain_rope() { + let c = model_config_from_hf_json("s", SMOLLM2_17B_CONFIG, Some(SMOLLM2_17B_GENERATION)) + .unwrap(); + // 32 KV heads = 32 query heads: no GQA sharing (group size 1). + assert_eq!( + (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim), + (24, 32, 32, 64) + ); + assert_eq!( + (c.hidden_dim, c.intermediate_dim, c.vocab_size), + (2048, 8192, 49152) + ); + assert_eq!(c.max_sequence_length, 8192); + assert_eq!(c.rms_norm_eps, 1e-5); + assert!(c.tie_word_embeddings); + assert_eq!(c.eos_token_ids, vec![2]); + // "rope_theta": 130000 is a JSON integer; rope_scaling null is plain rope. + assert_eq!(c.rope_scaling, None); + assert_eq!(c.rope(), aien_abi_core::RopeParams::plain(130000.0)); + let catalog = llama_catalog(&c); + // 218 tensors in the published model.safetensors: embed + norm + 9 per layer. + assert_eq!(catalog.len(), 2 + 9 * 24); + assert!(catalog.iter().all(|(n, _)| n != "lm_head.weight")); + let shape = |name: &str| catalog.iter().find(|(n, _)| n == name).unwrap().1.clone(); + assert_eq!(shape("model.embed_tokens.weight"), vec![49152, 2048]); + assert_eq!( + shape("model.layers.23.self_attn.k_proj.weight"), + vec![2048, 2048] + ); + assert_eq!( + shape("model.layers.0.self_attn.v_proj.weight"), + vec![2048, 2048] + ); + assert_eq!( + shape("model.layers.0.mlp.down_proj.weight"), + vec![2048, 8192] + ); + } + #[test] fn hf_cache_snapshot_dirs_get_the_repo_id() { let dir = Path::new("/c/hub/models--unsloth--Llama-3.2-1B-Instruct/snapshots/5a8a"); diff --git a/crates/aien-inference-abi/src/tokenizer.rs b/crates/aien-inference-abi/src/tokenizer.rs index 720b34cb..06202cca 100644 --- a/crates/aien-inference-abi/src/tokenizer.rs +++ b/crates/aien-inference-abi/src/tokenizer.rs @@ -1,9 +1,10 @@ //! Pure Rust tokenizer and chat template formatter for the Llama model family -//! (TinyLlama zephyr-style chat, Llama 3 instruct chat). +//! (TinyLlama zephyr-style chat, Llama 3 instruct chat, ChatML as shipped by SmolLM2). //! Wraps Hugging Face tokenizers crate without Python runtime dependencies. use std::fmt; use std::path::Path; +use std::sync::Arc; /// Loud error enum for tokenizer operations. #[derive(Debug, Clone, PartialEq, Eq)] @@ -36,7 +37,7 @@ impl std::error::Error for TokenizerError {} /// The chat layout a model was fine-tuned on. Selected from the model's own chat template /// text (no template engine): each variant renders the one layout that template produces /// for plain user/system/assistant turns ending in a generation prompt. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum ChatTemplate { /// TinyLlama-Chat (zephyr): `<|user|>\n{content}\n<|assistant|>\n`. Zephyr, @@ -45,6 +46,95 @@ pub enum ChatTemplate { /// (the Hugging Face template's default "Cutting Knowledge Date / Today Date" block /// depends on the wall clock, so it is left out). Llama3, + /// ChatML exactly as the publisher's template renders it (SmolLM2-Instruct): per turn + /// `<|im_start|>{role}\n{content}<|im_end|>\n`, then `<|im_start|>assistant\n`. Contents + /// are kept verbatim and empty turns are kept (the template neither trims nor skips). + /// When the template carries a default system message and the first turn is not a + /// system turn, that message is rendered first as a system turn, as the template does. + /// No BOS is part of the text; the model's tokenizer decides whether `encode` adds one + /// (SmolLM2's `tokenizer.json` has no post-processor, so it adds none). + ChatMl { + /// The default system message read from the model's own template, if it has one. + default_system: Option>, + }, +} + +/// The ChatML layouts this engine renders, as the exact Jinja text a model ships in +/// `tokenizer_config.json` `chat_template` (the SmolLM2-Instruct template, and the same +/// without its default system block). `{SYSTEM}` stands for the default system message +/// (plain text: no quote, backslash, Jinja brace or ChatML marker). Any other ChatML +/// template (tools, trimming, another generation prompt) is refused, not approximated. +const CHATML_WITH_DEFAULT_SYSTEM: &str = "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\n{SYSTEM}<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"; +const CHATML_PLAIN: &str = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"; + +/// Matches a chat template text against the two ChatML layouts above. Returns the layout +/// with its default system message (None for the plain layout), or a refusal. +fn parse_chatml(template_text: &str) -> Result { + let text = template_text.trim(); + if text == CHATML_PLAIN { + return Ok(ChatTemplate::ChatMl { + default_system: None, + }); + } + let (head, tail) = CHATML_WITH_DEFAULT_SYSTEM + .split_once("{SYSTEM}") + .expect("placeholder in the ChatML layout"); + let system = text + .strip_prefix(head) + .and_then(|rest| rest.strip_suffix(tail)) + .filter(|s| { + !s.is_empty() + && !s.contains(['\'', '\\', '{', '}']) + && !s.contains("<|im_start|>") + && !s.contains("<|im_end|>") + }); + match system { + Some(system) => Ok(ChatTemplate::ChatMl { + default_system: Some(Arc::from(system)), + }), + None => Err(TokenizerError::LoadError( + "unsupported ChatML chat template: only the plain ChatML layout (each turn \ + <|im_start|>role, newline, content, <|im_end|>, newline; generation prompt \ + <|im_start|>assistant and a newline), optionally with one plain-text default \ + system message, is rendered; this template differs (tools, trimming or another \ + layout)" + .to_string(), + )), + } +} + +/// The publisher's ChatML rendering for `(role, content)` turns ending in a generation +/// prompt (see [`ChatTemplate::ChatMl`]). Roles are normalized as for the other layouts. +fn render_chatml(default_system: Option<&str>, turns: &[(&str, &str)]) -> String { + let role_of = |role: &str| match role.trim().to_ascii_lowercase().as_str() { + "system" => "system", + "assistant" => "assistant", + _ => "user", + }; + let mut out = String::new(); + if let (Some(system), Some((first_role, _))) = (default_system, turns.first()) { + if role_of(first_role) != "system" { + out.push_str(&format!("<|im_start|>system\n{system}<|im_end|>\n")); + } + } + for (role, content) in turns { + out.push_str(&format!( + "<|im_start|>{}\n{content}<|im_end|>\n", + role_of(role) + )); + } + if !ends_in_assistant(turns) { + out.push_str("<|im_start|>assistant\n"); + } + out +} + +/// True when the last turn is a non-empty assistant turn: generation then continues it +/// instead of opening a new assistant turn. +fn ends_in_assistant(turns: &[(&str, &str)]) -> bool { + turns.last().is_some_and(|(role, content)| { + role.trim().eq_ignore_ascii_case("assistant") && !content.trim().is_empty() + }) } impl ChatTemplate { @@ -52,30 +142,45 @@ impl ChatTemplate { match self { Self::Zephyr => "zephyr (TinyLlama chat)", Self::Llama3 => "llama3 (Llama 3 instruct)", + Self::ChatMl { .. } => "chatml (<|im_start|> / <|im_end|>)", } } - /// Recognizes the layout from a Jinja chat template's text. + /// Recognizes the layout from a Jinja chat template's text. A ChatML template must be + /// one of the exact layouts this engine renders (see [`ChatTemplate::ChatMl`]). pub fn detect(template_text: &str) -> Result { if template_text.contains("<|start_header_id|>") && template_text.contains("<|eot_id|>") { Ok(Self::Llama3) } else if template_text.contains("<|user|>") && template_text.contains("<|assistant|>") { Ok(Self::Zephyr) + } else if template_text.contains("<|im_start|>") && template_text.contains("<|im_end|>") { + parse_chatml(template_text) } else { Err(TokenizerError::LoadError( - "unsupported chat template: neither zephyr (<|user|>) nor llama3 \ - (<|start_header_id|>) markers found" + "unsupported chat template: no zephyr (<|user|>), llama3 \ + (<|start_header_id|>) or chatml (<|im_start|>) markers found" .to_string(), )) } } - /// Renders `(role, content)` turns. Contents are trimmed and empty turns skipped; roles - /// other than system and assistant are user turns. Generation continues from an - /// assistant header unless the last turn is a non-empty assistant turn. The BOS token - /// is not part of the text: `encode` adds exactly one through the tokenizer's - /// post-processor. + /// The default system message the model's template adds (ChatML only). + pub fn default_system(&self) -> Option<&str> { + match self { + Self::ChatMl { default_system } => default_system.as_deref(), + _ => None, + } + } + + /// Renders `(role, content)` turns; roles other than system and assistant are user + /// turns. Generation continues from an assistant header unless the last turn is a + /// non-empty assistant turn. Zephyr and Llama 3: contents are trimmed and empty turns + /// 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 { + if let Self::ChatMl { default_system } = self { + return render_chatml(default_system.as_deref(), turns); + } let mut out = String::new(); for (role, content) in turns { let body = content.trim(); @@ -92,15 +197,14 @@ impl ChatTemplate { Self::Llama3 => out.push_str(&format!( "<|start_header_id|>{role}<|end_header_id|>\n\n{body}<|eot_id|>" )), + Self::ChatMl { .. } => unreachable!("ChatML returned above"), } } - let ends_in_assistant = turns.last().is_some_and(|(role, content)| { - role.trim().eq_ignore_ascii_case("assistant") && !content.trim().is_empty() - }); - if !ends_in_assistant { + if !ends_in_assistant(turns) { out.push_str(match self { Self::Zephyr => "<|assistant|>\n", Self::Llama3 => "<|start_header_id|>assistant<|end_header_id|>\n\n", + Self::ChatMl { .. } => unreachable!("ChatML returned above"), }); } out @@ -238,7 +342,7 @@ impl ChatTokenizer { /// The chat layout this tokenizer renders. pub fn template(&self) -> ChatTemplate { - self.template + self.template.clone() } /// Token ids that end generation (the model's `eos_token_id` set). @@ -398,6 +502,72 @@ mod tests { assert_eq!(TinyLlamaTokenizer::UNK_TOKEN_ID, 0); } + /// HuggingFaceTB/SmolLM2-1.7B-Instruct tokenizer_config.json `chat_template` at revision + /// 31b70e2e869a, verbatim (the decoded JSON string; its newlines are real newlines). + const SMOLLM2_TEMPLATE: &str = "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"; + + #[test] + fn smollm2_template_is_chatml_with_its_default_system_message() { + let t = ChatTemplate::detect(SMOLLM2_TEMPLATE).unwrap(); + assert_eq!( + t.default_system(), + Some("You are a helpful AI assistant named SmolLM, trained by Hugging Face") + ); + assert!(t.name().starts_with("chatml")); + // Expected strings: transformers 5.17.0 apply_chat_template(add_generation_prompt=True) + // on the same messages with the pinned tokenizer_config.json (scratch run, outside + // the repository). + assert_eq!( + t.render(&[("user", "Goal: X\nAuthorized workspace: /w")]), + "<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n\ + <|im_start|>user\nGoal: X\nAuthorized workspace: /w<|im_end|>\n<|im_start|>assistant\n" + ); + assert_eq!( + t.render(&[("system", "S"), ("user", "U")]), + "<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n" + ); + // Contents verbatim: the template does not trim. + assert!(t + .render(&[("user", " Hi \n")]) + .contains("<|im_start|>user\n Hi \n<|im_end|>\n")); + } + + #[test] + fn chatml_without_default_system_and_refusals() { + let plain = SMOLLM2_TEMPLATE.replace( + "{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n' }}{% endif %}", + "", + ); + let t = ChatTemplate::detect(&plain).unwrap(); + assert_eq!(t.default_system(), None); + assert_eq!( + t.render(&[("user", "U")]), + "<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n" + ); + // A ChatML template with other logic (tools, trimming) is refused, not approximated. + let tools = SMOLLM2_TEMPLATE.replace( + "{% for message in messages %}", + "{% if tools %}{{ tools | tojson }}{% endif %}{% for message in messages %}", + ); + let err = ChatTemplate::detect(&tools).unwrap_err().to_string(); + assert!(err.contains("unsupported ChatML"), "{err}"); + let trimmed = SMOLLM2_TEMPLATE.replace("message['content']", "message['content'] | trim"); + assert!(ChatTemplate::detect(&trimmed).is_err()); + // A default system message with a quote cannot be read as plain text. + let quoted = SMOLLM2_TEMPLATE.replace("named SmolLM", "named 'SmolLM'"); + assert!(ChatTemplate::detect("ed).is_err()); + // Zephyr and Llama 3 detection is unchanged. + assert_eq!( + ChatTemplate::detect("<|user|> ... <|assistant|>").unwrap(), + ChatTemplate::Zephyr + ); + assert_eq!( + ChatTemplate::detect("<|start_header_id|> <|eot_id|>").unwrap(), + ChatTemplate::Llama3 + ); + assert!(ChatTemplate::detect("{{ messages }}").is_err()); + } + #[test] fn test_synthetic_tokenizer_roundtrip() { // Construct a minimal BPE tokenizer JSON for testing encode and decode diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 4f5e73dc..d3e6a23b 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -443,8 +443,14 @@ pub fn model_proposer( role: "user".into(), content: prompt.to_string(), }]; - // The assistant turn starts with the fixed prefix; the reply the - // parser reads is prefix + generated text (ACCEPTANCE-v4 2(1)). + // The assistant turn starts with the template's fixed prefix; the + // reply the parser reads is prefix + generated text (ACCEPTANCE-v4 2(1)). + let prefix = tokenizer + .read() + .expect("tokenizer lock") + .as_ref() + .map(|t| crate::spine::compose_assistant_prefix(&t.template())) + .unwrap_or(crate::spine::COMPOSE_ASSISTANT_PREFIX); handle .block_on(generate_text( spine.clone(), @@ -453,10 +459,10 @@ pub fn model_proposer( max_tokens, 0.0, limit, - crate::spine::COMPOSE_ASSISTANT_PREFIX, + prefix, )) .map(|g| crate::spine::Generation { - text: format!("{}{}", crate::spine::COMPOSE_ASSISTANT_PREFIX, g.text), + text: format!("{prefix}{}", g.text), ..g }) }) diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 3460913a..1cbbcb0a 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -743,6 +743,20 @@ pub const COMPOSE_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::fro /// in front of the path. pub const COMPOSE_ASSISTANT_PREFIX: &str = "filename:"; +/// The compose assistant-response prefix for a model's chat template. Zephyr +/// and Llama 3 keep `COMPOSE_ASSISTANT_PREFIX` byte for byte. ChatML +/// (SmolLM2-Instruct) uses the same text: the proposal template asks for a +/// `filename: ` first line, and in SmolLM2's byte-level BPE +/// `filename:` ends on the colon token, so the path keeps its own leading +/// space token as in Llama 3. `proposal_prompt` is the same for every template. +pub fn compose_assistant_prefix(template: &aien_inference_abi::ChatTemplate) -> &'static str { + use aien_inference_abi::ChatTemplate; + match template { + ChatTemplate::Zephyr | ChatTemplate::Llama3 => COMPOSE_ASSISTANT_PREFIX, + ChatTemplate::ChatMl { .. } => "filename:", + } +} + /// The fixed proposal template of the production RunComposeTask path. pub fn proposal_prompt(goal: &str, workspace: &str) -> String { format!( diff --git a/crates/aien-runtime/tests/chat_template_test.rs b/crates/aien-runtime/tests/chat_template_test.rs index 2b952edd..84189a30 100644 --- a/crates/aien-runtime/tests/chat_template_test.rs +++ b/crates/aien-runtime/tests/chat_template_test.rs @@ -93,8 +93,20 @@ fn proposal_prompt_token_counts() { /// engine cut); nothing follows the colon. #[test] fn assistant_prefix_follows_the_assistant_marker() { - use aien_runtime::spine::{check_file_proposal, COMPOSE_ASSISTANT_PREFIX}; + use aien_inference_abi::ChatTemplate; + use aien_runtime::spine::{ + check_file_proposal, compose_assistant_prefix, COMPOSE_ASSISTANT_PREFIX, + }; assert_eq!(COMPOSE_ASSISTANT_PREFIX, "filename:"); + // The per-template seam keeps Zephyr and Llama 3 byte-identical to the v5 value. + assert_eq!( + compose_assistant_prefix(&ChatTemplate::Zephyr).as_bytes(), + b"filename:" + ); + assert_eq!( + compose_assistant_prefix(&ChatTemplate::Llama3).as_bytes(), + b"filename:" + ); let sent = format!( "{}{}", format_tinyllama_chat(&[turn("user", V2_PROMPT)]), @@ -195,3 +207,78 @@ fn llama3_model_dir_tokenizer_has_one_bos_and_eos_list() { assert_eq!(&tail[..5], &[128009, 128006, 78191, 128007, 271]); assert_eq!(tok.decode(&tail[5..]).unwrap(), "filename:"); } + +/// ChatML (SmolLM2-Instruct): the compose prefix for the ChatML template, and the bytes sent +/// end with the publisher's generation prompt followed directly by it. +#[test] +fn chatml_compose_prefix_follows_the_im_start_assistant_marker() { + use aien_inference_abi::ChatTemplate; + use aien_runtime::control::format_chat; + use aien_runtime::spine::compose_assistant_prefix; + let chatml = ChatTemplate::ChatMl { + default_system: Some( + "You are a helpful AI assistant named SmolLM, trained by Hugging Face".into(), + ), + }; + assert_eq!(compose_assistant_prefix(&chatml).as_bytes(), b"filename:"); + assert_eq!( + compose_assistant_prefix(&ChatTemplate::ChatMl { + default_system: None + }) + .as_bytes(), + b"filename:" + ); + let sent = format!( + "{}{}", + format_chat(chatml, &[turn("user", V2_PROMPT)]), + compose_assistant_prefix(&ChatTemplate::ChatMl { + default_system: None + }) + ); + assert!(sent.starts_with("<|im_start|>system\nYou are a helpful AI assistant named SmolLM")); + assert!(sent.ends_with("<|im_end|>\n<|im_start|>assistant\nfilename:")); +} + +/// With the pinned SmolLM2-1.7B-Instruct directory (`AIEN_SMOLLM2_DIR`, revision +/// 31b70e2e869a): the template is detected from the model's own files, the stop set is +/// `<|im_end|>` (2), encoding adds no BOS, and the prompt ids equal the ids of transformers +/// 5.17.0 `apply_chat_template(tokenize=True, add_generation_prompt=True)` on the same message. +#[test] +fn smollm2_model_dir_tokenizer_matches_the_publisher_template_ids() { + let Ok(dir) = std::env::var("AIEN_SMOLLM2_DIR") else { + eprintln!("AIEN_SMOLLM2_DIR not set: SmolLM2 tokenizer check skipped"); + return; + }; + use aien_inference_abi::ChatTokenizer; + use aien_runtime::control::format_chat; + use aien_runtime::spine::compose_assistant_prefix; + let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).expect("tokenizer"); + assert!(tok.template().name().starts_with("chatml")); + assert_eq!( + tok.template().default_system(), + Some("You are a helpful AI assistant named SmolLM, trained by Hugging Face") + ); + assert_eq!(tok.stop_token_ids(), &[2]); + assert_eq!(tok.token_to_id("<|im_start|>"), Some(1)); + assert_eq!(tok.token_to_id("<|im_end|>"), Some(2)); + let text = format_chat( + tok.template(), + &[turn("user", "Goal: X\nAuthorized workspace: /w")], + ); + let ids = tok.encode(&text).expect("encode"); + let hf: [u32; 40] = [ + 1, 9690, 198, 2683, 359, 253, 5356, 5646, 11173, 3365, 3511, 308, 34519, 28, 7018, 411, + 407, 19712, 8182, 2, 198, 1, 4093, 198, 44474, 42, 2273, 198, 15051, 1005, 26344, 42, 2272, + 103, 2, 198, 1, 520, 9531, 198, + ]; + assert_eq!(ids, hf); + // "filename:" is two tokens and ends on the colon. + let with_prefix = tok + .encode(&format!( + "{text}{}", + compose_assistant_prefix(&tok.template()) + )) + .expect("encode"); + assert_eq!(&with_prefix[..40], &hf); + assert_eq!(&with_prefix[40..], &[5805, 42]); +} From 3773052427cc8a20d1a271e449ef198a7dff78f2 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Tue, 6 Oct 2026 16:28:31 -0500 Subject: [PATCH 2/2] crumb compile Co-Authored-By: Claude Fable 5.1 --- .crumb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.crumb b/.crumb index 10fea390..2f5d180c 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:009593670dc7accc2b442a6a8c6f3b848ab73de4d6e61df57401bf4bf00b294a", - "compiled_at": "2026-10-06T21:14:31Z", + "compiled_at": "2026-10-06T21:28:13Z", "compiler": "crumb-compile/1", - "digest": "sha256:31fcc292b626833b6da475f452754476812be51b3a2775b73f55be12b239c577", + "digest": "sha256:2d1982c7c61e39e9a0c51037afc7cb7866224d773c9d27c3c5eb4bf20e1bc29d", "evidence_files": 25, "evidence_root": "sha256:714fb230bfff0e5d2dc3acefb5a7b31617ff6ff7acfdb94f5f64a6bd722389a5", "files": 854, - "generated_at_commit": "06c18bffa83f639cbc2b8a27fd29306498906b66", - "source_tree": "sha256:136ac93618cacf52622d42ae345bf78c7941d02bf26017068e85baec8f029d24" + "generated_at_commit": "58fd3b1bfd0b5682a3b45905348ce31c8046e6cc", + "source_tree": "sha256:27bb614939d5944febeabdb8be6bbee1221528e6dd96f9a921731e00633770c1" } }, "history": [],