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 / crumbs / src / gen / mechanisms.rs

1300 lines · 41618 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//! Generator mechanisms. Each is a genuinely distinct way of producing
17//! observations; registered families are parameterizations of these.
18//!
19//! Every mechanism returns honest observations: outputs are always the exact
20//! value of the hidden rule (noise families corrupt only visible outputs, and
21//! say so in the sealed record). Rabbit holes deceive through *which* inputs
22//! are shown, never by labeling a wrong output correct.
23
24use super::{
25 build_sets, default_sample, enumerate_basic, lane_bytes_for, out_mask_for, random_chain,
26 width_max, Ctx, Draft, FamilySpec, Stage, Vocab,
27};
28use crate::gen::registry::capability_pool;
29use crate::gen::rng::Rng;
30use crate::program::{Op, Program, Step};
31use crate::sealed::{Heldouts, KnownSolution, LaneExample, VerificationMethod};
32use std::collections::HashSet;
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum Mechanism {
36 OpChain,
37 Repeat,
38 Threshold,
39 ParityBranch,
40 MultiLinear,
41 AbsDifference,
42 Recurrence1,
43 Recurrence2,
44 BitAutomaton,
45 LaneFold,
46 ByteReverse,
47 BitMirror,
48 SymmetricLanes,
49 ModResidue,
50 ModAffine,
51 PopCount,
52 NibblePermute,
53 GraphComponents,
54 HiddenGraphReach,
55 PolySequence,
56 Euclid,
57 DigitSum,
58 LatentOffset,
59 LatentXorMask,
60 NoisyChain,
61 PartialObservation,
62 CounterexampleSensitive,
63 TheoryFamily,
64 DecoySimpleRule,
65 MultiFit,
66 SpuriousField,
67 PrefixDiverges,
68 ElegantArbitrary,
69 InsufficientEvidence,
70 NoStructure,
71 CapabilityPrimitive,
72 CapabilityComposition,
73 WrapBoundary,
74}
75
76impl Mechanism {
77 pub const ALL: [Mechanism; 38] = [
78 Mechanism::OpChain,
79 Mechanism::Repeat,
80 Mechanism::Threshold,
81 Mechanism::ParityBranch,
82 Mechanism::MultiLinear,
83 Mechanism::AbsDifference,
84 Mechanism::Recurrence1,
85 Mechanism::Recurrence2,
86 Mechanism::BitAutomaton,
87 Mechanism::LaneFold,
88 Mechanism::ByteReverse,
89 Mechanism::BitMirror,
90 Mechanism::SymmetricLanes,
91 Mechanism::ModResidue,
92 Mechanism::ModAffine,
93 Mechanism::PopCount,
94 Mechanism::NibblePermute,
95 Mechanism::GraphComponents,
96 Mechanism::HiddenGraphReach,
97 Mechanism::PolySequence,
98 Mechanism::Euclid,
99 Mechanism::DigitSum,
100 Mechanism::LatentOffset,
101 Mechanism::LatentXorMask,
102 Mechanism::NoisyChain,
103 Mechanism::PartialObservation,
104 Mechanism::CounterexampleSensitive,
105 Mechanism::TheoryFamily,
106 Mechanism::DecoySimpleRule,
107 Mechanism::MultiFit,
108 Mechanism::SpuriousField,
109 Mechanism::PrefixDiverges,
110 Mechanism::ElegantArbitrary,
111 Mechanism::InsufficientEvidence,
112 Mechanism::NoStructure,
113 Mechanism::CapabilityPrimitive,
114 Mechanism::CapabilityComposition,
115 Mechanism::WrapBoundary,
116 ];
117
118 pub fn key(self) -> &'static str {
119 match self {
120 Mechanism::OpChain => "op-chain",
121 Mechanism::Repeat => "repeat",
122 Mechanism::Threshold => "threshold",
123 Mechanism::ParityBranch => "parity-branch",
124 Mechanism::MultiLinear => "multi-linear",
125 Mechanism::AbsDifference => "abs-difference",
126 Mechanism::Recurrence1 => "recurrence-1",
127 Mechanism::Recurrence2 => "recurrence-2",
128 Mechanism::BitAutomaton => "bit-automaton",
129 Mechanism::LaneFold => "lane-fold",
130 Mechanism::ByteReverse => "byte-reverse",
131 Mechanism::BitMirror => "bit-mirror",
132 Mechanism::SymmetricLanes => "symmetric-lanes",
133 Mechanism::ModResidue => "mod-residue",
134 Mechanism::ModAffine => "mod-affine",
135 Mechanism::PopCount => "pop-count",
136 Mechanism::NibblePermute => "nibble-permute",
137 Mechanism::GraphComponents => "graph-components",
138 Mechanism::HiddenGraphReach => "hidden-graph-reach",
139 Mechanism::PolySequence => "poly-sequence",
140 Mechanism::Euclid => "euclid",
141 Mechanism::DigitSum => "digit-sum",
142 Mechanism::LatentOffset => "latent-offset",
143 Mechanism::LatentXorMask => "latent-xor-mask",
144 Mechanism::NoisyChain => "noisy-chain",
145 Mechanism::PartialObservation => "partial-observation",
146 Mechanism::CounterexampleSensitive => "counterexample-sensitive",
147 Mechanism::TheoryFamily => "theory-family",
148 Mechanism::DecoySimpleRule => "decoy-simple-rule",
149 Mechanism::MultiFit => "multi-fit",
150 Mechanism::SpuriousField => "spurious-field",
151 Mechanism::PrefixDiverges => "prefix-diverges",
152 Mechanism::ElegantArbitrary => "elegant-arbitrary",
153 Mechanism::InsufficientEvidence => "insufficient-evidence",
154 Mechanism::NoStructure => "no-structure",
155 Mechanism::CapabilityPrimitive => "capability-primitive",
156 Mechanism::CapabilityComposition => "capability-composition",
157 Mechanism::WrapBoundary => "wrap-boundary",
158 }
159 }
160
161 /// Per-mechanism code version (part of generator_code_digest).
162 pub fn version(self) -> u32 {
163 1
164 }
165}
166
167pub fn run(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
168 match spec.mechanism {
169 Mechanism::OpChain => op_chain(spec, ctx),
170 Mechanism::Repeat => repeat(spec, ctx),
171 Mechanism::Threshold => threshold(spec, ctx),
172 Mechanism::ParityBranch => parity_branch(spec, ctx),
173 Mechanism::MultiLinear => multi_linear(spec, ctx),
174 Mechanism::AbsDifference => abs_difference(spec, ctx),
175 Mechanism::Recurrence1 => recurrence1(spec, ctx),
176 Mechanism::Recurrence2 => recurrence2(spec, ctx),
177 Mechanism::BitAutomaton => bit_automaton(spec, ctx),
178 Mechanism::LaneFold => lane_fold(spec, ctx),
179 Mechanism::ByteReverse => byte_reverse(spec, ctx),
180 Mechanism::BitMirror => bit_mirror(spec, ctx),
181 Mechanism::SymmetricLanes => symmetric_lanes(spec, ctx),
182 Mechanism::ModResidue => mod_residue(spec, ctx),
183 Mechanism::ModAffine => mod_affine(spec, ctx),
184 Mechanism::PopCount => pop_count(spec, ctx),
185 Mechanism::NibblePermute => nibble_permute(spec, ctx),
186 Mechanism::GraphComponents => graph_components(spec, ctx),
187 Mechanism::HiddenGraphReach => hidden_graph_reach(spec, ctx),
188 Mechanism::PolySequence => poly_sequence(spec, ctx),
189 Mechanism::Euclid => euclid(spec, ctx),
190 Mechanism::DigitSum => digit_sum(spec, ctx),
191 Mechanism::LatentOffset => latent_offset(spec, ctx),
192 Mechanism::LatentXorMask => latent_xor_mask(spec, ctx),
193 Mechanism::NoisyChain => noisy_chain(spec, ctx),
194 Mechanism::PartialObservation => partial_observation(spec, ctx),
195 Mechanism::CounterexampleSensitive => counterexample_sensitive(spec, ctx),
196 Mechanism::TheoryFamily => theory_family(spec, ctx),
197 Mechanism::DecoySimpleRule => decoy_simple_rule(spec, ctx),
198 Mechanism::MultiFit => multi_fit(spec, ctx),
199 Mechanism::SpuriousField => spurious_field(spec, ctx),
200 Mechanism::PrefixDiverges => prefix_diverges(spec, ctx),
201 Mechanism::ElegantArbitrary => elegant_arbitrary(spec, ctx),
202 Mechanism::InsufficientEvidence => insufficient_evidence(spec, ctx),
203 Mechanism::NoStructure => no_structure(spec, ctx),
204 Mechanism::CapabilityPrimitive => capability_primitive(spec, ctx),
205 Mechanism::CapabilityComposition => capability_composition(spec, ctx),
206 Mechanism::WrapBoundary => wrap_boundary(spec, ctx),
207 }
208}
209
210// ---------------------------------------------------------------------------
211// helpers
212// ---------------------------------------------------------------------------
213
214fn unary_draft(
215 spec: &FamilySpec,
216 ctx: &mut Ctx,
217 out_width: u8,
218 known: KnownSolution,
219 sample: &mut dyn FnMut(&mut Rng, Stage) -> u64,
220 truth: &dyn Fn(u64) -> u64,
221) -> Draft {
222 let p = &spec.params;
223 let in_lb = lane_bytes_for(p.encoding, p.width);
224 let out_lb = lane_bytes_for(p.encoding, out_width);
225 let mask = out_mask_for(p.encoding, out_lb);
226 let (visible, heldouts) = build_sets(
227 ctx,
228 p.visible as usize,
229 mask,
230 &mut |r, s| vec![sample(r, s)],
231 &|x: &[u64]| vec![truth(x[0])],
232 );
233 Draft {
234 in_lane_bytes: in_lb,
235 out_lane_bytes: out_lb,
236 visible,
237 heldouts,
238 known,
239 alternatives: vec![],
240 noisy_visible: vec![],
241 domain: (0, width_max(p.width)),
242 requires: vec![],
243 provides: None,
244 verification: VerificationMethod::ExactGeneratorEvaluation,
245 }
246}
247
248fn multi_draft(
249 spec: &FamilySpec,
250 ctx: &mut Ctx,
251 arity: usize,
252 out_width: u8,
253 sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec<u64>,
254 truth: &dyn Fn(&[u64]) -> Vec<u64>,
255) -> Draft {
256 let p = &spec.params;
257 let in_lb = lane_bytes_for(p.encoding, p.width);
258 let out_lb = lane_bytes_for(p.encoding, out_width);
259 let mask = out_mask_for(p.encoding, out_lb);
260 let (visible, heldouts) = build_sets(ctx, p.visible as usize, mask, sample, truth);
261 debug_assert!(visible.iter().all(|(i, _)| i.len() == arity));
262 Draft {
263 in_lane_bytes: in_lb,
264 out_lane_bytes: out_lb,
265 visible,
266 heldouts,
267 known: KnownSolution::KnownOutsideProgramFormat,
268 alternatives: vec![],
269 noisy_visible: vec![],
270 domain: (0, width_max(p.width)),
271 requires: vec![],
272 provides: None,
273 verification: VerificationMethod::ExactGeneratorEvaluation,
274 }
275}
276
277fn dflt(width: u8) -> impl FnMut(&mut Rng, Stage) -> u64 {
278 move |r, s| default_sample(r, s, width)
279}
280
281fn lanes_sample(arity: usize, width: u8) -> impl FnMut(&mut Rng, Stage) -> Vec<u64> {
282 move |r, s| (0..arity).map(|_| default_sample(r, s, width)).collect()
283}
284
285/// Re-draw every tier from a fixed input predicate (used by rabbit holes).
286fn sets_from_pools(
287 ctx: &mut Ctx,
288 n_visible: usize,
289 visible_pool: &[u64],
290 interp_pool: &[u64],
291 extrap_pool: &[u64],
292 adversarial_pool: &[u64],
293 truth: &dyn Fn(u64) -> u64,
294) -> (super::Pairs, Heldouts) {
295 let mut used = HashSet::new();
296 let take = |rng: &mut Rng, pool: &[u64], n: usize, used: &mut HashSet<u64>| -> Vec<u64> {
297 let mut idx: Vec<usize> = (0..pool.len()).collect();
298 rng.shuffle(&mut idx);
299 let mut out = Vec::new();
300 for i in idx {
301 if out.len() == n {
302 break;
303 }
304 if used.insert(pool[i]) {
305 out.push(pool[i]);
306 }
307 }
308 out
309 };
310 let vis = take(&mut ctx.vis, visible_pool, n_visible, &mut used);
311 let mk = |xs: Vec<u64>| {
312 xs.into_iter()
313 .map(|x| LaneExample {
314 input: vec![x],
315 output: vec![truth(x)],
316 })
317 .collect()
318 };
319 let visible = vis.iter().map(|&x| (vec![x], vec![truth(x)])).collect();
320 let h = Heldouts {
321 interpolation: mk(take(
322 &mut ctx.hold,
323 interp_pool,
324 super::HELDOUT_PER_TIER,
325 &mut used,
326 )),
327 extrapolation: mk(take(
328 &mut ctx.hold,
329 extrap_pool,
330 super::HELDOUT_PER_TIER,
331 &mut used,
332 )),
333 adversarial: mk(take(
334 &mut ctx.hold,
335 adversarial_pool,
336 super::HELDOUT_PER_TIER,
337 &mut used,
338 )),
339 };
340 (visible, h)
341}
342
343fn pool(rng: &mut Rng, n: usize, stage: Stage, width: u8, keep: &dyn Fn(u64) -> bool) -> Vec<u64> {
344 let mut out = Vec::new();
345 let mut tries = 0;
346 while out.len() < n && tries < n * 400 {
347 tries += 1;
348 let x = default_sample(rng, stage, width);
349 if keep(x) {
350 out.push(x);
351 }
352 }
353 out
354}
355
356// ---------------------------------------------------------------------------
357// single / composed transformations
358// ---------------------------------------------------------------------------
359
360fn op_chain(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
361 let prog = random_chain(&mut ctx.rule, spec.params.vocab, spec.params.len as usize);
362 let t = prog.clone();
363 unary_draft(
364 spec,
365 ctx,
366 64,
367 KnownSolution::Known(prog),
368 &mut dflt(spec.params.width),
369 &move |x| t.run(x),
370 )
371}
372
373fn repeat(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
374 let glen = 1 + ctx.rule.below(2) as usize;
375 let g = random_chain(&mut ctx.rule, spec.params.vocab, glen);
376 let mut prog = Program::default();
377 for _ in 0..spec.params.len {
378 prog = prog.then(&g);
379 }
380 let t = prog.clone();
381 unary_draft(
382 spec,
383 ctx,
384 64,
385 KnownSolution::Known(prog),
386 &mut dflt(spec.params.width),
387 &move |x| t.run(x),
388 )
389}
390
391fn wrap_boundary(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
392 // A chain whose behaviour is dominated by wrap-around at the lane width.
393 let w = spec.params.width;
394 let mut prog = random_chain(&mut ctx.rule, Vocab::Basic, spec.params.len as usize);
395 prog.steps.push(Step {
396 op: Op::And,
397 imm: width_max(w),
398 });
399 let t = prog.clone();
400 unary_draft(
401 spec,
402 ctx,
403 w,
404 KnownSolution::Known(prog),
405 &mut dflt(w),
406 &move |x| t.run(x),
407 )
408}
409
410// ---------------------------------------------------------------------------
411// conditional
412// ---------------------------------------------------------------------------
413
414fn threshold(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
415 let w = spec.params.width;
416 let t = ctx.rule.range(8, width_max(w).min(4095));
417 let a = random_chain(&mut ctx.rule, Vocab::Basic, 1);
418 let b = random_chain(&mut ctx.rule, Vocab::Basic, 1);
419 unary_draft(
420 spec,
421 ctx,
422 64,
423 KnownSolution::KnownOutsideProgramFormat,
424 &mut dflt(w),
425 &move |x| {
426 if x < t {
427 a.run(x)
428 } else {
429 b.run(x)
430 }
431 },
432 )
433}
434
435fn parity_branch(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
436 let m = 2 + ctx.rule.below(spec.params.k.max(1));
437 let a = random_chain(&mut ctx.rule, Vocab::Basic, 1);
438 let b = random_chain(&mut ctx.rule, Vocab::Basic, 1);
439 unary_draft(
440 spec,
441 ctx,
442 64,
443 KnownSolution::KnownOutsideProgramFormat,
444 &mut dflt(spec.params.width),
445 &move |x| {
446 if x % m == 0 {
447 a.run(x)
448 } else {
449 b.run(x)
450 }
451 },
452 )
453}
454
455fn counterexample_sensitive(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
456 // Almost always rule R, but a sparse residue class is shifted. Exactly one
457 // visible example sits in the exceptional class: ignoring it is an error.
458 let w = spec.params.width;
459 let base = random_chain(&mut ctx.rule, Vocab::Basic, 2);
460 let m = ctx.rule.range(11, 29);
461 let r = ctx.rule.below(m);
462 let delta = ctx.rule.range(1, 7);
463 let truth = {
464 let base = base.clone();
465 move |x: u64| {
466 if x % m == r {
467 base.run(x).wrapping_add(delta)
468 } else {
469 base.run(x)
470 }
471 }
472 };
473 let n = spec.params.visible as usize;
474 let normal = pool(&mut ctx.vis, 400, Stage::Visible, w, &|x| x % m != r);
475 let special = pool(&mut ctx.vis, 50, Stage::Visible, w, &|x| x % m == r);
476 let mut vis_pool: Vec<u64> = normal.iter().take(n - 1).cloned().collect();
477 if let Some(s) = special.first() {
478 vis_pool.push(*s);
479 }
480 let interp = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|_| true);
481 let extrap = pool(&mut ctx.hold, 200, Stage::Extrapolation, w, &|_| true);
482 let adv = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|x| x % m == r);
483 let (visible, heldouts) = sets_from_pools(ctx, n, &vis_pool, &interp, &extrap, &adv, &truth);
484 Draft {
485 in_lane_bytes: 0,
486 out_lane_bytes: 0,
487 visible,
488 heldouts,
489 known: KnownSolution::KnownOutsideProgramFormat,
490 alternatives: vec![base],
491 noisy_visible: vec![],
492 domain: (0, width_max(w)),
493 requires: vec![],
494 provides: None,
495 verification: VerificationMethod::ExactGeneratorEvaluation,
496 }
497}
498
499// ---------------------------------------------------------------------------
500// multi-input relations
501// ---------------------------------------------------------------------------
502
503fn multi_linear(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
504 let arity = spec.params.len.clamp(2, 4) as usize;
505 let coef: Vec<u64> = (0..arity).map(|_| ctx.rule.range(1, 9)).collect();
506 let d = ctx.rule.range(0, 20);
507 multi_draft(
508 spec,
509 ctx,
510 arity,
511 64,
512 &mut lanes_sample(arity, spec.params.width),
513 &move |x| {
514 vec![x
515 .iter()
516 .zip(&coef)
517 .fold(d, |acc, (v, c)| acc.wrapping_add(v.wrapping_mul(*c)))]
518 },
519 )
520}
521
522fn abs_difference(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
523 let s = ctx.rule.range(0, 5);
524 multi_draft(
525 spec,
526 ctx,
527 2,
528 64,
529 &mut lanes_sample(2, spec.params.width),
530 &move |x| vec![x[0].abs_diff(x[1]) << s],
531 )
532}
533
534fn symmetric_lanes(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
535 // Invariant under any permutation of the input lanes.
536 let arity = spec.params.len.clamp(2, 4) as usize;
537 let c = ctx.rule.range(1, 9);
538 multi_draft(
539 spec,
540 ctx,
541 arity,
542 64,
543 &mut lanes_sample(arity, spec.params.width),
544 &move |x| {
545 let s: u64 = x.iter().fold(0u64, |a, v| a.wrapping_add(*v));
546 let q: u64 = x
547 .iter()
548 .fold(0u64, |a, v| a.wrapping_add(v.wrapping_mul(*v)));
549 vec![q.wrapping_add(s.wrapping_mul(c))]
550 },
551 )
552}
553
554fn theory_family(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
555 // One law, many parameterizations: lane 0 is a parameter p, lane 1 is x.
556 let a = ctx.rule.range(1, 5);
557 let b = ctx.rule.range(0, 9);
558 let w = spec.params.width;
559 multi_draft(
560 spec,
561 ctx,
562 2,
563 64,
564 &mut move |r, s| vec![r.range(1, 12), default_sample(r, s, w)],
565 &move |x| {
566 vec![x[0]
567 .wrapping_mul(x[1])
568 .wrapping_add(a.wrapping_mul(x[0]))
569 .wrapping_add(b)]
570 },
571 )
572}
573
574fn euclid(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
575 let _ = ctx.rule.next_u64();
576 multi_draft(
577 spec,
578 ctx,
579 2,
580 64,
581 &mut lanes_sample(2, spec.params.width),
582 &|x| {
583 let (mut a, mut b) = (x[0], x[1]);
584 while b != 0 {
585 let t = a % b;
586 a = b;
587 b = t;
588 }
589 vec![a]
590 },
591 )
592}
593
594// ---------------------------------------------------------------------------
595// recurrence / sequences
596// ---------------------------------------------------------------------------
597
598fn seq_sample(max_n: u64) -> impl FnMut(&mut Rng, Stage) -> u64 {
599 move |r, s| match s {
600 Stage::Visible | Stage::Interpolation => r.range(0, max_n),
601 Stage::Extrapolation | Stage::Adversarial => r.range(max_n + 1, max_n * 4),
602 }
603}
604
605fn recurrence1(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
606 let (a0, p, q) = (
607 ctx.rule.range(0, 9),
608 ctx.rule.range(2, 5),
609 ctx.rule.range(0, 9),
610 );
611 unary_draft(
612 spec,
613 ctx,
614 64,
615 KnownSolution::KnownOutsideProgramFormat,
616 &mut seq_sample(24),
617 &move |n| (0..n).fold(a0, |a, _| a.wrapping_mul(p).wrapping_add(q)),
618 )
619}
620
621fn recurrence2(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
622 let (s0, s1, p, q) = (
623 ctx.rule.range(0, 5),
624 ctx.rule.range(1, 5),
625 ctx.rule.range(1, 3),
626 ctx.rule.range(1, 3),
627 );
628 unary_draft(
629 spec,
630 ctx,
631 64,
632 KnownSolution::KnownOutsideProgramFormat,
633 &mut seq_sample(24),
634 &move |n| {
635 let (mut a, mut b) = (s0, s1);
636 for _ in 0..n {
637 let c = b.wrapping_mul(p).wrapping_add(a.wrapping_mul(q));
638 a = b;
639 b = c;
640 }
641 a
642 },
643 )
644}
645
646fn poly_sequence(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
647 let (a, b, c) = (
648 ctx.rule.range(1, 5),
649 ctx.rule.range(0, 9),
650 ctx.rule.range(0, 9),
651 );
652 unary_draft(
653 spec,
654 ctx,
655 64,
656 KnownSolution::KnownOutsideProgramFormat,
657 &mut seq_sample(40),
658 &move |n| {
659 a.wrapping_mul(n)
660 .wrapping_mul(n)
661 .wrapping_add(b.wrapping_mul(n))
662 .wrapping_add(c)
663 },
664 )
665}
666
667fn prefix_diverges(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
668 // f(n) = s(n) + c * prod_{i<K}(n - i): identical to the simple rule s on
669 // the visible prefix n < K, different from n = K on.
670 let s = random_chain(&mut ctx.rule, Vocab::Basic, 2);
671 let k = spec.params.visible as u64;
672 let c = ctx.rule.range(1, 3);
673 let truth = {
674 let s = s.clone();
675 move |n: u64| {
676 let prod = (0..k).fold(1u64, |acc, i| acc.wrapping_mul(n.wrapping_sub(i)));
677 s.run(n).wrapping_add(c.wrapping_mul(prod))
678 }
679 };
680 let vis_pool: Vec<u64> = (0..k).collect();
681 let interp: Vec<u64> = (k..k + 8).collect();
682 let extrap: Vec<u64> = (k + 8..k + 64).collect();
683 let adv: Vec<u64> = (k..k + 3).chain([k * 4, k * 16]).collect();
684 let (visible, heldouts) =
685 sets_from_pools(ctx, k as usize, &vis_pool, &interp, &extrap, &adv, &truth);
686 Draft {
687 in_lane_bytes: 0,
688 out_lane_bytes: 0,
689 visible,
690 heldouts,
691 known: KnownSolution::KnownOutsideProgramFormat,
692 alternatives: vec![s],
693 noisy_visible: vec![],
694 domain: (0, k + 64),
695 requires: vec![],
696 provides: None,
697 verification: VerificationMethod::ExactGeneratorEvaluation,
698 }
699}
700
701// ---------------------------------------------------------------------------
702// state
703// ---------------------------------------------------------------------------
704
705fn bit_automaton(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
706 let states = spec.params.len.clamp(2, 8) as usize;
707 let table: Vec<[u8; 2]> = (0..states)
708 .map(|_| {
709 [
710 ctx.rule.below(states as u64) as u8,
711 ctx.rule.below(states as u64) as u8,
712 ]
713 })
714 .collect();
715 let w = spec.params.width;
716 unary_draft(
717 spec,
718 ctx,
719 8,
720 KnownSolution::KnownOutsideProgramFormat,
721 &mut dflt(w),
722 &move |x| {
723 let mut s = 0usize;
724 for i in 0..w {
725 s = table[s][((x >> i) & 1) as usize] as usize;
726 }
727 s as u64
728 },
729 )
730}
731
732fn lane_fold(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
733 let arity = spec.params.len.clamp(2, 8) as usize;
734 let m = ctx.rule.range(2, 5);
735 let a = ctx.rule.range(0, 9);
736 multi_draft(
737 spec,
738 ctx,
739 arity,
740 64,
741 &mut lanes_sample(arity, spec.params.width),
742 &move |x| {
743 vec![x
744 .iter()
745 .fold(a, |acc, v| acc.wrapping_mul(m).wrapping_add(*v))]
746 },
747 )
748}
749
750// ---------------------------------------------------------------------------
751// symmetry / permutation / bits
752// ---------------------------------------------------------------------------
753
754fn byte_reverse(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
755 let _ = ctx.rule.next_u64();
756 let w = spec.params.width;
757 let bytes = (w as u32).div_ceil(8);
758 unary_draft(
759 spec,
760 ctx,
761 w,
762 KnownSolution::KnownOutsideProgramFormat,
763 &mut dflt(w),
764 &move |x| x.swap_bytes() >> (64 - 8 * bytes),
765 )
766}
767
768fn bit_mirror(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
769 let _ = ctx.rule.next_u64();
770 let w = spec.params.width as u32;
771 unary_draft(
772 spec,
773 ctx,
774 w as u8,
775 KnownSolution::KnownOutsideProgramFormat,
776 &mut dflt(w as u8),
777 &move |x| x.reverse_bits() >> (64 - w),
778 )
779}
780
781fn nibble_permute(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
782 let mut perm: Vec<u32> = (0..4).collect();
783 loop {
784 ctx.rule.shuffle(&mut perm);
785 if perm != [0, 1, 2, 3] {
786 break;
787 }
788 }
789 unary_draft(
790 spec,
791 ctx,
792 16,
793 KnownSolution::KnownOutsideProgramFormat,
794 &mut dflt(16),
795 &move |x| {
796 (0..4).fold(0u64, |acc, i| {
797 acc | (((x >> (4 * i)) & 0xF) << (4 * perm[i as usize]))
798 })
799 },
800 )
801}
802
803fn pop_count(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
804 let c = ctx.rule.range(0, 5);
805 let w = spec.params.width;
806 unary_draft(
807 spec,
808 ctx,
809 8,
810 KnownSolution::KnownOutsideProgramFormat,
811 &mut dflt(w),
812 &move |x| x.count_ones() as u64 + c,
813 )
814}
815
816// ---------------------------------------------------------------------------
817// modularity
818// ---------------------------------------------------------------------------
819
820fn mod_residue(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
821 let m = ctx.rule.range(3, 97) | 1;
822 unary_draft(
823 spec,
824 ctx,
825 8,
826 KnownSolution::KnownOutsideProgramFormat,
827 &mut dflt(spec.params.width),
828 &move |x| x % m,
829 )
830}
831
832fn mod_affine(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
833 let bits = ctx.rule.range(4, 12);
834 let prog = Program::of(&[
835 (Op::Mul, ctx.rule.range(2, 7)),
836 (Op::Add, ctx.rule.range(1, 9)),
837 (Op::And, (1u64 << bits) - 1),
838 ]);
839 let t = prog.clone();
840 unary_draft(
841 spec,
842 ctx,
843 bits as u8,
844 KnownSolution::Known(prog),
845 &mut dflt(spec.params.width),
846 &move |x| t.run(x),
847 )
848}
849
850// ---------------------------------------------------------------------------
851// graphs and algorithms
852// ---------------------------------------------------------------------------
853
854fn graph_components(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
855 let _ = ctx.rule.next_u64();
856 let v = spec.params.len.clamp(3, 6) as usize;
857 let edges: Vec<(usize, usize)> = (0..v)
858 .flat_map(|a| (a + 1..v).map(move |b| (a, b)))
859 .collect();
860 let e = edges.len() as u8;
861 let mut sample = move |r: &mut Rng, _s: Stage| r.below(1u64 << e);
862 unary_draft(
863 spec,
864 ctx,
865 8,
866 KnownSolution::KnownOutsideProgramFormat,
867 &mut sample,
868 &move |mask| {
869 let mut parent: Vec<usize> = (0..v).collect();
870 fn find(p: &mut [usize], x: usize) -> usize {
871 let mut x = x;
872 while p[x] != x {
873 p[x] = p[p[x]];
874 x = p[x];
875 }
876 x
877 }
878 for (i, &(a, b)) in edges.iter().enumerate() {
879 if mask >> i & 1 == 1 {
880 let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
881 parent[ra] = rb;
882 }
883 }
884 (0..v).filter(|&x| find(&mut parent, x) == x).count() as u64
885 },
886 )
887}
888
889fn hidden_graph_reach(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
890 // A hidden directed graph on N nodes; input = start node, output = reachable-set bitmask.
891 let n = spec.params.len.clamp(4, 16) as u64;
892 let adj: Vec<u64> = (0..n)
893 .map(|_| ctx.rule.below(1 << n) & ctx.rule.below(1 << n))
894 .collect();
895 let mut sample = move |r: &mut Rng, _s: Stage| r.below(n);
896 let mut d = unary_draft(
897 spec,
898 ctx,
899 16,
900 KnownSolution::KnownOutsideProgramFormat,
901 &mut sample,
902 &move |s| {
903 let mut seen = 1u64 << s;
904 let mut frontier = seen;
905 while frontier != 0 {
906 let mut next = 0;
907 for i in 0..n {
908 if frontier >> i & 1 == 1 {
909 next |= adj[i as usize];
910 }
911 }
912 frontier = next & !seen;
913 seen |= next;
914 }
915 seen
916 },
917 );
918 d.domain = (0, n - 1);
919 d
920}
921
922fn digit_sum(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
923 let _ = ctx.rule.next_u64();
924 unary_draft(
925 spec,
926 ctx,
927 8,
928 KnownSolution::KnownOutsideProgramFormat,
929 &mut dflt(spec.params.width),
930 &|mut x| {
931 let mut s = 0;
932 while x > 0 {
933 s += x % 10;
934 x /= 10;
935 }
936 s
937 },
938 )
939}
940
941// ---------------------------------------------------------------------------
942// latent variables, noise, partial observation
943// ---------------------------------------------------------------------------
944
945fn latent_offset(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
946 let prog = Program::of(&[
947 (Op::Mul, ctx.rule.range(2, 5)),
948 (Op::Add, ctx.rule.range(6, 40)),
949 ]);
950 let t = prog.clone();
951 unary_draft(
952 spec,
953 ctx,
954 64,
955 KnownSolution::Known(prog),
956 &mut dflt(spec.params.width),
957 &move |x| t.run(x),
958 )
959}
960
961fn latent_xor_mask(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
962 let w = spec.params.width;
963 let prog = Program::of(&[
964 (Op::Xor, ctx.rule.below(width_max(w))),
965 (Op::And, width_max(w)),
966 ]);
967 let t = prog.clone();
968 unary_draft(
969 spec,
970 ctx,
971 w,
972 KnownSolution::Known(prog),
973 &mut dflt(w),
974 &move |x| t.run(x),
975 )
976}
977
978fn noisy_chain(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
979 // Held-outs are exact; a minority of visible outputs carry a one-bit flip.
980 let prog = random_chain(&mut ctx.rule, Vocab::Basic, spec.params.len as usize);
981 let t = prog.clone();
982 let mut d = unary_draft(
983 spec,
984 ctx,
985 64,
986 KnownSolution::Known(prog),
987 &mut dflt(spec.params.width),
988 &move |x| t.run(x),
989 );
990 let n = d.visible.len();
991 let flips = (n / 8).max(1);
992 let mut idx: Vec<usize> = (0..n).collect();
993 ctx.rule.shuffle(&mut idx);
994 let mut noisy: Vec<u32> = idx[..flips].iter().map(|&i| i as u32).collect();
995 noisy.sort_unstable();
996 for &i in &noisy {
997 let bit = ctx.rule.below(6);
998 d.visible[i as usize].1[0] ^= 1u64 << bit;
999 }
1000 d.noisy_visible = noisy;
1001 d
1002}
1003
1004fn partial_observation(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1005 // Only the low part of a hidden computation is observed.
1006 let inner = random_chain(&mut ctx.rule, Vocab::Basic, 2);
1007 let keep = *ctx.rule.pick(&[0x0Fu64, 0xFF]);
1008 let prog = inner.then(&Program::of(&[(Op::And, keep)]));
1009 let t = prog.clone();
1010 unary_draft(
1011 spec,
1012 ctx,
1013 8,
1014 KnownSolution::Known(prog),
1015 &mut dflt(spec.params.width),
1016 &move |x| t.run(x),
1017 )
1018}
1019
1020// ---------------------------------------------------------------------------
1021// rabbit holes
1022// ---------------------------------------------------------------------------
1023
1024fn decoy_simple_rule(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1025 // A: truth = (a*x + b) & M. Visible inputs keep a*x+b <= M, so the
1026 // simpler rule a*x + b fits every visible example.
1027 let (a, b) = (ctx.rule.range(2, 7), ctx.rule.range(1, 9));
1028 let m = *ctx.rule.pick(&[0xFFu64, 0xFFF]);
1029 let truth_p = Program::of(&[(Op::Mul, a), (Op::Add, b), (Op::And, m)]);
1030 let decoy = Program::of(&[(Op::Mul, a), (Op::Add, b)]);
1031 let w = spec.params.width;
1032 let fits = |x: u64| a.wrapping_mul(x).wrapping_add(b) <= m;
1033 let vis_pool = pool(&mut ctx.vis, 400, Stage::Visible, w, &|x| fits(x));
1034 let interp = pool(&mut ctx.hold, 400, Stage::Visible, w, &|x| fits(x));
1035 let extrap = pool(&mut ctx.hold, 400, Stage::Extrapolation, w, &|x| !fits(x));
1036 let adv = pool(&mut ctx.hold, 400, Stage::Visible, w, &|x| !fits(x));
1037 let t = truth_p.clone();
1038 let (visible, heldouts) = sets_from_pools(
1039 ctx,
1040 spec.params.visible as usize,
1041 &vis_pool,
1042 &interp,
1043 &extrap,
1044 &adv,
1045 &move |x| t.run(x),
1046 );
1047 rabbit(
1048 visible,
1049 heldouts,
1050 KnownSolution::Known(truth_p),
1051 vec![decoy],
1052 w,
1053 )
1054}
1055
1056fn multi_fit(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1057 // B: truth T and rival R agree on the visible inputs, disagree on held-outs.
1058 let w = spec.params.width;
1059 let n = spec.params.visible as usize;
1060 let cands = enumerate_basic(2);
1061 for _ in 0..200 {
1062 let t = random_chain(&mut ctx.rule, Vocab::Basic, 2);
1063 let tb = t.behavior();
1064 let probe = pool(&mut ctx.rule, 256, Stage::Visible, w, &|_| true);
1065 let mut best: Option<(usize, &Program)> = None;
1066 for r in &cands {
1067 if r.behavior() == tb {
1068 continue;
1069 }
1070 let agree = probe.iter().filter(|&&x| r.run(x) == t.run(x)).count();
1071 if agree >= n * 3 && agree < probe.len() && best.is_none_or(|(b, _)| agree > b) {
1072 best = Some((agree, r));
1073 }
1074 }
1075 if let Some((_, r)) = best {
1076 let r = r.clone();
1077 let (tc, rc) = (t.clone(), r.clone());
1078 let agree = move |x: u64| tc.run(x) == rc.run(x);
1079 let vis_pool = pool(&mut ctx.vis, 600, Stage::Visible, w, &agree);
1080 let interp = pool(&mut ctx.hold, 600, Stage::Interpolation, w, &|_| true);
1081 let extrap = pool(&mut ctx.hold, 600, Stage::Extrapolation, w, &|_| true);
1082 let adv = pool(&mut ctx.hold, 600, Stage::Interpolation, w, &|x| !agree(x));
1083 if vis_pool.len() < n || adv.is_empty() {
1084 continue;
1085 }
1086 let tt = t.clone();
1087 let (visible, heldouts) =
1088 sets_from_pools(ctx, n, &vis_pool, &interp, &extrap, &adv, &move |x| {
1089 tt.run(x)
1090 });
1091 return rabbit(visible, heldouts, KnownSolution::Known(t), vec![r], w);
1092 }
1093 }
1094 op_chain(spec, ctx)
1095}
1096
1097fn spurious_field(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1098 // C: x = a | (z << 16). The answer depends only on a, but in the visible
1099 // sample the high field z equals the answer, so reading z also fits.
1100 let f = random_chain(&mut ctx.rule, Vocab::Basic, 2);
1101 let truth_p = Program::of(&[(Op::And, 0xFFFF)]).then(&f);
1102 let decoy = Program::of(&[(Op::Shr, 16)]);
1103 let mk_vis = |rng: &mut Rng, n: usize| -> Vec<u64> {
1104 let mut out = Vec::new();
1105 let mut tries = 0;
1106 while out.len() < n && tries < 10_000 {
1107 tries += 1;
1108 let a = rng.range(0, 0xFFFF);
1109 let y = f.run(a);
1110 if y <= 0xFFFF {
1111 out.push(a | (y << 16));
1112 }
1113 }
1114 out
1115 };
1116 let vis_pool = mk_vis(&mut ctx.vis, 200);
1117 let interp = mk_vis(&mut ctx.hold, 200);
1118 let extrap: Vec<u64> = (0..200)
1119 .map(|_| ctx.hold.range(0, 0xFFFF) | (ctx.hold.range(0, 0xFFFF) << 16))
1120 .collect();
1121 let adv: Vec<u64> = (0..200)
1122 .map(|_| ctx.hold.range(0, 0xFFFF) | (ctx.hold.range(0, 0xFFFF) << 32))
1123 .collect();
1124 let t = truth_p.clone();
1125 let (visible, heldouts) = sets_from_pools(
1126 ctx,
1127 spec.params.visible as usize,
1128 &vis_pool,
1129 &interp,
1130 &extrap,
1131 &adv,
1132 &move |x| t.run(x),
1133 );
1134 rabbit(
1135 visible,
1136 heldouts,
1137 KnownSolution::Known(truth_p),
1138 vec![decoy],
1139 48,
1140 )
1141}
1142
1143fn elegant_arbitrary(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1144 // E: an arbitrary 256-entry table whose first entries follow a neat chain.
1145 let s = random_chain(&mut ctx.rule, Vocab::Basic, 2);
1146 let k = spec.params.visible as u64;
1147 let table: Vec<u64> = (0..256u64)
1148 .map(|i| {
1149 if i < k {
1150 s.run(i)
1151 } else {
1152 ctx.rule.below(1 << 20)
1153 }
1154 })
1155 .collect();
1156 let vis_pool: Vec<u64> = (0..k).collect();
1157 let rest: Vec<u64> = (k..256).collect();
1158 let t2 = table.clone();
1159 let (visible, heldouts) =
1160 sets_from_pools(ctx, k as usize, &vis_pool, &rest, &rest, &rest, &move |x| {
1161 t2[x as usize]
1162 });
1163 let mut d = rabbit(
1164 visible,
1165 heldouts,
1166 KnownSolution::NoCompactStructure,
1167 vec![s],
1168 8,
1169 );
1170 d.domain = (0, 255);
1171 d
1172}
1173
1174fn insufficient_evidence(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1175 // F: too few examples to separate several short explanations.
1176 let w = spec.params.width;
1177 let n = spec.params.visible.clamp(2, 4) as usize;
1178 let cands = enumerate_basic(2);
1179 for _ in 0..200 {
1180 let t = random_chain(&mut ctx.rule, Vocab::Basic, 2);
1181 let xs = pool(&mut ctx.vis, n, Stage::Visible, w, &|x| x < 64);
1182 if xs.len() < n {
1183 continue;
1184 }
1185 let mut rivals: Vec<Program> = Vec::new();
1186 let mut seen = HashSet::new();
1187 seen.insert(t.behavior());
1188 for c in &cands {
1189 if xs.iter().all(|&x| c.run(x) == t.run(x)) && seen.insert(c.behavior()) {
1190 rivals.push(c.clone());
1191 }
1192 }
1193 if rivals.len() >= 2 {
1194 rivals.truncate(8);
1195 let tt = t.clone();
1196 let interp = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|_| true);
1197 let extrap = pool(&mut ctx.hold, 200, Stage::Extrapolation, w, &|_| true);
1198 // Every rival gets at least one held-out that separates it from the truth.
1199 let mut adv: Vec<u64> = Vec::new();
1200 for r in &rivals {
1201 let sep = pool(&mut ctx.hold, 1, Stage::Interpolation, w, &|x| {
1202 r.run(x) != tt.run(x) && !xs.contains(&x)
1203 });
1204 adv.extend(sep);
1205 }
1206 if adv.len() < rivals.len() {
1207 continue;
1208 }
1209 let t3 = t.clone();
1210 let (visible, heldouts) =
1211 sets_from_pools(ctx, n, &xs, &interp, &extrap, &adv, &move |x| t3.run(x));
1212 return rabbit(visible, heldouts, KnownSolution::Known(t), rivals, w);
1213 }
1214 }
1215 op_chain(spec, ctx)
1216}
1217
1218fn no_structure(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1219 let table: Vec<u64> = (0..256).map(|_| ctx.rule.below(1 << 24)).collect();
1220 let mut sample = |r: &mut Rng, _s: Stage| r.below(256);
1221 let mut d = unary_draft(
1222 spec,
1223 ctx,
1224 24,
1225 KnownSolution::NoCompactStructure,
1226 &mut sample,
1227 &move |x| table[x as usize],
1228 );
1229 d.domain = (0, 255);
1230 d
1231}
1232
1233fn rabbit(
1234 visible: Vec<(Vec<u64>, Vec<u64>)>,
1235 heldouts: Heldouts,
1236 known: KnownSolution,
1237 alternatives: Vec<Program>,
1238 width: u8,
1239) -> Draft {
1240 Draft {
1241 in_lane_bytes: 0,
1242 out_lane_bytes: 0,
1243 visible,
1244 heldouts,
1245 known,
1246 alternatives,
1247 noisy_visible: vec![],
1248 domain: (0, width_max(width)),
1249 requires: vec![],
1250 provides: None,
1251 verification: VerificationMethod::ExactGeneratorEvaluation,
1252 }
1253}
1254
1255// ---------------------------------------------------------------------------
1256// capabilities and their compositions (the breadcrumb trail)
1257// ---------------------------------------------------------------------------
1258
1259fn capability_primitive(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1260 let pool = capability_pool();
1261 let cap = &pool[spec.params.caps[0] as usize];
1262 let prog = cap.program.clone();
1263 let t = prog.clone();
1264 let mut d = unary_draft(
1265 spec,
1266 ctx,
1267 64,
1268 KnownSolution::Known(prog),
1269 &mut dflt(spec.params.width),
1270 &move |x| t.run(x),
1271 );
1272 d.provides = Some(cap.id);
1273 d
1274}
1275
1276fn capability_composition(spec: &FamilySpec, ctx: &mut Ctx) -> Draft {
1277 let pool = capability_pool();
1278 let mut prog = Program::default();
1279 let mut requires = Vec::new();
1280 for &c in &spec.params.caps {
1281 prog = prog.then(&pool[c as usize].program);
1282 requires.push(pool[c as usize].id);
1283 }
1284 let t = prog.clone();
1285 let mut d = unary_draft(
1286 spec,
1287 ctx,
1288 64,
1289 KnownSolution::Known(prog),
1290 &mut dflt(spec.params.width),
1291 &move |x| t.run(x),
1292 );
1293 d.requires = requires;
1294 d
1295}
1296
1297/// Count how many visible examples a program explains (used by tests).
1298pub fn visible_agreement(p: &Program, visible: &[(Vec<u64>, Vec<u64>)]) -> usize {
1299 visible.iter().filter(|(i, o)| p.run(i[0]) == o[0]).count()
1300}