Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/crumbs/src/gen/mod.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / crumbs / src / gen / mod.rs` 441 lines ยท 13516 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 framework: deterministic families built from reusable mechanisms. 17 //! 18 //! `generate(family, seed)` is a pure function of (family_id, 19 //! generator_version, seed, canonical parameters). It returns the 20 //! learner-visible crumb and its sealed record together; the two are separated 21 //! by type from that point on. 22 //! 23 //! Streams: the hidden rule is drawn from `rule`, visible inputs from 24 //! `visible`, and held-outs from `heldout` keyed by a separate heldout seed, 25 //! so the visible set can be regenerated without touching the held-outs. 26 27 pub mod mechanisms; 28 pub mod registry; 29 pub mod rng; 30 31 use crate::canon::Enc; 32 use crate::digest::{digest, Digest, Domain}; 33 use crate::program::{Op, Program, Step}; 34 use crate::provenance::Provenance; 35 use crate::sealed::{ 36 generator_instance_digest, CapabilityId, DecoyStatus, Heldouts, KnownSolution, LaneExample, 37 Rung, SealedCrumb, SourceFamily, TruthStatus, VerificationMethod, SEALED_SCHEMA_VERSION, 38 }; 39 use crate::visible::{lane_mask, Encoding, VisibleCrumb}; 40 use rng::Rng; 41 use serde::Serialize; 42 use std::collections::HashSet; 43 44 pub use mechanisms::Mechanism; 45 pub use registry::{capability_pool, registry, Registry}; 46 47 /// Version of every v1 generator. A behaviour change requires a bump; the 48 /// golden vectors in the test suite fail otherwise. 49 pub const GENERATOR_VERSION: &str = "1.0.0"; 50 51 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] 52 pub enum Vocab { 53 /// add/sub/mul/and/or with small constants. 54 Basic = 1, 55 /// Basic plus xor/shift/rotate. 56 Extended = 2, 57 } 58 59 /// Static, canonical family parameters (part of GeneratorInstanceDigest). 60 #[derive(Clone, Debug, PartialEq, Eq, Serialize)] 61 pub struct Params { 62 pub encoding: Encoding, 63 /// Input lane width in bits (lane 0 range for unary families). 64 pub width: u8, 65 /// Chain length, arity, repetition count or state count, per mechanism. 66 pub len: u8, 67 /// Extra integer parameter, per mechanism. 68 pub k: u64, 69 pub vocab: Vocab, 70 /// Capability pool indices (capability and composition families). 71 pub caps: Vec, 72 /// Visible example count. 73 pub visible: u8, 74 } 75 76 impl Params { 77 pub fn new(width: u8, len: u8) -> Params { 78 Params { 79 encoding: Encoding::DecimalUtf8, 80 width, 81 len, 82 k: 0, 83 vocab: Vocab::Basic, 84 caps: vec![], 85 visible: 8, 86 } 87 } 88 89 pub fn to_bytes(&self) -> Vec { 90 let mut e = Enc::new(); 91 e.u8(self.encoding as u8) 92 .u8(self.width) 93 .u8(self.len) 94 .u64(self.k) 95 .u8(self.vocab as u8); 96 e.u32(self.caps.len() as u32); 97 for c in &self.caps { 98 e.u16(*c); 99 } 100 e.u8(self.visible); 101 e.finish() 102 } 103 } 104 105 /// One registered family: a mechanism plus parameters plus sealed labels. 106 #[derive(Clone, Debug)] 107 pub struct FamilySpec { 108 pub id: u32, 109 pub key: String, 110 pub mechanism: Mechanism, 111 pub params: Params, 112 pub rung: Rung, 113 pub source_family: SourceFamily, 114 pub provenance: Provenance, 115 pub decoy: DecoyStatus, 116 pub difficulty: u16, 117 pub topic: &'static str, 118 } 119 120 /// A generated crumb: the visible half and the sealed half. 121 pub struct Generated { 122 pub visible: VisibleCrumb, 123 pub sealed: SealedCrumb, 124 } 125 126 /// What a mechanism produces before the framework seals it. 127 pub struct Draft { 128 pub in_lane_bytes: u8, 129 pub out_lane_bytes: u8, 130 pub visible: Vec<(Vec, Vec)>, 131 pub heldouts: Heldouts, 132 pub known: KnownSolution, 133 pub alternatives: Vec, 134 pub noisy_visible: Vec, 135 pub domain: (u64, u64), 136 pub requires: Vec, 137 pub provides: Option, 138 pub verification: VerificationMethod, 139 } 140 141 /// Random streams handed to a mechanism. 142 pub struct Ctx { 143 pub rule: Rng, 144 pub vis: Rng, 145 pub hold: Rng, 146 } 147 148 /// Which sample a sampler is being asked for. 149 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 150 pub enum Stage { 151 Visible, 152 Interpolation, 153 Extrapolation, 154 Adversarial, 155 } 156 157 pub fn heldout_seed(family_id: u32, seed: u64) -> u64 { 158 let mut e = Enc::new(); 159 e.bytes(b"heldout-seed").u32(family_id).u64(seed); 160 let d = digest(Domain::Rng, &e.finish()); 161 u64::from_le_bytes(d.0[..8].try_into().unwrap()) 162 } 163 164 /// Code identity of a mechanism at this generator version. 165 pub fn generator_code_digest(m: Mechanism) -> Digest { 166 let mut e = Enc::new(); 167 e.str(m.key()).u32(m.version()).str(GENERATOR_VERSION); 168 digest(Domain::GeneratorCode, &e.finish()) 169 } 170 171 pub fn generate(spec: &FamilySpec, seed: u64) -> Generated { 172 let hseed = heldout_seed(spec.id, seed); 173 let mut ctx = Ctx { 174 rule: Rng::named("rule", &[spec.id as u64, seed]), 175 vis: Rng::named("visible", &[spec.id as u64, seed]), 176 hold: Rng::named("heldout", &[spec.id as u64, hseed]), 177 }; 178 let draft = mechanisms::run(spec, &mut ctx); 179 let visible = VisibleCrumb::from_values( 180 spec.params.encoding, 181 draft.in_lane_bytes, 182 draft.out_lane_bytes, 183 &draft.visible, 184 None, 185 ) 186 .expect("mechanism produced a well-formed visible set"); 187 let params = spec.params.to_bytes(); 188 let sealed = SealedCrumb { 189 schema_version: SEALED_SCHEMA_VERSION, 190 crumb_digest: visible.digest(), 191 family_id: spec.id, 192 family_key: spec.key.clone(), 193 mechanism: spec.mechanism.key().to_string(), 194 generator_version: GENERATOR_VERSION.to_string(), 195 generator_code_digest: generator_code_digest(spec.mechanism), 196 seed, 197 heldout_seed: hseed, 198 generator_instance_digest: generator_instance_digest( 199 spec.id, 200 GENERATOR_VERSION, 201 seed, 202 ¶ms, 203 ), 204 generation_parameters: params, 205 verification_method: draft.verification, 206 difficulty: spec.difficulty, 207 rung: spec.rung, 208 required_capabilities: draft.requires, 209 provides_capability: draft.provides, 210 provenance: spec.provenance, 211 source_family: spec.source_family, 212 truth_status: TruthStatus::Verified, 213 decoy_status: spec.decoy, 214 known_solution: draft.known, 215 alternatives: draft.alternatives, 216 noisy_visible: draft.noisy_visible, 217 expected_domain: draft.domain, 218 topic_internal: spec.topic.to_string(), 219 heldouts: draft.heldouts, 220 }; 221 Generated { visible, sealed } 222 } 223 224 // --------------------------------------------------------------------------- 225 // Combinators shared by mechanisms. 226 // --------------------------------------------------------------------------- 227 228 pub fn width_max(width: u8) -> u64 { 229 if width >= 64 { 230 u64::MAX 231 } else { 232 (1u64 << width) - 1 233 } 234 } 235 236 /// The default unary input sampler for a lane of `width` bits. 237 pub fn default_sample(rng: &mut Rng, stage: Stage, width: u8) -> u64 { 238 let max = width_max(width); 239 let common = max.min(4095); 240 match stage { 241 Stage::Visible | Stage::Interpolation => match rng.below(10) { 242 0..=5 => rng.range(0, common), 243 6..=7 => rng.range(0, max.min(31)), 244 _ => rng.range(0, max), 245 }, 246 Stage::Extrapolation => { 247 if common < max { 248 rng.range(common + 1, max) 249 } else { 250 rng.range(0, max) 251 } 252 } 253 Stage::Adversarial => { 254 let k = rng.below(width as u64) as u32; 255 let p = 1u64.checked_shl(k).unwrap_or(0) & max; 256 match rng.below(8) { 257 0 => 0, 258 1 => 1, 259 2 => max, 260 3 => max.wrapping_sub(1) & max, 261 4 => p, 262 5 => p.wrapping_sub(1) & max, 263 6 => p.wrapping_add(1) & max, 264 _ => rng.range(0, max), 265 } 266 } 267 } 268 } 269 270 /// Sizes of the sealed held-out tiers. 271 pub const HELDOUT_PER_TIER: usize = 16; 272 273 /// Build visible + three held-out tiers from a truth function and a sampler. 274 /// Held-out inputs never repeat a visible input, and tiers never repeat each other. 275 pub type Pairs = Vec<(Vec, Vec)>; 276 277 pub fn build_sets( 278 ctx: &mut Ctx, 279 n_visible: usize, 280 out_mask: u64, 281 sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec, 282 truth: &dyn Fn(&[u64]) -> Vec, 283 ) -> (Pairs, Heldouts) { 284 let mut seen: HashSet> = HashSet::new(); 285 let mut visible = Vec::new(); 286 draw_unique( 287 &mut ctx.vis, 288 Stage::Visible, 289 n_visible, 290 &mut seen, 291 sample, 292 &mut |x| visible.push((x.clone(), mask_all(truth(&x), out_mask))), 293 ); 294 let mut h = Heldouts::default(); 295 for (stage, dst) in [ 296 (Stage::Interpolation, &mut h.interpolation), 297 (Stage::Extrapolation, &mut h.extrapolation), 298 (Stage::Adversarial, &mut h.adversarial), 299 ] { 300 draw_unique( 301 &mut ctx.hold, 302 stage, 303 HELDOUT_PER_TIER, 304 &mut seen, 305 sample, 306 &mut |x| { 307 dst.push(LaneExample { 308 output: mask_all(truth(&x), out_mask), 309 input: x, 310 }) 311 }, 312 ); 313 } 314 (visible, h) 315 } 316 317 fn mask_all(mut v: Vec, m: u64) -> Vec { 318 for x in v.iter_mut() { 319 *x &= m; 320 } 321 v 322 } 323 324 fn draw_unique( 325 rng: &mut Rng, 326 stage: Stage, 327 n: usize, 328 seen: &mut HashSet>, 329 sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec, 330 sink: &mut dyn FnMut(Vec), 331 ) { 332 let mut got = 0; 333 let mut tries = 0; 334 while got < n && tries < n * 200 { 335 tries += 1; 336 let x = sample(rng, stage); 337 if seen.insert(x.clone()) { 338 sink(x); 339 got += 1; 340 } 341 } 342 } 343 344 pub fn out_mask_for(encoding: Encoding, out_lane_bytes: u8) -> u64 { 345 match encoding { 346 Encoding::DecimalUtf8 => u64::MAX, 347 Encoding::RawLe => lane_mask(out_lane_bytes), 348 } 349 } 350 351 pub fn lane_bytes_for(encoding: Encoding, width_bits: u8) -> u8 { 352 match encoding { 353 Encoding::DecimalUtf8 => 0, 354 Encoding::RawLe => match width_bits { 355 0..=8 => 1, 356 9..=16 => 2, 357 17..=32 => 4, 358 _ => 8, 359 }, 360 } 361 } 362 363 /// Random step from a vocabulary. 364 pub fn random_step(rng: &mut Rng, vocab: Vocab) -> Step { 365 let n_ops = match vocab { 366 Vocab::Basic => 5, 367 Vocab::Extended => 9, 368 }; 369 let op = Op::from_u8(1 + rng.below(n_ops) as u8).unwrap(); 370 let imm = match op { 371 Op::Add | Op::Sub => rng.range(1, 9), 372 Op::Mul => rng.range(2, 7), 373 Op::And => *rng.pick(&[0xFF, 0x0F, 0x3F, 0xFFF, 0xFFFF]), 374 Op::Or => *rng.pick(&[1, 2, 4, 8, 16]), 375 Op::Xor => rng.range(1, 255), 376 Op::Shl | Op::Shr => rng.range(1, 4), 377 Op::Rotl => rng.range(1, 15), 378 }; 379 Step { op, imm } 380 } 381 382 /// Probe-behaviour is constant (the chain ignores its input). 383 pub fn is_constant(p: &Program) -> bool { 384 let first = p.run(crate::program::PROBES[0]); 385 crate::program::PROBES.iter().all(|&x| p.run(x) == first) 386 } 387 388 /// A chain of `len` steps with no dead step: removing any one step changes 389 /// its behaviour, and it is not constant. 390 pub fn random_chain(rng: &mut Rng, vocab: Vocab, len: usize) -> Program { 391 for _ in 0..10_000 { 392 let p = Program::new((0..len).map(|_| random_step(rng, vocab)).collect()); 393 if is_constant(&p) { 394 continue; 395 } 396 let b = p.behavior(); 397 let dead = (0..len).any(|i| { 398 let mut q = p.clone(); 399 q.steps.remove(i); 400 q.behavior() == b 401 }); 402 if !dead { 403 return p; 404 } 405 } 406 Program::of(&[(Op::Add, 1)]) 407 } 408 409 /// Every Basic chain of length 1..=max_len (the generator's own enumeration, 410 /// used to find rival explanations for ambiguity and multi-fit families). 411 pub fn enumerate_basic(max_len: usize) -> Vec { 412 let mut steps = Vec::new(); 413 for imm in 1..=9 { 414 steps.push(Step { op: Op::Add, imm }); 415 steps.push(Step { op: Op::Sub, imm }); 416 } 417 for imm in 2..=7 { 418 steps.push(Step { op: Op::Mul, imm }); 419 } 420 for imm in [0xFF, 0x0F, 0x3F, 0xFFF, 0xFFFF] { 421 steps.push(Step { op: Op::And, imm }); 422 } 423 for imm in [1, 2, 4, 8, 16] { 424 steps.push(Step { op: Op::Or, imm }); 425 } 426 let mut out: Vec = steps.iter().map(|s| Program::new(vec![*s])).collect(); 427 let mut frontier = out.clone(); 428 for _ in 1..max_len { 429 let mut next = Vec::new(); 430 for p in &frontier { 431 for s in &steps { 432 let mut q = p.clone(); 433 q.steps.push(*s); 434 next.push(q); 435 } 436 } 437 out.extend(next.iter().cloned()); 438 frontier = next; 439 } 440 out 441 }