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 / echo_walks.rs

563 lines · 21103 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//! The guardrail end to end on the host fake `EchoChainModel` (ADR 0004 section 4) with the
17//! 64-token synthetic table: exact walks, refusal through the rollback, the no-constraint path
18//! byte for byte, and (with `OMEGESE_BIN`) random walks against the real oracle.
19
20mod common;
21
22use std::cell::RefCell;
23use std::path::PathBuf;
24use std::rc::Rc;
25use std::sync::Arc;
26
27use aien_inference_abi::generation::echo_chain::EchoChainModel;
28use aien_inference_abi::generation::{
29 Constraint, ForwardPass, GenerationController, SampleNext, Sampler, Want,
30};
31use aien_inference_abi::qwen3_moe_omega::{
32 FinishReason, GenerateOutcome, GenerateParams, StepTiming,
33};
34use aien_omegese_constraint::{
35 Answer, Framing, ItemOracle, OmegeseConstraint, Shape, SubprocessOracle, TokenTable,
36};
37use common::*;
38
39type Ctl = GenerationController<EchoChainModel>;
40
41fn ctl(ctx: usize, graph: bool) -> Ctl {
42 let mut m = EchoChainModel::new(ctx);
43 m.graph_mode = graph;
44 GenerationController::new(m)
45}
46
47fn prompt(n: usize, seed: usize) -> Vec<u32> {
48 (0..n)
49 .map(|i| ((i * 7 + seed * 13 + 1) % 63) as u32)
50 .collect()
51}
52
53fn greedy(n: usize) -> GenerateParams {
54 GenerateParams::greedy(n, vec![STOP])
55}
56
57fn sampled(n: usize, seed: u64) -> GenerateParams {
58 GenerateParams {
59 max_new_tokens: n,
60 temperature: 1.0,
61 top_p: 1.0,
62 top_k: 0,
63 seed,
64 stop_token_ids: vec![STOP],
65 }
66}
67
68fn run(
69 c: &mut Ctl,
70 p: &[u32],
71 params: &GenerateParams,
72 sampler: &mut dyn Sampler,
73 constraint: Option<&mut dyn Constraint>,
74) -> Result<(Vec<u32>, GenerateOutcome), String> {
75 let mut out = Vec::new();
76 let o = c.generate(p, params, sampler, constraint, &mut |t| {
77 out.push(t);
78 true
79 })?;
80 Ok((out, o))
81}
82
83fn run_sn(
84 c: &mut Ctl,
85 p: &[u32],
86 params: &GenerateParams,
87 constraint: Option<&mut dyn Constraint>,
88) -> Result<(Vec<u32>, GenerateOutcome), String> {
89 run(c, p, params, &mut SampleNext(params.clone()), constraint)
90}
91
92fn counted(o: &GenerateOutcome) -> GenerateOutcome {
93 GenerateOutcome {
94 prefill_ms: 0,
95 decode_ms: 0,
96 ..o.clone()
97 }
98}
99
100fn full() -> Framing {
101 Framing {
102 open_fence: Some("```\n".into()),
103 header: Some(sig_f()),
104 mask_body: true,
105 close_fence: "```".into(),
106 stop_token: STOP,
107 }
108}
109
110const TARGET: &str = "fn f a uint b uint to uint\nret add a b\nend\n";
111
112/// Every walk under the exact one-program oracle writes the fence, the program (up to blank space)
113/// and the closing fence, whatever tokens the model prefers, and stops on the stop token.
114#[test]
115fn exact_walks_write_the_one_program() {
116 let table = Arc::new(synthetic_table());
117 let mut multi_item_picked = 0;
118 let mut multi_refused = 0;
119 for seed in 0..12 {
120 for params in [greedy(64), sampled(64, seed as u64 + 1)] {
121 let mut c = ctl(256, seed % 2 == 0);
122 let mut k =
123 OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), full()).unwrap();
124 let (toks, o) = run_sn(&mut c, &prompt(9, seed), &params, Some(&mut k)).unwrap();
125 assert_eq!(o.finish, FinishReason::Stop, "seed {seed}");
126 let text = table.decode(&toks).unwrap();
127 let program = k.program().to_vec();
128 assert_eq!(normalize(&program), TARGET.as_bytes(), "seed {seed}");
129 let mut want = b"```\n".to_vec();
130 want.extend(&program);
131 if !program.ends_with(b"\n") {
132 want.push(b'\n');
133 }
134 want.extend(b"```");
135 assert_eq!(text, want, "seed {seed}");
136 assert!(k.finished());
137 multi_item_picked += toks
138 .iter()
139 .filter(|&&t| {
140 matches!(table.shape(t), Shape::OneBoundary { .. })
141 && table.text(t).unwrap().len() > 1
142 })
143 .count();
144 multi_refused += k.stats().multi_boundary_refused;
145 }
146 }
147 assert!(multi_item_picked > 0, "some walk used a multi-item token");
148 assert!(multi_refused > 0, "` a ` is refused where ` a` is legal");
149}
150
151/// The masked arm with no fence: the header is forced, the body masked, and eof is the stop token
152/// itself, so the reply is the program and the run ends on stop.
153#[test]
154fn the_unfenced_arm_ends_on_the_stop_token() {
155 let table = Arc::new(synthetic_table());
156 for seed in 0..6 {
157 for params in [greedy(64), sampled(64, seed as u64 + 31)] {
158 let arm = Framing {
159 open_fence: None,
160 ..full()
161 };
162 let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), arm).unwrap();
163 let (toks, o) = run_sn(
164 &mut ctl(256, seed % 2 == 1),
165 &prompt(9, seed),
166 &params,
167 Some(&mut k),
168 )
169 .unwrap();
170 assert_eq!(o.finish, FinishReason::Stop, "seed {seed}");
171 let program = k.program().to_vec();
172 assert_eq!(normalize(&program), TARGET.as_bytes(), "seed {seed}");
173 assert_eq!(
174 table.decode(&toks).unwrap(),
175 program,
176 "the reply is the program"
177 );
178 // Completion here is `FinishReason::Stop` (asserted above): the stop was allowed among
179 // blank tokens, not forced, so `finished()` cannot know it was taken.
180 assert!(!k.finished());
181 }
182 }
183}
184
185/// The fake oracle answers REFUSED (or breaks its contract) from its `n`th call on.
186struct FailAt<O> {
187 inner: O,
188 n: usize,
189 calls: usize,
190 broken: bool,
191}
192
193impl<O: ItemOracle> ItemOracle for FailAt<O> {
194 fn next(&mut self, p: &[u8]) -> Result<Answer, String> {
195 self.calls += 1;
196 if self.calls >= self.n {
197 return if self.broken {
198 Err("oracle exit 0 with no item".into())
199 } else {
200 Ok(Answer::Refused("REFUSED omegese: line 2: injected".into()))
201 };
202 }
203 self.inner.next(p)
204 }
205}
206
207/// A REFUSED answer ends the generation with `Err` after the controller's rollback: the ledger
208/// keeps the tokens emitted before, every layer holds exactly the ledger, no head is pending, and
209/// a warm run then equals a cold one.
210#[test]
211fn an_oracle_refusal_goes_through_the_rollback() {
212 let table = Arc::new(synthetic_table());
213 let p = prompt(10, 3);
214 for broken in [false, true] {
215 // Call 1 is the header check when the constraint is built; call 2 is the first step.
216 for n in [2, 5] {
217 let mut c = ctl(256, true);
218 let oracle = FailAt {
219 inner: ExactText::new(TARGET),
220 n,
221 calls: 0,
222 broken,
223 };
224 let mut k = OmegeseConstraint::new(table.clone(), oracle, full()).unwrap();
225 let mut emitted = Vec::new();
226 let r = c.generate(
227 &p,
228 &greedy(64),
229 &mut SampleNext(greedy(64)),
230 Some(&mut k),
231 &mut |t| {
232 emitted.push(t);
233 true
234 },
235 );
236 let e = r.expect_err("the refusal is an error");
237 assert!(
238 e.contains(if broken { "no item" } else { "injected" }),
239 "{e}"
240 );
241 assert!(
242 emitted.len() >= 2,
243 "the fence was forced before the oracle ran"
244 );
245 assert_eq!(&c.history()[p.len()..], &emitted[..], "{n} {broken}");
246 let pos = c.position();
247 assert_eq!(
248 c.model().layer_lens(),
249 vec![pos; 2],
250 "every layer at the ledger"
251 );
252 assert!(
253 c.model_mut()
254 .next(0, Want::Logits, &mut StepTiming::default())
255 .is_err(),
256 "the rollback forgets the pending head"
257 );
258 let mut q = c.history().to_vec();
259 q.push(1);
260 let (warm, _) = run_sn(&mut c, &q, &greedy(12), None).unwrap();
261 let (cold, _) = run_sn(&mut ctl(256, true), &q, &greedy(12), None).unwrap();
262 assert_eq!(warm, cold);
263 }
264 }
265}
266
267/// With every switch off the constraint answers `Any` on every step and the run is byte for byte
268/// the run with no constraint (tokens, outcome, call log, head reads), with no oracle call.
269#[test]
270fn every_switch_off_is_byte_identical_to_no_constraint() {
271 let table = Arc::new(synthetic_table());
272 let p = prompt(12, 19);
273 for graph in [false, true] {
274 for params in [
275 GenerateParams::greedy(10, vec![]),
276 GenerateParams {
277 stop_token_ids: vec![],
278 ..sampled(10, 21)
279 },
280 ] {
281 let mut a = ctl(128, graph);
282 let (ta, oa) = run_sn(&mut a, &p, &params, None).unwrap();
283 let mut b = ctl(128, graph);
284 let off = Framing {
285 open_fence: None,
286 header: None,
287 mask_body: false,
288 close_fence: "```".into(),
289 stop_token: STOP,
290 };
291 let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), off).unwrap();
292 let (tb, ob) = run_sn(&mut b, &p, &params, Some(&mut k)).unwrap();
293 assert_eq!(ta, tb, "same tokens");
294 assert_eq!(counted(&oa), counted(&ob), "same outcome and counters");
295 assert_eq!(a.model().calls(), b.model().calls(), "same call log");
296 let (ma, mb) = (a.model(), b.model());
297 assert_eq!(
298 (ma.chip_reads, ma.lm_heads, ma.rows_reads),
299 (mb.chip_reads, mb.lm_heads, mb.rows_reads)
300 );
301 assert_eq!(mb.rows_reads, 0, "next_rows is never called");
302 assert_eq!(k.oracle().calls, 0, "no oracle call");
303 assert_eq!(k.stats().forced_steps, 0);
304 }
305 }
306}
307
308/// The unmasked arm: only the fence is forced; after it the model runs free, exactly as a run
309/// whose prompt ended with the fence, and the oracle is never asked.
310#[test]
311fn the_fence_only_arm_forces_the_fence_and_nothing_else() {
312 let table = Arc::new(synthetic_table());
313 let fence = table.encode("```\n").unwrap();
314 let p = prompt(12, 5);
315 for params in [
316 GenerateParams::greedy(12, vec![]),
317 GenerateParams {
318 stop_token_ids: vec![],
319 ..sampled(12, 9)
320 },
321 ] {
322 let arm = Framing {
323 open_fence: Some("```\n".into()),
324 header: None,
325 mask_body: false,
326 close_fence: "```".into(),
327 stop_token: STOP,
328 };
329 let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), arm).unwrap();
330 let (t, _) = run_sn(&mut ctl(128, true), &p, &params, Some(&mut k)).unwrap();
331 assert_eq!(&t[..fence.len()], &fence[..]);
332 assert_eq!(k.oracle().calls, 0);
333 let mut q = p.clone();
334 q.extend(&fence);
335 if params.temperature == 0.0 {
336 let (free, _) = run_sn(
337 &mut ctl(128, true),
338 &q,
339 &GenerateParams::greedy(12 - fence.len(), vec![]),
340 None,
341 )
342 .unwrap();
343 assert_eq!(&t[fence.len()..], &free[..], "the rest is the free run");
344 }
345 }
346}
347
348/// A seeded random walk among the allowed tokens, weighted by the fake's logits. From step
349/// `steer_after` on it steers home: it takes the longest allowed token that starts what
350/// `omegese complete` would write after the reply so far (shared through `reply`), or the closing
351/// fence when the program is already whole. The constraint alone decides what is allowed.
352struct Walk {
353 seed: u64,
354 table: Arc<TokenTable>,
355 reply: Rc<RefCell<Vec<u32>>>,
356 bin: PathBuf,
357 steer_after: Option<usize>,
358 plan: Vec<u8>,
359}
360
361fn mix(mut x: u64) -> u64 {
362 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
363 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
364 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
365 x ^ (x >> 31)
366}
367
368impl Walk {
369 fn steer(&mut self, allowed: &[u32]) -> Option<u32> {
370 let text = self.table.decode(&self.reply.borrow()).ok()?;
371 let program = text.strip_prefix(b"```\n".as_slice())?;
372 // Keep one plan (the prefix plus `omegese complete`'s text) while the walk follows it:
373 // asking again after every token can loop (a name's first letters are a keyword).
374 if !self.plan.starts_with(program) {
375 self.plan = program.to_vec();
376 self.plan.extend(complete(&self.bin, program).ok()?);
377 }
378 let rest = &self.plan[program.len()..];
379 allowed
380 .iter()
381 .copied()
382 .filter(|&id| {
383 let t = self.table.text(id).unwrap_or_default();
384 if rest.is_empty() {
385 t.contains(&b'`')
386 } else {
387 !t.is_empty() && rest.starts_with(t)
388 }
389 })
390 .max_by_key(|&id| self.table.text(id).map_or(0, <[u8]>::len))
391 }
392}
393
394impl Sampler for Walk {
395 fn wants_logits(&self) -> bool {
396 true
397 }
398 fn pick(&mut self, logits: &[f32], step: usize) -> u32 {
399 let allowed: Vec<u32> = (0..logits.len() as u32)
400 .filter(|&i| logits[i as usize].is_finite())
401 .collect();
402 if self.steer_after.is_some_and(|s| step >= s) {
403 if let Some(t) = self.steer(&allowed) {
404 return t;
405 }
406 }
407 let w: Vec<f32> = allowed
408 .iter()
409 .map(|&i| (3.0 * logits[i as usize]).exp())
410 .collect();
411 let total: f32 = w.iter().sum();
412 let r = (mix(self.seed ^ mix(step as u64)) >> 11) as f32 / (1u64 << 53) as f32 * total;
413 let mut acc = 0.0;
414 for (&i, &x) in allowed.iter().zip(&w) {
415 acc += x;
416 if acc >= r {
417 return i;
418 }
419 }
420 *allowed.last().unwrap_or(&0)
421 }
422}
423
424/// With the real oracle (`OMEGESE_BIN`): every guardrail-on walk is sound. A walk that ended on
425/// `eof` wrote a program `omegese emit` accepts, inside the fences; a walk cut by length wrote a
426/// prefix `omegese complete` finishes into one `emit` accepts.
427#[test]
428#[ignore = "needs OMEGESE_BIN (the omegese binary built from omega main)"]
429fn real_oracle_walks_write_programs_emit_accepts() {
430 let bin = omegese_bin();
431 let table = Arc::new(synthetic_table());
432 let (mut ended, mut cut, mut steps, mut calls, mut multi) = (0, 0, 0u64, 0u64, 0u64);
433 let mut times = Vec::new();
434 for seed in 0..40u64 {
435 let mut c = ctl(512, seed % 2 == 0);
436 let oracle = SubprocessOracle::new(&bin).unwrap();
437 let mut k = OmegeseConstraint::new(table.clone(), oracle, full()).unwrap();
438 let reply = Rc::new(RefCell::new(Vec::new()));
439 // Every eighth walk never steers, so some walks are cut by length.
440 let steer_after = (seed % 8 != 7).then_some(20 + (seed as usize % 5) * 30);
441 let mut s = Walk {
442 seed,
443 table: table.clone(),
444 reply: reply.clone(),
445 bin: bin.clone(),
446 steer_after,
447 plan: Vec::new(),
448 };
449 let params = sampled(300, seed + 1);
450 let p = prompt(8, seed as usize);
451 let o = c
452 .generate(&p, &params, &mut s, Some(&mut k), &mut |t| {
453 reply.borrow_mut().push(t);
454 true
455 })
456 .unwrap_or_else(|e| panic!("walk {seed}: {e}"));
457 let toks = reply.borrow().clone();
458 let text = table.decode(&toks).unwrap();
459 let program = k.program().to_vec();
460 match o.finish {
461 FinishReason::Stop => {
462 ended += 1;
463 emit(&bin, &program).unwrap_or_else(|e| {
464 panic!(
465 "walk {seed}: emit refused {:?}: {e}",
466 String::from_utf8_lossy(&program)
467 )
468 });
469 let mut want = b"```\n".to_vec();
470 want.extend(&program);
471 if !program.ends_with(b"\n") {
472 want.push(b'\n');
473 }
474 want.extend(b"```");
475 assert_eq!(text, want, "walk {seed}: the fences frame the program");
476 }
477 FinishReason::Length => {
478 cut += 1;
479 let rest = complete(&bin, &program).unwrap_or_else(|e| {
480 panic!(
481 "walk {seed}: no completion for {:?}: {e}",
482 String::from_utf8_lossy(&program)
483 )
484 });
485 let mut whole = program.clone();
486 whole.extend(&rest);
487 emit(&bin, &whole)
488 .unwrap_or_else(|e| panic!("walk {seed}: completed, refused: {e}"));
489 }
490 f => panic!("walk {seed}: finish {f:?}"),
491 }
492 let st = k.stats();
493 steps += st.masked_steps;
494 calls += st.oracle_calls;
495 multi += st.multi_boundary_refused;
496 times.extend(st.step_times.iter().copied());
497 }
498 times.sort();
499 let us = |d: std::time::Duration| d.as_micros();
500 println!(
501 "walks: {ended} ended on eof (emit accepted), {cut} cut by length (completed and accepted); \
502 {steps} masked steps, {calls} oracle calls ({:.2} per step), {multi} two-boundary refusals; \
503 step time median {} us, p95 {} us, max {} us",
504 calls as f64 / steps as f64,
505 us(times[times.len() / 2]),
506 us(times[times.len() * 95 / 100]),
507 us(times[times.len() - 1]),
508 );
509 assert!(
510 ended >= 20 && cut >= 3,
511 "walks of both kinds ({ended} ended, {cut} cut)"
512 );
513}
514
515/// The mask reads every blank run in its canonical form (`canonical_seps`): one space, or one
516/// newline when the run holds one. With the real oracle: at every cut of three programs, the
517/// text after a blank run and after its canonical form gets the same items (or both are
518/// refused), with brackets around and between the blanks too.
519#[test]
520#[ignore = "needs OMEGESE_BIN (the omegese binary built from omega main)"]
521fn real_oracle_blank_runs_are_interchangeable() {
522 let mut oracle = SubprocessOracle::new(omegese_bin()).unwrap();
523 let programs = [
524 TARGET,
525 "fn gcd a uint b uint to uint\nwhile ne b 0 bound 100\nt = rem a b\na = b\nb = t\nend\nret a\nend\n",
526 "fn g v view uint 4 to uint\ns = uint 0\nfor i uint 4\ns = add s (get v i)\nend\nret s\nend\n",
527 ];
528 let runs = [
529 " ", "\t", " \t ", "\n\n", " \n", "\n ", "\n\t\n ", " (\t ", "( ", ")\n\n", ") \n ",
530 "\t)\t", " ((", "(\n\n", "() ",
531 ];
532 let (mut compared, mut items_both) = (0, 0);
533 for prog in programs {
534 for cut in 0..=prog.len() {
535 let p = &prog.as_bytes()[..cut];
536 for run in runs {
537 let canon = aien_omegese_constraint::constraint::canonical_seps(run.as_bytes());
538 assert_ne!(canon, run.as_bytes(), "{run:?} is not already canonical");
539 let ask = |o: &mut SubprocessOracle, s: &[u8]| {
540 let mut q = p.to_vec();
541 q.extend_from_slice(s);
542 o.next(&q).unwrap()
543 };
544 let (x, y) = (ask(&mut oracle, run.as_bytes()), ask(&mut oracle, &canon));
545 match (&x, &y) {
546 (Answer::Items(a), Answer::Items(b)) => {
547 assert_eq!(a, b, "after {:?} + {run:?}", String::from_utf8_lossy(p));
548 items_both += 1;
549 }
550 (Answer::Refused(_), Answer::Refused(_)) => {}
551 _ => panic!(
552 "after {:?}: {run:?} gives {x:?}, {:?} gives {y:?}",
553 String::from_utf8_lossy(p),
554 String::from_utf8_lossy(&canon)
555 ),
556 }
557 compared += 1;
558 }
559 }
560 }
561 println!("blank runs: {compared} pairs compared, {items_both} with items on both sides");
562 assert!(items_both > 100);
563}