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
aien-sovereign-core-mv / crates / aien-omegese-constraint / src / table.rs
| 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 | //! The model vocabulary as byte strings, with each token's shape against Omegese's word |
| 17 | //! separators precomputed, and an encoder for the text the constraint forces. |
| 18 | |
| 19 | use std::collections::HashMap; |
| 20 | use std::path::Path; |
| 21 | |
| 22 | use crate::word::is_sep; |
| 23 | |
| 24 | /// A token's text against the word separators (space, tab, newline, brackets). |
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 26 | pub enum Shape { |
| 27 | /// No program text: a special or added token, or an empty one. |
| 28 | Special, |
| 29 | /// Word bytes only: the token grows the current word. |
| 30 | Word, |
| 31 | /// Word bytes `..a_end` (maybe none), one run of separators `a_end..sep_end`, then word |
| 32 | /// bytes to the end (maybe none): one word boundary. |
| 33 | OneBoundary { a_end: usize, sep_end: usize }, |
| 34 | /// A second separator run after word bytes: the token crosses two word boundaries. |
| 35 | Multi, |
| 36 | } |
| 37 | |
| 38 | fn shape_of(t: &[u8]) -> Shape { |
| 39 | if t.is_empty() { |
| 40 | return Shape::Special; |
| 41 | } |
| 42 | let Some(a_end) = t.iter().position(|&b| is_sep(b)) else { |
| 43 | return Shape::Word; |
| 44 | }; |
| 45 | let sep_end = a_end |
| 46 | + t[a_end..] |
| 47 | .iter() |
| 48 | .position(|&b| !is_sep(b)) |
| 49 | .unwrap_or(t.len() - a_end); |
| 50 | if t[sep_end..].iter().any(|&b| is_sep(b)) { |
| 51 | Shape::Multi |
| 52 | } else { |
| 53 | Shape::OneBoundary { a_end, sep_end } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | enum Encoder { |
| 58 | /// The model's own tokenizer: forced text is tokenized as the model would read it. |
| 59 | Hf(Box<tokenizers::Tokenizer>), |
| 60 | /// Longest match over the table (synthetic tables in tests). |
| 61 | Greedy { |
| 62 | by_text: HashMap<Vec<u8>, u32>, |
| 63 | longest: usize, |
| 64 | }, |
| 65 | } |
| 66 | |
| 67 | /// Every token id's bytes (`None` for special tokens) and the encoder for forced text. |
| 68 | pub struct TokenTable { |
| 69 | texts: Vec<Option<Vec<u8>>>, |
| 70 | shapes: Vec<Shape>, |
| 71 | encoder: Encoder, |
| 72 | } |
| 73 | |
| 74 | impl TokenTable { |
| 75 | /// A synthetic table: `texts[id]`, `None` for a special token; forced text is encoded by |
| 76 | /// longest match (the lowest id wins a duplicate). |
| 77 | pub fn from_texts(texts: Vec<Option<Vec<u8>>>) -> Self { |
| 78 | let mut by_text = HashMap::new(); |
| 79 | let mut longest = 0; |
| 80 | for (id, t) in texts.iter().enumerate() { |
| 81 | if let Some(t) = t.as_ref().filter(|t| !t.is_empty()) { |
| 82 | by_text.entry(t.clone()).or_insert(id as u32); |
| 83 | longest = longest.max(t.len()); |
| 84 | } |
| 85 | } |
| 86 | Self::build(texts, Encoder::Greedy { by_text, longest }) |
| 87 | } |
| 88 | |
| 89 | /// The vocabulary of a byte-level BPE `tokenizer.json` (Qwen's). Added tokens (the chat |
| 90 | /// specials) have no program text. `Err` if any other token is not byte-level text. |
| 91 | pub fn from_tokenizer_json(path: &Path) -> Result<Self, String> { |
| 92 | let tk = tokenizers::Tokenizer::from_file(path) |
| 93 | .map_err(|e| format!("load {}: {e}", path.display()))?; |
| 94 | let added = tk.get_added_tokens_decoder(); |
| 95 | let inv = byte_decoder(); |
| 96 | let n = tk.get_vocab_size(true); |
| 97 | let mut texts = Vec::with_capacity(n); |
| 98 | for id in 0..n as u32 { |
| 99 | if added.contains_key(&id) { |
| 100 | texts.push(None); |
| 101 | continue; |
| 102 | } |
| 103 | let Some(s) = tk.id_to_token(id) else { |
| 104 | texts.push(None); |
| 105 | continue; |
| 106 | }; |
| 107 | let bytes = s |
| 108 | .chars() |
| 109 | .map(|c| inv.get(&c).copied()) |
| 110 | .collect::<Option<Vec<u8>>>() |
| 111 | .ok_or_else(|| format!("token {id} ({s:?}) is not byte-level text"))?; |
| 112 | texts.push(Some(bytes)); |
| 113 | } |
| 114 | Ok(Self::build(texts, Encoder::Hf(Box::new(tk)))) |
| 115 | } |
| 116 | |
| 117 | fn build(texts: Vec<Option<Vec<u8>>>, encoder: Encoder) -> Self { |
| 118 | let shapes = texts |
| 119 | .iter() |
| 120 | .map(|t| t.as_deref().map_or(Shape::Special, shape_of)) |
| 121 | .collect(); |
| 122 | Self { |
| 123 | texts, |
| 124 | shapes, |
| 125 | encoder, |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | pub fn len(&self) -> usize { |
| 130 | self.texts.len() |
| 131 | } |
| 132 | |
| 133 | pub fn is_empty(&self) -> bool { |
| 134 | self.texts.is_empty() |
| 135 | } |
| 136 | |
| 137 | /// The bytes of `id`, `None` for a special token or an id outside the table. |
| 138 | pub fn text(&self, id: u32) -> Option<&[u8]> { |
| 139 | self.texts.get(id as usize)?.as_deref() |
| 140 | } |
| 141 | |
| 142 | pub fn shape(&self, id: u32) -> Shape { |
| 143 | self.shapes |
| 144 | .get(id as usize) |
| 145 | .copied() |
| 146 | .unwrap_or(Shape::Special) |
| 147 | } |
| 148 | |
| 149 | /// A special token's id by its content (`<|im_end|>`); only for a `tokenizer.json` table. |
| 150 | pub fn special_id(&self, content: &str) -> Option<u32> { |
| 151 | match &self.encoder { |
| 152 | Encoder::Hf(tk) => tk |
| 153 | .token_to_id(content) |
| 154 | .filter(|&id| self.text(id).is_none()), |
| 155 | Encoder::Greedy { .. } => None, |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// The bytes of a token sequence; `Err` on a special token. |
| 160 | pub fn decode(&self, ids: &[u32]) -> Result<Vec<u8>, String> { |
| 161 | let mut out = Vec::new(); |
| 162 | for &id in ids { |
| 163 | out.extend_from_slice( |
| 164 | self.text(id) |
| 165 | .ok_or_else(|| format!("token {id} has no program text"))?, |
| 166 | ); |
| 167 | } |
| 168 | Ok(out) |
| 169 | } |
| 170 | |
| 171 | /// Tokens for `text`, checked to decode back to exactly `text`. |
| 172 | pub fn encode(&self, text: &str) -> Result<Vec<u32>, String> { |
| 173 | let ids = match &self.encoder { |
| 174 | Encoder::Hf(tk) => tk |
| 175 | .encode(text, false) |
| 176 | .map_err(|e| format!("encode {text:?}: {e}"))? |
| 177 | .get_ids() |
| 178 | .to_vec(), |
| 179 | Encoder::Greedy { by_text, longest } => { |
| 180 | let b = text.as_bytes(); |
| 181 | let mut ids = Vec::new(); |
| 182 | let mut i = 0; |
| 183 | while i < b.len() { |
| 184 | let id = (1..=(*longest).min(b.len() - i)) |
| 185 | .rev() |
| 186 | .find_map(|n| by_text.get(&b[i..i + n]).map(|&id| (id, n))); |
| 187 | let (id, n) = id.ok_or_else(|| { |
| 188 | format!("no token in the table starts byte {i} of {text:?}") |
| 189 | })?; |
| 190 | ids.push(id); |
| 191 | i += n; |
| 192 | } |
| 193 | ids |
| 194 | } |
| 195 | }; |
| 196 | if self.decode(&ids)? != text.as_bytes() { |
| 197 | return Err(format!( |
| 198 | "{text:?} does not round-trip through the tokenizer" |
| 199 | )); |
| 200 | } |
| 201 | Ok(ids) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// GPT-2's byte-level alphabet, inverted: each printable stand-in character to its byte. |
| 206 | fn byte_decoder() -> HashMap<char, u8> { |
| 207 | let mut map = HashMap::new(); |
| 208 | let mut n = 0u32; |
| 209 | for b in 0..=255u8 { |
| 210 | let direct = (b'!'..=b'~').contains(&b) || (0xA1..=0xAC).contains(&b) || b >= 0xAE; |
| 211 | let c = if direct { |
| 212 | char::from(b) |
| 213 | } else { |
| 214 | n += 1; |
| 215 | char::from_u32(255 + n).expect("a valid code point") |
| 216 | }; |
| 217 | map.insert(c, b); |
| 218 | } |
| 219 | map |
| 220 | } |
| 221 | |
| 222 | #[cfg(test)] |
| 223 | mod tests { |
| 224 | use super::*; |
| 225 | |
| 226 | #[test] |
| 227 | fn shapes() { |
| 228 | assert_eq!(shape_of(b"add"), Shape::Word); |
| 229 | assert_eq!(shape_of(b"=-"), Shape::Word); |
| 230 | assert_eq!( |
| 231 | shape_of(b" add"), |
| 232 | Shape::OneBoundary { |
| 233 | a_end: 0, |
| 234 | sep_end: 1 |
| 235 | } |
| 236 | ); |
| 237 | assert_eq!( |
| 238 | shape_of(b"end\n"), |
| 239 | Shape::OneBoundary { |
| 240 | a_end: 3, |
| 241 | sep_end: 4 |
| 242 | } |
| 243 | ); |
| 244 | assert_eq!( |
| 245 | shape_of(b")\n"), |
| 246 | Shape::OneBoundary { |
| 247 | a_end: 0, |
| 248 | sep_end: 2 |
| 249 | } |
| 250 | ); |
| 251 | assert_eq!( |
| 252 | shape_of(b"a b"), |
| 253 | Shape::OneBoundary { |
| 254 | a_end: 1, |
| 255 | sep_end: 2 |
| 256 | } |
| 257 | ); |
| 258 | assert_eq!(shape_of(b" a "), Shape::Multi); |
| 259 | assert_eq!(shape_of(b"(x)"), Shape::Multi); |
| 260 | assert_eq!(shape_of(b""), Shape::Special); |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn the_byte_alphabet_is_a_bijection() { |
| 265 | let d = byte_decoder(); |
| 266 | assert_eq!(d.len(), 256); |
| 267 | assert_eq!(d[&'Ġ'], b' '); |
| 268 | assert_eq!(d[&'Ċ'], b'\n'); |
| 269 | assert_eq!(d[&'a'], b'a'); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn greedy_encoding_round_trips() { |
| 274 | let t = TokenTable::from_texts(vec![ |
| 275 | Some(b"a".to_vec()), |
| 276 | Some(b"ab".to_vec()), |
| 277 | Some(b"b".to_vec()), |
| 278 | None, |
| 279 | ]); |
| 280 | assert_eq!(t.encode("abab").unwrap(), vec![1, 1]); |
| 281 | assert_eq!(t.encode("ba").unwrap(), vec![2, 0]); |
| 282 | assert!(t.encode("c").is_err()); |
| 283 | assert!(t.decode(&[3]).is_err()); |
| 284 | assert_eq!(t.shape(3), Shape::Special); |
| 285 | assert_eq!(t.shape(99), Shape::Special); |
| 286 | } |
| 287 | } |