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-omegese-constraint / tests / qwen_vocab.rs

290 lines · 11190 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//! Host integration: the real Qwen vocabulary against the real oracle on the public dev programs.
17//! Each program is walked through the constraint one step at a time; at every masked step the
18//! token Qwen's own tokenizer would write next must be allowed, unless it crosses two word
19//! boundaries (the one refusal the mapping makes on purpose), in which case the longest allowed
20//! token that still writes the program is taken. Needs `OMEGESE_BIN`, `QWEN_TOKENIZER` (the
21//! model's tokenizer.json) and `OMEGESE_DEV_DIRS` (colon-separated folders searched for
22//! `*.omegese`).
23
24mod common;
25
26use std::collections::HashSet;
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::time::Duration;
30
31use aien_inference_abi::generation::{Constraint, StepRule};
32use aien_omegese_constraint::word::is_sep;
33use aien_omegese_constraint::{
34 Answer, Framing, ItemOracle, OmegeseConstraint, Shape, Signature, SubprocessOracle, TokenTable,
35};
36use common::*;
37
38fn programs() -> Vec<PathBuf> {
39 fn walk(d: &Path, out: &mut Vec<PathBuf>) {
40 let mut es: Vec<_> = std::fs::read_dir(d)
41 .unwrap_or_else(|e| panic!("{}: {e}", d.display()))
42 .map(|e| e.unwrap().path())
43 .collect();
44 es.sort();
45 for p in es {
46 if p.is_dir() {
47 walk(&p, out);
48 } else if p.extension().is_some_and(|x| x == "omegese") {
49 out.push(p);
50 }
51 }
52 }
53 let dirs = std::env::var("OMEGESE_DEV_DIRS").expect("set OMEGESE_DEV_DIRS");
54 let mut out = Vec::new();
55 for d in dirs.split(':').filter(|d| !d.is_empty()) {
56 walk(Path::new(d), &mut out);
57 }
58 assert!(!out.is_empty(), "no *.omegese under OMEGESE_DEV_DIRS");
59 out
60}
61
62#[derive(Default)]
63struct Tally {
64 masked: u64,
65 canonical_ok: u64,
66 refused_multi: u64,
67 refused_other: Vec<String>,
68 checked: u64,
69 unsound: Vec<String>,
70 forced: u64,
71 calls: u64,
72 masked_out_multi: u64,
73 times: Vec<Duration>,
74}
75
76/// Walks `text` (a whole program) through a fresh constraint; returns what it saw.
77fn walk(table: &Arc<TokenTable>, bin: &Path, stop: u32, text: &str, header: bool, t: &mut Tally) {
78 let framing = Framing {
79 open_fence: Some("```\n".into()),
80 header: header.then(|| Signature::from_header(text.lines().next().unwrap()).unwrap()),
81 mask_body: true,
82 close_fence: "```".into(),
83 stop_token: stop,
84 };
85 let oracle = SubprocessOracle::new(bin).unwrap();
86 let mut check = SubprocessOracle::new(bin).unwrap();
87 let mut k = OmegeseConstraint::new(table.clone(), oracle, framing).unwrap();
88 let mut gen: Vec<u32> = Vec::new();
89 loop {
90 let rule = k
91 .rule(&[], &gen)
92 .unwrap_or_else(|e| panic!("{e}\nafter {:?}", String::from_utf8_lossy(k.program())));
93 let prog = k.program();
94 assert!(
95 text.as_bytes().starts_with(prog),
96 "the program left the text"
97 );
98 let rest = &text[prog.len()..];
99 match rule {
100 StepRule::Force(id) => {
101 t.forced += 1;
102 gen.push(id);
103 if id == stop {
104 break;
105 }
106 }
107 StepRule::Allow(set) => {
108 t.masked += 1;
109 // Soundness: every allowed token that ends in a separator (the blank and bracket
110 // tokens among them) and about 8 others spread over the set must leave a prefix
111 // the oracle does not refuse.
112 let mut keys = HashSet::new();
113 let spread = (set.len() / 8).max(1);
114 for (i, &id) in set.iter().enumerate() {
115 let Some(x) = table.text(id) else { continue };
116 if x.contains(&b'`')
117 || !(x.last().is_some_and(|&b| is_sep(b)) || i % spread == 0)
118 {
119 continue;
120 }
121 let mut p = prog.to_vec();
122 p.extend_from_slice(x);
123 if !keys.insert(normalize(&p)) {
124 continue;
125 }
126 t.checked += 1;
127 if let Answer::Refused(r) = check.next(&p).unwrap() {
128 t.unsound.push(format!(
129 "{:?} after {:?}: {r}",
130 String::from_utf8_lossy(x),
131 String::from_utf8_lossy(prog)
132 ));
133 }
134 }
135 if rest.is_empty() {
136 let close = set
137 .iter()
138 .copied()
139 .find(|&id| table.text(id).is_some_and(|x| x.contains(&b'`')))
140 .expect("eof offers the closing fence");
141 gen.push(close);
142 continue;
143 }
144 let canon = table.encode(rest).unwrap()[0];
145 if set.binary_search(&canon).is_ok() {
146 t.canonical_ok += 1;
147 gen.push(canon);
148 continue;
149 }
150 let ct = String::from_utf8_lossy(table.text(canon).unwrap()).to_string();
151 if table.shape(canon) == Shape::Multi {
152 t.refused_multi += 1;
153 } else {
154 t.refused_other
155 .push(format!("{ct:?} after {:?}", String::from_utf8_lossy(prog)));
156 }
157 let fallback = set
158 .iter()
159 .copied()
160 .filter(|&id| {
161 table
162 .text(id)
163 .is_some_and(|x| rest.as_bytes().starts_with(x))
164 })
165 .max_by_key(|&id| table.text(id).unwrap().len())
166 .unwrap_or_else(|| panic!("no allowed token writes {rest:?}"));
167 gen.push(fallback);
168 }
169 StepRule::Finish => break,
170 StepRule::Any => panic!("Any inside a masked body"),
171 }
172 }
173 assert_eq!(k.program(), text.as_bytes());
174 let reply = table.decode(&gen[..gen.len() - 1]).unwrap();
175 assert_eq!(reply, format!("```\n{text}```").into_bytes());
176 let st = k.stats();
177 t.calls += st.oracle_calls;
178 t.masked_out_multi += st.multi_boundary_refused;
179 t.times.extend(st.step_times.iter().copied());
180}
181
182#[test]
183#[ignore = "needs OMEGESE_BIN, QWEN_TOKENIZER and OMEGESE_DEV_DIRS"]
184fn qwen_vocab_writes_every_dev_program_through_the_real_oracle() {
185 let bin = omegese_bin();
186 let tok = std::env::var("QWEN_TOKENIZER").expect("set QWEN_TOKENIZER to tokenizer.json");
187 let table = Arc::new(TokenTable::from_tokenizer_json(Path::new(&tok)).unwrap());
188 let stop = table.special_id("<|im_end|>").expect("<|im_end|>");
189 println!("vocabulary: {} tokens, stop {stop}", table.len());
190 // The vocabulary by shape, over tokens made only of bytes Omegese text can hold.
191 let mut census = [0u64; 3];
192 for id in 0..table.len() as u32 {
193 let Some(x) = table.text(id) else { continue };
194 if !x
195 .iter()
196 .all(|&b| b.is_ascii_alphanumeric() || b"_-= \t\n()".contains(&b))
197 {
198 continue;
199 }
200 census[match table.shape(id) {
201 Shape::Word => 0,
202 Shape::OneBoundary { .. } => 1,
203 _ => 2,
204 }] += 1;
205 }
206 println!(
207 "omegese-byte tokens: no boundary {}, one boundary {}, two or more boundaries {}",
208 census[0], census[1], census[2]
209 );
210 assert!(
211 census[2] > 0,
212 "the vocabulary has tokens the mapping refuses"
213 );
214 let mut all = Tally::default();
215 for p in programs() {
216 let mut text = std::fs::read_to_string(&p).unwrap();
217 if !text.ends_with('\n') {
218 text.push('\n');
219 }
220 emit(&bin, text.as_bytes()).unwrap_or_else(|e| panic!("{}: {e}", p.display()));
221 let header_ok = Signature::from_header(text.lines().next().unwrap()).is_ok()
222 && text.starts_with("fn ")
223 && text.matches("\nfn ").count() == 0;
224 for header in [false, true] {
225 if header && !header_ok {
226 continue;
227 }
228 let mut t = Tally::default();
229 walk(&table, &bin, stop, &text, header, &mut t);
230 println!(
231 "{} header={header}: masked {} canonical-ok {} two-boundary-refused {} other-refused {} forced {} oracle-calls {}",
232 p.display(),
233 t.masked,
234 t.canonical_ok,
235 t.refused_multi,
236 t.refused_other.len(),
237 t.forced,
238 t.calls
239 );
240 all.masked += t.masked;
241 all.canonical_ok += t.canonical_ok;
242 all.refused_multi += t.refused_multi;
243 all.refused_other.extend(t.refused_other);
244 all.checked += t.checked;
245 all.unsound.extend(t.unsound);
246 all.forced += t.forced;
247 all.calls += t.calls;
248 all.masked_out_multi += t.masked_out_multi;
249 all.times.extend(t.times);
250 }
251 }
252 all.times.sort();
253 let n = all.times.len();
254 let us = |d: Duration| d.as_micros();
255 let mean = all.times.iter().sum::<Duration>() / n as u32;
256 println!(
257 "TOTAL masked {} canonical-ok {} two-boundary-refused {} other-refused {} forced {} oracle-calls {} ({:.2} per masked step); two-boundary tokens masked out (token x step) {}",
258 all.masked,
259 all.canonical_ok,
260 all.refused_multi,
261 all.refused_other.len(),
262 all.forced,
263 all.calls,
264 all.calls as f64 / all.masked as f64
265,
266 all.masked_out_multi
267 );
268 println!(
269 "STEP LATENCY (oracle calls + vocabulary scan) over {n} masked steps: mean {} us, median {} us, p95 {} us, max {} us",
270 us(mean),
271 us(all.times[n / 2]),
272 us(all.times[n * 95 / 100]),
273 us(all.times[n - 1])
274 );
275 println!(
276 "SOUNDNESS {} allowed continuations checked against the oracle, {} refused",
277 all.checked,
278 all.unsound.len()
279 );
280 assert!(
281 all.unsound.is_empty(),
282 "allowed tokens the oracle refuses: {:#?}",
283 all.unsound
284 );
285 assert!(
286 all.refused_other.is_empty(),
287 "tokens refused although they cross at most one boundary: {:#?}",
288 all.refused_other
289 );
290}