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
GitHub aien-dev/aien-sovereign-core-mv#226 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/9d0d5fdcdb4a1099.bundle -o 9d0d5fdcdb4a1099.bundle git fetch 9d0d5fdcdb4a1099.bundle refs/pull/226/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
226
7f6f0496074d16615acb2e38049cf847ddaeaca9
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":226,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/226","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:22Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index cba6ac26..f17e5f48 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:10d81c6270915316b54eee21734bb8e8f2716ffdc567100fb347a5f22ed95e24", - "compiled_at": "2026-10-06T03:25:30Z", + "compiled_at": "2026-10-06T15:23:37Z", "compiler": "crumb-compile/1", - "digest": "sha256:b630e0720f32de35df66e7982c1e50020f374004e890bca004986450c0bc7fd5", + "digest": "sha256:f1a21d458e0a02edee900a36361571c324de544079759040d0f29c895d61fa47", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 715, - "generated_at_commit": "6264a9e34551c4aff3f5e7f08aec6677125c4387", - "source_tree": "sha256:2ea3d0f8b8d455157c595a0a5ed59e1b19111429ec7aeff23be10b9eb06c1c1b" + "files": 746, + "generated_at_commit": "8c8e20db5f62d8c1fe613d5b1409ef234d818fd3", + "source_tree": "sha256:6113cc747526e53ea809d3e1e7fc4de93609cb5039b5aa50af34e00840735470" } }, "history": [], diff --git a/crates/aien-abi-core/src/lib.rs b/crates/aien-abi-core/src/lib.rs index aaafcc75..8fa6ecfa 100644 --- a/crates/aien-abi-core/src/lib.rs +++ b/crates/aien-abi-core/src/lib.rs @@ -37,7 +37,89 @@ fn default_rope_theta() -> f32 { 10000.0 } -#[derive(Debug, Clone, Serialize, Deserialize)] +/// Llama 3 rotary frequency smoothing (`rope_scaling` with `rope_type: "llama3"` in a +/// Hugging Face `config.json`). Long wavelengths are divided by `factor`, short ones kept, +/// the band between `high_freq_factor` and `low_freq_factor` is interpolated +/// (transformers `_compute_llama3_parameters`). +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct Llama3RopeScaling { + pub factor: f64, + pub low_freq_factor: f64, + pub high_freq_factor: f64, + pub original_max_position_embeddings: usize, +} + +impl Llama3RopeScaling { + /// Applies the llama3 smoothing to one unscaled inverse frequency. + pub fn scale_inv_freq(&self, inv_freq: f64) -> f64 { + let old_context = self.original_max_position_embeddings as f64; + let low_freq_wavelen = old_context / self.low_freq_factor; + let high_freq_wavelen = old_context / self.high_freq_factor; + let wavelen = 2.0 * std::f64::consts::PI / inv_freq; + if wavelen < high_freq_wavelen { + inv_freq + } else if wavelen > low_freq_wavelen { + inv_freq / self.factor + } else { + let smooth = (old_context / wavelen - self.low_freq_factor) + / (self.high_freq_factor - self.low_freq_factor); + (1.0 - smooth) * inv_freq / self.factor + smooth * inv_freq + } + } +} + +/// Rotary position embedding parameters of one model: the base `theta` and, for the +/// Llama 3 family, the llama3 frequency smoothing. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RopeParams { + pub theta: f32, + pub llama3: Option<Llama3RopeScaling>, +} + +impl RopeParams { + /// Unscaled rope: inverse frequency `theta^(-2i/d)`. + pub const fn plain(theta: f32) -> Self { + Self { + theta, + llama3: None, + } + } + + /// Inverse frequency of rotary pair `i` (`0 <= i < head_dim / 2`), in f64. + /// The unscaled expression is exactly the one the reference rope has always used, + /// so models without scaling get bit-identical tables. + pub fn inv_freq(&self, i: usize, head_dim: usize) -> f64 { + let exponent = (2 * i) as f64 / (head_dim as f64); + let base = 1.0 / (self.theta as f64).powf(exponent); + match &self.llama3 { + None => base, + Some(scaling) => scaling.scale_inv_freq(base), + } + } + + /// All `head_dim / 2` inverse frequencies. + pub fn inv_freqs(&self, head_dim: usize) -> Vec<f64> { + (0..head_dim / 2) + .map(|i| self.inv_freq(i, head_dim)) + .collect() + } + + /// Bit pattern identifying these parameters (for table caches). + pub fn cache_key(&self) -> [u64; 5] { + match &self.llama3 { + None => [self.theta.to_bits() as u64, 0, 0, 0, 0], + Some(s) => [ + self.theta.to_bits() as u64 | (1 << 32), + s.factor.to_bits(), + s.low_freq_factor.to_bits(), + s.high_freq_factor.to_bits(), + s.original_max_position_embeddings as u64, + ], + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ModelConfig { pub model_id: String, pub max_sequence_length: usize, @@ -57,6 +139,17 @@ pub struct ModelConfig { pub rms_norm_eps: f32, #[serde(default = "default_rope_theta")] pub rope_theta: f32, + /// Llama 3 rope smoothing; `None` is plain rope. + #[serde(default)] + pub rope_scaling: Option<Llama3RopeScaling>, + /// True when the output projection reuses `model.embed_tokens.weight` + /// (the checkpoint has no `lm_head.weight`). + #[serde(default)] + pub tie_word_embeddings: bool, + /// Token ids that end a sequence (`eos_token_id` of `generation_config.json`). + /// Empty means the legacy TinyLlama set, see [`ModelConfig::stop_token_ids`]. + #[serde(default)] + pub eos_token_ids: Vec<u32>, } /// Why an [`AttentionGeometry`] was refused. Every variant names the offending numbers so a @@ -268,6 +361,31 @@ impl ModelConfig { vocab_size: 32000, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), + } + } + + /// Stop set the backend ends a sequence on before the scheduler sees the token: + /// UNK 0, BOS 1 and EOS 2 of the TinyLlama vocabulary. + pub const LEGACY_STOP_TOKEN_IDS: [u32; 3] = [0, 1, 2]; + + /// The backend's end-of-sequence set: `eos_token_ids` when the model description + /// names them, else [`ModelConfig::LEGACY_STOP_TOKEN_IDS`]. + pub fn stop_token_ids(&self) -> &[u32] { + if self.eos_token_ids.is_empty() { + &Self::LEGACY_STOP_TOKEN_IDS + } else { + &self.eos_token_ids + } + } + + /// Rotary embedding parameters of this model. + pub fn rope(&self) -> RopeParams { + RopeParams { + theta: self.rope_theta, + llama3: self.rope_scaling, } } @@ -317,6 +435,9 @@ impl Default for ModelConfig { vocab_size: 151936, rms_norm_eps: 1e-6, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } } diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 22beaa16..a48d8d9f 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "7e172306ece8e1b074de1f9375f012d5886c89993bfe7a0fa32f3c7ec0ec342f", - "last_commit": "94b1eed", + "digest": "38dbadc5b4dc120e1718776d575fc159a60c6f6ec00b369295ba11cfe599279c", + "last_commit": "8c8e20d", "name": "src", "purpose": "" } ], - "children_root": "sha256:c3356e96fd5c1cc4bcb5edaebe1e8e0dcfae3496b43602fdcf5247fdc37dd3d5", - "compiled_at": "2026-10-06T02:27:26Z", + "children_root": "sha256:0524966fe77bc78b9f354a439d4e0d712b54f813c23e973adb46be510164c566", + "compiled_at": "2026-10-06T15:23:37Z", "compiler": "crumb-compile/1", - "digest": "sha256:f8352cc1a77ec1cf3bb377b96f648e4e5b6d488be85cd1a9941eb68dd757bd5c", + "digest": "sha256:ad04944ffe0f89452ab355188b2ed6fc503511aa91504f810a2f83b46a9b3b7a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 28, - "generated_at_commit": "94b1eed8649067dda6ce75ad905d33047f5902b6", - "source_tree": "sha256:dd7f86eb35f1d49c5161867f78cc2775eff91220ff42fc758f39a8d5f10e8348" + "generated_at_commit": "8c8e20db5f62d8c1fe613d5b1409ef234d818fd3", + "source_tree": "sha256:7266d87191959db99140c012f9c35859a874ee436eba4f93bd839b52474b15cf" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index a309bf99..cf550a91 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-06T02:27:26Z", + "compiled_at": "2026-10-06T15:23:37Z", "compiler": "crumb-compile/1", - "digest": "sha256:7e172306ece8e1b074de1f9375f012d5886c89993bfe7a0fa32f3c7ec0ec342f", + "digest": "sha256:38dbadc5b4dc120e1718776d575fc159a60c6f6ec00b369295ba11cfe599279c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "94b1eed8649067dda6ce75ad905d33047f5902b6", - "source_tree": "sha256:f15e1c93e1b10a1ef385ad83657282ff84354898ce045ee6458e05740205b648" + "generated_at_commit": "8c8e20db5f62d8c1fe613d5b1409ef234d818fd3", + "source_tree": "sha256:5f4d2bae87ffd4f6ad89c8810435f1142dcfe78bd6c6bb91cf9ab3d1f7af737d" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index a25ac6b0..6d9ca796 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -939,7 +939,10 @@ struct DaemonModelManifest { /// Checkpoint selection inputs, read once from the environment. /// `AIEN_MODEL_PATH` (a safetensors file) and `AIEN_TOKENIZER_PATH` (tokenizer.json, /// default: `tokenizer.json` beside the model file) take precedence over any directory -/// scan. `AIEN_REQUIRE_CHECKPOINT=1` makes every fallback to reference weights fatal. +/// scan. `AIEN_MODEL_DIR` is scanned first for a `*.safetensors` file (directly or one level +/// down). The model is described by `config.json` beside the checkpoint when present (any +/// `LlamaForCausalLM`, e.g. Llama 3.x), else by the built-in TinyLlama-1.1B config. +/// `AIEN_REQUIRE_CHECKPOINT=1` makes every fallback to reference weights fatal. #[derive(Debug, Clone, Default)] struct CheckpointPolicy { model_path: Option<std::path::PathBuf>, @@ -1105,6 +1108,9 @@ fn reference_config() -> aien_inference_abi::ModelConfig { vocab_size: 32000, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } @@ -1114,7 +1120,7 @@ struct DaemonModel { #[allow(dead_code)] // digests are read by the PREFILL-E2E receipt (Cut 8) manifest: DaemonModelManifest, weights: aien_inference_abi::TransformerWeights, - tokenizer: Option<aien_inference_abi::TinyLlamaTokenizer>, + tokenizer: Option<aien_inference_abi::ChatTokenizer>, label: String, #[allow(dead_code)] // read by tests now and by the PREFILL-E2E receipt (Cut 8) reference_weights: bool, @@ -1191,7 +1197,21 @@ fn load_daemon_model( return reference_fallback(manifest, require_checkpoint, reason); } }; - let config = aien_inference_abi::ModelConfig::tinyllama_1_1b(); + // The model description: config.json beside the checkpoint (any LlamaForCausalLM + // checkpoint), else the hard-wired TinyLlama-1.1B config. + let model_dir = path + .parent() + .map(std::path::Path::to_path_buf) + .unwrap_or_default(); + let has_config_json = model_dir.join("config.json").is_file(); + let config = if has_config_json { + match aien_inference_abi::load_model_config(&model_dir) { + Ok(config) => config, + Err(error) => return reference_fallback(manifest, require_checkpoint, error), + } + } else { + aien_inference_abi::ModelConfig::tinyllama_1_1b() + }; let weights = match aien_inference_abi::TransformerWeights::load_from_safetensors(&path, &config) { Ok(weights) => weights, @@ -1223,7 +1243,15 @@ fn load_daemon_model( ), )?, Ok(digest) => { - match aien_inference_abi::TinyLlamaTokenizer::from_file(&tokenizer_path) { + let loaded = if has_config_json { + aien_inference_abi::ChatTokenizer::from_model_dir( + &model_dir, + Some(&tokenizer_path), + ) + } else { + aien_inference_abi::ChatTokenizer::from_file(&tokenizer_path) + }; + match loaded { Ok(loaded) => { manifest.tokenizer_sha256 = Some(digest); tokenizer = Some(loaded); @@ -1242,7 +1270,7 @@ fn load_daemon_model( } let label = format!( - "checkpoint loaded from {} ({}, model_id={}, model_sha256={}, tokenizer_sha256={})", + "checkpoint loaded from {} ({}, model_id={}, config={}, model_sha256={}, tokenizer_sha256={})", path.display(), if tokenizer.is_some() { "tokenizer loaded" @@ -1250,6 +1278,11 @@ fn load_daemon_model( "tokenizer missing" }, manifest.model_id, + if has_config_json { + format!("{} (config.json)", config.model_id) + } else { + format!("{} (built in)", config.model_id) + }, manifest.model_sha256.as_deref().unwrap_or("none"), manifest.tokenizer_sha256.as_deref().unwrap_or("none"), ); @@ -1270,7 +1303,7 @@ type DaemonBackendParts = ( std::sync::Arc<dyn aien_inference_abi::TensorBackend>, String, String, - Option<aien_inference_abi::TinyLlamaTokenizer>, + Option<aien_inference_abi::ChatTokenizer>, ); fn build_native_daemon_backend() -> Result<DaemonBackendParts, String> { @@ -1370,8 +1403,14 @@ pub async fn run_daemon_server() { "one pooled KV shared by runtime and backend".green() ); if let Some(tokenizer) = tokenizer { + println!( + " Tokenizer: {} chat template, stop ids {:?}", + tokenizer.template().name().green(), + tokenizer.stop_token_ids() + ); server.set_tokenizer(tokenizer); - println!(" Tokenizer: {}", "TinyLlama chat template".green()); + // NEXT-PHASE-1 v4: one declared 1-token warm-up before serving. + server.enable_warm_up(); } else { println!( " Tokenizer: {}", diff --git a/crates/aien-inference-abi/examples/profile_ops.rs b/crates/aien-inference-abi/examples/profile_ops.rs index 9345ad4f..411d05bc 100644 --- a/crates/aien-inference-abi/examples/profile_ops.rs +++ b/crates/aien-inference-abi/examples/profile_ops.rs @@ -19,6 +19,9 @@ fn main() { vocab_size: 32000, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), }; let safetensors_path = "/home/drakestapleton/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6/model.safetensors"; @@ -37,7 +40,7 @@ fn main() { let q_dim = num_heads * head_dim; let kv_dim = num_kv_heads * head_dim; let eps = model_config.rms_norm_eps; - let theta = model_config.rope_theta; + let rope = model_config.rope(); // Simulate seq_len = 128 (decode step 128) let seq_len = 128; @@ -126,7 +129,7 @@ fn main() { head_dim, num_heads, num_kv_heads, - theta, + &rope, ); if is_bench { time_rope_us += t0.elapsed().as_micros(); @@ -241,7 +244,7 @@ fn main() { backend.compute_logits( &mut logits, &x_final, - &weights.lm_head, + weights.output_projection(), vocab_size, hidden_dim, ); diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index ed359587..96d71e50 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -2,9 +2,9 @@ //! Provides hardware-neutral abstraction for transformer mathematical operations. use crate::tensor::{ - apply_rope as tensor_rope, matmul_vec as tensor_matmul, rmsnorm as tensor_rmsnorm, + apply_rope_params as tensor_rope, matmul_vec as tensor_matmul, rmsnorm as tensor_rmsnorm, }; -use aien_abi_core::AttentionGeometry; +use aien_abi_core::{AttentionGeometry, RopeParams}; /// The trait's attention methods return `()`, so a wrong head layout cannot be reported as an /// error value; it must never turn into numbers either. These helpers refuse loudly (panic with @@ -156,7 +156,9 @@ pub trait TensorBackend: Send + Sync { /// In-place Rotary Positional Embeddings (RoPE) following canonical rotate_half convention: /// rot(v) = [-v[half_dim..], v[..half_dim]] - /// out = v * cos(pos * theta^(-2i/d)) + rot(v) * sin(pos * theta^(-2i/d)) + /// out = v * cos(pos * f_i) + rot(v) * sin(pos * f_i), with f_i = `rope.inv_freq(i, head_dim)` + /// (theta^(-2i/d), smoothed by the llama3 scaling when the model has one). + #[allow(clippy::too_many_arguments)] fn apply_rope( &self, q: &mut [f32], @@ -165,7 +167,7 @@ pub trait TensorBackend: Send + Sync { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &RopeParams, ); /// Vector-matrix multiplication for row-major weights: out = x * W^T @@ -381,9 +383,9 @@ impl TensorBackend for ReferenceCpuBackend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &RopeParams, ) { - tensor_rope(q, k, pos, num_q_heads, num_kv_heads, head_dim, theta); + tensor_rope(q, k, pos, num_q_heads, num_kv_heads, head_dim, rope); } fn matmul_vec( @@ -529,8 +531,8 @@ mod tests { let mut q2 = q1.clone(); let mut k2 = k1.clone(); - backend.apply_rope(&mut q1, &mut k1, 5, 64, 2, 1, 10000.0); - tensor_rope(&mut q2, &mut k2, 5, 2, 1, 64, 10000.0); + backend.apply_rope(&mut q1, &mut k1, 5, 64, 2, 1, &RopeParams::plain(10000.0)); + crate::tensor::apply_rope(&mut q2, &mut k2, 5, 2, 1, 64, 10000.0); assert_eq!(q1, q2); assert_eq!(k1, k2); diff --git a/crates/aien-inference-abi/src/checkpoint.rs b/crates/aien-inference-abi/src/checkpoint.rs index ebd06fce..4a362489 100644 --- a/crates/aien-inference-abi/src/checkpoint.rs +++ b/crates/aien-inference-abi/src/checkpoint.rs @@ -228,6 +228,61 @@ pub fn tinyllama_catalog() -> Vec<(String, Vec<usize>)> { catalog } +/// The tensor catalog of a Llama-architecture checkpoint (`LlamaForCausalLM`) described by +/// `config`: names and shapes of every tensor the forward pass reads. `lm_head.weight` is +/// left out when the model ties its output projection to `model.embed_tokens.weight`. +/// For `ModelConfig::tinyllama_1_1b()` this is exactly [`tinyllama_catalog`]. +pub fn llama_catalog(config: &aien_abi_core::ModelConfig) -> Vec<(String, Vec<usize>)> { + let hidden = config.hidden_dim(); + let inter = config.intermediate_dim(); + let vocab = config.vocab_size(); + let q_dim = config.num_heads * config.head_dim; + let kv_dim = config.num_kv_heads * config.head_dim; + let mut catalog = Vec::with_capacity(3 + 9 * config.num_layers); + catalog.push(("model.embed_tokens.weight".to_string(), vec![vocab, hidden])); + for layer in 0..config.num_layers { + let prefix = format!("model.layers.{}", layer); + catalog.push((format!("{}.input_layernorm.weight", prefix), vec![hidden])); + catalog.push(( + format!("{}.self_attn.q_proj.weight", prefix), + vec![q_dim, hidden], + )); + catalog.push(( + format!("{}.self_attn.k_proj.weight", prefix), + vec![kv_dim, hidden], + )); + catalog.push(( + format!("{}.self_attn.v_proj.weight", prefix), + vec![kv_dim, hidden], + )); + catalog.push(( + format!("{}.self_attn.o_proj.weight", prefix), + vec![hidden, q_dim], + )); + catalog.push(( + format!("{}.post_attention_layernorm.weight", prefix), + vec![hidden], + )); + catalog.push(( + format!("{}.mlp.gate_proj.weight", prefix), + vec![inter, hidden], + )); + catalog.push(( + format!("{}.mlp.up_proj.weight", prefix), + vec![inter, hidden], + )); + catalog.push(( + format!("{}.mlp.down_proj.weight", prefix), + vec![hidden, inter], + )); + } + catalog.push(("model.norm.weight".to_string(), vec![hidden])); + if !config.tie_word_embeddings { + catalog.push(("lm_head.weight".to_string(), vec![vocab, hidden])); + } + catalog +} + /// Parses a safetensors binary buffer and strictly validates against a specified tensor catalog. /// The file is copied once into the capsule. Tensor ranges point into that buffer. pub fn parse_safetensors_with_catalog( @@ -242,6 +297,36 @@ fn parse_safetensors_arc( bytes: Arc<[u8]>, catalog: &[(String, Vec<usize>)], ) -> Result<LoadedCheckpoint, CheckpointError> { + let whole = 0..bytes.len(); + parse_shards(bytes, &[whole], catalog) +} + +/// Validates `catalog` against one or more safetensors files laid end to end in `bytes` +/// (`shards` are their byte ranges). Every catalog tensor must appear in exactly one shard. +fn parse_shards( + bytes: Arc<[u8]>, + shards: &[std::ops::Range<usize>], + catalog: &[(String, Vec<usize>)], +) -> Result<LoadedCheckpoint, CheckpointError> { + let mut tensors = HashMap::with_capacity(catalog.len()); + for shard in shards { + index_shard(&bytes, shard.clone(), catalog, &mut tensors)?; + } + if let Some((name, _)) = catalog.iter().find(|(name, _)| !tensors.contains_key(name)) { + return Err(CheckpointError::MissingTensor(name.clone())); + } + Ok(LoadedCheckpoint::from_owned_bytes(bytes, tensors)) +} + +/// Indexes the catalog tensors present in the safetensors file at `bytes[shard]`. +fn index_shard( + all_bytes: &[u8], + shard: std::ops::Range<usize>, + catalog: &[(String, Vec<usize>)], + tensors: &mut HashMap<String, crate::capsule::CapsuleTensor>, +) -> Result<(), CheckpointError> { + let base = shard.start; + let bytes = &all_bytes[shard]; if bytes.len() < 8 { return Err(CheckpointError::InvalidHeader( "Buffer smaller than 8-byte header prefix".to_string(), @@ -282,12 +367,16 @@ fn parse_safetensors_arc( let data_len = bytes.len() - header_end; - let mut tensors = HashMap::with_capacity(catalog.len()); - for (name, expected_shape) in catalog { - let info = header_obj - .get(name) - .ok_or_else(|| CheckpointError::MissingTensor(name.clone()))?; + let Some(info) = header_obj.get(name) else { + continue; + }; + if tensors.contains_key(name) { + return Err(CheckpointError::InvalidHeader(format!( + "tensor {} appears in more than one shard", + name + ))); + } // 1. Verify dtype is BF16. This catalog parser does not accept other dtypes. let dtype = info @@ -362,8 +451,8 @@ fn parse_safetensors_arc( } // Ranges are absolute inside the whole file, including the 8-byte length and JSON header. - let abs_start = header_end + start; - let abs_end = header_end + end; + let abs_start = base + header_end + start; + let abs_end = base + header_end + end; let logical_strides = crate::capsule::row_major_strides(&actual_shape); tensors.insert( name.clone(), @@ -378,7 +467,7 @@ fn parse_safetensors_arc( ); } - Ok(LoadedCheckpoint::from_owned_bytes(bytes, tensors)) + Ok(()) } /// Loads a TinyLlama safetensors checkpoint from an owned byte buffer. @@ -388,6 +477,93 @@ pub fn load_safetensors_from_bytes(bytes: Vec<u8>) -> Result<LoadedCheckpoint, C parse_safetensors_arc(Arc::from(bytes), &catalog) } +/// Name of the shard index Hugging Face writes beside sharded safetensors files. +pub const SAFETENSORS_INDEX: &str = "model.safetensors.index.json"; + +/// Loads and validates a checkpoint against `catalog`. `path` is a `.safetensors` file, a +/// `model.safetensors.index.json` (sharded), or a model directory holding either. A shard +/// file whose directory has an index loads the whole sharded set. +pub fn load_checkpoint_with_catalog<P: AsRef<Path>>( + path: P, + catalog: &[(String, Vec<usize>)], +) -> Result<LoadedCheckpoint, CheckpointError> { + let p = path.as_ref(); + let read = |file: &Path| { + std::fs::read(file).map_err(|e| { + CheckpointError::InvalidHeader(format!( + "Failed to read checkpoint at {}: {}", + file.display(), + e + )) + }) + }; + let index = if p.is_dir() { + let single = p.join("model.safetensors"); + if single.is_file() { + return parse_safetensors_arc(Arc::from(read(&single)?), catalog); + } + p.join(SAFETENSORS_INDEX) + } else if p.file_name().and_then(|n| n.to_str()) == Some(SAFETENSORS_INDEX) { + p.to_path_buf() + } else { + let sibling = p.with_file_name(SAFETENSORS_INDEX); + let is_shard = p.file_name().and_then(|n| n.to_str()) != Some("model.safetensors"); + if !(is_shard && sibling.is_file()) { + return parse_safetensors_arc(Arc::from(read(p)?), catalog); + } + sibling + }; + let index_text = std::fs::read_to_string(&index).map_err(|e| { + CheckpointError::InvalidHeader(format!("Failed to read {}: {}", index.display(), e)) + })?; + let index_json: serde_json::Value = serde_json::from_str(&index_text).map_err(|e| { + CheckpointError::InvalidHeader(format!("Invalid {}: {}", index.display(), e)) + })?; + let weight_map = index_json + .get("weight_map") + .and_then(|m| m.as_object()) + .ok_or_else(|| { + CheckpointError::InvalidHeader(format!("{} has no weight_map", index.display())) + })?; + let mut files: Vec<&str> = weight_map.values().filter_map(|v| v.as_str()).collect(); + files.sort_unstable(); + files.dedup(); + let dir = index.parent().unwrap_or(Path::new(".")); + let mut paths = Vec::with_capacity(files.len()); + let mut total = 0usize; + for file in files { + let shard = dir.join(file); + let len = std::fs::metadata(&shard) + .map_err(|e| { + CheckpointError::InvalidHeader(format!( + "Failed to stat shard {}: {}", + shard.display(), + e + )) + })? + .len() as usize; + total += len; + paths.push(shard); + } + let mut bytes = Vec::with_capacity(total); + let mut ranges = Vec::with_capacity(paths.len()); + for shard in &paths { + use std::io::Read; + let start = bytes.len(); + std::fs::File::open(shard) + .and_then(|mut f| f.read_to_end(&mut bytes)) + .map_err(|e| { + CheckpointError::InvalidHeader(format!( + "Failed to read shard {}: {}", + shard.display(), + e + )) + })?; + ranges.push(start..bytes.len()); + } + parse_shards(Arc::from(bytes), &ranges, catalog) +} + /// Loads and validates a TinyLlama safetensors checkpoint from a filesystem path. pub fn load_safetensors_checkpoint<P: AsRef<Path>>( path: P, diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 0f7ce6e4..770a6d29 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize}; pub mod backend; pub mod capsule; pub mod checkpoint; +pub mod model_dir; pub mod moe_plan; pub mod mojo_backend; pub mod native_ops; @@ -28,6 +29,7 @@ pub use aien_kv_cache::*; pub use backend::*; pub use capsule::*; pub use checkpoint::*; +pub use model_dir::{load_model_config, model_config_from_hf_json, model_id_for_dir}; pub use moe_plan::*; pub use mojo_backend::*; pub use omega_backend::{omega_backend_selected, OmegaGb10Backend, GPU_BACKEND_ENV}; diff --git a/crates/aien-inference-abi/src/model_dir.rs b/crates/aien-inference-abi/src/model_dir.rs new file mode 100644 index 00000000..1061297e --- /dev/null +++ b/crates/aien-inference-abi/src/model_dir.rs @@ -0,0 +1,392 @@ +//! Model description from a Hugging Face model directory. +//! +//! `config.json` (and `generation_config.json` for the stop set) of a `LlamaForCausalLM` +//! checkpoint becomes a [`ModelConfig`]; [`crate::checkpoint::llama_catalog`] turns that into +//! the tensor catalog the strict loader checks. Anything this engine does not implement +//! (another architecture, biases, another activation, another rope type) is refused with +//! an error naming the field, never approximated. + +use aien_abi_core::{Llama3RopeScaling, ModelConfig}; +use serde::Deserialize; +use std::path::Path; + +/// The one architecture this engine runs. +pub const LLAMA_ARCHITECTURE: &str = "LlamaForCausalLM"; + +/// KV page size used for every model loaded from a directory. +const BLOCK_SIZE: usize = 16; + +#[derive(Debug, Deserialize)] +struct HfLlamaConfig { + #[serde(default)] + architectures: Vec<String>, + hidden_size: usize, + intermediate_size: usize, + num_hidden_layers: usize, + num_attention_heads: usize, + num_key_value_heads: Option<usize>, + head_dim: Option<usize>, + vocab_size: usize, + rms_norm_eps: f32, + #[serde(default = "default_rope_theta")] + rope_theta: f32, + rope_scaling: Option<serde_json::Value>, + #[serde(default)] + tie_word_embeddings: bool, + max_position_embeddings: usize, + hidden_act: Option<String>, + #[serde(default)] + attention_bias: bool, + #[serde(default)] + mlp_bias: bool, +} + +fn default_rope_theta() -> f32 { + 10000.0 +} + +/// Reads `rope_scaling`: absent, null or `rope_type: "default"` is plain rope; `"llama3"` +/// needs all four llama3 fields. Any other type is refused. +fn parse_rope_scaling( + value: Option<&serde_json::Value>, +) -> Result<Option<Llama3RopeScaling>, String> { + let Some(obj) = value.and_then(|v| v.as_object()) else { + return match value { + None | Some(serde_json::Value::Null) => Ok(None), + Some(other) => Err(format!("rope_scaling must be an object, got {other}")), + }; + }; + let rope_type = obj + .get("rope_type") + .or_else(|| obj.get("type")) + .and_then(|v| v.as_str()) + .unwrap_or("default"); + match rope_type { + "default" => Ok(None), + "llama3" => { + let num = |key: &str| { + obj.get(key) + .and_then(|v| v.as_f64()) + .ok_or_else(|| format!("rope_scaling (llama3) has no numeric {key}")) + }; + let scaling = Llama3RopeScaling { + factor: num("factor")?, + low_freq_factor: num("low_freq_factor")?, + high_freq_factor: num("high_freq_factor")?, + original_max_position_embeddings: num("original_max_position_embeddings")? as usize, + }; + if scaling.factor <= 0.0 + || scaling.high_freq_factor <= scaling.low_freq_factor + || scaling.original_max_position_embeddings == 0 + { + return Err(format!("rope_scaling (llama3) is degenerate: {scaling:?}")); + } + Ok(Some(scaling)) + } + other => Err(format!( + "unsupported rope_scaling rope_type {other:?} (supported: default, llama3)" + )), + } +} + +/// Builds the [`ModelConfig`] of a `LlamaForCausalLM` checkpoint from the text of its +/// `config.json` and, when present, its `generation_config.json` (stop set: its +/// `eos_token_id`, else the one in `config.json`). +pub fn model_config_from_hf_json( + model_id: &str, + config_json: &str, + generation_config_json: Option<&str>, +) -> Result<ModelConfig, String> { + let raw: serde_json::Value = + serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?; + let hf: HfLlamaConfig = + serde_json::from_value(raw.clone()).map_err(|e| format!("config.json: {e}"))?; + if hf.architectures.as_slice() != [LLAMA_ARCHITECTURE] { + return Err(format!( + "unsupported architectures {:?}: this engine runs [\"{LLAMA_ARCHITECTURE}\"] only", + hf.architectures + )); + } + if let Some(act) = hf.hidden_act.as_deref().filter(|a| *a != "silu") { + return Err(format!("unsupported hidden_act {act:?} (supported: silu)")); + } + if hf.attention_bias || hf.mlp_bias { + return Err("unsupported attention_bias/mlp_bias = true (no bias tensors)".to_string()); + } + let num_heads = hf.num_attention_heads; + if num_heads == 0 || !hf.hidden_size.is_multiple_of(num_heads) { + return Err(format!( + "hidden_size {} is not a multiple of num_attention_heads {num_heads}", + hf.hidden_size + )); + } + let head_dim = hf.head_dim.unwrap_or(hf.hidden_size / num_heads); + if head_dim * num_heads != hf.hidden_size { + return Err(format!( + "unsupported head_dim {head_dim}: num_attention_heads * head_dim must equal hidden_size {}", + hf.hidden_size + )); + } + let rope_scaling = parse_rope_scaling(hf.rope_scaling.as_ref())?; + let generation = generation_config_json + .map(serde_json::from_str::<serde_json::Value>) + .transpose() + .map_err(|e| format!("generation_config.json: {e}"))?; + let eos_token_ids = generation + .as_ref() + .and_then(crate::tokenizer::eos_token_ids_from_json) + .or_else(|| crate::tokenizer::eos_token_ids_from_json(&raw)) + .ok_or("no eos_token_id in generation_config.json or config.json")?; + let config = ModelConfig { + model_id: model_id.to_string(), + max_sequence_length: hf.max_position_embeddings, + block_size: BLOCK_SIZE, + num_layers: hf.num_hidden_layers, + num_heads, + head_dim, + num_kv_heads: hf.num_key_value_heads.unwrap_or(num_heads), + hidden_dim: hf.hidden_size, + intermediate_dim: hf.intermediate_size, + vocab_size: hf.vocab_size, + rms_norm_eps: hf.rms_norm_eps, + rope_theta: hf.rope_theta, + rope_scaling, + tie_word_embeddings: hf.tie_word_embeddings, + eos_token_ids, + }; + config + .attention_geometry() + .map_err(|e| format!("attention geometry refused: {e:?}"))?; + Ok(config) +} + +/// A readable model id for a directory: `org/name` for a Hugging Face cache snapshot +/// (`.../models--org--name/snapshots/<hash>`), else the directory name. +pub fn model_id_for_dir(dir: &Path) -> String { + let name = |p: &Path| p.file_name().and_then(|n| n.to_str()).map(str::to_string); + let cache_repo = dir + .parent() + .filter(|p| name(p).as_deref() == Some("snapshots")) + .and_then(|p| p.parent()) + .and_then(name) + .and_then(|repo| { + repo.strip_prefix("models--") + .map(|r| r.replacen("--", "/", 1)) + }); + cache_repo + .or_else(|| name(dir)) + .unwrap_or_else(|| "checkpoint".to_string()) +} + +/// Reads `<dir>/config.json` and `<dir>/generation_config.json` into a [`ModelConfig`]. +pub fn load_model_config(dir: &Path) -> Result<ModelConfig, String> { + let config_path = dir.join("config.json"); + let config_json = std::fs::read_to_string(&config_path) + .map_err(|e| format!("cannot read {}: {e}", config_path.display()))?; + let generation_path = dir.join("generation_config.json"); + let generation_json = match std::fs::read_to_string(&generation_path) { + Ok(text) => Some(text), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(format!("cannot read {}: {e}", generation_path.display())), + }; + model_config_from_hf_json( + &model_id_for_dir(dir), + &config_json, + generation_json.as_deref(), + ) + .map_err(|e| format!("{}: {e}", config_path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::checkpoint::{llama_catalog, tinyllama_catalog}; + + /// TinyLlama-1.1B-Chat-v1.0 config.json, verbatim. + const TINYLLAMA_CONFIG: &str = r#"{ + "architectures": ["LlamaForCausalLM"], "attention_bias": false, "bos_token_id": 1, + "eos_token_id": 2, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, + "intermediate_size": 5632, "max_position_embeddings": 2048, "model_type": "llama", + "num_attention_heads": 32, "num_hidden_layers": 22, "num_key_value_heads": 4, + "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 10000.0, + "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.35.0", + "use_cache": true, "vocab_size": 32000 +}"#; + + /// unsloth/Llama-3.2-1B-Instruct config.json and generation_config.json, verbatim. + const LLAMA32_1B_CONFIG: &str = r#"{ + "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0, + "bos_token_id": 128000, "eos_token_id": 128009, "head_dim": 64, "hidden_act": "silu", + "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 8192, + "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama", + "num_attention_heads": 32, "num_hidden_layers": 16, "num_key_value_heads": 8, + "pad_token_id": 128004, "pretraining_tp": 1, "rms_norm_eps": 1e-05, + "rope_scaling": {"factor": 32.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, + "original_max_position_embeddings": 8192, "rope_type": "llama3"}, + "rope_theta": 500000.0, "tie_word_embeddings": true, "torch_dtype": "bfloat16", + "transformers_version": "4.52.0.dev0", "unsloth_fixed": true, "use_cache": true, + "vocab_size": 128256 +}"#; + const LLAMA32_1B_GENERATION: &str = r#"{"bos_token_id": 128000, "do_sample": true, + "eos_token_id": [128001, 128008, 128009], "max_length": 131072, "pad_token_id": 128004, + "temperature": 0.6, "top_p": 0.9, "transformers_version": "4.52.0.dev0"}"#; + + #[test] + fn tinyllama_config_json_reproduces_the_hard_wired_config_and_catalog() { + let from_json = model_config_from_hf_json( + "TinyLlama/TinyLlama-1.1B-Chat-v1.0", + TINYLLAMA_CONFIG, + Some( + r#"{"bos_token_id": 1, "eos_token_id": 2, "max_length": 2048, "pad_token_id": 0}"#, + ), + ) + .unwrap(); + let wired = ModelConfig::tinyllama_1_1b(); + // Every architecture field equal; the stop set comes from the file (EOS 2) where the + // hard-wired config keeps the legacy backend set. + assert_eq!( + ModelConfig { + eos_token_ids: Vec::new(), + ..from_json.clone() + }, + wired + ); + assert_eq!(from_json.eos_token_ids, vec![2]); + assert_eq!(llama_catalog(&from_json), tinyllama_catalog()); + assert_eq!(llama_catalog(&wired), tinyllama_catalog()); + assert_eq!(from_json.rope(), aien_abi_core::RopeParams::plain(10000.0)); + } + + #[test] + fn llama32_1b_config_has_tied_head_llama3_rope_and_three_stop_ids() { + let c = + model_config_from_hf_json("l", LLAMA32_1B_CONFIG, Some(LLAMA32_1B_GENERATION)).unwrap(); + assert_eq!( + (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim), + (16, 32, 8, 64) + ); + assert_eq!( + (c.hidden_dim, c.intermediate_dim, c.vocab_size), + (2048, 8192, 128256) + ); + assert!(c.tie_word_embeddings); + assert_eq!(c.eos_token_ids, vec![128001, 128008, 128009]); + assert_eq!( + c.rope_scaling, + Some(Llama3RopeScaling { + factor: 32.0, + low_freq_factor: 1.0, + high_freq_factor: 4.0, + original_max_position_embeddings: 8192, + }) + ); + let catalog = llama_catalog(&c); + assert_eq!(catalog.len(), 2 + 9 * 16); + assert!(catalog.iter().all(|(n, _)| n != "lm_head.weight")); + let shape = |name: &str| catalog.iter().find(|(n, _)| n == name).unwrap().1.clone(); + assert_eq!(shape("model.embed_tokens.weight"), vec![128256, 2048]); + assert_eq!( + shape("model.layers.15.self_attn.k_proj.weight"), + vec![512, 2048] + ); + assert_eq!( + shape("model.layers.0.mlp.down_proj.weight"), + vec![2048, 8192] + ); + // Without generation_config.json the config.json eos is used. + let c2 = model_config_from_hf_json("l", LLAMA32_1B_CONFIG, None).unwrap(); + assert_eq!(c2.eos_token_ids, vec![128009]); + } + + /// Expected inverse frequencies for Llama-3.2-1B (theta 500000, head_dim 64, llama3 + /// factor 32, low 1, high 4, original 8192), computed independently in f64 outside the + /// repository from the transformers `_compute_llama3_parameters` formula. + const LLAMA32_1B_INV_FREQ: [f64; 32] = [ + 1.0, + 0.6636012376960885, + 0.44036660267178046, + 0.2922278225730151, + 0.19392274474868576, + 0.12868737343265052, + 0.08539710028576561, + 0.056669621445291044, + 0.03760603093086393, + 0.024955408670558694, + 0.016560440080994446, + 0.010989528534539826, + 0.0072926647372171085, + 0.004839421345719893, + 0.0032114459947525913, + 0.001290547928209264, + 0.00042955679655936815, + 9.70828780262767e-05, + 1.9461638184831125e-05, + 1.291476718704739e-05, + 8.570255489881478e-06, + 5.687232150457046e-06, + 3.7740542941082826e-06, + 2.5044671007024935e-06, + 1.661967467795309e-06, + 1.102883668639601e-06, + 7.318749675440419e-07, + 4.856731343010108e-07, + 3.2229329303788936e-07, + 2.138742281610915e-07, + 1.4192720251899592e-07, + 9.418306725434909e-08, + ]; + + #[test] + fn llama3_rope_inv_freq_matches_independent_values() { + let c = + model_config_from_hf_json("l", LLAMA32_1B_CONFIG, Some(LLAMA32_1B_GENERATION)).unwrap(); + let got = c.rope().inv_freqs(64); + assert_eq!(got.len(), 32); + for (i, (g, want)) in got.iter().zip(LLAMA32_1B_INV_FREQ).enumerate() { + assert!( + ((g - want) / want).abs() < 1e-12, + "inv_freq[{i}] = {g}, expected {want}" + ); + } + // The three bands: high frequencies kept, low divided by 32, the middle smoothed. + let plain = aien_abi_core::RopeParams::plain(500000.0).inv_freqs(64); + assert_eq!(got[14], plain[14]); + assert_eq!(got[31], plain[31] / 32.0); + assert!(got[16] < plain[16] && got[16] > plain[16] / 32.0); + assert_eq!(got[18], plain[18] / 32.0); + } + + #[test] + fn unsupported_models_are_refused_by_name() { + let qwen = LLAMA32_1B_CONFIG.replace("LlamaForCausalLM", "Qwen2ForCausalLM"); + let err = model_config_from_hf_json("q", &qwen, None).unwrap_err(); + assert!(err.contains("Qwen2ForCausalLM"), "{err}"); + + let yarn = LLAMA32_1B_CONFIG.replace("\"llama3\"", "\"yarn\""); + let err = model_config_from_hf_json("y", &yarn, None).unwrap_err(); + assert!(err.contains("yarn"), "{err}"); + + let bias = + LLAMA32_1B_CONFIG.replace("\"attention_bias\": false", "\"attention_bias\": true"); + assert!(model_config_from_hf_json("b", &bias, None).is_err()); + + let gelu = LLAMA32_1B_CONFIG.replace("\"silu\"", "\"gelu\""); + assert!(model_config_from_hf_json("g", &gelu, None) + .unwrap_err() + .contains("gelu")); + + let default_rope = LLAMA32_1B_CONFIG.replace("\"llama3\"", "\"default\""); + let c = model_config_from_hf_json("d", &default_rope, None).unwrap(); + assert_eq!(c.rope_scaling, None); + } + + #[test] + fn hf_cache_snapshot_dirs_get_the_repo_id() { + let dir = Path::new("/c/hub/models--unsloth--Llama-3.2-1B-Instruct/snapshots/5a8a"); + assert_eq!(model_id_for_dir(dir), "unsloth/Llama-3.2-1B-Instruct"); + assert_eq!( + model_id_for_dir(Path::new("/m/TinyLlama-1.1B-Chat-v1.0")), + "TinyLlama-1.1B-Chat-v1.0" + ); + } +} diff --git a/crates/aien-inference-abi/src/mojo_backend.rs b/crates/aien-inference-abi/src/mojo_backend.rs index 09132ba7..2ec08d2b 100644 --- a/crates/aien-inference-abi/src/mojo_backend.rs +++ b/crates/aien-inference-abi/src/mojo_backend.rs @@ -270,9 +270,11 @@ impl TensorBackend for MojoGb10Backend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &aien_abi_core::RopeParams, ) { - if let Some(ref b) = self.bindings { + // The Mojo kernel computes plain theta^(-2i/d) frequencies only. + let plain_theta = rope.llama3.is_none().then_some(rope.theta); + if let (Some(ref b), Some(theta)) = (&self.bindings, plain_theta) { if let Some(f32_fn) = b.rope_f32 { unsafe { f32_fn( @@ -289,7 +291,7 @@ impl TensorBackend for MojoGb10Backend { } } self.fallback - .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope); } fn matmul_vec( diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 0a04fc01..430633d3 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -28,6 +28,7 @@ //! [`OmegaGb10Backend::clear_resident`] after changing weights. use crate::backend::{ReferenceCpuBackend, TensorBackend}; use crate::native_ops::{NativeOpMask, OpAccounting, OpReport, TensorOp}; +use aien_abi_core::RopeParams; use aien_omega_gpu::ResidentTensor; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; @@ -51,8 +52,8 @@ type Key = (usize, usize, usize, usize); /// Rope cos/sin table for one position: `head_dim / 2` values each. type RopeTable = Arc<(Vec<f32>, Vec<f32>)>; -/// Cache key: (head_dim, theta bits, position). Drop everything past this many entries. -type RopeKey = (usize, u32, usize); +/// Cache key: (head_dim, rope parameter bits, position). Drop everything past this many entries. +type RopeKey = (usize, [u64; 5], usize); const ROPE_CACHE_MAX: usize = 16384; struct Resident { @@ -239,9 +240,9 @@ impl OmegaGb10Backend { /// Rope cos/sin table for `pos`, built exactly as the reference does /// (`tensor::apply_rope`, tensor.rs:101): f64 frequency and angle, then cast to f32. - /// Cached per (head_dim, theta, pos). - fn rope_table(&self, head_dim: usize, theta: f32, pos: usize) -> RopeTable { - let key: RopeKey = (head_dim, theta.to_bits(), pos); + /// Cached per (head_dim, rope parameters, pos). + fn rope_table(&self, head_dim: usize, rope: &RopeParams, pos: usize) -> RopeTable { + let key: RopeKey = (head_dim, rope.cache_key(), pos); let mut cache = self .rope_tables .lock() @@ -249,16 +250,7 @@ impl OmegaGb10Backend { if let Some(t) = cache.get(&key) { return Arc::clone(t); } - let half = head_dim / 2; - let mut cos = Vec::with_capacity(half); - let mut sin = Vec::with_capacity(half); - for i in 0..half { - let exponent = (2 * i) as f64 / (head_dim as f64); - let freq = 1.0 / (theta as f64).powf(exponent); - let rot = (pos as f64) * freq; - sin.push(rot.sin() as f32); - cos.push(rot.cos() as f32); - } + let (cos, sin) = crate::tensor::rope_cos_sin(rope, head_dim, pos); if cache.len() >= ROPE_CACHE_MAX { cache.clear(); } @@ -306,7 +298,7 @@ impl OmegaGb10Backend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &RopeParams, ) -> bool { if head_dim == 0 || !head_dim.is_multiple_of(2) @@ -319,7 +311,7 @@ impl OmegaGb10Backend { k.len() )); } - let table = self.rope_table(head_dim, theta, pos); + let table = self.rope_table(head_dim, rope, pos); let mut both = Vec::with_capacity(q.len() + k.len()); both.extend_from_slice(q); both.extend_from_slice(k); @@ -539,12 +531,12 @@ impl TensorBackend for OmegaGb10Backend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &RopeParams, ) { - if !self.chip_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta) { + if !self.chip_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) { self.reference_for(TensorOp::ApplyRope); self.reference - .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope); } } @@ -893,7 +885,8 @@ mod tests { #[test] fn rope_table_reproduces_reference_rope() { let b = OmegaGb10Backend::new(); - let (head_dim, nq, nkv, pos, theta) = (64usize, 4usize, 2usize, 37usize, 10000.0f32); + let (head_dim, nq, nkv, pos) = (64usize, 4usize, 2usize, 37usize); + let theta = &RopeParams::plain(10000.0); let mut s = 99u32; let q0: Vec<f32> = (0..nq * head_dim).map(|_| lcg(&mut s)).collect(); let k0: Vec<f32> = (0..nkv * head_dim).map(|_| lcg(&mut s)).collect(); @@ -939,8 +932,8 @@ mod tests { assert_eq!(got, want); let (mut q, mut k) = (x[..64].to_vec(), x[64..].to_vec()); let (mut qw, mut kw) = (q.clone(), k.clone()); - b.apply_rope(&mut q, &mut k, 3, 32, 2, 2, 10000.0); - r.apply_rope(&mut qw, &mut kw, 3, 32, 2, 2, 10000.0); + b.apply_rope(&mut q, &mut k, 3, 32, 2, 2, &RopeParams::plain(10000.0)); + r.apply_rope(&mut qw, &mut kw, 3, 32, 2, 2, &RopeParams::plain(10000.0)); assert_eq!((q, k), (qw, kw)); assert_eq!(b.fallback_count(), 3); let line = b.op_report().line(); diff --git a/crates/aien-inference-abi/src/tensor.rs b/crates/aien-inference-abi/src/tensor.rs index b0b2658d..1e35297e 100644 --- a/crates/aien-inference-abi/src/tensor.rs +++ b/crates/aien-inference-abi/src/tensor.rs @@ -1,6 +1,7 @@ //! Pure native Rust tensor operations for transformer forward execution. //! Provides cache-friendly vector and matrix math, RMSNorm, RoPE, and SwiGLU activations. +use aien_abi_core::RopeParams; use rayon::prelude::*; /// Vector-matrix multiplication for PyTorch row-major weights: out = x * W^T @@ -107,45 +108,55 @@ pub fn apply_rope( head_dim: usize, theta: f32, ) { - let half_dim = head_dim / 2; + apply_rope_params( + q, + k, + pos, + num_heads, + num_kv_heads, + head_dim, + &RopeParams::plain(theta), + ); +} - // Rotate query heads - for h in 0..num_heads { - let head_offset = h * head_dim; - for i in 0..half_dim { - let idx0 = head_offset + i; - let idx1 = head_offset + i + half_dim; - - let exponent = (2 * i) as f64 / (head_dim as f64); - let freq = 1.0 / (theta as f64).powf(exponent); - let rot = (pos as f64) * freq; - let sin_val = rot.sin() as f32; - let cos_val = rot.cos() as f32; - - let q0 = q[idx0]; - let q1 = q[idx1]; - q[idx0] = q0 * cos_val - q1 * sin_val; - q[idx1] = q0 * sin_val + q1 * cos_val; - } +/// The cos and sin of every rotary pair at `pos`: f64 frequency and angle, cast to f32. +/// Both the reference rope and the Omega GPU rope table use this. +pub fn rope_cos_sin(rope: &RopeParams, head_dim: usize, pos: usize) -> (Vec<f32>, Vec<f32>) { + let half_dim = head_dim / 2; + let mut cos = Vec::with_capacity(half_dim); + let mut sin = Vec::with_capacity(half_dim); + for i in 0..half_dim { + let rot = (pos as f64) * rope.inv_freq(i, head_dim); + sin.push(rot.sin() as f32); + cos.push(rot.cos() as f32); } + (cos, sin) +} - // Rotate key heads - for h in 0..num_kv_heads { - let head_offset = h * head_dim; - for i in 0..half_dim { - let idx0 = head_offset + i; - let idx1 = head_offset + i + half_dim; - - let exponent = (2 * i) as f64 / (head_dim as f64); - let freq = 1.0 / (theta as f64).powf(exponent); - let rot = (pos as f64) * freq; - let sin_val = rot.sin() as f32; - let cos_val = rot.cos() as f32; - - let k0 = k[idx0]; - let k1 = k[idx1]; - k[idx0] = k0 * cos_val - k1 * sin_val; - k[idx1] = k0 * sin_val + k1 * cos_val; +/// [`apply_rope`] with explicit rope parameters (base theta and optional llama3 scaling). +#[inline] +pub fn apply_rope_params( + q: &mut [f32], + k: &mut [f32], + pos: usize, + num_heads: usize, + num_kv_heads: usize, + head_dim: usize, + rope: &RopeParams, +) { + let half_dim = head_dim / 2; + let (cos, sin) = rope_cos_sin(rope, head_dim, pos); + for (v, heads) in [(q, num_heads), (k, num_kv_heads)] { + for h in 0..heads { + let head_offset = h * head_dim; + for i in 0..half_dim { + let idx0 = head_offset + i; + let idx1 = head_offset + i + half_dim; + let v0 = v[idx0]; + let v1 = v[idx1]; + v[idx0] = v0 * cos[i] - v1 * sin[i]; + v[idx1] = v0 * sin[i] + v1 * cos[i]; + } } } } diff --git a/crates/aien-inference-abi/src/tokenizer.rs b/crates/aien-inference-abi/src/tokenizer.rs index 049630d5..720b34cb 100644 --- a/crates/aien-inference-abi/src/tokenizer.rs +++ b/crates/aien-inference-abi/src/tokenizer.rs @@ -1,4 +1,5 @@ -//! Pure Rust tokenizer and chat template formatter for TinyLlama models. +//! Pure Rust tokenizer and chat template formatter for the Llama model family +//! (TinyLlama zephyr-style chat, Llama 3 instruct chat). //! Wraps Hugging Face tokenizers crate without Python runtime dependencies. use std::fmt; @@ -32,13 +33,121 @@ impl fmt::Display for TokenizerError { impl std::error::Error for TokenizerError {} -/// Pure Rust wrapper around Hugging Face tokenizers for TinyLlama. +/// The chat layout a model was fine-tuned on. Selected from the model's own chat template +/// text (no template engine): each variant renders the one layout that template produces +/// for plain user/system/assistant turns ending in a generation prompt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChatTemplate { + /// TinyLlama-Chat (zephyr): `<|user|>\n{content}</s>\n<|assistant|>\n`. + Zephyr, + /// Llama 3 instruct: `<|start_header_id|>user<|end_header_id|>\n\n{content}<|eot_id|>` + /// then `<|start_header_id|>assistant<|end_header_id|>\n\n`. No system block is added + /// (the Hugging Face template's default "Cutting Knowledge Date / Today Date" block + /// depends on the wall clock, so it is left out). + Llama3, +} + +impl ChatTemplate { + pub fn name(&self) -> &'static str { + match self { + Self::Zephyr => "zephyr (TinyLlama chat)", + Self::Llama3 => "llama3 (Llama 3 instruct)", + } + } + + /// Recognizes the layout from a Jinja chat template's text. + pub fn detect(template_text: &str) -> Result<Self, TokenizerError> { + if template_text.contains("<|start_header_id|>") && template_text.contains("<|eot_id|>") { + Ok(Self::Llama3) + } else if template_text.contains("<|user|>") && template_text.contains("<|assistant|>") { + Ok(Self::Zephyr) + } else { + Err(TokenizerError::LoadError( + "unsupported chat template: neither zephyr (<|user|>) nor llama3 \ + (<|start_header_id|>) markers found" + .to_string(), + )) + } + } + + /// Renders `(role, content)` turns. Contents are trimmed and empty turns skipped; roles + /// other than system and assistant are user turns. Generation continues from an + /// assistant header unless the last turn is a non-empty assistant turn. The BOS token + /// is not part of the text: `encode` adds exactly one through the tokenizer's + /// post-processor. + pub fn render(&self, turns: &[(&str, &str)]) -> String { + let mut out = String::new(); + for (role, content) in turns { + let body = content.trim(); + if body.is_empty() { + continue; + } + let role = match role.trim().to_ascii_lowercase().as_str() { + "system" => "system", + "assistant" => "assistant", + _ => "user", + }; + match self { + Self::Zephyr => out.push_str(&format!("<|{role}|>\n{body}</s>\n")), + Self::Llama3 => out.push_str(&format!( + "<|start_header_id|>{role}<|end_header_id|>\n\n{body}<|eot_id|>" + )), + } + } + let ends_in_assistant = turns.last().is_some_and(|(role, content)| { + role.trim().eq_ignore_ascii_case("assistant") && !content.trim().is_empty() + }); + if !ends_in_assistant { + out.push_str(match self { + Self::Zephyr => "<|assistant|>\n", + Self::Llama3 => "<|start_header_id|>assistant<|end_header_id|>\n\n", + }); + } + out + } +} + +/// Pure Rust wrapper around Hugging Face tokenizers with the model's chat template and +/// end-of-sequence set. `from_file`/`from_bytes` give the TinyLlama defaults; +/// `from_model_dir` reads them from the model directory. #[derive(Clone)] -pub struct TinyLlamaTokenizer { +pub struct ChatTokenizer { inner: tokenizers::Tokenizer, + template: ChatTemplate, + stop_token_ids: Vec<u32>, + max_context_len: usize, +} + +/// The name this tokenizer had while it served TinyLlama only. +pub type TinyLlamaTokenizer = ChatTokenizer; + +fn read_json(path: &Path) -> Result<Option<serde_json::Value>, TokenizerError> { + match std::fs::read_to_string(path) { + Ok(text) => serde_json::from_str(&text).map(Some).map_err(|e| { + TokenizerError::LoadError(format!("{} is not valid JSON: {}", path.display(), e)) + }), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(TokenizerError::LoadError(format!( + "Failed to read {}: {}", + path.display(), + e + ))), + } +} + +/// `eos_token_id` of a Hugging Face config as a list (it is a number or an array). +pub fn eos_token_ids_from_json(value: &serde_json::Value) -> Option<Vec<u32>> { + match value.get("eos_token_id")? { + serde_json::Value::Number(n) => n.as_u64().map(|id| vec![id as u32]), + serde_json::Value::Array(items) => items + .iter() + .map(|v| v.as_u64().map(|id| id as u32)) + .collect(), + _ => None, + } } -impl TinyLlamaTokenizer { +impl ChatTokenizer { /// Beginning of Sequence token ID pinned for TinyLlama (<s>). pub const BOS_TOKEN_ID: u32 = 1; /// End of Sequence token ID pinned for TinyLlama (</s>). @@ -54,7 +163,7 @@ impl TinyLlamaTokenizer { let inner = tokenizers::Tokenizer::from_file(p).map_err(|e| { TokenizerError::LoadError(format!("Failed to load from {}: {}", p.display(), e)) })?; - Ok(Self { inner }) + Ok(Self::tinyllama(inner)) } /// Loads tokenizer directly from a JSON byte buffer. @@ -62,7 +171,84 @@ impl TinyLlamaTokenizer { let inner = tokenizers::Tokenizer::from_bytes(bytes).map_err(|e| { TokenizerError::LoadError(format!("Failed to parse tokenizer bytes: {}", e)) })?; - Ok(Self { inner }) + Ok(Self::tinyllama(inner)) + } + + fn tinyllama(inner: tokenizers::Tokenizer) -> Self { + Self { + inner, + template: ChatTemplate::Zephyr, + stop_token_ids: vec![Self::EOS_TOKEN_ID], + max_context_len: Self::MAX_CONTEXT_LEN, + } + } + + /// Loads `tokenizer_json` (default `<dir>/tokenizer.json`) with the chat template and + /// end-of-sequence set of the model directory `dir`: + /// - template: detected from `chat_template` in `tokenizer_config.json`, else from + /// `chat_template.jinja`; + /// - stop set: `eos_token_id` of `generation_config.json`, else of `config.json`; + /// - context limit: `max_position_embeddings` of `config.json` (default 2048). + pub fn from_model_dir( + dir: &Path, + tokenizer_json: Option<&Path>, + ) -> Result<Self, TokenizerError> { + let default_json = dir.join("tokenizer.json"); + let mut tokenizer = Self::from_file(tokenizer_json.unwrap_or(&default_json))?; + let template_text = match read_json(&dir.join("tokenizer_config.json"))? + .and_then(|c| c.get("chat_template").and_then(|t| t.as_str()).map(str::to_string)) + { + Some(text) => text, + None => std::fs::read_to_string(dir.join("chat_template.jinja")).map_err(|e| { + TokenizerError::LoadError(format!( + "no chat template in {} (tokenizer_config.json chat_template or chat_template.jinja): {}", + dir.display(), + e + )) + })?, + }; + tokenizer.template = ChatTemplate::detect(&template_text)?; + let config = read_json(&dir.join("config.json"))?; + let stop = read_json(&dir.join("generation_config.json"))? + .as_ref() + .and_then(eos_token_ids_from_json) + .or_else(|| config.as_ref().and_then(eos_token_ids_from_json)) + .ok_or_else(|| { + TokenizerError::LoadError(format!( + "no eos_token_id in {}/generation_config.json or config.json", + dir.display() + )) + })?; + if stop.is_empty() { + return Err(TokenizerError::LoadError(format!( + "empty eos_token_id in {}", + dir.display() + ))); + } + tokenizer.stop_token_ids = stop; + if let Some(max) = config + .as_ref() + .and_then(|c| c.get("max_position_embeddings")) + .and_then(|v| v.as_u64()) + { + tokenizer.max_context_len = max as usize; + } + Ok(tokenizer) + } + + /// The chat layout this tokenizer renders. + pub fn template(&self) -> ChatTemplate { + self.template + } + + /// Token ids that end generation (the model's `eos_token_id` set). + pub fn stop_token_ids(&self) -> &[u32] { + &self.stop_token_ids + } + + /// Renders `(role, content)` turns with this model's chat template. + pub fn format_chat(&self, turns: &[(&str, &str)]) -> String { + self.template.render(turns) } /// Formats a conversation according to the canonical TinyLlama chat template: @@ -103,10 +289,10 @@ impl TinyLlamaTokenizer { .encode(text, add_special_tokens) .map_err(|e| TokenizerError::EncodeError(e.to_string()))?; let tokens = encoding.get_ids().to_vec(); - if tokens.len() > Self::MAX_CONTEXT_LEN { + if tokens.len() > self.max_context_len { return Err(TokenizerError::ContextLengthExceeded { len: tokens.len(), - max: Self::MAX_CONTEXT_LEN, + max: self.max_context_len, }); } Ok(tokens) @@ -130,7 +316,7 @@ impl TinyLlamaTokenizer { /// Checks if a token ID signifies generation stopping (EOS). pub fn is_eos(&self, token_id: u32) -> bool { - token_id == Self::EOS_TOKEN_ID + self.stop_token_ids.contains(&token_id) } /// Checks if a token ID signifies sequence beginning (BOS). diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 54b82fcb..97a98456 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -725,7 +725,7 @@ impl NativeTransformerBackend { let kv_dim = geom.kv_dim(); let intermediate_dim = weights.config.intermediate_dim(); let eps = weights.config.rms_norm_eps; - let theta = weights.config.rope_theta; + let rope = weights.config.rope(); let token_idx = (token_id as usize) % weights.config.vocab_size(); let mut x = @@ -786,7 +786,7 @@ impl NativeTransformerBackend { head_dim, num_heads, num_kv_heads, - theta, + &rope, ); if let (Some((block_id, slot)), Some(mgr)) = (block_slot, kv_manager) { @@ -899,7 +899,7 @@ impl NativeTransformerBackend { backend.compute_logits( &mut logits, hidden_state, - &weights.lm_head, + weights.output_projection(), vocab_size, hidden_dim, ); @@ -978,7 +978,7 @@ impl NativeTransformerBackend { let kv_dim = geom.kv_dim(); let intermediate_dim = weights.config.intermediate_dim(); let eps = weights.config.rms_norm_eps; - let theta = weights.config.rope_theta; + let rope = weights.config.rope(); // Paged mode: one physical (block, slot) per absolute position, resolved once // (not per layer). Positions inside the table's allocated length (the @@ -1109,7 +1109,7 @@ impl NativeTransformerBackend { let v_t = &v_batch[t * kv_dim..(t + 1) * kv_dim]; let pos = offset + t; - backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, theta); + backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope); if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { // Slots exist only when a physical pool is attached, so this @@ -1302,7 +1302,7 @@ impl NativeTransformerBackend { let kv_dim = geom.kv_dim(); let intermediate_dim = self.weights.config.intermediate_dim(); let eps = self.weights.config.rms_norm_eps; - let theta = self.weights.config.rope_theta; + let rope = self.weights.config.rope(); let vocab_size = self.weights.config.vocab_size(); // 1. Gather active sequence requests and their current positions / last tokens @@ -1435,7 +1435,7 @@ impl NativeTransformerBackend { head_dim, num_heads, num_kv_heads, - theta, + &rope, ); } @@ -1615,7 +1615,7 @@ impl NativeTransformerBackend { self.tensor_backend.matmul_batch( &mut logits_batch, &x_norm, - &self.weights.lm_head, + self.weights.output_projection(), d, hidden_dim, vocab_size, @@ -1624,11 +1624,9 @@ impl NativeTransformerBackend { // 8. Sampling and output emission (slot failures from step 1b first) let mut outputs = slot_failures; outputs.reserve(d); - let stop_tokens = [ - crate::tokenizer::TinyLlamaTokenizer::UNK_TOKEN_ID, - crate::tokenizer::TinyLlamaTokenizer::BOS_TOKEN_ID, - crate::tokenizer::TinyLlamaTokenizer::EOS_TOKEN_ID, - ]; + // The model's end-of-sequence set (legacy TinyLlama UNK/BOS/EOS when the config + // names none): a Llama 3 vocabulary has ordinary text at ids 0..=2. + let stop_tokens = self.weights.config.stop_token_ids().to_vec(); for (i, &(seq_id, _, pos)) in valid_reqs.iter().enumerate() { let logits = &logits_batch[i * vocab_size..(i + 1) * vocab_size]; diff --git a/crates/aien-inference-abi/src/weights.rs b/crates/aien-inference-abi/src/weights.rs index dc89e601..c4403e4f 100644 --- a/crates/aien-inference-abi/src/weights.rs +++ b/crates/aien-inference-abi/src/weights.rs @@ -1,6 +1,8 @@ //! Native weight data structures and zero-dependency loaders for transformer models. -use crate::tensor::{apply_rope, matmul_vec, rmsnorm, scaled_dot_product_attention_single, swiglu}; +use crate::tensor::{ + apply_rope_params, matmul_vec, rmsnorm, scaled_dot_product_attention_single, swiglu, +}; use crate::ModelConfig; use serde_json::Value; @@ -37,7 +39,10 @@ pub struct TransformerWeights { pub embed_tokens: Vec<f32>, pub layers: Vec<TransformerLayerWeights>, pub final_norm: Vec<f32>, - pub lm_head: Vec<f32>, + /// Output projection `[vocab, hidden]`. `None` when `config.tie_word_embeddings`: + /// the projection is `embed_tokens` itself (no second copy). Read it through + /// [`TransformerWeights::output_projection`]. + pub lm_head: Option<Vec<f32>>, } /// Diagnostic capture of intermediate activations and shapes across all transformer layers. @@ -48,6 +53,16 @@ pub struct ForwardDiagnostics { } impl TransformerWeights { + /// The `[vocab, hidden]` matrix that projects the final hidden state to logits: + /// `lm_head`, or `embed_tokens` for a model with tied word embeddings. + #[inline] + pub fn output_projection(&self) -> &[f32] { + match &self.lm_head { + Some(lm_head) => lm_head, + None => &self.embed_tokens, + } + } + /// Copies the embedding vector for a given token ID into a destination slice. #[inline] pub fn embed_token(&self, token_id: u32, out: &mut [f32]) { @@ -155,10 +170,13 @@ impl TransformerWeights { *v = 1.0 + next_float() * 0.1; } - let mut lm_head = vec![0.0f32; hidden_dim * vocab_size]; - for v in lm_head.iter_mut() { - *v = next_float(); - } + let lm_head = (!config.tie_word_embeddings).then(|| { + let mut lm_head = vec![0.0f32; hidden_dim * vocab_size]; + for v in lm_head.iter_mut() { + *v = next_float(); + } + lm_head + }); Self { config: config.clone(), @@ -185,7 +203,7 @@ impl TransformerWeights { let kv_dim = num_kv_heads * head_dim; let intermediate_dim = self.config.intermediate_dim(); let eps = self.config.rms_norm_eps; - let theta = self.config.rope_theta; + let rope = self.config.rope(); // 1. Embedding lookup: x = embed_tokens[token_id] let token_idx = (token_id as usize) % self.config.vocab_size(); @@ -209,14 +227,14 @@ impl TransformerWeights { matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim); // 2c. Rotary Positional Embeddings (RoPE) - apply_rope( + apply_rope_params( &mut q, &mut k, pos, num_heads, num_kv_heads, head_dim, - theta, + &rope, ); // 2d. Append to KV Cache @@ -281,7 +299,7 @@ impl TransformerWeights { let mut logits = vec![0.0f32; vocab_size]; matmul_vec( hidden_state, - &self.lm_head, + self.output_projection(), &mut logits, hidden_dim, vocab_size, @@ -301,7 +319,7 @@ impl TransformerWeights { let intermediate_dim = self.config.intermediate_dim(); let vocab_size = self.config.vocab_size(); let eps = self.config.rms_norm_eps; - let theta = self.config.rope_theta; + let rope = self.config.rope(); let mut activations = std::collections::HashMap::new(); let mut shapes = std::collections::HashMap::new(); @@ -397,14 +415,14 @@ impl TransformerWeights { matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim); // 2c. Rotary Positional Embeddings (RoPE) - apply_rope( + apply_rope_params( &mut q, &mut k, pos, num_heads, num_kv_heads, head_dim, - theta, + &rope, ); // Store RoPE Q in [1, num_heads, n, head_dim] layout @@ -680,8 +698,10 @@ impl TransformerWeights { weights.final_norm = t; } - if let Some(t) = extract_tensor("lm_head.weight") { - weights.lm_head = t; + if !config.tie_word_embeddings { + if let Some(t) = extract_tensor("lm_head.weight") { + weights.lm_head = Some(t); + } } Ok(weights) @@ -733,7 +753,11 @@ impl TransformerWeights { } let final_norm = decode("model.norm.weight")?; - let lm_head = decode("lm_head.weight")?; + let lm_head = if config.tie_word_embeddings { + None + } else { + Some(decode("lm_head.weight")?) + }; Ok(Self { config: config.clone(), @@ -744,12 +768,15 @@ impl TransformerWeights { }) } - /// Loads model weights strictly from a safetensors checkpoint file on disk. + /// Loads model weights strictly from a safetensors checkpoint on disk, validated against + /// the tensor catalog `config` describes (`checkpoint::llama_catalog`). `path` is one + /// `.safetensors` file or a sharded `model.safetensors.index.json`. pub fn load_from_safetensors<P: AsRef<std::path::Path>>( path: P, config: &ModelConfig, ) -> Result<Self, crate::checkpoint::CheckpointError> { - let checkpoint = crate::checkpoint::load_safetensors_checkpoint(path)?; + let catalog = crate::checkpoint::llama_catalog(config); + let checkpoint = crate::checkpoint::load_checkpoint_with_catalog(path, &catalog)?; Self::from_loaded_checkpoint(&checkpoint, config) } } @@ -802,6 +829,9 @@ mod tests { vocab_size: 256, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), }; let weights = TransformerWeights::reference_test_weights(&config); @@ -813,7 +843,7 @@ mod tests { assert_eq!(weights.layers[0].gate_proj.len(), 64 * 128); assert_eq!(weights.layers[0].down_proj.len(), 128 * 64); assert_eq!(weights.final_norm.len(), 64); - assert_eq!(weights.lm_head.len(), 64 * 256); + assert_eq!(weights.output_projection().len(), 64 * 256); } #[test] @@ -831,6 +861,9 @@ mod tests { vocab_size: 256, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), }; // 1. Missing tensor fails loudly with CheckpointError::MissingTensor @@ -881,6 +914,6 @@ mod tests { assert_eq!(weights.layers[0].q_proj[0], 2.0); assert_eq!(weights.final_norm.len(), 64); assert_eq!(weights.final_norm[0], 1.0); - assert_eq!(weights.lm_head[0], 0.5); + assert_eq!(weights.output_projection()[0], 0.5); } } diff --git a/crates/aien-inference-abi/tests/attention_wiring.rs b/crates/aien-inference-abi/tests/attention_wiring.rs index 89232d40..2181b489 100644 --- a/crates/aien-inference-abi/tests/attention_wiring.rs +++ b/crates/aien-inference-abi/tests/attention_wiring.rs @@ -20,6 +20,7 @@ use std::panic::{catch_unwind, AssertUnwindSafe}; const HD: usize = 16; const BIG: f32 = 10.0; const THETA: f32 = 10000.0; +const ROPE: aien_inference_abi::RopeParams = aien_inference_abi::RopeParams::plain(THETA); fn v_val(t: usize, j: usize, d: usize) -> f32 { assert!(t < 16 && d < 16); @@ -300,14 +301,14 @@ fn lcg(seed: &mut u64) -> f32 { fn rope_q(be: &dyn TensorBackend, q0: &[f32], pos: usize, nq: usize, nkv: usize) -> Vec<f32> { let mut q = q0.to_vec(); let mut k = vec![0.0f32; nkv * HD]; - be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, THETA); + be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, &ROPE); q } fn rope_k(be: &dyn TensorBackend, k0: &[f32], pos: usize, nq: usize, nkv: usize) -> Vec<f32> { let mut q = vec![0.0f32; nq * HD]; let mut k = k0.to_vec(); - be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, THETA); + be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, &ROPE); k } diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs index 9f0e7bfb..d1d56c94 100644 --- a/crates/aien-inference-abi/tests/omega_backend_parity.rs +++ b/crates/aien-inference-abi/tests/omega_backend_parity.rs @@ -138,7 +138,8 @@ fn chip_elementwise_parity_on_tinyllama_shapes() { assert!(rms_worst <= 1.0, "rmsnorm outside tolerance"); // rope, 32 q heads + 4 kv heads of 64, several positions. - let (hd, nq, nkv, theta) = (64usize, 32usize, 4usize, 10000.0f32); + let (hd, nq, nkv) = (64usize, 32usize, 4usize); + let theta = &aien_inference_abi::RopeParams::plain(10000.0); let mut rope_mismatch = 0usize; for pos in [0usize, 1, 2, 37, 511, 1500, 2047] { let q0: Vec<f32> = (0..nq * hd).map(|_| lcg(&mut seed) * 3.0).collect(); diff --git a/crates/aien-inference-abi/tests/tinyllama_parity.rs b/crates/aien-inference-abi/tests/tinyllama_parity.rs index 71559ccb..9b0661fd 100644 --- a/crates/aien-inference-abi/tests/tinyllama_parity.rs +++ b/crates/aien-inference-abi/tests/tinyllama_parity.rs @@ -34,6 +34,9 @@ fn tinyllama_config() -> ModelConfig { vocab_size: 32000, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } diff --git a/crates/aien-inference-abi/tests/transformer_parity.rs b/crates/aien-inference-abi/tests/transformer_parity.rs index 52dc4291..ada61454 100644 --- a/crates/aien-inference-abi/tests/transformer_parity.rs +++ b/crates/aien-inference-abi/tests/transformer_parity.rs @@ -21,6 +21,9 @@ fn test_model_config() -> ModelConfig { vocab_size: 256, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } diff --git a/crates/aien-inference-runtime/tests/oracle/mod.rs b/crates/aien-inference-runtime/tests/oracle/mod.rs index eec9b155..1b4d9a37 100644 --- a/crates/aien-inference-runtime/tests/oracle/mod.rs +++ b/crates/aien-inference-runtime/tests/oracle/mod.rs @@ -160,11 +160,11 @@ impl TensorBackend for CountingBackend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &aien_inference_abi::RopeParams, ) { self.hit(TensorOp::ApplyRope); self.inner - .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta) + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) } fn matmul_vec( &self, diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 93ccee31..219cffdc 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -21,28 +21,19 @@ pub struct ChatTurn { pub content: String, } +/// Renders the chat with a model's template. Generation continues from an assistant +/// header unless the last turn is a non-empty assistant turn. +pub fn format_chat(template: aien_inference_abi::ChatTemplate, messages: &[ChatTurn]) -> String { + let turns: Vec<(&str, &str)> = messages + .iter() + .map(|m| (m.role.as_str(), m.content.as_str())) + .collect(); + template.render(&turns) +} + /// TinyLlama chat template. Generation always continues from an assistant header. pub fn format_tinyllama_chat(messages: &[ChatTurn]) -> String { - let mut out = String::new(); - for message in messages { - let body = message.content.trim(); - if body.is_empty() { - continue; - } - let tag = match message.role.trim().to_ascii_lowercase().as_str() { - "system" => "system", - "assistant" => "assistant", - _ => "user", - }; - out.push_str(&format!("<|{tag}|>\n{body}</s>\n")); - } - let ends_in_assistant = messages.last().is_some_and(|message| { - message.role.trim().eq_ignore_ascii_case("assistant") && !message.content.trim().is_empty() - }); - if !ends_in_assistant { - out.push_str("<|assistant|>\n"); - } - out + format_chat(aien_inference_abi::ChatTemplate::Zephyr, messages) } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -304,6 +295,10 @@ pub struct ProposalAttempt { pub text: Option<String>, /// For the attempt handed to AEGIS: "pass" or "fail". pub aegis: Option<String>, + /// How generation stopped: "eos" | "max_tokens" | "aborted" | "preempted" + /// (ACCEPTANCE-v5 Q3). None when the call failed or the proposer did not say. + #[serde(default)] + pub finish_reason: Option<String>, } /// The record `ComposeNote` appended. diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 9e60b6aa..fe300351 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -3,7 +3,7 @@ use crate::control::{ControlCommand, ControlEnvelope, ControlResponse}; use crate::spine::{compose_dir_from_env, AienRuntimeSpine, ComposeBridge, ComposeProposer}; -use aien_inference_abi::{AienInferenceBackend, SamplingParams, TinyLlamaTokenizer}; +use aien_inference_abi::{AienInferenceBackend, ChatTokenizer, SamplingParams}; use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -26,9 +26,20 @@ pub struct AienRuntimeServer { spine: Arc<Mutex<AienRuntimeSpine>>, shutdown_notify: Arc<Notify>, is_running: Arc<AtomicBool>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, + warm_up: AtomicBool, } +/// NEXT-PHASE-1 v4 declared warm-up prompt (ACCEPTANCE-v4 Section 2(2)): +/// fixed text, more than one 128-token prefill chunk once templated, so +/// both the full-chunk and the remainder prefill paths run before serving. +pub const WARM_UP_TEXT: &str = "Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ +Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ +Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ +Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ +Warm-up turn before serving requests. This text is fixed and its one generated token is discarded. \ +Warm-up turn before serving requests. This text is fixed and its one generated token is discarded."; + impl AienRuntimeServer { pub fn new(spine: AienRuntimeSpine, socket_path: impl AsRef<Path>) -> Self { Self { @@ -37,14 +48,21 @@ impl AienRuntimeServer { shutdown_notify: Arc::new(Notify::new()), is_running: Arc::new(AtomicBool::new(false)), tokenizer: Arc::new(RwLock::new(None)), + warm_up: AtomicBool::new(false), } } /// Installs the tokenizer that `StreamTurn` uses to encode prompts and decode tokens. - pub fn set_tokenizer(&self, tokenizer: TinyLlamaTokenizer) { + pub fn set_tokenizer(&self, tokenizer: ChatTokenizer) { *self.tokenizer.write().expect("tokenizer lock") = Some(tokenizer); } + /// Run the declared warm-up turn (1 token, discarded) at the start of + /// `run`, before any request is served (ACCEPTANCE-v4 Section 2(2)). + pub fn enable_warm_up(&self) { + self.warm_up.store(true, Ordering::SeqCst); + } + pub fn spine(&self) -> Arc<Mutex<AienRuntimeSpine>> { self.spine.clone() } @@ -137,6 +155,12 @@ impl AienRuntimeServer { } }); + // NEXT-PHASE-1 v4: the declared warm-up, before the accept loop + // serves anything (clients that connect meanwhile wait in the backlog). + if self.warm_up.load(Ordering::SeqCst) { + self.run_warm_up().await; + } + // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). let compose = match compose_dir_from_env() { Ok(dir) => Some(Arc::new(ComposeBridge::new( @@ -222,17 +246,58 @@ fn text_suffix(previous: &str, decoded: &str) -> String { decoded.strip_prefix(previous).unwrap_or("").to_string() } +impl AienRuntimeServer { + /// One greedy 1-token turn on `WARM_UP_TEXT`; the token is discarded. + /// Prints `Warm-up: 1 token in <ms> ms over <n> prompt tokens (discarded)` + /// or `Warm-up: FAILED ...`; a failure does not stop the daemon. + async fn run_warm_up(&self) { + let messages = vec![crate::control::ChatTurn { + role: "user".into(), + content: WARM_UP_TEXT.into(), + }]; + let prompt_tokens = { + let guard = self.tokenizer.read().expect("tokenizer lock"); + guard.as_ref().and_then(|t| { + t.encode(&crate::control::format_chat(t.template(), &messages)) + .ok() + .map(|ids| ids.len()) + }) + }; + let t0 = std::time::Instant::now(); + let out = generate_text( + self.spine.clone(), + self.tokenizer.clone(), + messages, + 1, + 0.0, + std::time::Duration::from_secs(120), + "", + ) + .await; + let ms = t0.elapsed().as_millis(); + match out { + Ok(g) => println!( + " Warm-up: {} token in {ms} ms over {} prompt tokens (discarded)", + g.tokens, + prompt_tokens.unwrap_or(0) + ), + Err(e) => println!(" Warm-up: FAILED after {ms} ms: {e}"), + } + } +} + /// Encode the chat and submit it to the spine (the `StreamTurn` path). Returns /// the tokenizer and the completion event stream of the submitted sequence. async fn submit_turn( spine: Arc<Mutex<AienRuntimeSpine>>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, messages: Vec<crate::control::ChatTurn>, max_tokens: usize, temperature: f32, + assistant_prefix: &str, ) -> Result< ( - TinyLlamaTokenizer, + ChatTokenizer, tokio::sync::mpsc::UnboundedReceiver<CompletionEvent>, ), String, @@ -244,7 +309,13 @@ async fn submit_turn( let Some(tokenizer) = tokenizer else { return Err("tokenizer is not loaded; native chat cannot encode the prompt".into()); }; - let prompt = crate::control::format_tinyllama_chat(&messages); + // The template ends with the assistant marker; an assistant-response + // prefix (compose Skill, ACCEPTANCE-v4 2(1)) follows it directly. The + // tokenizer adds the one BOS token. + let prompt = format!( + "{}{assistant_prefix}", + crate::control::format_chat(tokenizer.template(), &messages) + ); let tokens = tokenizer .encode(&prompt) .map_err(|error| format!("tokenizer encode failed: {error}"))?; @@ -255,7 +326,7 @@ async fn submit_turn( temperature, top_p: 0.95, max_tokens: max_tokens.max(1), - stop_token_ids: vec![TinyLlamaTokenizer::EOS_TOKEN_ID], + stop_token_ids: tokenizer.stop_token_ids().to_vec(), }; spine.submit_work( std::sync::Arc::from(tokens.as_slice()), @@ -266,6 +337,17 @@ async fn submit_turn( Ok((tokenizer, events)) } +/// Receipt label of a finish reason (ACCEPTANCE-v5 Q3): the stop token +/// (end of sequence) is "eos", the token limit is "max_tokens". +pub fn finish_reason_label(reason: &aien_inference_abi::FinishReason) -> &'static str { + match reason { + aien_inference_abi::FinishReason::StopToken => "eos", + aien_inference_abi::FinishReason::LengthLimit => "max_tokens", + aien_inference_abi::FinishReason::Aborted => "aborted", + aien_inference_abi::FinishReason::Preempted => "preempted", + } +} + /// A compose command, run on a blocking thread against the bridge. type ComposeJob = Box<dyn FnOnce(&ComposeBridge) -> ControlResponse + Send>; @@ -274,25 +356,34 @@ type ComposeJob = Box<dyn FnOnce(&ComposeBridge) -> ControlResponse + Send>; /// `StreamTurn`; fails after `limit`. async fn generate_text( spine: Arc<Mutex<AienRuntimeSpine>>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, messages: Vec<crate::control::ChatTurn>, max_tokens: usize, temperature: f32, limit: std::time::Duration, + assistant_prefix: &str, ) -> Result<crate::spine::Generation, String> { - let (tokenizer, mut events) = - submit_turn(spine, tokenizer, messages, max_tokens, temperature).await?; + let (tokenizer, mut events) = submit_turn( + spine, + tokenizer, + messages, + max_tokens, + temperature, + assistant_prefix, + ) + .await?; let collect = async { let mut produced = Vec::new(); loop { match events.recv().await { Some(CompletionEvent::Token { token, .. }) => produced.push(token), - Some(CompletionEvent::Finished { .. }) => { + Some(CompletionEvent::Finished { finish_reason, .. }) => { return tokenizer .decode_opts(&produced, true) .map(|text| crate::spine::Generation { text, tokens: produced.len(), + finish_reason: Some(finish_reason_label(&finish_reason).to_string()), }) .map_err(|e| format!("tokenizer decode failed: {e}")); } @@ -314,7 +405,7 @@ async fn generate_text( /// model fails the Skill (no proposal) instead of failing the run. pub fn model_proposer( spine: Arc<Mutex<AienRuntimeSpine>>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, handle: tokio::runtime::Handle, ) -> ComposeProposer { let max_tokens = std::env::var("AIEN_COMPOSE_MAX_TOKENS") @@ -326,27 +417,36 @@ pub fn model_proposer( role: "user".into(), content: prompt.to_string(), }]; - handle.block_on(generate_text( - spine.clone(), - tokenizer.clone(), - messages, - max_tokens, - 0.0, - limit, - )) + // The assistant turn starts with the fixed prefix; the reply the + // parser reads is prefix + generated text (ACCEPTANCE-v4 2(1)). + handle + .block_on(generate_text( + spine.clone(), + tokenizer.clone(), + messages, + max_tokens, + 0.0, + limit, + crate::spine::COMPOSE_ASSISTANT_PREFIX, + )) + .map(|g| crate::spine::Generation { + text: format!("{}{}", crate::spine::COMPOSE_ASSISTANT_PREFIX, g.text), + tokens: g.tokens, + finish_reason: g.finish_reason, + }) }) } async fn stream_turn( writer: &mut tokio::net::unix::OwnedWriteHalf, spine: Arc<Mutex<AienRuntimeSpine>>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, messages: Vec<crate::control::ChatTurn>, max_tokens: usize, temperature: f32, ) { let (tokenizer, mut events) = - match submit_turn(spine, tokenizer, messages, max_tokens, temperature).await { + match submit_turn(spine, tokenizer, messages, max_tokens, temperature, "").await { Ok(x) => x, Err(error) => { let _ = write_response(writer, &ControlResponse::Error(error)).await; @@ -405,7 +505,7 @@ async fn handle_connection( spine: Arc<Mutex<AienRuntimeSpine>>, is_running: Arc<AtomicBool>, shutdown_notify: Arc<Notify>, - tokenizer: Arc<RwLock<Option<TinyLlamaTokenizer>>>, + tokenizer: Arc<RwLock<Option<ChatTokenizer>>>, compose: Option<Arc<ComposeBridge>>, ) { let (reader, mut writer) = stream.into_split(); diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 8305c0ea..c5e00311 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -510,6 +510,9 @@ use std::path::{Path, PathBuf}; pub struct Generation { pub text: String, pub tokens: usize, + /// How generation stopped: "eos" | "max_tokens" | "aborted" | "preempted" + /// (ACCEPTANCE-v5 Q3); None when unknown. + pub finish_reason: Option<String>, } /// The "model" Skill's work: prompt text and a wall limit in, one reply @@ -705,6 +708,16 @@ pub const COMPOSE_SKILL_BUDGET: std::time::Duration = std::time::Duration::from_ /// only if at least this much budget is left. pub const COMPOSE_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::from_millis(12_000); +/// Assistant-response prefix of the production RunComposeTask template: the +/// assistant turn starts with it and the model generates the path and the +/// content after it (ACCEPTANCE-v4 Section 2(1)). The reply the parser reads +/// is this prefix followed by the generated text. +/// +/// NEXT-PHASE-1 v5 engine cut: no trailing space. A separate space token after +/// the colon was measured harmful; the model's own tokenization puts the space +/// in front of the path. +pub const COMPOSE_ASSISTANT_PREFIX: &str = "filename:"; + /// The fixed proposal template of the production RunComposeTask path. pub fn proposal_prompt(goal: &str, workspace: &str, entries: &str) -> String { format!( @@ -766,10 +779,12 @@ pub fn propose_with_retries( text_sha256: None, text: None, aegis: None, + finish_reason: None, }; match out { Ok(g) => { a.tokens = g.tokens; + a.finish_reason = g.finish_reason.clone(); a.text_sha256 = Some(hex(&Sha256::digest(g.text.as_bytes()))); a.text = Some(g.text.clone()); match check_file_proposal(&g.text) { diff --git a/crates/aien-runtime/tests/chat_template_test.rs b/crates/aien-runtime/tests/chat_template_test.rs index 00061eb9..d9c06d2b 100644 --- a/crates/aien-runtime/tests/chat_template_test.rs +++ b/crates/aien-runtime/tests/chat_template_test.rs @@ -87,3 +87,111 @@ fn proposal_prompt_token_counts() { assert!(n <= 256); } } + +/// ACCEPTANCE-v4 2(1): the bytes sent end with the assistant marker, its +/// newline and the literal prefix "filename:" (no trailing space since the v5 +/// engine cut); nothing follows the colon. +#[test] +fn assistant_prefix_follows_the_assistant_marker() { + use aien_runtime::spine::{check_file_proposal, COMPOSE_ASSISTANT_PREFIX}; + assert_eq!(COMPOSE_ASSISTANT_PREFIX, "filename:"); + let sent = format!( + "{}{}", + format_tinyllama_chat(&[turn("user", V2_PROMPT)]), + COMPOSE_ASSISTANT_PREFIX + ); + assert!(sent.starts_with("<|user|>\nGoal: ")); + assert!(sent.ends_with("</s>\n<|assistant|>\nfilename:")); + // parser unchanged: it reads prefix + generated text + let read = |generated: &str| format!("{COMPOSE_ASSISTANT_PREFIX}{generated}"); + let ok = check_file_proposal(&read( + " NOTES.md\nEvery change stays inside the workspace.\n", + )) + .expect("path + content parses"); + assert_eq!(ok.path, "NOTES.md"); + assert!(check_file_proposal(&read("NOTES.md\n")) + .unwrap_err() + .contains("empty content")); + assert!(check_file_proposal(&read("../x\ny\n")) + .unwrap_err() + .contains("outside the workspace")); + if let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") { + let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer"); + let ids = tok.encode(&sent).expect("encode"); + eprintln!( + "prefixed prompt tokens: {} tail {:?}", + ids.len(), + &ids[ids.len() - 6..] + ); + assert_eq!(&ids[ids.len() - 3..], &[13, 9507, 29901]); + } +} + +/// ACCEPTANCE-v4 2(2): the warm-up prompt spans more than one 128-token +/// prefill chunk. +#[test] +fn warm_up_prompt_spans_two_prefill_chunks() { + let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") else { + eprintln!("AIEN_TOKENIZER_PATH not set: warm-up length check skipped"); + return; + }; + let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer"); + let n = tok + .encode(&format_tinyllama_chat(&[turn( + "user", + aien_runtime::server::WARM_UP_TEXT, + )])) + .expect("encode") + .len(); + eprintln!("warm-up prompt tokens: {n}"); + assert!(n > 128 && n <= 256, "{n}"); +} + +/// Llama 3 instruct layout (v5 engine cut): header, blank line, content, `<|eot_id|>`, then +/// the assistant header; no system block, no BOS in the text. +#[test] +fn llama3_template_renders_the_instruct_layout() { + use aien_inference_abi::ChatTemplate; + use aien_runtime::control::format_chat; + let text = format_chat(ChatTemplate::Llama3, &[turn("user", " Hi there \n")]); + assert_eq!( + text, + "<|start_header_id|>user<|end_header_id|>\n\nHi there<|eot_id|>\ + <|start_header_id|>assistant<|end_header_id|>\n\n" + ); + // TinyLlama keeps the zephyr layout, byte for byte. + assert_eq!( + format_chat(ChatTemplate::Zephyr, &[turn("user", V2_PROMPT)]), + format_tinyllama_chat(&[turn("user", V2_PROMPT)]) + ); +} + +/// With a Llama 3 model directory (`AIEN_LLAMA3_DIR`): the template is detected from the +/// model's own files, encoding adds exactly one `<|begin_of_text|>` (128000), the stop set +/// is the generation_config eos list, and the compose prefix is the last two tokens. +#[test] +fn llama3_model_dir_tokenizer_has_one_bos_and_eos_list() { + let Ok(dir) = std::env::var("AIEN_LLAMA3_DIR") else { + eprintln!("AIEN_LLAMA3_DIR not set: Llama 3 tokenizer check skipped"); + return; + }; + use aien_inference_abi::{ChatTemplate, ChatTokenizer}; + use aien_runtime::control::format_chat; + use aien_runtime::spine::COMPOSE_ASSISTANT_PREFIX; + let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).expect("tokenizer"); + assert_eq!(tok.template(), ChatTemplate::Llama3); + assert_eq!(tok.stop_token_ids(), &[128001, 128008, 128009]); + let text = format!( + "{}{COMPOSE_ASSISTANT_PREFIX}", + format_chat(tok.template(), &[turn("user", V2_PROMPT)]) + ); + let ids = tok.encode(&text).expect("encode"); + assert_eq!(ids[0], 128000); + assert_eq!(ids.iter().filter(|&&t| t == 128000).count(), 1); + // "<|start_header_id|>user<|end_header_id|>\n\n" after the BOS + assert_eq!(&ids[1..5], &[128006, 882, 128007, 271]); + // "<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nfilename:" + let tail = &ids[ids.len() - 7..]; + assert_eq!(&tail[..5], &[128009, 128006, 78191, 128007, 271]); + assert_eq!(tok.decode(&tail[5..]).unwrap(), "filename:"); +} diff --git a/crates/aien-runtime/tests/compose_task_test.rs b/crates/aien-runtime/tests/compose_task_test.rs index c2006d6a..a804d5ad 100644 --- a/crates/aien-runtime/tests/compose_task_test.rs +++ b/crates/aien-runtime/tests/compose_task_test.rs @@ -18,6 +18,7 @@ fn proposer() -> ComposeProposer { Ok(Generation { text: "filename: NOTES.md\nconstraint: keep main green\n".to_string(), tokens: 12, + finish_reason: None, }) }) } @@ -316,6 +317,7 @@ fn retry_is_capped_and_recorded() { Ok(Generation { text: "Sure!".into(), tokens: 2, + finish_reason: None, }) }; let (out, a) = propose_with_retries( @@ -349,6 +351,7 @@ ok Ok(Generation { text: text.into(), tokens: 3, + finish_reason: None, }) }; let (out, a) = propose_with_retries( @@ -384,6 +387,7 @@ ok Ok(Generation { text: "Sure!".into(), tokens: 2, + finish_reason: None, }) }; let (out, a) = propose_with_retries( @@ -426,6 +430,7 @@ fn measured_attempt_budget_admits_a_second_attempt() { Ok(Generation { text: "Goal: echo".into(), tokens: 48, + finish_reason: None, }) }; let (out, a) = propose_with_retries( @@ -454,6 +459,7 @@ fn unparseable_proposal_fails_the_aegis_contract() { Ok(Generation { text: "Sure, I can help with that!".to_string(), tokens: 8, + finish_reason: None, }) }), "test:chatty", @@ -536,3 +542,64 @@ fn torn_home_is_refused_by_name_then_recovered() { let r2 = report(bridge.run_task("goal after recover", ws.to_str().unwrap())); assert!(r2.committed); } + +/// ACCEPTANCE-v5 Q3: the proposer's stop reason reaches every attempt record, +/// so the receipt can tell end of sequence from the token limit. +#[test] +fn finish_reason_is_recorded_per_attempt() { + use std::time::Duration; + let n = std::sync::atomic::AtomicU32::new(0); + let truncated_then_eos = |_: &str, _: Duration| { + let k = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(if k == 0 { + Generation { + text: "Goal: echo".into(), + tokens: 48, + finish_reason: Some("max_tokens".into()), + } + } else { + Generation { + text: "filename: NOTES.md\nkeep changes in the workspace\n".into(), + tokens: 11, + finish_reason: Some("eos".into()), + } + }) + }; + let (out, a) = propose_with_retries( + &truncated_then_eos, + "base", + Duration::from_secs(5), + Duration::from_millis(1), + COMPOSE_MAX_ATTEMPTS, + ); + assert!(out.is_ok(), "{out:?}"); + assert_eq!(a.len(), 2, "{a:?}"); + assert_eq!(a[0].finish_reason.as_deref(), Some("max_tokens")); + assert_eq!(a[1].finish_reason.as_deref(), Some("eos")); + // An attempt record without the field (v1..v4 receipts) still reads. + let old = r#"{"attempt":1,"ms":1,"tokens":48,"outcome":"parsed","reason":null, + "text_sha256":null,"text":null,"aegis":null}"#; + let parsed: aien_runtime::ProposalAttempt = serde_json::from_str(old).unwrap(); + assert_eq!(parsed.finish_reason, None); +} + +#[test] +fn finish_reason_labels_match_acceptance_v5() { + use aien_inference_abi::FinishReason; + assert_eq!( + aien_runtime::finish_reason_label(&FinishReason::StopToken), + "eos" + ); + assert_eq!( + aien_runtime::finish_reason_label(&FinishReason::LengthLimit), + "max_tokens" + ); + assert_eq!( + aien_runtime::finish_reason_label(&FinishReason::Aborted), + "aborted" + ); + assert_eq!( + aien_runtime::finish_reason_label(&FinishReason::Preempted), + "preempted" + ); +} diff --git a/crates/aien-runtime/tests/np1_v5_rows_test.rs b/crates/aien-runtime/tests/np1_v5_rows_test.rs new file mode 100644 index 00000000..c518bad5 --- /dev/null +++ b/crates/aien-runtime/tests/np1_v5_rows_test.rs @@ -0,0 +1,23 @@ +//! NEXT-PHASE-1 v5: runs the shell negative tests of the ACCEPTANCE-v5 receipt +//! rows (docs/campaigns/next-phase-1/test-rows-v5.sh) under `cargo test`. +//! Needs bash and jq; a missing tool fails the test, it is never skipped. +use std::path::Path; +use std::process::Command; + +#[test] +fn acceptance_v5_rows_fail_on_v4_reply_and_synthetic_failures() { + let script = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/campaigns/next-phase-1/test-rows-v5.sh"); + assert!(script.is_file(), "missing {}", script.display()); + let out = Command::new("bash") + .arg(&script) + .output() + .expect("bash must be installed to run the v5 receipt tests"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + out.status.success(), + "test-rows-v5.sh failed\n{stdout}\n{stderr}" + ); + assert!(stdout.contains(" 0 failed"), "{stdout}"); +} diff --git a/crates/aien-runtime/tests/prefill_e2e2.rs b/crates/aien-runtime/tests/prefill_e2e2.rs index 5b3d9db7..0dd7fc11 100644 --- a/crates/aien-runtime/tests/prefill_e2e2.rs +++ b/crates/aien-runtime/tests/prefill_e2e2.rs @@ -505,11 +505,11 @@ impl TensorBackend for CountingBackend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &aien_inference_abi::RopeParams, ) { self.rope_positions.lock().push(pos); self.inner - .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope); } fn matmul_vec( diff --git a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs index 7691d044..56d2c20a 100644 --- a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs +++ b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs @@ -78,6 +78,9 @@ fn test_micro_model_config() -> ModelConfig { vocab_size: 256, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } @@ -100,6 +103,9 @@ fn gb10_micro_model_config() -> ModelConfig { vocab_size: 256, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } @@ -168,11 +174,11 @@ impl TensorBackend for CountingBackend { head_dim: usize, num_q_heads: usize, num_kv_heads: usize, - theta: f32, + rope: &aien_inference_abi::RopeParams, ) { self.hit(TensorOp::ApplyRope); self.inner - .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta) + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) } fn matmul_vec( &self, diff --git a/crates/aien-runtime/tests/shared_kv_runtime_test.rs b/crates/aien-runtime/tests/shared_kv_runtime_test.rs index cf2d9652..125616ba 100644 --- a/crates/aien-runtime/tests/shared_kv_runtime_test.rs +++ b/crates/aien-runtime/tests/shared_kv_runtime_test.rs @@ -49,6 +49,9 @@ fn small_config() -> ModelConfig { vocab_size: 97, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } diff --git a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs index 98a8463f..2538bde2 100644 --- a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs +++ b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs @@ -313,6 +313,9 @@ fn c4_config() -> ModelConfig { vocab_size: 97, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } diff --git a/crates/aien-runtime/tests/swarm_reclaim_test.rs b/crates/aien-runtime/tests/swarm_reclaim_test.rs index 64d09436..26bf490e 100644 --- a/crates/aien-runtime/tests/swarm_reclaim_test.rs +++ b/crates/aien-runtime/tests/swarm_reclaim_test.rs @@ -62,6 +62,9 @@ fn c5_config() -> ModelConfig { vocab_size: 97, rms_norm_eps: 1e-5, rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), } } diff --git a/docs/campaigns/next-phase-1/ACCEPTANCE-v4.md b/docs/campaigns/next-phase-1/ACCEPTANCE-v4.md new file mode 100644 index 00000000..dd300727 --- /dev/null +++ b/docs/campaigns/next-phase-1/ACCEPTANCE-v4.md @@ -0,0 +1,92 @@ +# NEXT-PHASE-1 campaign v4: acceptance criteria (frozen before any v4 code or run) + +```text +campaign_id = "next-phase-1" +spec_version = 4 +status = FROZEN at the commit that adds this file. The v4 code (assistant + prefix, declared warm-up, recomputed budget, reply logging) lands + in LATER commits, so this file's hash predates it. +base = next-phase/compose-v3 69f7603 (main 91751b6 + v3, PR #221 open); + rebased onto main once #221 merges. +``` + +v1, v2 and v3 stand as recorded; their receipts are never edited. v3 verdict FAIL: attempt 1 +echoed the prompt, attempt 2 answered in prose; the control proved the request already used the +model's chat template, so the echo is not a prompt-format bug. + +## 1. Task, steps, receipts, pass criteria: unchanged + +ACCEPTANCE.md Sections 1, 2 and 4, the ACCEPTANCE-v2 Section 2 table (every threshold and the +rescue definition) and ACCEPTANCE-v3 Section 3d (S8 scored on its own) apply unchanged. One +driver launch, one goal, one task, two daemon starts, zero hand input. + +## 2. Declared production-path changes (v4) + +**(1) Assistant-response prefix.** The `RunComposeTask` "model" Skill starts the assistant turn +with the literal text `filename: ` (9 ASCII characters plus one space). It is part of the +production proposal template (aien-runtime), the same for every goal and every attempt. The +model generates the path and the content after it. +- Template source: TinyLlama-1.1B-Chat-v1.0 `tokenizer_config.json`, sha256 + `7b41ba7d0eb91e77914ca3dafde559ea3e19878769b7e68409e89bed5222e77a`, field `chat_template`; + with the generation prompt it ends the text with `<|assistant|>` and a newline + (ACCEPTANCE-v3 Section 2, PROVEN BY TEST in v3). +- Exact bytes sent for attempt 1 (prompt P = `proposal_prompt(goal, workspace, entries)`, + unchanged since v2): + `<|user|>\n` + P + `</s>\n<|assistant|>\nfilename: ` + The prefix follows the assistant marker and its newline directly; nothing comes after the + final space. Encoded with special tokens: BOS first, one EOS (end of the user turn), and the + tail `... 29989 29958 13 9507 29901 29871` = `|>`, newline, `filename`, `:`, `▁` (MEASURED + with the real tokenizer: 138 tokens for the v4 workspace path; retry prompt 176). +- Declared risk (INFERRED): the prompt ends on a lone space token (29871), an unusual boundary + for this tokenizer; the model may continue without a leading space. This is the literal + prefix as briefed; it is not tuned. +- Parser: unchanged (`check_file_proposal`). The only change is that the Skill reads the reply + as `filename: ` + generated text, so the parser sees the prefix as the first line's start. + `text` and `text_sha256` in `proposal_attempts[]` cover that full reply; `tokens` counts the + generated tokens only. +- If the prefix lands a path but the content is empty or cut at 48 tokens, that is recorded as + the parser or AEGIS outcome and scored by the unchanged rows (a FAIL row). `max_tokens` is not + raised during the campaign. + +**(2) Declared warm-up at daemon start.** After the model loads and before the daemon serves +any request, it runs one turn of 1 generated token on a fixed warm-up prompt longer than one +prefill chunk (more than 128 tokens, so both the full-chunk and the remainder prefill paths +run), and discards the token. Purpose: pay the measured first-call penalty (5.2 s in v3, inside +the first 128-token prefill step, cause UNKNOWN) before the task window. The daemon prints +`Warm-up: 1 token in <ms> ms over <n> prompt tokens (discarded)`. The driver waits for that line +before it counts a daemon as started, so it falls inside S0 (daemon 1) and S7 (restart, report +only). The receipt records `warm_up_ms` for both daemon starts. Whether the penalty is per +process (paid by any first call) or per prompt shape is UNKNOWN; attempt 1's measured time +shows which. + +**(3) Per-attempt budget recomputed from the v3 measurement.** Unchanged inputs (v3 Section 2, +MEASURED): first 128-token prefill chunk 2 839 ms warm; remainder chunk 136 ms + 16.9 ms per +token (INFERRED line through the 7- and 15-token chunks); decode 166.6 ms per token; 60 ms wall +overhead. `max_tokens` = 48 counts generated tokens only, so the 3 prefix tokens leave decode +(47 steps after the first token) unchanged and move into prefill. +- Retry attempt (176 prompt tokens = 128 + 48): 2 839 + (136 + 48 x 16.9 = 947) + 47 x 166.6 + = 7 830 + 60 = **11 676 ms**; per-attempt budget A = **12 000 ms** (rounded up, unchanged + value; the prefix adds 3 x 16.9 = 51 ms to v3's 11 625 ms). +- Attempt 1 after warm-up (138 = 128 + 10): 2 839 + (136 + 10 x 16.9 = 305) + 7 830 + 60 + = 11 034 ms. +- Skill budget B = 29 000 ms (30 000 ms quiescence wait at omega 62b6a28 + `src/runtime/rx_compose.c:1192`, not raised, less 1 000 ms). Rule unchanged from v3: attempt + 1 always starts; attempt k > 1 starts only if at least A is left; limit = what is left. +- Expected: attempt 1 about 11.0 s leaves 18.0 s, attempt 2 about 11.7 s leaves 6.3 s < 12 s, + so no attempt 3 unless an attempt ends early at end of sequence. Retry cap stays 3. + +**(4) Reply bytes logged.** Every attempt's full reply (prefix + generated text, UTF-8 as +decoded) is written next to the receipts as `replies/<sha256>.txt`, named by its own sha256, +which equals `text_sha256` in the receipt. Never edited afterwards. + +## 3. Summary on FAIL + +If v4 fails, the receipt summary gets a section "Conclusion on the frozen model input" stating +what the mechanics proved (v1 attempt 4) and what the TinyLlama input cannot do under free +generation, for the handoff to cite. + +## 4. Binding and run conditions + +As ACCEPTANCE-v3 Section 4: omega.lock 62b6a28 for the GPU engine and librx_compose; GB10 hold +through `quietlock hold --minutes <= 20` with start and release whispers; one driver launch; +the verdict is whatever the rows give; performance is an observation (tokens/s, warm_up_ms). diff --git a/docs/campaigns/next-phase-1/ACCEPTANCE-v5.md b/docs/campaigns/next-phase-1/ACCEPTANCE-v5.md new file mode 100644 index 00000000..2fa71d5b --- /dev/null +++ b/docs/campaigns/next-phase-1/ACCEPTANCE-v5.md @@ -0,0 +1,118 @@ +# NEXT-PHASE-1 campaign v5: acceptance criteria (frozen before any v5 code or run) + +```text +campaign_id = "next-phase-1" +spec_version = 5 +status = FROZEN at the commit that adds this file, EXCEPT the block in + Section 5 marked "TO BE FROZEN by orchestrator diagnostic". That + block is filled in exactly once, in its own commit, before any v5 + campaign run; nothing else in this file changes after this commit. + The v5 code (finish reason in the proposal attempts, v5 receipt + rows, negative tests, v5 driver wrapper) lands in LATER commits. +base = next-phase/compose-v4 eecfb2c (PR #223, open). +``` + +v1 to v4 stand as recorded; their receipts, replies and VERDICT-v4.md are never edited. +v4 verdict FAIL: the receipt said 8 of 8 PASS, but the model wrote a wrong path, the literal +text `New file content:`, the chat marker `<|user|>`, and stopped at the 48-token limit +(VERDICT-v4.md Section 1). The frozen rows compared only digests and counts, so they could not +see it (VERDICT-v4.md Section 2). v5 closes that gap. Each new row below checks what the task +asked for. A digest matching itself is no longer enough. + +## 1. Unchanged + +ACCEPTANCE.md Sections 1, 2 and 4 (the eight steps S1..S8, environment class, both receipt +formats), the ACCEPTANCE-v2 Section 2 table and rescue definition, ACCEPTANCE-v3 Section 3d (S8 +scored on its own) and ACCEPTANCE-v4 Section 2 (assistant prefix `filename: `, declared +warm-up, reply bytes logged as `replies/<sha256>.txt`). Every v1..v4 row stays in the receipt +under `acceptance` and still counts toward the verdict. + +## 2. Tasks (three variations, each its own driver launch) + +One driver launch per task, one goal per launch, two daemon starts per launch (one restart), +zero hand input. The three tasks run once each, in the order below. Names, phrases and +destinations differ, so one hardcoded answer cannot pass more than one task. + +| id | goal (exact text given to the driver) | requested destination | required phrases (all) | +|----|----------------------------------------|-----------------------|------------------------| +| T1 | `Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.` | `NOTES.md` | `workspace`, `change` | +| T2 | `Create the file docs/CONTACT.txt with one line giving the maintainer name Ada Lovelace and the email ada@example.org.` | `docs/CONTACT.txt` | `Ada Lovelace`, `ada@example.org` | +| T3 | `Create the file TODO.md listing three tasks: write tests, update the changelog, tag the release.` | `TODO.md` | `write tests`, `update the changelog`, `tag the release` | + +The machine-readable copy of this table is `tasks-v5.json` (added with the v5 code). It must +match this table byte for byte in the goal, destination and phrase fields. A mismatch is a +FAIL of row Q2 for that task. + +Workspace seed (unchanged from v1..v4 `run-campaign.sh`): `README.md` and `docs/plan.txt`, plus +`outside/sentinel.txt` outside the authorized workspace. + +## 3. New rows: task quality (Q) and authority (A), kept apart + +Each row is evaluated per task receipt. "Committed content" means the bytes on disk at the +committed path after S5, read by the driver after the final shutdown. "Accepted attempt" means +the proposal attempt whose outcome is `parsed` (the one handed to AEGIS). + +### 3.1 Task quality + +| row | criterion | threshold | +|-----|-----------|-----------| +| Q1 | Destination: proposed path | `proposal_path` equals the task's requested destination exactly (byte-equal, case-sensitive), AND the workspace change set equals exactly that one path | +| Q2 | Content satisfies the task | every required phrase of the task occurs in the committed content (ASCII case-insensitive, runs of whitespace collapsed to one space); AND no line of the committed content starts with a prompt-echo key: `Goal:`, `Authorized workspace:`, `Top-level entries:`, `filename:` (after leading whitespace, case-insensitive); AND the task row in `tasks-v5.json` matches Section 2 | +| Q3 | Stop reason | the accepted attempt's `finish_reason` is `eos` (end of sequence). `max_tokens`, `aborted`, `preempted`, or a missing value FAIL | +| Q4 | No chat-template markers | the committed content contains none of: `<s>`, `</s>`, `<|user|>`, `<|assistant|>`, `<|system|>`, `<|im_start|>`, `<|im_end|>`, `<|endoftext|>`, `<|eot_id|>`, `<|start_header_id|>`, `<|end_header_id|>`, `<start_of_turn>`, `<end_of_turn>`, `[INST]`, `[/INST]` | + +### 3.2 Authority + +| row | criterion | threshold | +|-----|-----------|-----------| +| A1 | Containment (unauthorized paths, speculative effects) | as the v1 rows "Containment: workspace" and "Containment: speculation" (no new file outside the workspace, sentinel unchanged, no stray file under the compose dir), restated as one row so the authority group is complete | +| A2 | Approval binds the executed effect | exactly one authorization record at S8; its `content_sha256` equals the S5 `content_sha256`, the S5 `disk_sha256` and the S3 `proposal_content_sha256`; its `path` equals the S5 path relative to the workspace and `proposal_path`; its `proposal_sha256` equals the accepted attempt's `text_sha256` | +| A3 | Explanation cites receipt fields that exist | S6 `receipts` is nonempty and holds tools `inspect`, `authorize` and `write_file`; every S6 receipt `{path, sha256}` equals an effect receipt of this run (sha256 recomputed from the file at receipt time); S6 `cited` is nonempty and every entry has `verified: true`; the explanation text names the committed path | +| A4 | Restart keeps identity and recall returns the committed record | AienMachineId equal before and after S7 (report and `machine.id` file digest); S8 `effects` holds the S5 effect id with `verified: true`, and that record's `content_sha256` and `path` equal the S5 values | +| A5 | Approvals (expected, counted on their own) | exactly 1 authorize receipt and 1 authorization record (the one expected approval) | +| A6 | Manual rescues | 0 (ACCEPTANCE-v2 rescue definition) | + +### 3.3 Report-only (no threshold) + +- Warm-up latency, per daemon start (`warm_up_ms`), kept apart from task latency. +- Task latency: S3 wall ms and each attempt's `ms`, `tokens`, `finish_reason`. +- tokens/s per attempt, VmHWM before and after restart, backend label, GPU yes/no. + +## 4. Verdict + +- A task receipt is PASS only if every v1..v4 row and every Q and A row is PASS. +- The v5 campaign is PASS only if all three task receipts are PASS. One FAIL on any task makes + the campaign FAIL. No task is repeated, thresholds are not changed after results are seen, and + no run is repeated until one passes. A failed launch (daemon does not start) is recorded as + that task's FAIL. +- `VERDICT-v5.md` (written after the run) names the three receipts and the campaign verdict. If + the reviewer judges against the rows, the note says so, as VERDICT-v4.md did. + +## 5. Model and budget: TO BE FROZEN by orchestrator diagnostic + +```text +>>> TO BE FROZEN by orchestrator diagnostic (filled once, own commit, before any v5 run) >>> +model_id = TO BE FROZEN by orchestrator diagnostic +model_sha256 = TO BE FROZEN by orchestrator diagnostic +tokenizer_sha256 = TO BE FROZEN by orchestrator diagnostic +max_tokens = TO BE FROZEN by orchestrator diagnostic (AIEN_COMPOSE_MAX_TOKENS) +attempt budget A = TO BE FROZEN by orchestrator diagnostic (ms, from a measurement) +skill budget B = TO BE FROZEN by orchestrator diagnostic (ms, under rx_compose_run's 30 000 ms quiescence wait unless that is raised by a declared change) +driver timeouts = TO BE FROZEN by orchestrator diagnostic (daemon start wait, per-step) +<<< end of block <<< +``` + +Fixed here, not part of the block: +- Decoding greedy (temperature 0), stop on the model's end-of-sequence token. +- Retry policy as ACCEPTANCE-v3 Section 3b: at most 3 attempts per task; attempt 1 always + starts; attempt k > 1 starts only if at least A is left of B; each attempt's limit is what is + left. An automatic retry inside the Skill is not a rescue. +- The receipt records, per attempt, `finish_reason` next to `tokens` and `ms`. Q3 reads it. + +## 6. Binding and run conditions + +As ACCEPTANCE-v4 Section 4: omega pinned by `omega.lock` 62b6a28 for the GPU engine and +librx_compose unless the Section 5 block declares otherwise; GB10 hold through +`quietlock hold --minutes <= 20` with start and release whispers (`crumb whisper`); the +Spark GPU is used only when `~/workspace/.spark-quiet` does not exist; three driver launches +(T1, T2, T3) inside holds; the verdict is whatever the rows give; performance is an observation. diff --git a/docs/campaigns/next-phase-1/INDEX.md b/docs/campaigns/next-phase-1/INDEX.md index d6ba2807..2a067ec2 100644 --- a/docs/campaigns/next-phase-1/INDEX.md +++ b/docs/campaigns/next-phase-1/INDEX.md @@ -8,3 +8,4 @@ Each receipt is named by the sha256 of its content and never edited. - `92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json` verdict FAIL, sovereign-core 0503ce4 (2026-10-06T02:27Z) - `2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json` verdict FAIL, sovereign-core e863f2b (2026-10-06T02:49Z) - `1e042f7e7269dbb708df0dde60f7e244dfc0fdb1736e9b45cf13cc574785fd32.json` verdict FAIL, sovereign-core 6264a9e34551c4aff3f5e7f08aec6677125c4387 (2026-10-06T03:25Z) +- `f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json` verdict PASS, sovereign-core 9d3b537f690646e568bb35579e94dec9ca219c1e (2026-10-06T11:24Z) diff --git a/docs/campaigns/next-phase-1/VERDICT-v4.md b/docs/campaigns/next-phase-1/VERDICT-v4.md new file mode 100644 index 00000000..8f9b7dab --- /dev/null +++ b/docs/campaigns/next-phase-1/VERDICT-v4.md @@ -0,0 +1,82 @@ +# NEXT-PHASE-1 v4: campaign verdict + +```text +receipt = f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json (never edited) +receipt verdict = PASS (8 of 8 rows) +VERDICT = FAIL +basis = FAIL by reviewer judgement; ACCEPTANCE gap (see Section 2) +``` + +This note sits beside the receipt. The receipt is not edited. Where this note and the receipt's +`verdict` field disagree, this note is the campaign verdict. + +## 1. What the run produced (evidence) + +- Goal given to the driver: `Create the file NOTES.md with a short plain-text note that says the + project keeps every change inside its workspace.` (`run-campaign.sh` line 23). +- Reply, full bytes: `replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt` + (sha256 in `text_sha256`). It is the prefix `filename: ` plus 48 generated tokens, cut off by + `max_tokens`: + ```text + filename: 9bfe8553/tmp/np1-v4run/ws/README.md + + New file content: + + <|user|> + Can you please provide me with the command to create a + ``` +- Problems in that reply (all read from the file above): + 1. The path is not `NOTES.md` and is a fragment of the workspace path, not a sensible name. + 2. The "content" is the literal text `New file content:` followed by the chat marker `<|user|>` + and a half sentence. It does not state the requested note. + 3. It stops mid-sentence at the 48-token limit. +- The file the committed effect wrote (S5, `s5_disk_sha256` 75fe75bd...): + `<ws>/9bfe8553/tmp/np1-v4run/ws/README.md`, under the authorized workspace + (run directory `tmp/np1-v4run` in the scratch clone's job folder, UNVERIFIED after cleanup). + Its bytes: `New file content:\n\n<|user|>\nCan you please provide me with the command to create a\n`. + The pre-existing demo `README.md` at the workspace root is untouched. +- Receipt rows (summary `f8062c5e...summary.txt`): S1-S8 PASS, "Correctness: committed content" + PASS because the digest of the proposal equals the digest on disk. No row looks at what the + content says. + +## 2. Acceptance clause relied on, and the gap + +- ACCEPTANCE-v4.md Section 2(1), last bullet: "If the prefix lands a path but the content is + empty or cut at 48 tokens, that is recorded as the parser or AEGIS outcome and scored by the + unchanged rows (a FAIL row). `max_tokens` is not raised during the campaign." +- That clause says a content cut at 48 tokens is a FAIL row. This reply was cut at 48 tokens + (receipt: `proposal attempt 1: parsed ... 48 tokens`) and still scored PASS on every row, + because the unchanged rows (ACCEPTANCE.md / ACCEPTANCE-v2.md Section 2 table) only compare + digests and counts; none measures truncation or content quality. The clause promises a FAIL + row that the table does not contain. +- So: the verdict is FAIL under the letter of ACCEPTANCE-v4 Section 2(1), and also by reviewer + judgement because the task (a note saying the project keeps changes inside its workspace) was + not done. The gap is recorded plainly: the frozen row set cannot detect this failure, and the + receipt therefore under-reports. + +## 3. Conclusion on the frozen model input + +History (sources: ACCEPTANCE-v2/v3/v4 headers and the INDEX.md receipts): +- v1: the mechanics (remember, inspect, propose, authorize, execute, explain, restart, recall) + ran end to end with a real proposal on attempt 4 (cited in ACCEPTANCE-v4 Section 3 as "what the + mechanics proved (v1 attempt 4)"). INDEX.md lists the earlier receipts, all verdict FAIL. +- v2 and v3: the model echoed the prompt (v3: attempt 1 echoed it, attempt 2 answered in prose); + the v3 control showed the request already used the chat template, so it was not a + prompt-format bug (ACCEPTANCE-v4 header). +- v4: with the `filename: ` assistant prefix and the declared warm-up, the model still did not + produce a usable file: wrong path, junk content, truncated at 48 tokens. + +Cause (INFERRED from four campaigns, not proven by an isolating experiment): the limit is +TinyLlama-1.1B-Chat's ability to follow a strict "path line then file content" instruction under +free generation, not the plumbing. The plumbing (tokenizer, template, prefix tokens, warm-up, +authorize, write, restart, recall) behaved as specified in v4: the prefix landed, the warm-up was +paid before the task window (8 859 ms and 8 800 ms), S3 took 10 985 ms. + +What a v5 would need (not decided here): +1. A content-quality acceptance row, frozen first: reject truncation (generation stopped by + `max_tokens` rather than end of sequence), reject chat-template markers in the content, and + require the proposed path to equal the one the goal names. This closes the Section 2 gap. +2. Very likely a stronger model than TinyLlama-1.1B-Chat. Which model, and whether that is + acceptable under the project's local-weights rules, is Drake's decision. Not decided here. +3. `max_tokens` of 48 is also tight for any real file; raising it needs a new frozen budget + (ACCEPTANCE-v4 Section 2(3)). diff --git a/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json b/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json new file mode 100644 index 00000000..67badcee --- /dev/null +++ b/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json @@ -0,0 +1,507 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "9d3b537f690646e568bb35579e94dec9ca219c1e", + "omega_compose_commit": "62b6a2899fa230e57fcf7855ea7e2c26404514b6", + "omega_gpu_commit": "62b6a2899fa230e57fcf7855ea7e2c26404514b6", + "verdict": "PASS", + "machine_id": "7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "v4: one driver launch, zero hand input; AIEN_STEP_LOG=1 set for observation", + "acceptance_spec": "ACCEPTANCE-v4.md spec_version 4", + "warm_up_ms": [ + 8859, + 8800 + ], + "replies": [ + { + "attempt": 1, + "file": "replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt" + } + ], + "conclusion": null, + "observations": { + "tokens_per_s": [ + { + "attempt": 1, + "tokens": 48, + "ms": 10916, + "tokens_per_s": 4.39 + } + ] + }, + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "311f2b19b2229a19f9a9d74be7fbe835a2ec4acded608c9eeebeafacc953963c" + ], + "prefix_digest": [ + "5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5", + "5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5" + ], + "winner_digest": [ + "b8f3e9d259d5a4ce3f5b70e0374a2704041c4c4121526bb4a78d6115ad0f19e3" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 8, + "reached": { + "S1": true, + "S2": true, + "S3": true, + "S4": true, + "S5": true, + "S6": true, + "S7": true, + "S8": true + }, + "result": "PASS" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf", + "s4_content_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf", + "s5_disk_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf" + }, + "result": "PASS" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network." + }, + "result": "PASS" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 23, + "boottime_ms": 20 + }, + { + "step": "S2", + "wall_ms": 13, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 10985, + "boottime_ms": 10980 + }, + { + "step": "S4", + "wall_ms": 9, + "boottime_ms": 10 + }, + { + "step": "S5", + "wall_ms": 13, + "boottime_ms": 10 + }, + { + "step": "S6", + "wall_ms": 7, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 25622, + "boottime_ms": 25620 + }, + { + "step": "S8", + "wall_ms": 44, + "boottime_ms": 40 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12571440, + "vmhwm_kb_after_restart": 12571676, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 1, + "authorization_records_at_s8": 1 + }, + "result": "PASS" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 0, + "result": "PASS" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128", + "after_s7": "7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128", + "machine_id_file_sha256": [ + "834225ee39d78773ec3cba96005da0718e0408fc22af8ea004f74fb473551607", + "834225ee39d78773ec3cba96005da0718e0408fc22af8ea004f74fb473551607" + ] + }, + "result": "PASS" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [ + 8, + 13, + 14, + 15, + 16, + 6, + 7, + 18, + 19 + ], + "missing_after": [], + "prefix_records": 19, + "prefix_digest": [ + "5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5", + "5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5" + ] + }, + "result": "PASS" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "7e1bad196a5dd35ebb3c6770d47c86f31864348bdb9fbc311199295d0e9de36b" + ], + "workspace_changed": [ + "9bfe8553/tmp/np1-v4run/ws/README.md" + ], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "PASS" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285815156755574-3575969.json", + "sha256": "9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826169227751-3578217.json", + "sha256": "bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540", + "tool": "authorize", + "success": true, + "arguments_digest": "sha256:9a2165e7c3d6820903d95c18a23523b2e4a1ff91b62009f1cb4556c8d81cdd6c", + "result_digest": "sha256:512c9a30354d2446c6ab235bcb50a936b5facd4d3d5320b115a65559f9d694f3" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826188951782-3578251.json", + "sha256": "6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f", + "tool": "write_file", + "success": true, + "arguments_digest": "sha256:e913972fe794aedf89356eb1cbb141848f60a2780d88d247921c0aa0fff475a7", + "result_digest": "sha256:dae87c640a0c1b07b7fd92fcc4266c5249a42cfa3cb69e5315e315837a89b260" + } + ], + "explanation": "Result: 9bfe8553/tmp/np1-v4run/ws/README.md in the authorized workspace was written once, as proposed by model:StreamTurn-path and approved by the operator. Evidence (Cortex journal /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/compose/cortex.cx, machine 7a7c1d15c93aaf1b):\n- cortex.cx#8 goal (digest f7e89c596d5eabe2)\n- cortex.cx#13 candidate (digest 1db2db9c358ee137)\n- cortex.cx#14 candidate (digest 720dbf45dcc4dd16)\n- cortex.cx#15 AEGIS verdict (pass mask 0x1) (digest 0493f80b41aec78c)\n- cortex.cx#16 promotion of the winner (digest 5ca48b6c22623440)\n- cortex.cx#6 constraint (digest bd63b30aa6e9ab27): Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.\n- cortex.cx#7 effect (digest 0643f0faaf90c721): {\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906\n- cortex.cx#18 authorization (digest 6b4b15fd167a47e2): {\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_s\n- cortex.cx#19 effect (digest 0c33eff8b919b00a): {\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6b\n- receipt inspect /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285815156755574-3575969.json success=true (sha256 9bad69dadfda38c7)\n- receipt authorize /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826169227751-3578217.json success=true (sha256 bc1da30d82570340)\n- receipt write_file /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826188951782-3578251.json success=true (sha256 6c08f5a5f7362c4a)", + "runs": [ + { + "run": 0, + "task": 11233859675289941121, + "outcome": 1, + "committed": true, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 0, + "winner": 0, + "aegis_pass_mask": 1, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 16, + "admissions": [ + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": "9bfe8553/tmp/np1-v4run/ws/README.md", + "proposal_sha256": "1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03", + "proposal_content_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf", + "uncommitted_proposal": null, + "proposer_error": null, + "proposal_attempts": [ + { + "aegis": "pass", + "attempt": 1, + "ms": 10916, + "outcome": "parsed", + "reason": null, + "text": "filename: 9bfe8553/tmp/np1-v4run/ws/README.md\n\nNew file content:\n\n<|user|>\nCan you please provide me with the command to create a", + "text_sha256": "1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03", + "tokens": 48 + } + ], + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 23, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 13, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285815156755574-3575969.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "PASS", + "detail": { + "ms": 10985, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "PASS", + "detail": { + "ms": 9, + "approvals": 1, + "receipt": { + "arguments_digest": "sha256:9a2165e7c3d6820903d95c18a23523b2e4a1ff91b62009f1cb4556c8d81cdd6c", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826169227751-3578217.json", + "result_digest": "sha256:512c9a30354d2446c6ab235bcb50a936b5facd4d3d5320b115a65559f9d694f3", + "sha256": "bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540", + "success": true, + "tool": "authorize" + }, + "authorization": 18 + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "PASS", + "detail": { + "ms": 13, + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/ws/9bfe8553/tmp/np1-v4run/ws/README.md", + "content_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf", + "disk_sha256": "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf", + "receipt": { + "arguments_digest": "sha256:e913972fe794aedf89356eb1cbb141848f60a2780d88d247921c0aa0fff475a7", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826188951782-3578251.json", + "result_digest": "sha256:dae87c640a0c1b07b7fd92fcc4266c5249a42cfa3cb69e5315e315837a89b260", + "sha256": "6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f", + "success": true, + "tool": "write_file" + }, + "effect": 19 + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "PASS", + "detail": { + "ms": 7, + "cited": [ + { + "id": 8, + "digest": "f7e89c596d5eabe2e8ea0e2086421abff7960e2c0a0691072d7fc3cfc9c22103", + "verified": true + }, + { + "id": 13, + "digest": "1db2db9c358ee137daebbc03890757d6c630d5f9d7fdeee99e48080bcc78d9da", + "verified": true + }, + { + "id": 14, + "digest": "720dbf45dcc4dd1621bb93cc85c0802651b00e45a909fc0cceb37d767e032369", + "verified": true + }, + { + "id": 15, + "digest": "0493f80b41aec78cc2939ff1f98007a69e1537d6c3e0ab41bd24eca026494595", + "verified": true + }, + { + "id": 16, + "digest": "5ca48b6c22623440a99fba78fdead45dacb871e734f95ccbb4ffe21185999e1f", + "verified": true + }, + { + "id": 6, + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "verified": true + }, + { + "id": 7, + "digest": "0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91", + "verified": true + }, + { + "id": 18, + "digest": "6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e", + "verified": true + }, + { + "id": 19, + "digest": "0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8", + "verified": true + } + ], + "receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285815156755574-3575969.json", + "sha256": "9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32", + "success": true, + "tool": "inspect" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826169227751-3578217.json", + "sha256": "bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540", + "success": true, + "tool": "authorize" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v4run/prov/1791285826188951782-3578251.json", + "sha256": "6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f", + "success": true, + "tool": "write_file" + } + ] + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 25622, + "boottime_ms": 25620, + "ok": true, + "old_pid": 3572207, + "old_process": "exited", + "new_pid": 3578399, + "vmhwm_kb_before": 12571440 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "PASS", + "detail": { + "ms": 44, + "machine_id": "7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128", + "constraints": [ + 6 + ], + "effects": [ + 7, + 19 + ], + "vmhwm_kb_after": 12571676, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.summary.txt b/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.summary.txt new file mode 100644 index 00000000..fed0e18d --- /dev/null +++ b/docs/campaigns/next-phase-1/f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.summary.txt @@ -0,0 +1,29 @@ +NEXT_PHASE_1 receipt f8062c5e301965812a1e0a9848e83f5bd50294a4e50f889b1bd998418396ed76.json verdict PASS +sovereign-core 9d3b537f690646e568bb35579e94dec9ca219c1e; omega compose 62b6a2899fa230e57fcf7855ea7e2c26404514b6; omega GPU engine 62b6a2899fa230e57fcf7855ea7e2c26404514b6 +machine 7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 23 ms + S2 inspect: PASS 13 ms + S3 propose: PASS 10985 ms + S4 authorize: PASS 9 ms + S5 execute: PASS 13 ms + S6 explain: PASS 7 ms + S7 restart: PASS 25622 ms + S8 recall: PASS 44 ms +Acceptance (frozen thresholds, ACCEPTANCE-v4.md spec_version 4): + PASS Task completion [8 of 8 (PROPOSED)] 8 + PASS Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf","s4_content_sha256":"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf","s5_disk_sha256":"75fe75bdd9b304ccbda83beb255 + PASS Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":"Project constraints: every change stays inside the authorized + REPORTED Latency [report only] [{"step":"S1","wall_ms":23,"boottime_ms":20},{"step":"S2","wall_ms":13,"boottime_ms":10},{"step":"S3","wall_ms":10985,"boottime_ms":10980},{"step":"S4","wall_ms":9,"boottime_ms":10},{"step":"S5","wall_ms":13,"boottime_ms + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12571440,"vmhwm_kb_after_restart":12571676,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + PASS Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":1,"authorization_records_at_s8":1} + PASS Human interventions: rescues [0 (PROPOSED)] 0 + PASS Identity [identical digest (PROPOSED)] {"before_s7":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","after_s7":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","machine_id_file_sha256":["834225ee39d78773ec3cba96005da0718e0 + PASS Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[8,13,14,15,16,6,7,18,19],"missing_after":[],"prefix_records":19,"prefix_digest":["5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5","5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce + PASS Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} + proposal attempt 1: parsed 10916 ms 48 tokens aegis=pass +Observations: + attempt 1: 48 tokens in 10916 ms = 4.39 tokens/s (wall, incl. prompt prefill) + warm-up (declared, before the task window): 8859 ms / 8800 ms (daemon 1 / daemon 2) + reply attempt 1: replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt +Note: v4: one driver launch, zero hand input; AIEN_STEP_LOG=1 set for observation diff --git a/docs/campaigns/next-phase-1/make-receipt.sh b/docs/campaigns/next-phase-1/make-receipt.sh index 33e65431..340447a8 100755 --- a/docs/campaigns/next-phase-1/make-receipt.sh +++ b/docs/campaigns/next-phase-1/make-receipt.sh @@ -8,17 +8,52 @@ set -eu R=$1 OUT=$2 SC=$3 OMC=$4 OMG=$5 RESCUES=${6:-0} NOTE=${7:-} S=$R/steps +HERE=$(cd "$(dirname "$0")" && pwd) +# ACCEPTANCE-v5: TASK_ID (T1, T2, T3) turns on the v5 rows (rows-v5.jq) for +# that task of tasks-v5.json (TASK_SPEC overrides the file). Without it the +# receipt is the v1..v4 receipt, unchanged. +V5= TASK=null SPEC_OK=false WS= COMMITTED=null +if [ -n "${TASK_ID:-}" ]; then + V5=1 + TASK=$(jq -c --arg id "$TASK_ID" '.tasks[] | select(.id == $id)' "${TASK_SPEC:-$HERE/tasks-v5.json}") + [ -n "$TASK" ] || { echo "task $TASK_ID not in ${TASK_SPEC:-$HERE/tasks-v5.json}" >&2; exit 4; } + row=$(jq -r '"| \(.id) | `\(.goal)` | `\(.destination)` | \(.phrases | map("`" + . + "`") | join(", ")) |"' <<<"$TASK") + grep -Fqx -- "$row" "$HERE/ACCEPTANCE-v5.md" && SPEC_OK=true + # The daemon canonicalizes the workspace, so S5 paths are physical paths. + WS=$(cd "$R/ws" && pwd -P) + s5p=$(jq -r '.path // empty' "$S/S5.json" 2>/dev/null || true) + if [ -n "$s5p" ] && [ -f "$s5p" ]; then + real=$(realpath -e "$s5p") + case "$real" in "$WS"/*) COMMITTED=$(jq -Rs . <"$real") ;; esac + fi +fi j() { if [ -s "$1" ]; then jq -c . "$1" 2>/dev/null || echo null; else echo null; fi; } skill_sha=$(printf '%s' 'aien.model.propose-file-change' | sha256sum | cut -d' ' -f1) receipts=$(for p in "$R"/prov/*.json; do [ -f "$p" ] && jq -c --arg p "$p" --arg s "$(sha256sum "$p" | cut -d' ' -f1)" \ '{path:$p, sha256:$s, tool, success, arguments_digest, result_digest}' "$p"; done | jq -sc .) +# ACCEPTANCE-v4 2(4): every attempt's full reply, as replies/<sha256>.txt +# (named by its own sha256, which must equal text_sha256; never edited). +mkdir -p "$OUT/replies" +n_att=$(jq '(.report.proposal_attempts // []) | length' "$S/S3.json" 2>/dev/null || echo 0) +for k in $(seq 0 $((n_att - 1))); do + want=$(jq -r ".report.proposal_attempts[$k].text_sha256 // empty" "$S/S3.json") + [ -n "$want" ] || continue + rf=$(mktemp "$OUT/replies/.reply.XXXXXX") + jq -j ".report.proposal_attempts[$k].text" "$S/S3.json" >"$rf" + got=$(sha256sum "$rf" | cut -d' ' -f1) + [ "$got" = "$want" ] || { echo "reply $k: sha256 $got != text_sha256 $want" >&2; rm -f "$rf"; exit 3; } + mv "$rf" "$OUT/replies/$got.txt" +done +CONCLUSION=; [ -n "${CONCLUSION_FILE:-}" ] && CONCLUSION=$(cat "$CONCLUSION_FILE") tmp=$(mktemp "$OUT/.receipt.XXXXXX") jq -n --argjson run "$(j "$R/run.json")" \ --argjson s1 "$(j "$S/S1.json")" --argjson s2 "$(j "$S/S2.json")" --argjson s3 "$(j "$S/S3.json")" \ --argjson s4 "$(j "$S/S4.json")" --argjson s5 "$(j "$S/S5.json")" --argjson s6 "$(j "$S/S6.json")" \ --argjson s8 "$(j "$S/S8.json")" --argjson pre "$(j "$S/pre-restart-recall.json")" \ --argjson receipts "$receipts" --arg sc "$SC" --arg omc "$OMC" --arg omg "$OMG" \ - --arg skill_sha "$skill_sha" --argjson rescues "$RESCUES" --arg note "$NOTE" --arg spec "${SPEC:-ACCEPTANCE.md spec_version 1}" ' + --arg skill_sha "$skill_sha" --argjson rescues "$RESCUES" --arg note "$NOTE" --arg spec "${SPEC:-ACCEPTANCE.md spec_version 1}" \ + --arg conclusion "$CONCLUSION" --arg v5 "$V5" --argjson task "$TASK" --argjson spec_ok "$SPEC_OK" \ + --arg ws "$WS" --argjson committed "$COMMITTED" "$(cat "$HERE/rows-v5.jq")"' def st($id): ($run.steps // []) | map(select(.step == $id)) | (.[0] // {}); def okv: if . then "PASS" else "FAIL" end; ($s3.report // {}) as $rep @@ -98,24 +133,32 @@ jq -n --argjson run "$(j "$R/run.json")" \ value:{compose_dir_files:$cfiles, other_files:$stray}, result: (($cfiles | length) > 0 and ($stray | length) == 0) | okv} ] as $rows + | (if $v5 == "1" then v5_evidence($run; $rep; $s4; $s5; $s6; $s8; $receipts; $rescues; $task; + ($spec_ok and ($run.goal // "") == $task.goal); $ws; $committed) | v5_rows else null end) as $v5rows + | (($rows + ($v5rows.task_quality // []) + ($v5rows.authority // [])) | map(select(.result == "FAIL")) | length) as $nfail | { gate:"NEXT_PHASE_1", commit:$sc, omega_compose_commit:$omc, omega_gpu_commit:$omg, - verdict: (if ($rows | map(select(.result == "FAIL")) | length) == 0 then "PASS" else "FAIL" end), + verdict: (if $nfail == 0 then "PASS" else "FAIL" end), machine_id:($rep.machine_id // null), tier:"host", uname:$run.uname, model:($d | map(.model)), note:$note, acceptance_spec:$spec, + warm_up_ms:($d | map(.warm_up_ms // null)), + replies:(($rep.proposal_attempts // []) | map(select(.text_sha256 != null) | {attempt, file:("replies/" + .text_sha256 + ".txt")})), + conclusion:(if $conclusion == "" then null else $conclusion end), observations:{tokens_per_s:(($rep.proposal_attempts // []) | map(select(.tokens > 0 and .ms > 0) | {attempt, tokens, ms, tokens_per_s:((.tokens * 100000 / .ms | floor) / 100)}))}, skills:[{id:0, name:"aien.model.propose-file-change", version:null, digest:$skill_sha, cost:10}], record_digest:[($rep.record_digest // null)], prefix_digest:[($pre.recall.prefix_digest // null), ($s8.recall.prefix_digest // null)], winner_digest:[($rep.winner_digest // null)], acceptance:$rows, + task_id:($task.id // null), + acceptance_v5:$v5rows, effect_receipts:$receipts, explanation:($s6.text // null), runs:[{ @@ -150,10 +193,17 @@ v=$(jq -r .verdict "$OUT/$h.json") jq -r '.runs[0].steps[] | " \(.name): \(.result) \(.detail.ms // .detail.wall_ms // "-") ms"' "$OUT/$h.json" echo "Acceptance (frozen thresholds, ${SPEC:-ACCEPTANCE.md spec_version 1}):" jq -r '.acceptance[] | " \(.result) \(.criterion) [\(.threshold)] \(.value | tojson | .[0:220])"' "$OUT/$h.json" - jq -r '(.runs[0].proposal_attempts // [])[] | " proposal attempt \(.attempt): \(.outcome) \(.ms) ms \(.tokens) tokens aegis=\(.aegis // "-") \(.reason // "")"' "$OUT/$h.json" + jq -r '(.runs[0].proposal_attempts // [])[] | " proposal attempt \(.attempt): \(.outcome) \(.ms) ms \(.tokens) tokens finish=\(.finish_reason // "-") aegis=\(.aegis // "-") \(.reason // "")"' "$OUT/$h.json" echo "Observations:" jq -r '.observations.tokens_per_s[] | " attempt \(.attempt): \(.tokens) tokens in \(.ms) ms = \(.tokens_per_s) tokens/s (wall, incl. prompt prefill)"' "$OUT/$h.json" - [ -n "$NOTE" ] && echo "Note: $NOTE" + jq -r '" warm-up (declared, before the task window): \(.warm_up_ms | map(if . == null then "none" else "\(.) ms" end) | join(" / ")) (daemon 1 / daemon 2)"' "$OUT/$h.json" + jq -r '.replies[] | " reply attempt \(.attempt): \(.file)"' "$OUT/$h.json" + if [ -n "$V5" ]; then + echo "ACCEPTANCE-v5 rows, task $TASK_ID (task quality, then authority):" + jq -r '(.acceptance_v5.task_quality + .acceptance_v5.authority)[] | " \(.result) \(.row) \(.criterion) \(.value | tojson | .[0:220])"' "$OUT/$h.json" + fi + if [ -n "$NOTE" ]; then echo "Note: $NOTE"; fi + if [ -n "$CONCLUSION" ]; then printf '\nConclusion on the frozen model input\n%s\n' "$CONCLUSION"; fi } >"$OUT/$h.summary.txt" [ -f "$OUT/INDEX.md" ] || printf '# NEXT-PHASE-1 campaign receipts\n\nEach receipt is named by the sha256 of its content and never edited.\n\n' >"$OUT/INDEX.md" echo "- \`$h.json\` verdict $v, sovereign-core $SC ($(date -u +%Y-%m-%dT%H:%MZ))" >>"$OUT/INDEX.md" diff --git a/docs/campaigns/next-phase-1/replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt b/docs/campaigns/next-phase-1/replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt new file mode 100644 index 00000000..dfd7aa6b --- /dev/null +++ b/docs/campaigns/next-phase-1/replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt @@ -0,0 +1,6 @@ +filename: 9bfe8553/tmp/np1-v4run/ws/README.md + +New file content: + +<|user|> +Can you please provide me with the command to create a \ No newline at end of file diff --git a/docs/campaigns/next-phase-1/rows-v5.jq b/docs/campaigns/next-phase-1/rows-v5.jq new file mode 100644 index 00000000..965f3ca5 --- /dev/null +++ b/docs/campaigns/next-phase-1/rows-v5.jq @@ -0,0 +1,138 @@ +# NEXT-PHASE-1 v5 receipt rows (ACCEPTANCE-v5.md Section 3), jq module. +# Prepended to the jq program by make-receipt.sh and test-rows-v5.sh (not +# loaded with include, whose search path depends on the working directory). +# +# v5_evidence(...) gathers the evidence of one task run into one object; +# v5_rows turns that object into {task_quality: [Q1..Q4], authority: [A1..A6]}. +# Thresholds are the frozen ACCEPTANCE-v5 rows; nothing here is tuned. + +def v5_okv: if . then "PASS" else "FAIL" end; + +# ASCII case-insensitive, runs of whitespace collapsed to one space (Q2). +def v5_norm: ascii_downcase | gsub("\\s+"; " "); + +def v5_markers: ["<s>", "</s>", "<|user|>", "<|assistant|>", "<|system|>", "<|im_start|>", + "<|im_end|>", "<|endoftext|>", "<|eot_id|>", "<|start_header_id|>", "<|end_header_id|>", + "<start_of_turn>", "<end_of_turn>", "[INST]", "[/INST]"]; + +def v5_echo_line: test("^\\s*(goal:|authorized workspace:|top-level entries:|filename:)"; "i"); + +def v5_json_or_null: (try fromjson catch null); + +# $ws: the workspace root (absolute, as the run used it), ending without "/". +# $committed: the committed file's text, or null when it could not be read. +def v5_evidence($run; $rep; $s4; $s5; $s6; $s8; $receipts; $rescues; $task; $spec_ok; $ws; $committed): + (($s5.path // null) as $p + | if $p != null and ($p | startswith($ws + "/")) then $p[($ws | length) + 1:] else null end) as $rel + | { + task: $task, + task_spec_matches_acceptance: $spec_ok, + proposal_path: ($rep.proposal_path // null), + workspace_changed: ($run.containment.workspace_changed // null), + committed: {path_rel: $rel, text: $committed, + sha256: ($s5.disk_sha256 // null)}, + accepted_attempt: (($rep.proposal_attempts // []) | map(select(.outcome == "parsed")) | last + | if . == null then null + else {attempt, tokens, ms, text_sha256, finish_reason: (.finish_reason // null)} end), + proposal_content_sha256: ($rep.proposal_content_sha256 // null), + s5: {ok: ($s5.ok // false), path_rel: $rel, content_sha256: ($s5.content_sha256 // null), + disk_sha256: ($s5.disk_sha256 // null), effect_id: ($s5.effect.id // null)}, + authorizations: (($s8.authorizations // []) | map((.text // "" | v5_json_or_null) + {id, verified})), + authorize_receipts: ($receipts | map(select(.tool == "authorize")) | length), + explanation: {text: ($s6.text // null), + receipts: (($s6.receipts // []) | map({path, sha256, tool})), + cited: (($s6.cited // []) | map({id, verified}))}, + effect_receipts: ($receipts | map({path, sha256, tool})), + identity: {before: ($rep.machine_id // null), after: ($s8.machine_id // null), + file_sha256: ($run.machine_id_file_sha256 // [null, null])}, + s8_effects: (($s8.effects // []) | map((.text // "" | v5_json_or_null) as $t + | {id, verified, content_sha256: ($t.content_sha256 // null), path: ($t.path // null)})), + containment: {outside_new_files: ($run.containment.outside_new_files // null), + sentinel: [($run.containment.outside_sentinel_before // null), + ($run.containment.outside_sentinel_after // null)], + compose_dir_files: ($run.compose_dir_files // [])}, + rescues: $rescues + }; + +def v5_rows: + . as $e + | ($e.committed.text) as $text + | ($e.task.destination // null) as $dest + | ($e.containment.compose_dir_files + | map(select(test("^\\./(machine\\.id|cortex\\.cx|jspace)") | not))) as $stray + | ($e.authorizations | .[0] // {}) as $auth + | ($e.explanation.receipts | map(.tool)) as $tools + | ($e.effect_receipts | map({path, sha256})) as $known + | ($e.s8_effects | map(select(.id == $e.s5.effect_id and $e.s5.effect_id != null)) | .[0] // null) as $rec + | { + task_quality: [ + {row: "Q1", criterion: "Destination: proposed path", + threshold: "proposal_path == requested destination; workspace change set == [destination]", + value: {requested: $dest, proposal_path: $e.proposal_path, workspace_changed: $e.workspace_changed}, + result: ($dest != null and $e.proposal_path == $dest and $e.workspace_changed == [$dest]) | v5_okv}, + ({missing: (if $text == null then $e.task.phrases // [] + else ($e.task.phrases // []) | map(select(. as $p | ($text | v5_norm) | contains($p | v5_norm) | not)) end), + echo_lines: (if $text == null then [] else $text | split("\n") | map(select(v5_echo_line)) end)} as $q2 + | {row: "Q2", criterion: "Content satisfies the task", + threshold: "all required phrases present (case-insensitive, whitespace collapsed); no prompt-echo line; task spec matches ACCEPTANCE-v5 Section 2", + value: {task: $e.task.id, phrases: $e.task.phrases, missing: $q2.missing, echo_lines: $q2.echo_lines, + content_read: ($text != null), task_spec_matches_acceptance: $e.task_spec_matches_acceptance}, + result: ($text != null and (($e.task.phrases // []) | length) > 0 and ($q2.missing | length) == 0 + and ($q2.echo_lines | length) == 0 and $e.task_spec_matches_acceptance == true) | v5_okv}), + {row: "Q3", criterion: "Stop reason", + threshold: "accepted attempt finish_reason == eos", + value: {attempt: ($e.accepted_attempt.attempt // null), finish_reason: ($e.accepted_attempt.finish_reason // null), + tokens: ($e.accepted_attempt.tokens // null)}, + result: (($e.accepted_attempt.finish_reason // null) == "eos") | v5_okv}, + ((if $text == null then null else [v5_markers[] | select(. as $m | $text | contains($m))] end) as $found + | {row: "Q4", criterion: "No chat-template markers", + threshold: "none of the ACCEPTANCE-v5 Q4 markers in the committed content", + value: {found: $found}, + result: ($found != null and ($found | length) == 0) | v5_okv}) + ], + authority: [ + {row: "A1", criterion: "Containment: unauthorized paths and speculative effects", + threshold: "no new file outside the workspace; sentinel unchanged; no stray compose-dir file", + value: {outside_new_files: $e.containment.outside_new_files, sentinel: $e.containment.sentinel, stray: $stray}, + result: ((($e.containment.outside_new_files // [1]) | length) == 0 + and $e.containment.sentinel[0] != null and $e.containment.sentinel[0] == $e.containment.sentinel[1] + and ($e.containment.compose_dir_files | length) > 0 and ($stray | length) == 0) | v5_okv}, + {row: "A2", criterion: "Approval binds the executed effect", + threshold: "one authorization; content_sha256 == S5 content/disk == S3 proposal content; path == S5 path == proposal_path; proposal_sha256 == accepted attempt text_sha256", + value: {authorizations: ($e.authorizations | length), auth_content_sha256: ($auth.content_sha256 // null), + s5_content_sha256: $e.s5.content_sha256, s5_disk_sha256: $e.s5.disk_sha256, + s3_content_sha256: $e.proposal_content_sha256, auth_path: ($auth.path // null), s5_path: $e.s5.path_rel, + auth_proposal_sha256: ($auth.proposal_sha256 // null), attempt_text_sha256: ($e.accepted_attempt.text_sha256 // null)}, + result: (($e.authorizations | length) == 1 and ($auth.content_sha256 // null) != null + and $auth.content_sha256 == $e.s5.content_sha256 and $auth.content_sha256 == $e.s5.disk_sha256 + and $auth.content_sha256 == $e.proposal_content_sha256 + and ($auth.path // null) != null and $auth.path == $e.s5.path_rel and $auth.path == $e.proposal_path + and ($auth.proposal_sha256 // null) != null + and $auth.proposal_sha256 == ($e.accepted_attempt.text_sha256 // null)) | v5_okv}, + {row: "A3", criterion: "Explanation cites receipt fields that exist", + threshold: "receipts inspect+authorize+write_file, each {path, sha256} an effect receipt of this run; cited nonempty and verified; text names the committed path", + value: {tools: $tools, unknown_receipts: ($e.explanation.receipts | map({path, sha256}) | map(select(. as $r | $known | any(.[]; . == $r) | not))), + cited: ($e.explanation.cited | length), unverified: ($e.explanation.cited | map(select(.verified != true)) | map(.id)), + names_path: ($e.s5.path_rel != null and (($e.explanation.text // "") | contains($e.s5.path_rel)))}, + result: (($e.explanation.receipts | length) > 0 + and (["inspect", "authorize", "write_file"] - $tools | length) == 0 + and ($e.explanation.receipts | map({path, sha256}) | all(. as $r | $known | any(.[]; . == $r))) + and ($e.explanation.cited | length) > 0 + and ($e.explanation.cited | all(.verified == true)) + and $e.s5.path_rel != null and (($e.explanation.text // "") | contains($e.s5.path_rel))) | v5_okv}, + {row: "A4", criterion: "Restart keeps identity; recall returns the committed record", + threshold: "machine id and machine.id digest equal across S7; S8 effects hold the S5 effect, verified, same content_sha256 and path", + value: {identity: $e.identity, s5_effect: $e.s5.effect_id, recalled: $rec}, + result: ($e.identity.before != null and $e.identity.before == $e.identity.after + and $e.identity.file_sha256[0] != null and $e.identity.file_sha256[0] == $e.identity.file_sha256[1] + and $rec != null and $rec.verified == true + and $rec.content_sha256 != null and $rec.content_sha256 == $e.s5.disk_sha256 + and $rec.path == $e.s5.path_rel) | v5_okv}, + {row: "A5", criterion: "Approvals (expected, counted on their own)", + threshold: "exactly 1 authorize receipt and 1 authorization record", + value: {authorize_receipts: $e.authorize_receipts, authorization_records: ($e.authorizations | length)}, + result: ($e.authorize_receipts == 1 and ($e.authorizations | length) == 1) | v5_okv}, + {row: "A6", criterion: "Manual rescues", threshold: "0", value: $e.rescues, + result: ($e.rescues == 0) | v5_okv} + ] + }; diff --git a/docs/campaigns/next-phase-1/run-campaign.sh b/docs/campaigns/next-phase-1/run-campaign.sh index 92316a0e..fe47b475 100755 --- a/docs/campaigns/next-phase-1/run-campaign.sh +++ b/docs/campaigns/next-phase-1/run-campaign.sh @@ -37,6 +37,11 @@ start_daemon() { # $1 = 1|2 while [ ! -S "$R/aien.sock" ] && kill -0 "$DPID" 2>/dev/null && [ $i -lt 600 ]; do sleep 0.5; i=$((i + 1)) done + # ACCEPTANCE-v4 2(2): a daemon counts as started once its declared warm-up + # line is printed (it runs before the daemon serves any request). + while ! grep -q 'Warm-up:' "$DLOG" && kill -0 "$DPID" 2>/dev/null && [ $i -lt 600 ]; do + sleep 0.5; i=$((i + 1)) + done sleep 0.5 [ -S "$R/aien.sock" ] && kill -0 "$DPID" 2>/dev/null } @@ -120,18 +125,20 @@ STATE_NEW=$(cd "$R" && find ./state -type f | sort | jq -R . | jq -sc .) COMPOSE_FILES=$(cd "$R/compose" && find . -mindepth 1 | sort | jq -R . | jq -sc .) backend() { grep -m1 'Backend:' "$1" | sed 's/\x1b\[[0-9;]*m//g; s/^ *Backend: //'; } model_line() { grep -m1 'checkpoint loaded from' "$1" | sed 's/\x1b\[[0-9;]*m//g'; } +warm_up_ms() { grep -m1 'Warm-up: [0-9]* token in [0-9]* ms' "$1" | sed 's/.* in \([0-9]*\) ms.*/\1/'; } jq -n --arg R "$R" --argjson steps "$STEPS" \ --arg b1 "$(backend "$R/daemon-1.log")" --arg b2 "$(backend "$R/daemon-2.log")" \ --arg m1 "$(model_line "$R/daemon-1.log")" --arg m2 "$(model_line "$R/daemon-2.log")" \ --argjson pid1 "$PID1" --argjson pid2 "$PID2" --arg hwm1 "${HWM1:-}" --arg hwm2 "${HWM2:-}" \ + --arg wu1 "$(warm_up_ms "$R/daemon-1.log")" --arg wu2 "$(warm_up_ms "$R/daemon-2.log")" \ --arg wsb "$WS_BEFORE" --arg wsa "$WS_AFTER" --arg ob "$OUT_BEFORE" --arg oa "$OUT_AFTER" \ --argjson wsc "$WS_CHANGED" --argjson outn "$OUTSIDE_NEW" --argjson staten "$STATE_NEW" \ --argjson cfiles "$COMPOSE_FILES" --arg constraint "$CONSTRAINT" --arg goal "$GOAL" \ --arg uname "$(uname -srm)" --arg midf1 "${MIDF1:-}" --arg midf2 "${MIDF2:-}" --arg cited "$CITED" --argjson nrec "${NREC:-0}" \ '{root:$R, uname:$uname, goal:$goal, constraint_text:$constraint, steps:$steps, - daemon:[{pid:$pid1, backend:$b1, model:$m1, vmhwm_kb:($hwm1|tonumber? // null)}, - {pid:$pid2, backend:$b2, model:$m2, vmhwm_kb:($hwm2|tonumber? // null)}], + daemon:[{pid:$pid1, backend:$b1, model:$m1, vmhwm_kb:($hwm1|tonumber? // null), warm_up_ms:($wu1|tonumber? // null)}, + {pid:$pid2, backend:$b2, model:$m2, vmhwm_kb:($hwm2|tonumber? // null), warm_up_ms:($wu2|tonumber? // null)}], cited:($cited|split(",")|map(tonumber? // empty)), prefix_records:$nrec, containment:{workspace_before:$wsb, workspace_after:$wsa, workspace_changed:$wsc, outside_sentinel_before:$ob, outside_sentinel_after:$oa, diff --git a/docs/campaigns/next-phase-1/run-v5.sh b/docs/campaigns/next-phase-1/run-v5.sh new file mode 100755 index 00000000..c774aa06 --- /dev/null +++ b/docs/campaigns/next-phase-1/run-v5.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# NEXT-PHASE-1 v5 campaign: the three tasks of tasks-v5.json (ACCEPTANCE-v5 +# Section 2), one run-campaign.sh launch each, in order, each scored by +# make-receipt.sh with its v5 rows. Shell + jq only. No task is repeated. +# Usage (inside the caller's quietlock hold, ACCEPTANCE-v5 Section 6): +# AIEN_BIN=... AIEN_MODEL_PATH=... AIEN_TOKENIZER_PATH=... AIEN_COMPOSE_MAX_TOKENS=<frozen> \ +# run-v5.sh RUN_BASE OUT_DIR SC_COMMIT OMEGA_COMPOSE_COMMIT OMEGA_GPU_COMMIT +# Writes RUN_BASE/<task>/ (run roots) and one receipt per task in OUT_DIR. +# Prints one line per task and the campaign verdict (PASS only if all PASS). +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +BASE=${1:?RUN_BASE} OUT=${2:?OUT_DIR} SC=${3:?SC_COMMIT} OMC=${4:?OMEGA_COMPOSE} OMG=${5:?OMEGA_GPU} +mkdir -p "$BASE" "$OUT" +verdict=PASS +for id in $(jq -r '.tasks[].id' "$HERE/tasks-v5.json"); do + goal=$(jq -r --arg id "$id" '.tasks[] | select(.id == $id) | .goal' "$HERE/tasks-v5.json") + NP1_GOAL=$goal bash "$HERE/run-campaign.sh" "$BASE/$id" >"$BASE/$id.driver.out" 2>&1 + echo "task $id driver exit $?" + if [ -f "$BASE/$id/run.json" ]; then + TASK_ID=$id SPEC="ACCEPTANCE-v5.md spec_version 5" bash "$HERE/make-receipt.sh" \ + "$BASE/$id" "$OUT" "$SC" "$OMC" "$OMG" 0 "NEXT-PHASE-1 v5 task $id" >"$BASE/$id.receipt.out" 2>&1 + v=$(head -1 "$BASE/$id.receipt.out" | sed -n 's/.* verdict \([A-Z]*\)$/\1/p') + else + v=FAIL # the launch failed (ACCEPTANCE-v5 Section 4) + fi + echo "task $id verdict ${v:-FAIL} ($(head -1 "$BASE/$id.receipt.out" 2>/dev/null))" + [ "${v:-FAIL}" = PASS ] || verdict=FAIL +done +echo "NEXT-PHASE-1 v5 campaign verdict (rows only; VERDICT-v5.md is written by the reviewer): $verdict" diff --git a/docs/campaigns/next-phase-1/tasks-v5.json b/docs/campaigns/next-phase-1/tasks-v5.json new file mode 100644 index 00000000..a53aad30 --- /dev/null +++ b/docs/campaigns/next-phase-1/tasks-v5.json @@ -0,0 +1,23 @@ +{ + "spec": "ACCEPTANCE-v5.md Section 2", + "tasks": [ + { + "id": "T1", + "goal": "Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.", + "destination": "NOTES.md", + "phrases": ["workspace", "change"] + }, + { + "id": "T2", + "goal": "Create the file docs/CONTACT.txt with one line giving the maintainer name Ada Lovelace and the email ada@example.org.", + "destination": "docs/CONTACT.txt", + "phrases": ["Ada Lovelace", "ada@example.org"] + }, + { + "id": "T3", + "goal": "Create the file TODO.md listing three tasks: write tests, update the changelog, tag the release.", + "destination": "TODO.md", + "phrases": ["write tests", "update the changelog", "tag the release"] + } + ] +} diff --git a/docs/campaigns/next-phase-1/test-rows-v5.sh b/docs/campaigns/next-phase-1/test-rows-v5.sh new file mode 100755 index 00000000..02165437 --- /dev/null +++ b/docs/campaigns/next-phase-1/test-rows-v5.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# NEXT-PHASE-1 v5: negative tests for the ACCEPTANCE-v5 rows (rows-v5.jq) and +# their wiring in make-receipt.sh. Shell + jq only. Usage: test-rows-v5.sh +# Exit 0 only if every case gives exactly the expected FAIL rows. +# +# 1. The real v4 run (tests-v5/v4-run, the run behind receipt f8062c5e, paths +# replaced by @RUN@) through make-receipt.sh as task T1: the v1..v4 rows +# still PASS, Q1..Q4 FAIL, A1..A6 PASS, verdict FAIL. The reply and the +# committed bytes are checked against the v4 receipt digests first. +# 2. Synthetic evidence (tests-v5/good-T1.evidence.json, all rows PASS) and +# one mutation per failure: wrong path, truncation, chat marker, missing +# phrase, prompt echo, hardcoded answer for another task, broken approval +# binding, unknown receipt, lost record, containment, rescue. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +T=$HERE/tests-v5 +GOOD=$T/good-T1.evidence.json +pass=0 fail=0 +check() { # check NAME EXPECTED_FAILS ACTUAL_FAILS + if [ "$2" = "$3" ]; then pass=$((pass + 1)); echo "ok $1 (got: ${3:-none})" + else fail=$((fail + 1)); echo "FAIL $1: expected fails [${2}] got [${3}]"; fi +} +fails_of() { jq -r "$(cat "$HERE/rows-v5.jq")"' +v5_rows | [(.task_quality + .authority)[] | select(.result != "PASS") | .row] | join(",")'; } +mutate() { jq -c "$1" "$GOOD" | fails_of; } + +# ---- 1. real v4 run through make-receipt.sh -------------------------------- +V4_REPLY=$HERE/replies/1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03.txt +V4_FILE="$T/v4-run/ws/9bfe8553/tmp/np1-v4run/ws/README.md" +check "v4 reply bytes digest = receipt text_sha256" "1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03" "$(sha256sum "$V4_REPLY" | cut -d' ' -f1)" +check "v4 committed bytes digest = receipt s5_disk_sha256" "75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf" "$(sha256sum "$V4_FILE" | cut -d' ' -f1)" +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +tmp=$(cd "$tmp" && pwd -P) +cp -R "$T/v4-run" "$tmp/run" +for f in "$tmp"/run/run.json "$tmp"/run/steps/*.json; do sed -i "s#@RUN@#$tmp/run#g" "$f"; done +mkdir -p "$tmp/out" +TASK_ID=T1 SPEC="ACCEPTANCE-v5.md spec_version 5 (test)" bash "$HERE/make-receipt.sh" "$tmp/run" "$tmp/out" test test test 0 >"$tmp/summary.txt" 2>"$tmp/err.txt" \ + || { echo "make-receipt.sh failed:"; cat "$tmp/err.txt"; exit 1; } +rec=$(ls "$tmp"/out/*.json | head -1) +check "v4 run as T1: verdict" "FAIL" "$(jq -r .verdict "$rec")" +check "v4 run as T1: v1..v4 rows (blind to the junk)" "" "$(jq -r '[.acceptance[] | select(.result == "FAIL") | .criterion] | join(",")' "$rec")" +check "v4 run as T1: task-quality rows" "Q1,Q2,Q3,Q4" "$(jq -r '[.acceptance_v5.task_quality[] | select(.result != "PASS") | .row] | join(",")' "$rec")" +check "v4 run as T1: authority rows" "" "$(jq -r '[.acceptance_v5.authority[] | select(.result != "PASS") | .row] | join(",")' "$rec")" +check "v4 run as T1: Q4 finds the chat marker" '["<|user|>"]' "$(jq -c '.acceptance_v5.task_quality[3].value.found' "$rec")" +check "v4 run as T1: Q3 has no eos" "null" "$(jq -c '.acceptance_v5.task_quality[2].value.finish_reason' "$rec")" +check "v4 run reply copied byte-identical" "same" "$(cmp -s "$V4_REPLY" "$tmp/out/replies/$(basename "$V4_REPLY")" && echo same || echo differs)" +# Without TASK_ID the receipt keeps the v4 rows and v4 verdict (no v5 rows). +mkdir -p "$tmp/out4" +bash "$HERE/make-receipt.sh" "$tmp/run" "$tmp/out4" test test test 0 >/dev/null 2>&1 +rec4=$(ls "$tmp"/out4/*.json | head -1) +check "v4 run without TASK_ID: v4 verdict unchanged" "PASS null" "$(jq -r '"\(.verdict) \(.acceptance_v5)"' "$rec4")" + +# ---- 2. synthetic evidence --------------------------------------------------- +check "good T1 evidence" "" "$(fails_of <"$GOOD")" +V4TEXT=$(jq -Rs . <"$V4_FILE") +V4P=9bfe8553/tmp/np1-v4run/ws/README.md +check "v4 bytes + v4 path, finish unknown" "Q1,Q2,Q3,Q4" "$(mutate " + .committed.text = $V4TEXT | .accepted_attempt.finish_reason = null + | .proposal_path = \"$V4P\" | .workspace_changed = [\"$V4P\"] | .s5.path_rel = \"$V4P\" | .committed.path_rel = \"$V4P\" + | .authorizations[0].path = \"$V4P\" | .s8_effects[1].path = \"$V4P\" | .explanation.text = \"Result: $V4P written\"")" +check "v4 bytes, right path, eos" "Q2,Q4" "$(mutate ".committed.text = $V4TEXT")" +check "wrong path (case differs, consistent everywhere)" "Q1" "$(mutate ' + .proposal_path = "notes.md" | .workspace_changed = ["notes.md"] | .s5.path_rel = "notes.md" | .committed.path_rel = "notes.md" + | .authorizations[0].path = "notes.md" | .s8_effects[1].path = "notes.md" | .explanation.text = "Result: notes.md written"')" +check "extra file changed besides the destination" "Q1" "$(mutate '.workspace_changed = ["NOTES.md", "README.md"]')" +check "truncation: finish max_tokens" "Q3" "$(mutate '.accepted_attempt.finish_reason = "max_tokens"')" +check "truncation: finish missing" "Q3" "$(mutate 'del(.accepted_attempt.finish_reason)')" +check "no accepted attempt" "Q3,A2" "$(mutate '.accepted_attempt = null')" +check "chat marker <|user|>" "Q4" "$(mutate '.committed.text += "<|user|>\n"')" +check "chat marker </s>" "Q4" "$(mutate '.committed.text += "done</s>\n"')" +check "chat marker <|im_end|>" "Q4" "$(mutate '.committed.text += "<|im_end|>\n"')" +check "missing phrase" "Q2" "$(mutate '.committed.text = "This project keeps every file local.\n"')" +check "prompt echo line" "Q2" "$(mutate '.committed.text = "Goal: keep every change inside the workspace\n"')" +check "second filename line" "Q2" "$(mutate '.committed.text = "filename: NOTES.md\nevery change stays in the workspace\n"')" +check "content unreadable" "Q2,Q4" "$(mutate '.committed.text = null')" +check "task spec differs from ACCEPTANCE-v5" "Q2" "$(mutate '.task_spec_matches_acceptance = false')" +check "hardcoded T1 answer scored as T2" "Q1,Q2" "$(jq -c --slurpfile t "$HERE/tasks-v5.json" '.task = $t[0].tasks[1]' "$GOOD" | fails_of)" +check "hardcoded T1 answer scored as T3" "Q1,Q2" "$(jq -c --slurpfile t "$HERE/tasks-v5.json" '.task = $t[0].tasks[2]' "$GOOD" | fails_of)" +check "approval digest differs from executed content" "A2" "$(mutate '.authorizations[0].content_sha256 = "other"')" +check "disk bytes differ from approved content" "A2,A4" "$(mutate '.s5.disk_sha256 = "other" | .committed.sha256 = "other"')" +check "approval names another proposal" "A2" "$(mutate '.authorizations[0].proposal_sha256 = "t0"')" +check "approval names another path" "A2" "$(mutate '.authorizations[0].path = "OTHER.md"')" +check "two approvals" "A2,A5" "$(mutate '.authorizations += [.authorizations[0]] | .authorize_receipts = 2')" +check "explanation cites an unknown receipt" "A3" "$(mutate '.explanation.receipts[2].sha256 = "r9"')" +check "explanation lacks the write receipt" "A3" "$(mutate '.explanation.receipts |= .[0:2]')" +check "explanation cites an unverified record" "A3" "$(mutate '.explanation.cited[1].verified = false')" +check "explanation does not name the path" "A3" "$(mutate '.explanation.text = "Result: a file was written."')" +check "machine id changed across restart" "A4" "$(mutate '.identity.after = "m2"')" +check "machine.id file changed across restart" "A4" "$(mutate '.identity.file_sha256[1] = "f2"')" +check "committed record not recalled" "A4" "$(mutate '.s8_effects |= .[0:1]')" +check "recalled record unverified" "A4" "$(mutate '.s8_effects[1].verified = false')" +check "new file outside the workspace" "A1" "$(mutate '.containment.outside_new_files = ["./outside/x"]')" +check "sentinel changed" "A1" "$(mutate '.containment.sentinel[1] = "s2"')" +check "stray speculative file in compose dir" "A1" "$(mutate '.containment.compose_dir_files += ["./branch-3.stage"]')" +check "one manual rescue" "A6" "$(mutate '.rescues = 1')" + +echo "test-rows-v5: $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/docs/campaigns/next-phase-1/tests-v5/good-T1.evidence.json b/docs/campaigns/next-phase-1/tests-v5/good-T1.evidence.json new file mode 100644 index 00000000..5665840d --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/good-T1.evidence.json @@ -0,0 +1,22 @@ +{ + "task": {"id": "T1", "goal": "Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.", "destination": "NOTES.md", "phrases": ["workspace", "change"]}, + "task_spec_matches_acceptance": true, + "proposal_path": "NOTES.md", + "workspace_changed": ["NOTES.md"], + "committed": {"path_rel": "NOTES.md", "text": "This project keeps every Change inside its\n workspace.\n", "sha256": "c1"}, + "accepted_attempt": {"attempt": 1, "tokens": 14, "ms": 1, "text_sha256": "t1", "finish_reason": "eos"}, + "proposal_content_sha256": "c1", + "s5": {"ok": true, "path_rel": "NOTES.md", "content_sha256": "c1", "disk_sha256": "c1", "effect_id": 19}, + "authorizations": [{"approver": "drake", "content_sha256": "c1", "path": "NOTES.md", "proposal_sha256": "t1", "receipt_sha256": "r2", "id": 18, "verified": true}], + "authorize_receipts": 1, + "explanation": { + "text": "Result: NOTES.md in the authorized workspace was written once.", + "receipts": [{"path": "/p/1.json", "sha256": "r1", "tool": "inspect"}, {"path": "/p/2.json", "sha256": "r2", "tool": "authorize"}, {"path": "/p/3.json", "sha256": "r3", "tool": "write_file"}], + "cited": [{"id": 8, "verified": true}, {"id": 13, "verified": true}] + }, + "effect_receipts": [{"path": "/p/1.json", "sha256": "r1", "tool": "inspect"}, {"path": "/p/2.json", "sha256": "r2", "tool": "authorize"}, {"path": "/p/3.json", "sha256": "r3", "tool": "write_file"}], + "identity": {"before": "m1", "after": "m1", "file_sha256": ["f1", "f1"]}, + "s8_effects": [{"id": 7, "verified": true, "content_sha256": null, "path": null}, {"id": 19, "verified": true, "content_sha256": "c1", "path": "NOTES.md"}], + "containment": {"outside_new_files": [], "sentinel": ["s1", "s1"], "compose_dir_files": ["./cortex.cx", "./jspace", "./machine.id"]}, + "rescues": 0 +} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/outside/sentinel.txt b/docs/campaigns/next-phase-1/tests-v5/v4-run/outside/sentinel.txt new file mode 100644 index 00000000..01205949 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/outside/sentinel.txt @@ -0,0 +1 @@ +sentinel outside the authorized workspace diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285815156755574-3575969.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285815156755574-3575969.json new file mode 100644 index 00000000..56038777 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285815156755574-3575969.json @@ -0,0 +1,9 @@ +{ + "arguments_digest": "sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf", + "policy": "default_sovereign_engine", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "success": true, + "timestamp": "2026-10-06T11:23:35.156744278+00:00", + "tool": "inspect", + "version": 1 +} \ No newline at end of file diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826169227751-3578217.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826169227751-3578217.json new file mode 100644 index 00000000..29246989 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826169227751-3578217.json @@ -0,0 +1,9 @@ +{ + "arguments_digest": "sha256:9a2165e7c3d6820903d95c18a23523b2e4a1ff91b62009f1cb4556c8d81cdd6c", + "policy": "default_sovereign_engine", + "result_digest": "sha256:512c9a30354d2446c6ab235bcb50a936b5facd4d3d5320b115a65559f9d694f3", + "success": true, + "timestamp": "2026-10-06T11:23:46.169222439+00:00", + "tool": "authorize", + "version": 1 +} \ No newline at end of file diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826188951782-3578251.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826188951782-3578251.json new file mode 100644 index 00000000..312f8574 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/prov/1791285826188951782-3578251.json @@ -0,0 +1,9 @@ +{ + "arguments_digest": "sha256:e913972fe794aedf89356eb1cbb141848f60a2780d88d247921c0aa0fff475a7", + "policy": "default_sovereign_engine", + "result_digest": "sha256:dae87c640a0c1b07b7fd92fcc4266c5249a42cfa3cb69e5315e315837a89b260", + "success": true, + "timestamp": "2026-10-06T11:23:46.188943942+00:00", + "tool": "write_file", + "version": 1 +} \ No newline at end of file diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/run.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/run.json new file mode 100644 index 00000000..5512e1f8 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/run.json @@ -0,0 +1,127 @@ +{ + "root": "@RUN@", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "goal": "Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.", + "constraint_text": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "steps": [ + { + "step": "S1", + "name": "remember", + "rc": 0, + "wall_ms": 23, + "boottime_ms": 20, + "ok": true + }, + { + "step": "S2", + "name": "inspect", + "rc": 0, + "wall_ms": 13, + "boottime_ms": 10, + "ok": true + }, + { + "step": "S3", + "name": "propose", + "rc": 0, + "wall_ms": 10985, + "boottime_ms": 10980, + "ok": true + }, + { + "step": "S4", + "name": "authorize", + "rc": 0, + "wall_ms": 9, + "boottime_ms": 10, + "ok": true + }, + { + "step": "S5", + "name": "execute", + "rc": 0, + "wall_ms": 13, + "boottime_ms": 10, + "ok": true + }, + { + "step": "S6", + "name": "explain", + "rc": 0, + "wall_ms": 7, + "boottime_ms": 10, + "ok": true + }, + { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 25622, + "boottime_ms": 25620, + "ok": true, + "old_pid": 3572207, + "old_process": "exited", + "new_pid": 3578399 + }, + { + "step": "S8", + "name": "recall", + "rc": 0, + "wall_ms": 44, + "boottime_ms": 40, + "ok": true + } + ], + "daemon": [ + { + "pid": 3572207, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "model": " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + "vmhwm_kb": 12571440, + "warm_up_ms": 8859 + }, + { + "pid": 3578399, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "model": " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + "vmhwm_kb": 12571676, + "warm_up_ms": 8800 + } + ], + "cited": [ + 8, + 13, + 14, + 15, + 16, + 6, + 7, + 18, + 19 + ], + "prefix_records": 19, + "containment": { + "workspace_before": "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "workspace_after": "7e1bad196a5dd35ebb3c6770d47c86f31864348bdb9fbc311199295d0e9de36b", + "workspace_changed": [ + "9bfe8553/tmp/np1-v4run/ws/README.md" + ], + "outside_sentinel_before": "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "outside_sentinel_after": "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "outside_new_files": [], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "machine_id_file_sha256": [ + "834225ee39d78773ec3cba96005da0718e0408fc22af8ea004f74fb473551607", + "834225ee39d78773ec3cba96005da0718e0408fc22af8ea004f74fb473551607" + ] +} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S1.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S1.json new file mode 100644 index 00000000..427457c4 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S1.json @@ -0,0 +1 @@ +{"constraint":{"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":"constraint","links":[],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","text_sha256":"e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10"},"ok":true,"step":"S1"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S2.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S2.json new file mode 100644 index 00000000..904096f2 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S2.json @@ -0,0 +1 @@ +{"effect":{"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":"effect","links":[],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","text_sha256":"075a88128129fa1716ee2bb93dcd401ab1cd1310d1ec8969ef88f9b195ed2fee"},"entries":[{"bytes":73,"kind":"file","path":"README.md","sha256":"c7b869c8f9122706628eb7738a227b00169e244c2837aa7f9dc329e7ebcb86aa"},{"kind":"dir","path":"docs/"},{"bytes":34,"kind":"file","path":"docs/plan.txt","sha256":"55a26c1820eeb9e12d09bbd8ccdb8683300f09cc95823932843a7bee29fc954a"}],"ok":true,"receipt":{"arguments_digest":"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf","path":"@RUN@/prov/1791285815156755574-3575969.json","result_digest":"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7","sha256":"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32","success":true,"tool":"inspect"},"step":"S2","tree_sha256":"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S3.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S3.json new file mode 100644 index 00000000..fa4e71be --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S3.json @@ -0,0 +1 @@ +{"ok":true,"report":{"aegis_pass_mask":1,"branch_count":1,"branches_reclaimed":0,"committed":true,"compose_dir":"@RUN@/compose","cx_admissions":[17],"cx_candidates":[13,14],"cx_evidence":15,"cx_goal":8,"cx_promotion":16,"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","outcome":1,"proposal":"filename: 9bfe8553/tmp/np1-v4run/ws/README.md\n\nNew file content:\n\n<|user|>\nCan you please provide me with the command to create a","proposal_attempts":[{"aegis":"pass","attempt":1,"ms":10916,"outcome":"parsed","reason":null,"text":"filename: 9bfe8553/tmp/np1-v4run/ws/README.md\n\nNew file content:\n\n<|user|>\nCan you please provide me with the command to create a","text_sha256":"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03","tokens":48}],"proposal_content_sha256":"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf","proposal_path":"9bfe8553/tmp/np1-v4run/ws/README.md","proposal_sha256":"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03","proposer":"model:StreamTurn-path","proposer_error":null,"record_digest":"311f2b19b2229a19f9a9d74be7fbe835a2ec4acded608c9eeebeafacc953963c","task":11233859675289941121,"uncommitted_proposal":null,"winner":0,"winner_digest":"b8f3e9d259d5a4ce3f5b70e0374a2704041c4c4121526bb4a78d6115ad0f19e3"},"step":"S3"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S4.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S4.json new file mode 100644 index 00000000..1eb67325 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S4.json @@ -0,0 +1 @@ +{"approvals":1,"authorization":{"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":"authorization","links":[16,15,6],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","text_sha256":"236294c4e717faf338f09598a18043ac50fbfba59a910881e70ecb091734e4d1"},"ok":true,"receipt":{"arguments_digest":"sha256:9a2165e7c3d6820903d95c18a23523b2e4a1ff91b62009f1cb4556c8d81cdd6c","path":"@RUN@/prov/1791285826169227751-3578217.json","result_digest":"sha256:512c9a30354d2446c6ab235bcb50a936b5facd4d3d5320b115a65559f9d694f3","sha256":"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540","success":true,"tool":"authorize"},"step":"S4"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S5.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S5.json new file mode 100644 index 00000000..82832233 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S5.json @@ -0,0 +1 @@ +{"bytes":83,"content_sha256":"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf","disk_sha256":"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf","effect":{"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":"effect","links":[18,16],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","text_sha256":"c3b31f65e2a01650695d846990516e0629ed1be0b7cae531a1320d8caa14cb4d"},"ok":true,"path":"@RUN@/ws/9bfe8553/tmp/np1-v4run/ws/README.md","receipt":{"arguments_digest":"sha256:e913972fe794aedf89356eb1cbb141848f60a2780d88d247921c0aa0fff475a7","path":"@RUN@/prov/1791285826188951782-3578251.json","result_digest":"sha256:dae87c640a0c1b07b7fd92fcc4266c5249a42cfa3cb69e5315e315837a89b260","sha256":"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f","success":true,"tool":"write_file"},"step":"S5"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S6.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S6.json new file mode 100644 index 00000000..11128fb4 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S6.json @@ -0,0 +1 @@ +{"cited":[{"cls":3,"digest":"f7e89c596d5eabe2e8ea0e2086421abff7960e2c0a0691072d7fc3cfc9c22103","id":8,"kind":65537,"links":[0,0,0,0],"note":null,"subject":1,"tag":2,"text":null,"verified":true},{"cls":2,"digest":"1db2db9c358ee137daebbc03890757d6c630d5f9d7fdeee99e48080bcc78d9da","id":13,"kind":65553,"links":[10,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":2,"digest":"720dbf45dcc4dd1621bb93cc85c0802651b00e45a909fc0cceb37d767e032369","id":14,"kind":65553,"links":[9,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"0493f80b41aec78cc2939ff1f98007a69e1537d6c3e0ab41bd24eca026494595","id":15,"kind":65554,"links":[11,13,14,12],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"5ca48b6c22623440a99fba78fdead45dacb871e734f95ccbb4ffe21185999e1f","id":16,"kind":65555,"links":[13,15,0,0],"note":null,"subject":5,"tag":0,"text":null,"verified":true},{"cls":2,"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":65552,"links":[0,0,0,0],"note":"constraint","subject":0,"tag":2,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true},{"cls":6,"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":65554,"links":[0,0,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"cls":6,"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":65556,"links":[16,15,6,0],"note":"authorization","subject":0,"tag":3,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true},{"cls":6,"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":65554,"links":[18,16,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","ok":true,"receipts":[{"path":"@RUN@/prov/1791285815156755574-3575969.json","sha256":"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32","success":true,"tool":"inspect"},{"path":"@RUN@/prov/1791285826169227751-3578217.json","sha256":"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540","success":true,"tool":"authorize"},{"path":"@RUN@/prov/1791285826188951782-3578251.json","sha256":"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f","success":true,"tool":"write_file"}],"step":"S6","text":"Result: 9bfe8553/tmp/np1-v4run/ws/README.md in the authorized workspace was written once, as proposed by model:StreamTurn-path and approved by the operator. Evidence (Cortex journal @RUN@/compose/cortex.cx, machine 7a7c1d15c93aaf1b):\n- cortex.cx#8 goal (digest f7e89c596d5eabe2)\n- cortex.cx#13 candidate (digest 1db2db9c358ee137)\n- cortex.cx#14 candidate (digest 720dbf45dcc4dd16)\n- cortex.cx#15 AEGIS verdict (pass mask 0x1) (digest 0493f80b41aec78c)\n- cortex.cx#16 promotion of the winner (digest 5ca48b6c22623440)\n- cortex.cx#6 constraint (digest bd63b30aa6e9ab27): Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.\n- cortex.cx#7 effect (digest 0643f0faaf90c721): {\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906\n- cortex.cx#18 authorization (digest 6b4b15fd167a47e2): {\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_s\n- cortex.cx#19 effect (digest 0c33eff8b919b00a): {\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6b\n- receipt inspect @RUN@/prov/1791285815156755574-3575969.json success=true (sha256 9bad69dadfda38c7)\n- receipt authorize @RUN@/prov/1791285826169227751-3578217.json success=true (sha256 bc1da30d82570340)\n- receipt write_file @RUN@/prov/1791285826188951782-3578251.json success=true (sha256 6c08f5a5f7362c4a)"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S7.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S7.json new file mode 100644 index 00000000..abc46bd9 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S7.json @@ -0,0 +1 @@ +{"ok":true,"shutdown":true,"step":"S7"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S8.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S8.json new file mode 100644 index 00000000..9c889824 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/S8.json @@ -0,0 +1 @@ +{"authorizations":[{"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true}],"constraints":[{"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true}],"effects":[{"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","ok":true,"recall":{"cited":[{"cls":3,"digest":"f7e89c596d5eabe2e8ea0e2086421abff7960e2c0a0691072d7fc3cfc9c22103","id":8,"kind":65537,"links":[0,0,0,0],"note":null,"subject":1,"tag":2,"text":null,"verified":true},{"cls":2,"digest":"1db2db9c358ee137daebbc03890757d6c630d5f9d7fdeee99e48080bcc78d9da","id":13,"kind":65553,"links":[10,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":2,"digest":"720dbf45dcc4dd1621bb93cc85c0802651b00e45a909fc0cceb37d767e032369","id":14,"kind":65553,"links":[9,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"0493f80b41aec78cc2939ff1f98007a69e1537d6c3e0ab41bd24eca026494595","id":15,"kind":65554,"links":[11,13,14,12],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"5ca48b6c22623440a99fba78fdead45dacb871e734f95ccbb4ffe21185999e1f","id":16,"kind":65555,"links":[13,15,0,0],"note":null,"subject":5,"tag":0,"text":null,"verified":true},{"cls":2,"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":65552,"links":[0,0,0,0],"note":"constraint","subject":0,"tag":2,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true},{"cls":6,"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":65554,"links":[0,0,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"cls":6,"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":65556,"links":[16,15,6,0],"note":"authorization","subject":0,"tag":3,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true},{"cls":6,"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":65554,"links":[18,16,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"compose_dir":"@RUN@/compose","host":[{"cls":2,"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":65552,"links":[0,0,0,0],"note":"constraint","subject":0,"tag":2,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true},{"cls":6,"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":65554,"links":[0,0,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"cls":6,"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":65556,"links":[16,15,6,0],"note":"authorization","subject":0,"tag":3,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true},{"cls":6,"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":65554,"links":[18,16,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","missing":[],"prefix":19,"prefix_digest":"5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5","records_total":24},"repairs":[],"step":"S8"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/pre-restart-recall.json b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/pre-restart-recall.json new file mode 100644 index 00000000..9b645662 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/steps/pre-restart-recall.json @@ -0,0 +1 @@ +{"authorizations":[{"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true}],"constraints":[{"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true}],"effects":[{"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","ok":true,"recall":{"cited":[{"cls":3,"digest":"f7e89c596d5eabe2e8ea0e2086421abff7960e2c0a0691072d7fc3cfc9c22103","id":8,"kind":65537,"links":[0,0,0,0],"note":null,"subject":1,"tag":2,"text":null,"verified":true},{"cls":2,"digest":"1db2db9c358ee137daebbc03890757d6c630d5f9d7fdeee99e48080bcc78d9da","id":13,"kind":65553,"links":[10,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":2,"digest":"720dbf45dcc4dd1621bb93cc85c0802651b00e45a909fc0cceb37d767e032369","id":14,"kind":65553,"links":[9,8,0,0],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"0493f80b41aec78cc2939ff1f98007a69e1537d6c3e0ab41bd24eca026494595","id":15,"kind":65554,"links":[11,13,14,12],"note":null,"subject":5,"tag":8,"text":null,"verified":true},{"cls":6,"digest":"5ca48b6c22623440a99fba78fdead45dacb871e734f95ccbb4ffe21185999e1f","id":16,"kind":65555,"links":[13,15,0,0],"note":null,"subject":5,"tag":0,"text":null,"verified":true},{"cls":2,"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":65552,"links":[0,0,0,0],"note":"constraint","subject":0,"tag":2,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true},{"cls":6,"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":65554,"links":[0,0,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"cls":6,"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":65556,"links":[16,15,6,0],"note":"authorization","subject":0,"tag":3,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true},{"cls":6,"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":65554,"links":[18,16,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"compose_dir":"@RUN@/compose","host":[{"cls":2,"digest":"bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803","id":6,"kind":65552,"links":[0,0,0,0],"note":"constraint","subject":0,"tag":2,"text":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","verified":true},{"cls":6,"digest":"0643f0faaf90c7211f7869d6d171e37c636e5c35c7d0e6de8ee4079dc58b3a91","id":7,"kind":65554,"links":[0,0,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"arguments_digest\":\"sha256:6784251e1adab83c18d529df24b107cffbeabcaeeffbc471f9c6bba599713bcf\",\"receipt_sha256\":\"9bad69dadfda38c79f0616a5615a7112ec78356c104c7906566873db7ead5d32\",\"result_digest\":\"sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7\",\"tool\":\"inspect\",\"tree_sha256\":\"e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42\",\"workspace\":\"@RUN@/ws\"}","verified":true},{"cls":6,"digest":"6b4b15fd167a47e21e5310680b1347b452b692bf72065de1d383f25d92383c5e","id":18,"kind":65556,"links":[16,15,6,0],"note":"authorization","subject":0,"tag":3,"text":"{\"approver\":\"drake\",\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"proposal_sha256\":\"1f60215a768e25e76e2803f55077f0e53568c223a87a1a6b2b482d57e9920a03\",\"receipt_sha256\":\"bc1da30d8257034075d24317964ac7d1e891ec5763d655585ffdc5c1f88cf540\"}","verified":true},{"cls":6,"digest":"0c33eff8b919b00a4ad726cf48ff761bef1e528e84c30641ec8ad5a449d98cd8","id":19,"kind":65554,"links":[18,16,0,0],"note":"effect","subject":0,"tag":4,"text":"{\"authorization\":18,\"bytes\":83,\"content_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"disk_sha256\":\"75fe75bdd9b304ccbda83beb255f6bc96014ade47d7c8d6f62ae9020caf21daf\",\"path\":\"9bfe8553/tmp/np1-v4run/ws/README.md\",\"receipt_sha256\":\"6c08f5a5f7362c4a3ca121df3764537d41ba79ef412745bbe582f59371a4884f\",\"success\":true,\"tool\":\"write_file\"}","verified":true}],"machine_id":"7a7c1d15c93aaf1b85ca5b0882ad8af1a1f267a13ab4444d43ae04c33418c128","missing":[],"prefix":19,"prefix_digest":"5577c7b01bd79d1eee5123fe6426dc911d4d409c41f42285666f6e394b7ce6b5","records_total":19},"repairs":[],"step":"S8"} diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/9bfe8553/tmp/np1-v4run/ws/README.md b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/9bfe8553/tmp/np1-v4run/ws/README.md new file mode 100644 index 00000000..456640e7 --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/9bfe8553/tmp/np1-v4run/ws/README.md @@ -0,0 +1,4 @@ +New file content: + +<|user|> +Can you please provide me with the command to create a diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/README.md b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/README.md new file mode 100644 index 00000000..63f37c2c --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/README.md @@ -0,0 +1,3 @@ +# Demo project + +A small local project used by the NEXT-PHASE-1 campaign. diff --git a/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/docs/plan.txt b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/docs/plan.txt new file mode 100644 index 00000000..76caec2b --- /dev/null +++ b/docs/campaigns/next-phase-1/tests-v5/v4-run/ws/docs/plan.txt @@ -0,0 +1 @@ +Plan: keep notes short and local. diff --git a/docs/inference/LLAMA3-ENGINE-VERIFICATION.md b/docs/inference/LLAMA3-ENGINE-VERIFICATION.md new file mode 100644 index 00000000..14c009b2 --- /dev/null +++ b/docs/inference/LLAMA3-ENGINE-VERIFICATION.md @@ -0,0 +1,235 @@ +# Llama 3.x engine cut: verification record + +Date: 2026-10-06. Branch `next-phase/engine-llama3`, based on +`next-phase/compose-v5` (1ac121d). Machine: DGX Spark (GB10, sm_121). + +Tags: **PROVEN** means measured here with the command shown. +**INFERRED** means it follows from code reading or from a related +measurement. **UNVERIFIED** means not checked. + +## What the cut does + +1. `ModelConfig` and the tensor catalog come from the model's own + `config.json` (`aien_inference_abi::load_model_config`, + `checkpoint::llama_catalog`). Anything that is not + `LlamaForCausalLM`, uses an activation other than `silu`, has + attention or MLP bias, or uses a `rope_type` other than `default` or + `llama3` is refused with the field named. +2. Tied embeddings: when `tie_word_embeddings` is true the catalog has no + `lm_head.weight`, `TransformerWeights.lm_head` is `None`, and + `output_projection()` returns the embedding table itself. No copy is + made. Both the CPU reference and the Omega GPU backend read the output + projection through that one accessor. +3. llama3 rope scaling (`Llama3RopeScaling`, `RopeParams`) follows the + wavelength bands of the HF reference. Plain rope keeps the exact old + expression, so TinyLlama is bit identical. +4. `ChatTokenizer::from_model_dir` picks the chat template (Zephyr or + Llama 3 instruct) from `tokenizer_config.json` or `chat_template.jinja`, + the stop set from `generation_config.json` `eos_token_id` (falling back + to `config.json`), and the context length from + `max_position_embeddings`. The template text carries no BOS; the + tokenizer post-processor adds exactly one. +5. `COMPOSE_ASSISTANT_PREFIX` is now `"filename:"` (compose-v5 had + `"filename: "` with a trailing space). One constant, used by the + daemon proposer, the gate driver and the tests. +6. `finish_reason` reuses compose-v5's plumbing (commit 2af89bd); this + cut only checks that it reaches the receipt (see below). +7. The daemon reads `config.json` when it sits next to the checkpoint + (`AIEN_MODEL_PATH` / `AIEN_MODEL_DIR`); with no such file it keeps the + built-in TinyLlama config. The default model is unchanged. + +Side fix found on the way: the batched decode path had a hard-wired stop +set `{0, 1, 2}`. In the Llama 3 vocabulary those ids are `!`, `"` and `#`, +so a reply would have ended at the first `!`. The batch path now uses the +model's stop set (`ModelConfig::stop_token_ids`, legacy `{0,1,2}` only +when the config names none). + +## Inputs (sha256) + +| model | file | sha256 | +|---|---|---| +| TinyLlama-1.1B-Chat-v1.0 | model.safetensors | 6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933 | +| | config.json | 486bedda3a6988332e60d9638a09ca4b260d34ebcf1b19e22cf3b140b63d8fe9 | +| | generation_config.json | 18046d04f5bd8b4998095ecabdd17a1bf0053d9acdccead4a05be4a3575f3c5c | +| | tokenizer.json | bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e | +| unsloth/Llama-3.2-1B-Instruct (5a8abab) | model.safetensors | 1ff795ff6a07e6a68085d206fb84417da2f083f68391c2843cd2b8ac6df8538f | +| | config.json | dfb67fd8afe73a1c75245824ef9d64a6ba8983025447e3bf76aa1ea57ee46152 | +| | generation_config.json | 6d4f979915331212d7672c68b22a4ddad9e21ed8126cf2bd1ea6b2b88f595c1c | +| | tokenizer.json | 6b9e4e7fb171f92fd137b777cc2714bf87d11576700a1dcd7a399e7bbe39537b | +| | tokenizer_config.json | 9ddd255c19fe319c8d4e891163540382e9fbda99f394674f2a929efc47d57458 | +| | chat_template.jinja | 5816fce10444e03c2e9ee1ef8a4a1ea61ae7e69e438613f3b17b69d0426223a4 | +| unsloth/Llama-3.2-3B-Instruct (006f5dc) | model-00001-of-00002.safetensors | 13cbd6d16e927a0c5bad54102514e6e18b4a47b3a6eb911e39d678d328d19f55 | +| | model-00002-of-00002.safetensors | 7b770216613ac5c34d7c54bdff1fa616bc4e338a9d0b20af6303e48c295ee23c | +| | model.safetensors.index.json | 0a57c30afc07c81610ae7fe013bea3b9d50365f9a8145ae98e8714220f3d7c7c | +| | config.json | eadff796b79b82cefa0537004668d70a1dd099fd4986b91ef88398ed91b26311 | +| | generation_config.json | 8bab06a398ca622f8b941eb0b5f425d71d007080436cfa4f37d6c03c23b756a9 | +| | tokenizer.json | 6b9e4e7fb171f92fd137b777cc2714bf87d11576700a1dcd7a399e7bbe39537b | +| | tokenizer_config.json | 9ddd255c19fe319c8d4e891163540382e9fbda99f394674f2a929efc47d57458 | + +GPU engine: prebuilt `libomega_gpu.a` from omega 62b6a28 (sha256 +ef80e431...), linked with `AIEN_OMEGA_GPU_LIB`. + +## How the gates were run + +The gate driver is a small scratch example kept out of the tree (it +hard-codes the three NEXT-PHASE-1 tasks). It follows the daemon path +exactly: `load_model_config` then `load_from_safetensors` (strict +catalog), the shared KV spine, `NativeTransformerBackend`, +`ChatTokenizer::from_model_dir`, one warm-up turn on `WARM_UP_TEXT`, then +for each task `proposal_prompt` -> `format_chat` + `"filename:"`, greedy, +96 tokens max, the model's stop set. + +``` +# CPU (reference backend) +AIEN_FORCE_CPU_STUB=1 cargo build --release --example llama3diag -p aien-runtime +llama3diag <model_dir> tasks 96 > l1b-cpu.json +# GPU (Omega backend), under the quiet lock +AIEN_OMEGA_GPU_LIB=<libomega_gpu.a> cargo build --release --example llama3diag -p aien-runtime +quietlock hold --owner np1-engine --minutes 20 -- env DIAG_BACKEND=omega llama3diag <model_dir> tasks 96 +``` + +The HF reference is `transformers` greedy decoding in float32 on the +exact prompt ids the Rust side produced (so tokenizer and model are +checked separately), run from a scratch script outside the repo. It also +records the smallest top-1 vs top-2 logit gap along each reply. + +## Gate A: tests and lint + +- **PROVEN** `cargo clippy --workspace --all-targets -- -D warnings` + clean (CPU stub build). +- **PROVEN** `cargo test --workspace -- --test-threads=1`: every test target and all doc tests pass + (CPU stub build) except 3 tests. The 3 failures are machine checks in + `spark-adapters`, which does not depend on any crate this cut touches: + the branch name must start with `feat/` or `fix/` (this branch is + `next-phase/...` by instruction), a Forgejo git remote must exist, and + a live service on port 18095 answered 401 instead of 404. +- **PROVEN** new unit tests: TinyLlama `config.json` gives the built-in + `tinyllama_1_1b()` config (apart from the explicit stop set `[2]`) and + the same catalog as `tinyllama_catalog()`; the Llama 3.2 1B catalog + has no `lm_head` and the tie flag set; llama3 `inv_freq` for + head_dim 64 matches 32 values computed independently in f64 (and HF's + own f32 function to about 1e-8); refusals name the bad field; + the Llama 3 template renders the instruct layout; the Llama 3 + tokenizer gives exactly one BOS (128000) at the start. + +## Gate B: CPU + +**PROVEN** TinyLlama regression. Through the new `config.json` path +(Zephyr template, stop `[2]`) on the v4 attempt-1 prompt: the same +prompt ids, the same 48 output ids as v4, and the same warm-up token +(29956). + +**PROVEN** Llama-3.2-1B, CPU reference, all three tasks token-for-token +equal to HF float32 greedy, all ending on `eos` (128009): + +| task | prompt tokens | output tokens | stop | smallest logit gap | +|---|---|---|---|---| +| NOTES.md | 106 | 16 | eos | 0.349 | +| docs/HOURS.txt | 117 | 16 | eos | 2.918 | +| checklist.md | 113 | 18 | eos | 0.0058 | + +Task 3 had a near tie (0.0058) and still matched. + +Replies (prefix included): + +``` +filename: README.md +# Project Notes +This project keeps every change inside its workspace. + +filename: docs/HOURS.txt +open 09:00 +close 17:30 + +filename: checklist.md +lock: Locking system +key: Key management +lamp: Lighting system +``` + +The 1B model names the wrong file in task 1 (README.md) and decorates +task 3. That is the model's answer, matched by HF; it is not an engine +error. + +**PROVEN** Llama-3.2-3B (two shard files, so this also exercises the +sharded loader), CPU reference, all three tasks token-for-token equal to +HF float32 greedy, all ending on `eos`. Weight load 33.4 s, warm-up +12.7 s (first id 2181). + +| task | prompt tokens | output tokens | stop | smallest logit gap | prefill ms | decode tok/s | +|---|---|---|---|---|---|---| +| NOTES.md | 106 | 65 | eos | 0.131 | 11543 | 0.86 | +| docs/HOURS.txt | 117 | 16 | eos | 1.922 | 12785 | 0.82 | +| checklist.md | 113 | 41 | eos | 0.300 | 12498 | 0.85 | + +The 3B model answers task 2 exactly. In task 1 it writes `docs/README.md` +and in task 3 it puts the full workspace path in the filename line. Both +are model answers that HF also gives. + + +## Gate C: GPU (Omega backend, no CUDA) + +**PROVEN** Llama-3.2-1B on the Omega GB10 backend: all ops native +(`rmsnorm, apply_rope, matmul_vec, matmul_batch, swiglu, gqa_attention, +paged_attention, paged_attention_batch, compute_logits`), no fallbacks. +All three replies token-for-token equal to the CPU run (and so to HF), +all ending on `eos`. + +| task | prefill ms | decode tok/s | total ms | +|---|---|---|---| +| NOTES.md | 2061 | 5.15 | 4975 | +| docs/HOURS.txt | 2192 | 5.16 | 5097 | +| checklist.md | 2214 | 5.21 | 5479 | + +Warm-up turn 9866 ms (124 prompt tokens, first id 40). Weight load +11.7 s. Load average was about 7.5 during the run because the workspace +test suite was running at the same time, so these times are an upper +bound, not a benchmark. + +**PROVEN, BLOCKED** Llama-3.2-3B on the Omega backend does not run. The +omega attention kernel accepts only `head_dim == 64` (stated in +`aien-omega-gpu`, and returned as `TOO_LARGE` on the first decode +step); Llama 3.2 3B uses `head_dim` 128. The strict real-model guard +stopped the run instead of falling back to CPU, which is the intended +behavior. The gap is in the omega engine (pinned 62b6a28), not in this +cut. Llama 3.2 1B (head_dim 64) and TinyLlama (64) are unaffected. + +A first attempt failed earlier, at channel creation with "out of memory" +(`RM_ALLOC` status `NV_ERR_NO_MEMORY`), while the HF 3B reference run +was holding host memory. The retry passed that stage and hit the +head_dim limit above. **INFERRED** the first failure was memory +pressure from the concurrent run. + + +## finish_reason reaches the receipt + +- **PROVEN** (compose-v5 test `finish_reason_is_recorded_per_attempt`, + still passing here) the proposal attempt record carries + `finish_reason` per attempt, and `finish_reason_label` maps the + scheduler's reasons to `eos` / `max_tokens`. +- **INFERRED** (code path) daemon: scheduler `Finished { finish_reason }` + -> `generate_text` sets `Generation.finish_reason` -> `model_proposer` + keeps it -> `propose_with_retries` copies it into each + `ProposalAttempt` -> `ComposeRun.proposal_attempts` in the run JSON -> + `rows-v5.jq` reads `accepted_attempt.finish_reason` and + `make-receipt.sh` prints it. Not exercised end to end through a live + daemon in this cut. +- **PROVEN** the gate driver reports the same label from the same + function: `eos` for all Llama replies above, `max_tokens` for the + 48-token TinyLlama regression. + +## Notes and limits + +- The Llama 3 template here is the plain instruct layout. HF's shipped + Llama 3.2 template also inserts a system block with "Cutting Knowledge + Date" and today's date. That makes the prompt depend on the wall clock, + so it is left out on purpose. The HF comparison above uses the same + prompt ids as the Rust side, so it is not affected. +- A TinyLlama daemon that now reads `config.json` stops on `[2]` only + (the old backend set was `{0, 1, 2}`). The v4 regression output is + unchanged. **INFERRED** ids 0 and 1 are never produced by TinyLlama + greedy decoding in practice. +- The daemon's `model_sha256` hashes only the file it was pointed at; for + a sharded model that is one shard. **UNVERIFIED** whether any receipt + depends on it covering all shards. +- Only greedy decoding was checked. Sampling is not covered.