interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-serve-http / src / codec.rs

214 lines · 7020 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Text <-> token ids and chat rendering, behind a trait so the server's tests run
17//! without a model directory.
18//!
19//! [`HfCodec`] wraps the workspace's `ChatTokenizer` (pure Rust Hugging Face
20//! tokenizer plus the pinned chat templates): for the Qwen3-30B-A3B-Instruct-2507
21//! checkpoint it detects the Qwen3-Instruct-2507 ChatML branch (no `<think>` block,
22//! no tools) and the stop set `[151645, 151643]` from `generation_config.json`.
23//! [`ByteCodec`] is the test double: one token per byte, stop id 256.
24
25use std::fmt;
26use std::path::Path;
27
28use aien_inference_abi::tokenizer::{ChatOptions, ChatTemplate, ChatTokenizer, TokenizerError};
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum CodecError {
32 /// The conversation cannot be rendered (tool role, unsupported layout, no template).
33 Unrenderable(String),
34 /// Encoding or decoding failed, or the text is longer than the context.
35 Failed(String),
36}
37
38impl fmt::Display for CodecError {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::Unrenderable(m) => write!(f, "{m}"),
42 Self::Failed(m) => write!(f, "{m}"),
43 }
44 }
45}
46
47impl std::error::Error for CodecError {}
48
49impl From<TokenizerError> for CodecError {
50 fn from(e: TokenizerError) -> Self {
51 match e {
52 TokenizerError::NoChatTemplate(_)
53 | TokenizerError::ToolTurnRefused(_)
54 | TokenizerError::UnsupportedChatLayout(_) => Self::Unrenderable(e.to_string()),
55 other => Self::Failed(other.to_string()),
56 }
57 }
58}
59
60pub trait Codec: Send + Sync {
61 /// Renders `(role, content)` turns ending in a generation prompt.
62 fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError>;
63 /// [`Self::render_chat`] with the request's template switches. Only templates that define
64 /// them read them; the default ignores them.
65 fn render_chat_with(
66 &self,
67 turns: &[(&str, &str)],
68 _opts: &ChatOptions,
69 ) -> Result<String, CodecError> {
70 self.render_chat(turns)
71 }
72 /// The token that closes a thinking block, for a template whose generation prompt opens one
73 /// (`<think>\n`). `None`: the model has no thinking block.
74 fn reasoning_end_id(&self) -> Option<u32> {
75 None
76 }
77 fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError>;
78 /// Decodes without special tokens. A sequence cut inside a multi-byte
79 /// character must decode with a trailing U+FFFD, never fail.
80 fn decode(&self, tokens: &[u32]) -> Result<String, CodecError>;
81 fn stop_token_ids(&self) -> Vec<u32>;
82}
83
84/// The model's own tokenizer and chat template.
85pub struct HfCodec {
86 tokenizer: ChatTokenizer,
87 template_name: &'static str,
88}
89
90impl HfCodec {
91 pub fn from_model_dir(dir: &Path) -> Result<Self, CodecError> {
92 let tokenizer = ChatTokenizer::from_model_dir(dir, None)?;
93 let template_name = tokenizer.template().name();
94 Ok(Self {
95 tokenizer,
96 template_name,
97 })
98 }
99
100 /// The detected chat layout, e.g. `chatml-qwen3` (for the operator log).
101 pub fn template_name(&self) -> &'static str {
102 self.template_name
103 }
104}
105
106impl Codec for HfCodec {
107 fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> {
108 Ok(self.tokenizer.try_format_chat(turns)?)
109 }
110
111 fn render_chat_with(
112 &self,
113 turns: &[(&str, &str)],
114 opts: &ChatOptions,
115 ) -> Result<String, CodecError> {
116 Ok(self.tokenizer.try_format_chat_with(turns, opts)?)
117 }
118
119 fn reasoning_end_id(&self) -> Option<u32> {
120 if !matches!(
121 self.tokenizer.template(),
122 ChatTemplate::Qwen38 | ChatTemplate::Qwen36 | ChatTemplate::Qwen35
123 ) {
124 return None;
125 }
126 match self
127 .tokenizer
128 .encode_with_special("</think>", true)
129 .ok()?
130 .as_slice()
131 {
132 [id] => Some(*id),
133 _ => None,
134 }
135 }
136
137 fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> {
138 Ok(self.tokenizer.encode_with_special(text, true)?)
139 }
140
141 fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> {
142 Ok(self.tokenizer.decode_opts(tokens, true)?)
143 }
144
145 fn stop_token_ids(&self) -> Vec<u32> {
146 self.tokenizer.stop_token_ids().to_vec()
147 }
148}
149
150/// Test codec: token id = byte value, stop id 256. The chat layout is
151/// `<role>content</role>\n` per turn then `<assistant>`.
152#[derive(Debug, Default, Clone)]
153pub struct ByteCodec;
154
155impl ByteCodec {
156 pub const STOP: u32 = 256;
157}
158
159impl Codec for ByteCodec {
160 fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> {
161 if turns.iter().any(|(r, _)| r.eq_ignore_ascii_case("tool")) {
162 return Err(CodecError::Unrenderable("role tool refused".into()));
163 }
164 let mut out = String::new();
165 for (role, content) in turns {
166 out.push_str(&format!("<{role}>{content}</{role}>\n"));
167 }
168 out.push_str("<assistant>");
169 Ok(out)
170 }
171
172 fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> {
173 Ok(text.bytes().map(u32::from).collect())
174 }
175
176 fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> {
177 let bytes: Vec<u8> = tokens
178 .iter()
179 .filter(|&&t| t < 256)
180 .map(|&t| t as u8)
181 .collect();
182 Ok(String::from_utf8_lossy(&bytes).into_owned())
183 }
184
185 fn stop_token_ids(&self) -> Vec<u32> {
186 vec![Self::STOP]
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn byte_codec_round_trips_and_marks_partial_utf8() {
196 let c = ByteCodec;
197 let ids = c.encode("héllo").unwrap();
198 assert_eq!(ids.len(), 6);
199 assert_eq!(c.decode(&ids).unwrap(), "héllo");
200 let cut = c.decode(&ids[..2]).unwrap();
201 assert!(cut.ends_with('\u{FFFD}'), "{cut:?}");
202 }
203
204 #[test]
205 fn byte_codec_renders_turns_and_refuses_tool() {
206 let c = ByteCodec;
207 let s = c.render_chat(&[("system", "s"), ("user", "u")]).unwrap();
208 assert_eq!(s, "<system>s</system>\n<user>u</user>\n<assistant>");
209 assert!(matches!(
210 c.render_chat(&[("tool", "x")]),
211 Err(CodecError::Unrenderable(_))
212 ));
213 }
214}