diff --git a/.crumb b/.crumb index f89f348f..085bd9c0 100644 --- a/.crumb +++ b/.crumb @@ -65,7 +65,7 @@ "children": [ { "digest": "2ee39207bb3a0f0466731ae4e9adbe2063cd8b4f82456a1c2b3fd7588974a557", - "last_commit": "19549b0", + "last_commit": "003784e", "name": "scripts", "purpose": "" }, @@ -77,14 +77,14 @@ } ], "children_root": "sha256:285ca7eafbe46d808ebe5e4fb533e464bfdf0fedaf3eef486ac2e2c8826baf6f", - "compiled_at": "2026-10-08T13:07:13Z", + "compiled_at": "2026-10-08T15:05:23Z", "compiler": "crumb-compile/1", - "digest": "sha256:fa03dfcea50b3119665d76176631edeb792ec89ccebc5b8f5256dc7e9f5f4121", + "digest": "sha256:e9907f62d09e3e92df5f54662063735d53bd2737d8eac1e08d9fd39b6b7d8084", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1594, - "generated_at_commit": "e6a0bf74914fcc3eaf7547f88398ea3bb0c48054", - "source_tree": "sha256:2e1c0bc765ab0483542fb82c70f6e796bc4a598eb33441cc9f5ac5a36d9db9c6" + "files": 1595, + "generated_at_commit": "6852c48c0b0007fc193be3d67de7fdbd41c5e1c2", + "source_tree": "sha256:2bc55c64c7718d347430227c0f981a350577b1ee1a1a3d37bc1ca6a56d8a1e36" } }, "history": [], diff --git a/crates/aien-abi-core/src/lib.rs b/crates/aien-abi-core/src/lib.rs index ff67dd75..91d18e1d 100644 --- a/crates/aien-abi-core/src/lib.rs +++ b/crates/aien-abi-core/src/lib.rs @@ -470,6 +470,47 @@ impl Default for SamplingParams { } } +/// How a backend actually chose the tokens of one request, counted at the +/// point of choice, never read back from the request's `SamplingParams` +/// (Qwen3 v4 review, sc#294: greedy decoding must be observed, not only +/// documented). Evidence only: no scheduling or decoding decision reads it. +/// +/// Counts every token the backend chose for the request: the token after the +/// final prefill chunk (a mid-prompt chunk's discarded pick is not counted) +/// and every decode token, the stop token included. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct DecodeObservation { + /// Tokens taken as the argmax of the logits (greedy). + pub greedy_tokens: u64, + /// Tokens drawn at random from the temperature-scaled distribution. + pub sampled_tokens: u64, + /// Temperature of the sampled draws (the last draw's). None when no draw sampled. + pub temperature: Option, + /// top_p of the sampled decode draws when nucleus filtering was applied + /// (`0 < top_p < 1`). None when no draw applied it. + pub top_p: Option, + /// The request id the sampled draws were seeded from (the stream is a + /// pure function of it and the position). None when no draw sampled. + pub seed_request_id: Option, +} + +// Temperatures recorded here passed through the sampler, which never sees a +// NaN from the runtime; equality is used only to compare records. +impl Eq for DecodeObservation {} + +impl DecodeObservation { + /// "greedy" (every chosen token was the argmax), "sampled" (every one was + /// drawn), "mixed", or "none" (no token was chosen). + pub fn mode(&self) -> &'static str { + match (self.greedy_tokens > 0, self.sampled_tokens > 0) { + (true, false) => "greedy", + (false, true) => "sampled", + (true, true) => "mixed", + (false, false) => "none", + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SequenceRequest { pub request_id: u64, @@ -567,4 +608,12 @@ pub trait AienInferenceBackend: Send + Sync { fn release_sequence(&mut self, _seq_id: u64) -> Result<(), String> { Ok(()) } + + /// Takes (and forgets) how the backend chose `request_id`'s tokens so + /// far. The scheduler calls it once, when the request finishes, and + /// attaches it to `CompletionEvent::Finished`. Default: None, for a + /// backend that does not observe its decoding (an absent claim, not greedy). + fn take_decode_observation(&mut self, _request_id: u64) -> Option { + None + } } diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 4bffa9a3..0c5dcce0 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -6,8 +6,8 @@ use crate::mojo_backend::MojoGb10Backend; use crate::tensor::{sample_argmax, sample_temperature}; use crate::weights::{LayerKvCache, SequenceState, TransformerWeights}; use crate::{ - AienInferenceBackend, AienUsageReceipt, BranchHandle, ContextHandle, DecodeOutput, - FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics, + AienInferenceBackend, AienUsageReceipt, BranchHandle, ContextHandle, DecodeObservation, + DecodeOutput, FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics, }; use aien_kv_cache::{ create_shared_kv_manager_with_pool, AienKvManager, KvDType, KvPoolConfig, SharedKvManager, @@ -54,9 +54,25 @@ pub fn decode_sampling_seed(request_id: u64, position: usize) -> u64 { /// /// Returns the token and its log-probability under the kept distribution. pub fn sample_with_params(logits: &[f32], params: &SamplingParams, seed: u64) -> (u32, f32) { + sample_with_params_observed(logits, params, seed, &mut DecodeObservation::default()) +} + +/// `sample_with_params` that also counts, inside the branch it takes, how the +/// token was chosen (sc#294): greedy, or a draw at `temperature` (with +/// `top_p` when nucleus filtering ran). The seed's request id is the caller's +/// to record. The chosen token is identical to `sample_with_params`. +pub fn sample_with_params_observed( + logits: &[f32], + params: &SamplingParams, + seed: u64, + obs: &mut DecodeObservation, +) -> (u32, f32) { if params.temperature <= 0.001 { + obs.greedy_tokens += 1; return sample_argmax(logits); } + obs.sampled_tokens += 1; + obs.temperature = Some(params.temperature); assert!(!logits.is_empty(), "Logits cannot be empty"); let inv_t = 1.0f64 / params.temperature as f64; let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v)) as f64; @@ -72,6 +88,7 @@ pub fn sample_with_params(logits: &[f32], params: &SamplingParams, seed: u64) -> let mut kept: Vec = (0..probs.len()).collect(); let top_p = params.top_p as f64; if top_p > 0.0 && top_p < 1.0 { + obs.top_p = Some(params.top_p); kept.sort_by(|&a, &b| { probs[b] .partial_cmp(&probs[a]) @@ -123,6 +140,32 @@ pub struct NativeTransformerBackend { /// decode (or fork) commits it. While a request is prefilling, `tokens.len()` /// therefore always equals the number of positions whose K/V is cached. pub pending_prefill_token: HashMap, + /// How each request's tokens were actually chosen (sc#294), filled inside the + /// branch that chose them and taken once by the scheduler when the request + /// finishes (`take_decode_observation`). + decode_observed: HashMap, +} + +/// Per-request tally behind `DecodeObservation` (sc#294). The pick after a +/// prefill chunk is held apart and replaced by the next chunk's, like +/// `pending_prefill_token`, so a mid-prompt pick that is discarded is not counted. +#[derive(Debug, Default)] +struct DecodeTally { + prefill_pick: DecodeObservation, + decode: DecodeObservation, +} + +impl DecodeTally { + fn merged(self) -> DecodeObservation { + let (p, d) = (self.prefill_pick, self.decode); + DecodeObservation { + greedy_tokens: p.greedy_tokens + d.greedy_tokens, + sampled_tokens: p.sampled_tokens + d.sampled_tokens, + temperature: d.temperature.or(p.temperature), + top_p: d.top_p.or(p.top_p), + seed_request_id: d.seed_request_id.or(p.seed_request_id), + } + } } impl NativeTransformerBackend { @@ -132,6 +175,7 @@ impl NativeTransformerBackend { weights, sequences: HashMap::new(), sampling: HashMap::new(), + decode_observed: HashMap::new(), tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: None, pending_prefill_token: HashMap::new(), @@ -147,6 +191,7 @@ impl NativeTransformerBackend { weights, sequences: HashMap::new(), sampling: HashMap::new(), + decode_observed: HashMap::new(), tensor_backend, kv_manager: None, pending_prefill_token: HashMap::new(), @@ -205,6 +250,7 @@ impl NativeTransformerBackend { weights, sequences: HashMap::new(), sampling: HashMap::new(), + decode_observed: HashMap::new(), tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), @@ -231,6 +277,7 @@ impl NativeTransformerBackend { weights, sequences: HashMap::new(), sampling: HashMap::new(), + decode_observed: HashMap::new(), tensor_backend, kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), @@ -247,6 +294,7 @@ impl NativeTransformerBackend { weights, sequences: HashMap::new(), sampling: HashMap::new(), + decode_observed: HashMap::new(), tensor_backend, kv_manager: Some(kv_manager), pending_prefill_token: HashMap::new(), @@ -565,6 +613,7 @@ impl NativeTransformerBackend { pub fn release_sequence(&mut self, seq_id: u64) { self.sequences.remove(&seq_id); self.pending_prefill_token.remove(&seq_id); + self.decode_observed.remove(&seq_id); if let Some(kv_mgr) = &self.kv_manager { let _ = kv_mgr.write().release_branch(seq_id); } @@ -1645,12 +1694,21 @@ impl NativeTransformerBackend { // PREFILL-E2E C6: the request's own sampling params (recorded at // prefill or by the fork hook), seeded per request and position. // No params, or temperature 0: argmax as before. + // sc#294: counted inside the branch taken. + let obs = &mut self.decode_observed.entry(seq_id).or_default().decode; let (sampled_tok, logprob) = match self.sampling.get(&seq_id) { Some(params) => { let seed = decode_sampling_seed(seq_id, pos + 1); - sample_with_params(logits, params, seed) + let picked = sample_with_params_observed(logits, params, seed, obs); + if obs.sampled_tokens > 0 { + obs.seed_request_id = Some(seq_id); + } + picked + } + None => { + obs.greedy_tokens += 1; + sample_argmax(logits) } - None => sample_argmax(logits), }; if let Some(seq) = self.sequences.get_mut(&seq_id) { @@ -1683,6 +1741,7 @@ impl AienInferenceBackend for NativeTransformerBackend { self.sequences.clear(); self.sampling.clear(); self.pending_prefill_token.clear(); + self.decode_observed.clear(); Ok(()) } @@ -1807,9 +1866,19 @@ impl AienInferenceBackend for NativeTransformerBackend { self.pending_prefill_token.remove(&seq_id); // PREFILL-E2E C6: the per-request sampling params entry goes too. self.sampling.remove(&seq_id); + self.decode_observed.remove(&seq_id); Ok(()) } + /// sc#294: how this request's tokens were chosen, counted inside the + /// sampling branch taken (`sample_with_params_observed` and the prefill + /// pick); removed once taken. + fn take_decode_observation(&mut self, request_id: u64) -> Option { + self.decode_observed + .remove(&request_id) + .map(DecodeTally::merged) + } + async fn execute_step( &mut self, batch: &ScheduledBatch, @@ -1857,11 +1926,22 @@ impl AienInferenceBackend for NativeTransformerBackend { let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &last_hidden); + // sc#294: this chunk's pick replaces the previous chunk's (only the + // final chunk's pick is kept, like `pending_prefill_token`). + let mut pick = DecodeObservation::default(); let (sampled_tok, logprob) = if req.sampling_params.temperature <= 0.001 { + pick.greedy_tokens = 1; sample_argmax(&logits) } else { + pick.sampled_tokens = 1; + pick.temperature = Some(req.sampling_params.temperature); + pick.seed_request_id = Some(req.request_id); sample_temperature(&logits, req.sampling_params.temperature, req.request_id) }; + self.decode_observed + .entry(req.request_id) + .or_default() + .prefill_pick = pick; // Not pushed to `seq.tokens`: if another chunk of this prompt follows, the // next prefill call replaces this sample; otherwise the first decode @@ -2249,4 +2329,166 @@ mod tests { async fn c3_chunked_prefill_execute_step_paged() { c3_execute_step_chunked(true).await; } + + /// sc#294: prefill in chunks, then `decodes` decode steps, through + /// `execute_step` (the scheduler path). Returns the observation the + /// scheduler would take at finish and the chosen tokens after the prompt. + async fn sc294_run(params: SamplingParams, decodes: usize) -> (DecodeObservation, Vec) { + use crate::SequenceRequest; + let prompt = c3_prompt(); + let id = 11u64; + let batch = |prefill: Vec, decode: Vec| ScheduledBatch { + prefill_requests: prefill, + decode_requests: decode, + block_tables: HashMap::new(), + step_id: 0, + }; + let mut b = c3_backend(false); + for chunk in prompt.chunks(C3_CHUNK) { + let req = SequenceRequest { + request_id: id, + prompt_tokens: chunk.to_vec(), + sampling_params: params.clone(), + arrival_time_ns: 0, + priority: 0, + }; + b.execute_step(&batch(vec![req], vec![])).await.unwrap(); + } + for _ in 0..decodes { + b.execute_step(&batch(vec![], vec![id])).await.unwrap(); + } + let chosen = b.sequences[&id].tokens[C3_PROMPT_LEN..].to_vec(); + let obs = b.take_decode_observation(id).expect("observed"); + assert_eq!(b.take_decode_observation(id), None, "taken once"); + (obs, chosen) + } + + /// Greedy request: every chosen token is counted as greedy, the + /// discarded mid-prompt picks are not, and nothing claims sampling. + #[tokio::test] + async fn sc294_greedy_request_is_observed_greedy() { + const { + assert!( + C3_PROMPT_LEN > C3_CHUNK, + "prompt must take more than one chunk" + ) + }; + let greedy = SamplingParams { + temperature: 0.0, + ..Default::default() + }; + let (obs, chosen) = sc294_run(greedy, 3).await; + // 1 pick after the final prefill chunk (committed by the first decode) + // plus 3 decode picks; the last decode's pick is pushed too. + assert_eq!(chosen.len(), 4); + assert_eq!(obs.greedy_tokens, 4); + assert_eq!(obs.sampled_tokens, 0); + assert_eq!(obs.mode(), "greedy"); + assert_eq!( + (obs.temperature, obs.top_p, obs.seed_request_id), + (None, None, None) + ); + } + + /// Sampling request: every token is counted as drawn, with the + /// temperature, the top_p the decode draws applied, and the seed's request id. + #[tokio::test] + async fn sc294_sampled_request_is_observed_sampled() { + let sampled = SamplingParams { + temperature: 0.7, + top_p: 0.95, + ..Default::default() + }; + let (obs, _) = sc294_run(sampled, 3).await; + assert_eq!(obs.sampled_tokens, 4); + assert_eq!(obs.greedy_tokens, 0); + assert_eq!(obs.mode(), "sampled"); + assert_eq!(obs.temperature, Some(0.7)); + assert_eq!(obs.top_p, Some(0.95)); + assert_eq!(obs.seed_request_id, Some(11)); + } + + /// Observing never changes the chosen token: the same token and logprob + /// as `sample_with_params`, greedy and sampled, over many seeds. + #[test] + fn sc294_observing_does_not_change_the_choice() { + let logits: Vec = (0..64).map(|i| ((i * 37 % 64) as f32) * 0.1).collect(); + for temperature in [0.0f32, 0.0005, 0.3, 0.7, 1.5] { + for top_p in [0.0f32, 0.5, 0.95, 1.0] { + let p = SamplingParams { + temperature, + top_p, + ..Default::default() + }; + for seed in 0..50u64 { + let seed = decode_sampling_seed(seed, 3); + let mut o = DecodeObservation::default(); + assert_eq!( + sample_with_params(&logits, &p, seed), + sample_with_params_observed(&logits, &p, seed, &mut o) + ); + } + } + } + } + + /// A decoding request with no recorded sampling params takes the argmax + /// arm of decode; those picks are counted as greedy too. + #[tokio::test] + async fn sc294_decode_without_params_is_observed_greedy() { + use crate::SequenceRequest; + let id = 7u64; + let mut b = c3_backend(false); + let req = SequenceRequest { + request_id: id, + prompt_tokens: c3_prompt()[..4].to_vec(), + sampling_params: SamplingParams { + temperature: 0.0, + ..Default::default() + }, + arrival_time_ns: 0, + priority: 0, + }; + let batch = |prefill: Vec, decode: Vec| ScheduledBatch { + prefill_requests: prefill, + decode_requests: decode, + block_tables: HashMap::new(), + step_id: 0, + }; + b.execute_step(&batch(vec![req], vec![])).await.unwrap(); + b.sampling.remove(&id); + for _ in 0..2 { + b.execute_step(&batch(vec![], vec![id])).await.unwrap(); + } + let obs = b.take_decode_observation(id).expect("observed"); + assert_eq!((obs.greedy_tokens, obs.sampled_tokens), (3, 0)); + assert_eq!(obs.mode(), "greedy"); + } + + /// A released or never-seen request has no observation. + #[tokio::test] + async fn sc294_release_drops_the_observation() { + use crate::SequenceRequest; + let mut b = c3_backend(false); + let req = SequenceRequest { + request_id: 5, + prompt_tokens: c3_prompt()[..4].to_vec(), + sampling_params: SamplingParams { + temperature: 0.0, + ..Default::default() + }, + arrival_time_ns: 0, + priority: 0, + }; + let batch = ScheduledBatch { + prefill_requests: vec![req], + decode_requests: vec![], + block_tables: HashMap::new(), + step_id: 0, + }; + b.execute_step(&batch).await.unwrap(); + AienInferenceBackend::release_sequence(&mut b, 5).unwrap(); + assert_eq!(b.take_decode_observation(5), None); + assert_eq!(b.take_decode_observation(6), None); + } } diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index e99a5b4e..d6841a23 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -737,6 +737,10 @@ pub struct ProposalAttempt { /// sha256 of the prompt ids, each 4 little-endian bytes (NEXT-PHASE-1 v6 R1). #[serde(default)] pub prompt_ids_sha256: Option, + /// How the backend chose this attempt's tokens (sc#294). None when the + /// call failed or nothing observed it; omitted from the JSON then. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub decoding: Option, /// Requirements of the goal this attempt's complete document failed /// (crate::requirements); empty when none failed or none were recognized. #[serde(default)] diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index 870dd05d..e020e5c8 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -2001,6 +2001,7 @@ mod tests { finish_reason: "eos", request_id: 7, operation_id: 8, + decoding: None, }, crate::generation::DaemonStart(1), ); diff --git a/crates/aien-runtime/src/generation.rs b/crates/aien-runtime/src/generation.rs index 34fd8874..817ffacd 100644 --- a/crates/aien-runtime/src/generation.rs +++ b/crates/aien-runtime/src/generation.rs @@ -36,6 +36,8 @@ pub struct TurnEvidence<'a> { /// Caller-supplied envelope ids (self-asserted by the client, no authority). pub request_id: u64, pub operation_id: u128, + /// How the backend chose the output tokens (sc#294); None: no claim. + pub decoding: Option<&'a aien_abi_core::DecodeObservation>, } /// When this daemon started: unix milliseconds, captured once. @@ -57,10 +59,42 @@ fn hex_sha256(bytes: &[u8]) -> String { aien_omega_compose::hex(&Sha256::digest(bytes)) } +/// An f32 setting as the JSON number it was written as (0.7, not 0.699999988). +fn f32_number(v: f32) -> Value { + v.to_string() + .parse::() + .ok() + .and_then(serde_json::Number::from_f64) + .map_or(Value::Null, Value::Number) +} + +/// Adds `decoding` (sc#294): how the backend chose the output tokens, counted +/// in the sampling branch it took, not read from the request's settings. The +/// field is left out when nothing observed it (a stub or a backend without the +/// observation): no field means no claim, never "greedy". +fn with_decoding(record: &mut Value, d: Option<&aien_abi_core::DecodeObservation>) { + let Some(d) = d else { return }; + let mut o = json!({ + "mode": d.mode(), + "greedy_tokens": d.greedy_tokens, + "sampled_tokens": d.sampled_tokens, + }); + if let Some(t) = d.temperature { + o["temperature"] = f32_number(t); + } + if let Some(p) = d.top_p { + o["top_p"] = f32_number(p); + } + if let Some(s) = d.seed_request_id { + o["seed_request_id"] = json!(s); + } + record["decoding"] = o; +} + /// The record's JSON body (field list is documented in docs/DAEMON_GENERATION_RECORD.md). pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> Value { let (pid, start_ticks) = crate::effects::self_executor(); - json!({ + let mut record = json!({ GENERATION: 1, "v": 1, "model_sha256": id.model_sha256, @@ -77,7 +111,9 @@ pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> // Caller-asserted: the client chooses the envelope ids; recorded, not trusted. "request_id": t.request_id, "operation_id": t.operation_id.to_string(), - }) + }); + with_decoding(&mut record, t.decoding); + record } /// Why an `effect`-class note carrying a `generation` marker, and not a new @@ -271,6 +307,8 @@ pub struct ComposeEvidence<'a> { /// The compose task and attempt (1-based) that made the generation. Daemon-assigned. pub task: u64, pub attempt: u32, + /// How the backend chose the output tokens (sc#294); None: no claim. + pub decoding: Option<&'a aien_abi_core::DecodeObservation>, } /// The generation record of one compose proposal attempt: the same fields as @@ -279,7 +317,7 @@ pub struct ComposeEvidence<'a> { /// compose task makes itself. pub fn build_compose_record(id: &ModelIdentity, e: &ComposeEvidence, start: DaemonStart) -> Value { let (pid, start_ticks) = crate::effects::self_executor(); - json!({ + let mut record = json!({ GENERATION: 1, "v": 1, "origin": "compose_proposal", @@ -298,5 +336,7 @@ pub fn build_compose_record(id: &ModelIdentity, e: &ComposeEvidence, start: Daem "daemon": {"pid": pid, "start_ticks": start_ticks, "started_unix_ms": start.0.to_string()}, "request_id": 0, "operation_id": "0", - }) + }); + with_decoding(&mut record, e.decoding); + record } diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 0518f226..25fe19db 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -534,7 +534,11 @@ async fn generate_text( loop { match events.recv().await { Some(CompletionEvent::Token { token, .. }) => produced.push(token), - Some(CompletionEvent::Finished { finish_reason, .. }) => { + Some(CompletionEvent::Finished { + finish_reason, + decoding, + .. + }) => { return tokenizer .decode_opts(&produced, true) .map(|text| crate::spine::Generation { @@ -544,6 +548,7 @@ async fn generate_text( token_ids: Some(produced.clone()), prompt_tokens: Some(prompt_ids.len()), prompt_ids_sha256: Some(crate::spine::token_ids_sha256(&prompt_ids)), + decoding: decoding.clone(), }) .map_err(|e| format!("tokenizer decode failed: {e}")); } @@ -640,6 +645,7 @@ struct GenerationOwned { finish_reason: &'static str, request_id: u64, operation_id: u128, + decoding: Option, } /// Write the daemon's generation record for a finished turn and return its @@ -665,6 +671,7 @@ async fn record_generation( finish_reason: g.finish_reason, request_id: g.request_id, operation_id: g.operation_id, + decoding: g.decoding.as_ref(), }, started, ); @@ -734,6 +741,7 @@ async fn stream_turn( Ok(Some(CompletionEvent::Finished { total_tokens, finish_reason, + decoding, .. })) => { let generation_record = record_generation( @@ -748,6 +756,7 @@ async fn stream_turn( finish_reason: finish_reason_label(&finish_reason), request_id, operation_id, + decoding, }, ) .await; @@ -1031,6 +1040,7 @@ mod generation_record_tests { finish_reason: "eos", request_id: 1, operation_id: 1, + decoding: None, } } diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 3a0fa6a3..3e80d88d 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -539,6 +539,10 @@ pub struct Generation { pub prompt_tokens: Option, /// NEXT-PHASE-1 v6 R1: `token_ids_sha256` of the submitted prompt ids. pub prompt_ids_sha256: Option, + /// How the backend chose the generated tokens (sc#294), as the scheduler + /// reported it when the sequence finished. None when the proposer or the + /// backend does not observe it: an absent claim, not greedy. + pub decoding: Option, } /// sha256 (hex) of token ids, each as 4 little-endian bytes (NEXT-PHASE-1 v6 @@ -1462,6 +1466,7 @@ fn new_attempt(k: u32) -> ProposalAttempt { token_ids: None, prompt_tokens: None, prompt_ids_sha256: None, + decoding: None, unmet_requirements: Vec::new(), } } @@ -1593,6 +1598,7 @@ pub fn propose_task_checked( a.token_ids = g.token_ids.clone(); a.prompt_tokens = g.prompt_tokens; a.prompt_ids_sha256 = g.prompt_ids_sha256.clone(); + a.decoding = g.decoding.clone(); a.text_sha256 = Some(hex(&Sha256::digest(g.text.as_bytes()))); a.text = Some(g.text.clone()); // NEXT-PHASE-1 v6 N2: a length-cut reply is refused before parsing. @@ -2312,6 +2318,7 @@ impl ComposeBridge { finish_reason: a.finish_reason.as_deref().unwrap_or("unknown"), task, attempt: a.attempt, + decoding: a.decoding.as_ref(), }, started, ); diff --git a/crates/aien-runtime/tests/decoding_observed_test.rs b/crates/aien-runtime/tests/decoding_observed_test.rs new file mode 100644 index 00000000..1ed3c935 --- /dev/null +++ b/crates/aien-runtime/tests/decoding_observed_test.rs @@ -0,0 +1,185 @@ +//! sc#294 (Qwen3 v4 review): greedy decoding must be OBSERVED, not only +//! documented. The real submission path the daemon uses (`submit_work` -> +//! scheduler -> `NativeTransformerBackend::execute_step`) reports, in +//! `CompletionEvent::Finished`, how the backend chose the tokens, counted in +//! the sampling branch it took. CPU reference tensors, micro model. +use aien_inference_abi::{ + DecodeObservation, MockInferenceBackend, ModelConfig, NativeTransformerBackend, + ReferenceCpuBackend, SamplingParams, TransformerWeights, +}; +use aien_kv_cache::{create_shared_kv_manager, SharedKvManager}; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::{ChannelCompletionSink, CompletionEvent, PromptHandle, SchedulerConfig}; +use std::sync::Arc; + +fn micro_config() -> ModelConfig { + ModelConfig { + model_id: "aien-micro-v1".to_string(), + max_sequence_length: 512, + block_size: 16, + num_layers: 2, + num_heads: 4, + head_dim: 16, + num_kv_heads: 2, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + rope_scaling: None, + tie_word_embeddings: false, + eos_token_ids: Vec::new(), + qk_norm: false, + } +} + +fn spine() -> (AienRuntimeSpine, SharedKvManager) { + let kv = create_shared_kv_manager(64, 16); + let cfg = SchedulerConfig { + max_batch_size: 16, + max_batch_tokens: 512, + max_prefill_tokens: 256, + prefill_chunk_size: 64, + chunk_prefill: true, + watermark_blocks: 4, + }; + (AienRuntimeSpine::new(64, cfg, kv.clone()), kv) +} + +/// Runs one request to completion; returns the streamed tokens, the +/// `Finished` decoding report and the sequence id. +async fn run( + spine: &mut AienRuntimeSpine, + backend: &mut B, + sampling: SamplingParams, +) -> (Vec, Option, u64) { + let (sink, mut rx) = ChannelCompletionSink::channel(); + let sink_id = spine.register_completion_sink(Arc::new(sink)); + let prompt: PromptHandle = Arc::from([1u32, 10, 25, 42].as_slice()); + let seq = spine + .submit_work(prompt, sampling, 1, Some(sink_id)) + .unwrap(); + spine.run_until_complete(backend, 40).await.unwrap(); + let (mut tokens, mut decoding, mut finished) = (Vec::new(), None, false); + while let Ok(event) = rx.try_recv() { + match event { + CompletionEvent::Token { token, .. } => tokens.push(token), + CompletionEvent::Finished { decoding: d, .. } => { + finished = true; + decoding = d; + } + CompletionEvent::Error { message, .. } => panic!("{message}"), + } + } + assert!(finished, "the request must finish"); + (tokens, decoding, seq) +} + +fn native(kv: SharedKvManager) -> NativeTransformerBackend { + NativeTransformerBackend::with_shared_kv_and_backend( + TransformerWeights::reference_test_weights(µ_config()), + Arc::new(ReferenceCpuBackend::new()), + kv, + ) +} + +/// Every token the backend chose was streamed, plus at most the final one +/// (a stop token is chosen but not streamed). +fn assert_counts_cover(tokens: &[u32], chosen: u64) { + let n = tokens.len() as u64; + assert!(n >= 1, "the request produced no token"); + assert!( + chosen == n || chosen == n + 1, + "backend chose {chosen} tokens, {n} were streamed" + ); +} + +#[tokio::test] +async fn greedy_request_reports_greedy_from_the_backend() { + let (mut spine, kv) = spine(); + let mut backend = native(kv); + let sampling = SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 5, + stop_token_ids: vec![], + }; + let (tokens, d, _) = run(&mut spine, &mut backend, sampling).await; + let d = d.expect("the native backend reports how it decoded"); + assert_eq!(d.mode(), "greedy", "{d:?}"); + assert_eq!(d.sampled_tokens, 0); + assert_counts_cover(&tokens, d.greedy_tokens); + assert_eq!( + (d.temperature, d.top_p, d.seed_request_id), + (None, None, None) + ); +} + +#[tokio::test] +async fn sampled_request_reports_sampling_from_the_backend() { + let (mut spine, kv) = spine(); + let mut backend = native(kv); + let sampling = SamplingParams { + temperature: 0.7, + top_p: 0.9, + max_tokens: 5, + stop_token_ids: vec![], + }; + let (tokens, d, seq) = run(&mut spine, &mut backend, sampling).await; + let d = d.expect("the native backend reports how it decoded"); + assert_eq!(d.mode(), "sampled", "{d:?}"); + assert_eq!(d.greedy_tokens, 0); + assert_counts_cover(&tokens, d.sampled_tokens); + assert_eq!(d.temperature, Some(0.7)); + assert_eq!(d.top_p, Some(0.9)); + assert_eq!(d.seed_request_id, Some(seq)); +} + +/// A backend that does not observe its decoding makes no claim: None, never +/// a default "greedy". +#[tokio::test] +async fn a_backend_without_the_observation_makes_no_claim() { + let (mut spine, _kv) = spine(); + let mut backend = MockInferenceBackend::new(1); + let sampling = SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 3, + stop_token_ids: vec![], + }; + let (_, d, _) = run(&mut spine, &mut backend, sampling).await; + assert_eq!(d, None); +} + +/// The record field: present with the backend's report, absent without one. +#[test] +fn record_field_matches_the_report_and_is_absent_without_one() { + let id = aien_runtime::generation::ModelIdentity { + model_sha256: "m".repeat(64), + model_path: "/m".into(), + tokenizer_sha256: "t".repeat(64), + tokenizer_path: "/t".into(), + }; + let report = DecodeObservation { + greedy_tokens: 4, + ..Default::default() + }; + let ev = |d| aien_runtime::generation::TurnEvidence { + prompt_ids: &[1, 2], + output_ids: &[3, 4, 5], + text: "abc", + total_tokens: 5, + finish_reason: "eos", + request_id: 1, + operation_id: 1, + decoding: d, + }; + let start = aien_runtime::generation::DaemonStart(1); + let with = aien_runtime::generation::build_record(&id, &ev(Some(&report)), start); + assert_eq!( + with["decoding"], + serde_json::json!({"mode": "greedy", "greedy_tokens": 4, "sampled_tokens": 0}) + ); + let without = aien_runtime::generation::build_record(&id, &ev(None), start); + assert!(without.get("decoding").is_none(), "{without}"); +} diff --git a/crates/aien-runtime/tests/generation_record_test.rs b/crates/aien-runtime/tests/generation_record_test.rs index abeac013..0090ed76 100644 --- a/crates/aien-runtime/tests/generation_record_test.rs +++ b/crates/aien-runtime/tests/generation_record_test.rs @@ -3,7 +3,10 @@ //! Socket-level, mock backend, toy tokenizer. Every test needs the linked //! composition archive and is IGNORED in a stub build, never passed (the //! no-record cases that hold in a stub build are unit tests in server.rs). -use aien_inference_abi::{ChatTokenizer, MockInferenceBackend}; +use aien_inference_abi::{ + AienInferenceBackend, ChatTokenizer, DecodeObservation, DecodeOutput, MockInferenceBackend, + ModelConfig, ScheduledBatch, StepMetrics, +}; use aien_kv_cache::create_shared_kv_manager; use aien_omega_compose::hex; use aien_runtime::client::AienRuntimeClient; @@ -62,6 +65,14 @@ async fn start(identity: Option) -> Daemon { } async fn start_with(identity: Option, tokenizer: ChatTokenizer) -> Daemon { + start_on(identity, tokenizer, MockInferenceBackend::new(1)).await +} + +async fn start_on( + identity: Option, + tokenizer: ChatTokenizer, + backend: B, +) -> Daemon { let tmp = tempfile::tempdir().unwrap(); let socket = tmp.path().join("runtime.sock"); let cfg = SchedulerConfig { @@ -85,7 +96,7 @@ async fn start_with(identity: Option, tokenizer: ChatTokenizer) - if let Some(id) = identity { server.set_model_identity(id); } - let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let handle = tokio::spawn(async move { server.run(backend).await }); let client = AienRuntimeClient::new(&socket); for _ in 0..200 { if client.is_alive().await { @@ -200,6 +211,9 @@ async fn record_carries_the_digests_of_the_turn() { )); assert_eq!(r["daemon"]["pid"], std::process::id()); assert!(r["daemon"]["started_unix_ms"].as_str().unwrap().len() > 8); + // sc#294: the mock backend observes nothing, so the record makes no + // decoding claim (absent, never a default "greedy"). + assert!(r.get("decoding").is_none(), "{r}"); // The envelope ids are the client's own, recorded as asserted. assert!(r["request_id"].as_u64().unwrap() > 0); assert!(r["operation_id"].as_str().unwrap().len() > 3); @@ -312,3 +326,63 @@ fn turn_finished_without_a_record_serializes_as_before() { .unwrap() .contains(r#""generation_record":9"#)); } + +/// The mock backend, plus a fixed report of how it decoded: stands in for a +/// backend that observes its sampling branch (sc#294). +struct ObservingMock { + inner: MockInferenceBackend, + report: DecodeObservation, +} + +#[async_trait::async_trait] +impl AienInferenceBackend for ObservingMock { + async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { + self.inner.load_model(config).await + } + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec, StepMetrics), String> { + self.inner.execute_step(batch).await + } + fn take_decode_observation(&mut self, _request_id: u64) -> Option { + Some(self.report.clone()) + } +} + +/// sc#294: the StreamTurn record states the decoding the backend reported at +/// finish (from `CompletionEvent::Finished`), not the request's temperature: +/// the client asks for 0.0 here and the backend reports sampling, so a record +/// built from the settings would say greedy. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn record_states_the_decoding_the_backend_reported() { + let _g = ONE_HOME.lock().await; + let report = DecodeObservation { + greedy_tokens: 1, + sampled_tokens: 3, + temperature: Some(0.7), + top_p: Some(0.95), + seed_request_id: Some(42), + }; + let backend = ObservingMock { + inner: MockInferenceBackend::new(1), + report, + }; + let d = start_on(Some(identity()), toy_tokenizer(), backend).await; + let (_, id) = d.turn("hello hello").await; + let r = d.record(id.expect("a record id")).await; + assert_eq!( + r["decoding"], + serde_json::json!({ + "mode": "mixed", + "greedy_tokens": 1, + "sampled_tokens": 3, + "temperature": 0.7, + "top_p": 0.95, + "seed_request_id": 42 + }), + "{r}" + ); + d.stop().await; +} diff --git a/crates/aien-runtime/tests/np1_v6_test.rs b/crates/aien-runtime/tests/np1_v6_test.rs index b36c0e10..d78aa910 100644 --- a/crates/aien-runtime/tests/np1_v6_test.rs +++ b/crates/aien-runtime/tests/np1_v6_test.rs @@ -77,6 +77,7 @@ fn token_ids_reach_the_attempt_record() { token_ids: Some(ids2.clone()), prompt_tokens: Some(p2.len()), prompt_ids_sha256: Some(token_ids_sha256(&p2)), + decoding: None, }) }; let (out, a) = propose_with_retries( diff --git a/crates/aien-runtime/tests/provenance_link_test.rs b/crates/aien-runtime/tests/provenance_link_test.rs index 7da01c16..d0b7dc6e 100644 --- a/crates/aien-runtime/tests/provenance_link_test.rs +++ b/crates/aien-runtime/tests/provenance_link_test.rs @@ -58,6 +58,14 @@ fn identity() -> ModelIdentity { } } +/// How the backend chose OUT_IDS: all greedy (sc#294). +fn greedy_observation() -> aien_inference_abi::DecodeObservation { + aien_inference_abi::DecodeObservation { + greedy_tokens: OUT_IDS.len() as u64, + ..Default::default() + } +} + /// The reply the real inference path gives: text, generated ids, prompt ids hash. fn proposer() -> ComposeProposer { Arc::new(|_p: &str, _l: Duration| { @@ -68,6 +76,8 @@ fn proposer() -> ComposeProposer { token_ids: Some(OUT_IDS.to_vec()), prompt_tokens: Some(PROMPT_IDS.len()), prompt_ids_sha256: Some(token_ids_sha256(&PROMPT_IDS)), + // sc#294: what the scheduler reports for a greedy run of these ids. + decoding: Some(greedy_observation()), }) }) } @@ -277,6 +287,12 @@ async fn assert_linked(d: &Daemon, f: &Flow, want_agent: &str) { assert_eq!(g["output_tokens"], OUT_IDS.len()); assert_eq!(g["finish_reason"], "eos"); assert_eq!(g["daemon"]["pid"], std::process::id()); + // sc#294: the decoding the backend reported travels into the record. + assert_eq!( + g["decoding"], + json!({"mode": "greedy", "greedy_tokens": OUT_IDS.len(), "sampled_tokens": 0}), + "{g}" + ); // The grant, intent and commit still say what they said before. assert_eq!( d.record(f.commit).await["proposal_sha256"], 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 8b83592b..7f296cc4 100644 --- a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs +++ b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs @@ -448,6 +448,7 @@ async fn test_end_to_end_ticket_submission_and_channel_streaming_cpu() { seq_id: sid, total_tokens, finish_reason, + .. } => { assert_eq!(sid.to_u64(), seq_id); saw_finished = true; diff --git a/crates/aien-scheduler/src/lib.rs b/crates/aien-scheduler/src/lib.rs index 654ad22c..74727048 100644 --- a/crates/aien-scheduler/src/lib.rs +++ b/crates/aien-scheduler/src/lib.rs @@ -1113,6 +1113,8 @@ impl AienScheduler { reason: finish_reason, total_tokens, }); + // sc#294: taken on every finish, listened to or not. + let decoding = backend.take_decode_observation(request_id); if let Some(sink_id) = finished_sink { self.completion_router.emit( sink_id, @@ -1120,6 +1122,7 @@ impl AienScheduler { seq_id, finish_reason, total_tokens, + decoding, }, ); } @@ -1146,6 +1149,8 @@ impl AienScheduler { let _ = self.kv_manager.write().free_sequence(request_id); self.arena.free_sequence(seq_id); self.metrics.finished_requests += 1; + // sc#294: taken on every finish, listened to or not. + let decoding = backend.take_decode_observation(request_id); if let Some(sink_id) = finished_sink { self.completion_router.emit( sink_id, @@ -1153,6 +1158,7 @@ impl AienScheduler { seq_id, finish_reason: reason, total_tokens, + decoding, }, ); } diff --git a/crates/aien-scheduler/src/sequence.rs b/crates/aien-scheduler/src/sequence.rs index 71b2208a..dcec6461 100644 --- a/crates/aien-scheduler/src/sequence.rs +++ b/crates/aien-scheduler/src/sequence.rs @@ -1,4 +1,4 @@ -use aien_abi_core::{FinishReason, SamplingParams, SequenceRequest}; +use aien_abi_core::{DecodeObservation, FinishReason, SamplingParams, SequenceRequest}; use aien_platform::{InferenceWork, KvHandle, ModelHandle, Priority, Ticks}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -85,6 +85,11 @@ pub enum CompletionEvent { seq_id: SequenceId, finish_reason: FinishReason, total_tokens: usize, + /// How the backend chose this sequence's tokens, taken from the backend + /// when the sequence finished (sc#294). None when the backend does not + /// observe its decoding: an absent claim, not greedy. + #[serde(default)] + decoding: Option, }, Error { seq_id: SequenceId, diff --git a/docs/DAEMON_GENERATION_RECORD.md b/docs/DAEMON_GENERATION_RECORD.md index 3bccd340..7fb648f7 100644 --- a/docs/DAEMON_GENERATION_RECORD.md +++ b/docs/DAEMON_GENERATION_RECORD.md @@ -30,11 +30,49 @@ An `effect`-class host note whose JSON has the marker field `generation`: | `output_text_sha256` | sha256 of the exact `text` returned in `TurnFinished` | | `total_tokens`, `output_tokens` | token count the engine reported; generated tokens | | `finish_reason` | `eos`, `max_tokens`, `aborted` or `preempted` | +| `decoding` | how the backend chose the output tokens (below); ABSENT when the backend did not report it | | `daemon` | `pid`, `start_ticks` (process start, clock ticks) and `started_unix_ms` | | `request_id`, `operation_id` | CALLER-ASSERTED: the request envelope's ids, exactly as the client sent them | The envelope ids are chosen by the client. They are recorded, not trusted (names kept to match the envelope fields). +### `decoding`: the decoding actually taken (sc#294) + +The Qwen3 v4 review found greedy decoding documented but not observed: no +record said which decoding a run used. `decoding` is that observation. The +native backend (`NativeTransformerBackend`) counts every token it chooses +inside the branch that chose it (`sample_with_params_observed` for decode, the +prefill pick in `execute_step`), and the scheduler takes the count when the +sequence finishes (`take_decode_observation`) and puts it in +`CompletionEvent::Finished.decoding`. The daemon copies it into the record. It +is never derived from the request's `temperature` or from any config file. + +| field | meaning | +|---|---| +| `mode` | `greedy` (every chosen token was the argmax), `sampled` (every one was a random draw), `mixed`, or `none` | +| `greedy_tokens`, `sampled_tokens` | how many chosen tokens took each branch | +| `temperature` | temperature of the sampled draws; only when a draw sampled | +| `top_p` | nucleus mass of the sampled decode draws; only when filtering ran (`0 < top_p < 1`) | +| `seed_request_id` | the backend request id the draws were seeded from; only when a draw sampled | + +There is no top-k: `SamplingParams` has none. Counted tokens are the pick +after the final prefill chunk (a mid-prompt pick that is discarded is not +counted) and every decode pick, the stop token included, so the count can be +one more than `output_tokens`. A swarm branch counts only its own decode picks. +A preempted request finishes once at the preemption (the scheduler takes its +count then); after it resumes, counting starts again, so a later record covers +only the tokens chosen after the resume. + +`decoding` is ABSENT, not `greedy`, when the backend does not observe its +decoding (the mock backend, a backend without the hook): an absent field is an +absent claim. A verifier that needs greedy decoding requires `decoding.mode == +"greedy"` and `decoding.sampled_tokens == 0` on every record. + +What it does not prove: like the rest of the record, it is the daemon's own +report, not signed. It covers the native backend's scheduler path +(`execute_step`); the standalone generation helpers (`generate_tokens*`) and +example binaries are not observed. + ## What it proves The daemon process with that pid and start time generated text with that