diff --git a/control-plane/src/harmony_family/tests.rs b/control-plane/src/harmony_family/tests.rs index b4073868..ca303937 100644 --- a/control-plane/src/harmony_family/tests.rs +++ b/control-plane/src/harmony_family/tests.rs @@ -1,6 +1,7 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). use super::*; +use leleka_tokenizer::gguf_bpe::SpecialIds; /// A tiny vocabulary: the byte tokens, a few merges, and the Harmony markers as control tokens. fn codec() -> GptOssCodec { @@ -21,7 +22,7 @@ fn codec() -> GptOssCodec { types.push(3); } let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); - GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], None, None, None).unwrap()).unwrap() + GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], SpecialIds::default()).unwrap()).unwrap() } /// Token ids for a script of text and markers. diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index f8538385..3ce87e91 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -10,7 +10,7 @@ use sha2::{Digest, Sha256}; use crate::{kar_codec, model::Manifest}; -use leleka_model_format::kar::KarInspection; +use leleka_model_format::kar::{DecodeSource, ElementRange, KarInspection}; pub use leleka_model_format::kar::KarSummary as Summary; #[derive(Debug)] pub struct TensorSource { @@ -97,6 +97,17 @@ impl From for TensorSource { pub(crate) use leleka_model_format::kar::{crc32, crc32_step}; +/// The shared KAR scalar decoder behind the inspector's callback shape. +fn scalar_decode(source: &DecodeSource<'_>, start: usize, output: &mut [f32]) -> Result<(), String> { + let prefix = kar_codec::KarPrefix { + scales: source.scales, + book: source.book, + planes: source.planes, + group: source.group, + }; + kar_codec::decode_range(&prefix, start, output) +} + pub struct VerifiedRangeDecoder { reader: KarInspection, } @@ -119,9 +130,7 @@ impl VerifiedRangeDecoder { start: usize, count: usize, ) -> Result, String> { - self.reader - .decode_range(name, level, start, count, kar_codec::decode_range) - .map_err(|e| e.to_string()) + self.reader.decode_range(name, level, ElementRange { start, count }, scalar_decode).map_err(|e| e.to_string()) } pub fn element_count(&self, name: &str) -> Result { let n = self diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs index c220478f..8a51e080 100644 --- a/control-plane/src/kar_codec.rs +++ b/control-plane/src/kar_codec.rs @@ -51,13 +51,17 @@ mod tests { const BOOK1: [u16; 2] = [0xb800, 0x3800]; const BOOK2: [u16; 4] = [0xba00, 0xb400, 0x3400, 0x3a00]; + fn prefix<'a>(encoded: &'a EncodedPlanes, book: &'a [u16], planes: &'a [&'a [u32]]) -> KarPrefix<'a> { + KarPrefix { scales: &encoded.scales, book, planes, group: 32 } + } + fn assert_planes_decode_in_koference_order(encoded: &EncodedPlanes, planes: &[&[u32]]) { let mut decoded = [0.0f32; 5]; - decode_range(&encoded.scales, &BOOK2, planes, 32, 3, &mut decoded).unwrap(); + decode_range(&prefix(&encoded, &BOOK2, planes), 3, &mut decoded).unwrap(); assert_eq!(decoded, [0.75, -0.75, -0.25, 0.25, 0.75]); - decode_range(&encoded.scales, &BOOK1, &planes[..1], 32, 3, &mut decoded).unwrap(); + decode_range(&prefix(&encoded, &BOOK1, &planes[..1]), 3, &mut decoded).unwrap(); assert_eq!(decoded, [0.5, -0.5, -0.5, 0.5, 0.5]); - assert!(decode_range(&encoded.scales, &BOOK2, planes, 32, 31, &mut decoded).is_err()); + assert!(decode_range(&prefix(&encoded, &BOOK2, planes), 31, &mut decoded).is_err()); } fn write_synthetic_archive(encoded: &EncodedPlanes, planes: &[&[u32]], path: &std::path::Path) { diff --git a/control-plane/src/prepare_preview/encode_preview_tensor.rs b/control-plane/src/prepare_preview/encode_preview_tensor.rs index 03ed39b3..af06bc34 100644 --- a/control-plane/src/prepare_preview/encode_preview_tensor.rs +++ b/control-plane/src/prepare_preview/encode_preview_tensor.rs @@ -34,14 +34,13 @@ impl Quantized { fn relative_l2(&self, weights: &[f32], plane_refs: &[&[u32]]) -> Result { let mut decoded = vec![0.0f32; weights.len()]; - kar_codec::decode_range( - &self.encoded.scales, - &self.calibration.books[usize::from(self.levels) - 1], - plane_refs, - 32, - 0, - &mut decoded, - )?; + let prefix = kar_codec::KarPrefix { + scales: &self.encoded.scales, + book: &self.calibration.books[usize::from(self.levels) - 1], + planes: plane_refs, + group: 32, + }; + kar_codec::decode_range(&prefix, 0, &mut decoded)?; Ok(relative_l2_error(weights, &decoded)) } diff --git a/control-plane/tests/kar_kernel_model.rs b/control-plane/tests/kar_kernel_model.rs index f6310b7e..e91e59b8 100644 --- a/control-plane/tests/kar_kernel_model.rs +++ b/control-plane/tests/kar_kernel_model.rs @@ -6,7 +6,7 @@ //! This is a CPU-only check of the addressing specification; no CUDA is used. use leleka_model_format::kar::{KarInspection, KarNestedRecord}; use leleka_model_format::kar_kernel_model::{ - MAX_LEVEL, MIN_LEVEL, expert_rows, f16_to_f32, kernel_decode, kernel_multiply, plan_rows, + MAX_LEVEL, MIN_LEVEL, MultiplyDims, expert_rows, f16_to_f32, kernel_decode, kernel_multiply, plan_rows, plan_window, stage_packet, }; use sha2::{Digest, Sha256}; @@ -305,8 +305,8 @@ fn check_expert_rows(archive: (&PathBuf, &[u8]), experts: &KarNestedRecord) { .unwrap(); let mut got = vec![0f32; 7]; let mut want = vec![0f32; 7]; - assert_eq!(kernel_multiply(&weights, &x, 20, 7, 1, &mut got), 0); - assert_eq!(kernel_multiply(&oracle, &x, 20, 7, 1, &mut want), 0); + assert_eq!(kernel_multiply(&weights, &x, MultiplyDims::new(20, 7, 1), &mut got), 0); + assert_eq!(kernel_multiply(&oracle, &x, MultiplyDims::new(20, 7, 1), &mut want), 0); assert_eq!(bits(&got), bits(&want)); } } diff --git a/control-plane/tests/output_golden/vocab.rs b/control-plane/tests/output_golden/vocab.rs index 874649b3..9dfa646a 100644 --- a/control-plane/tests/output_golden/vocab.rs +++ b/control-plane/tests/output_golden/vocab.rs @@ -5,6 +5,7 @@ use std::{fs, path::PathBuf, sync::Arc}; +use leleka_tokenizer::gguf_bpe::SpecialIds; use serde_json::{Map, json}; use strata_control::{ codec::{QwenCodec, qwen_codec}, @@ -101,7 +102,7 @@ fn gptoss_vocabulary() -> leleka_tokenizer::gguf_bpe::GgufBpe { types.push(1); } let parts: Vec<&str> = tokens.iter().map(String::as_str).collect(); - leleka_tokenizer::gguf_bpe::GgufBpe::from_parts(&parts, &types, &[], None, None, None).unwrap() + leleka_tokenizer::gguf_bpe::GgufBpe::from_parts(&parts, &types, &[], SpecialIds::default()).unwrap() } impl Codecs { diff --git a/crates/context/src/rope_scaling/fill_rope_table.rs b/crates/context/src/rope_scaling/fill_rope_table.rs index 8ed2d6e6..652aaa72 100644 --- a/crates/context/src/rope_scaling/fill_rope_table.rs +++ b/crates/context/src/rope_scaling/fill_rope_table.rs @@ -39,11 +39,11 @@ fn fill_unscaled(inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut } /// The scaled loop: linear interpolation of the angle, the YaRN ramp blend and the magnitude scale. -fn fill_scaled(sc: &RopeScaling, n_rot: usize, inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { +fn fill_scaled(sc: &RopeScaling, inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { let RowSpan { half, first_pos, rows } = span; let fs = sc.freq_scale(); let ms = sc.mscale(); - let cd = sc.corr_dims(n_rot as i32); + let cd = sc.corr_dims((2 * half) as i32); let correct = sc.ext_factor != 0.0; let (low, high) = (cd[0] as f32, cd[1] as f32); // the ramp depends on the pair only @@ -86,7 +86,7 @@ pub fn fill_rope_table( if sc.kind == RopeScalingType::None { fill_unscaled(&inv, span, cos_out, sin_out); } else { - fill_scaled(sc, n_rot, &inv, span, cos_out, sin_out); + fill_scaled(sc, &inv, span, cos_out, sin_out); } Ok(()) } diff --git a/crates/context/src/rope_scaling/impl_ropescalingtype.rs b/crates/context/src/rope_scaling/impl_ropescalingtype.rs index 812107c0..d3549415 100644 --- a/crates/context/src/rope_scaling/impl_ropescalingtype.rs +++ b/crates/context/src/rope_scaling/impl_ropescalingtype.rs @@ -156,15 +156,8 @@ pub fn rope_yarn_ramp(low: f32, high: f32, pair: i32) -> f32 { } /// `rope_scaled_angle`: the analytic paths' float32 contract. Returns `(cos, sin)` with mscale folded in. -pub fn rope_scaled_angle( - theta_extrap: f32, - freq_scale: f32, - corr_low: f32, - corr_high: f32, - ext_factor: f32, - mscale_in: f32, - pair: i32, -) -> (f32, f32) { +pub fn rope_scaled_angle(theta_extrap: f32, args: &RopeKernelArgs, pair: i32) -> (f32, f32) { + let RopeKernelArgs { freq_scale, corr_low, corr_high, ext_factor, attn_factor: mscale_in } = *args; let mut theta = freq_scale * theta_extrap; let mut mscale = mscale_in; if ext_factor != 0.0 { diff --git a/crates/context/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs index 5719dbe5..a4ff993b 100644 --- a/crates/context/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -147,15 +147,7 @@ fn check_kernel_args(c: &Value, name: &str, a: &RopeKernelArgs) { fn check_analytic_path(c: &Value, name: &str, a: &RopeKernelArgs) { // analytic float32 path for s in c["analytic"].as_array().unwrap() { - let (co, si) = rope_scaled_angle( - bits32(&s["theta_extrap"]), - a.freq_scale, - a.corr_low, - a.corr_high, - a.ext_factor, - a.attn_factor, - s["pair"].as_i64().unwrap() as i32, - ); + let (co, si) = rope_scaled_angle(bits32(&s["theta_extrap"]), a, s["pair"].as_i64().unwrap() as i32); assert_close(&format!("{name}: analytic cos"), co, bits32(&s["cos"]), 2); assert_close(&format!("{name}: analytic sin"), si, bits32(&s["sin"]), 2); } diff --git a/crates/cpu-worker/src/protocol.rs b/crates/cpu-worker/src/protocol.rs index c38f8607..28328e56 100644 --- a/crates/cpu-worker/src/protocol.rs +++ b/crates/cpu-worker/src/protocol.rs @@ -5,5 +5,5 @@ pub use leleka_worker_protocol::command::{Command, Generate, parse_command}; pub use leleka_worker_protocol::events::Finish; pub use leleka_worker_protocol::lines::{ - done_line, error_line, progress_line, ready_line, reused_line, token_line, + PhaseMs, done_line, error_line, progress_line, ready_line, reused_line, token_line, }; diff --git a/crates/cpu-worker/src/serve.rs b/crates/cpu-worker/src/serve.rs index 3a5b1fad..67d03225 100644 --- a/crates/cpu-worker/src/serve.rs +++ b/crates/cpu-worker/src/serve.rs @@ -227,7 +227,8 @@ fn generate( let prompt_ms = started.elapsed().as_secs_f64() * 1000.0; let prompt_tokens = request.prompt.len() as u64; let Some(reused) = reused else { - let cancelled = protocol::done_line(0, prompt_tokens, prompt_ms, 0.0, Finish::Cancel, 0); + let phases = protocol::PhaseMs { prompt_ms, decode_ms: 0.0 }; + let cancelled = protocol::done_line(0, prompt_tokens, phases, Finish::Cancel, 0); return Ok(write_line(output, &cancelled)?); }; write_line(output, &protocol::reused_line(reused))?; @@ -260,7 +261,8 @@ fn decode_and_finish( decoding.log(decode_started); let decode_ms = decode_started.elapsed().as_secs_f64() * 1000.0; let (generated, reused) = (decoding.generated, prompt.reused as u64); - let done = protocol::done_line(generated, prompt.tokens, prompt.ms, decode_ms, finish, reused); + let phases = protocol::PhaseMs { prompt_ms: prompt.ms, decode_ms }; + let done = protocol::done_line(generated, prompt.tokens, phases, finish, reused); write_line(output, &done)?; Ok(()) } diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs index 47347578..7dad059c 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs @@ -74,7 +74,8 @@ impl<'ctx> OriginalExpertCache<'ctx> { needed: impl FnMut(usize) -> Result, ) -> Result> { self.ensure_live()?; - self.table.choose_loan(requested, auto, auto_max, context, lend_percent, needed) + let request = crate::original_expert_slots::LoanRequest { requested, auto, auto_max, context, lend_percent }; + self.table.choose_loan(request, needed) } /// generate.cpp `part_slots`: the slots from the end of the cache that hold `bytes_needed`. pub fn lend_slots(&self, bytes_needed: usize) -> Result { diff --git a/crates/cuda-driver/src/qsa_prompt_attention.rs b/crates/cuda-driver/src/qsa_prompt_attention.rs index 7a057a8f..2de0d971 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention.rs @@ -2,10 +2,12 @@ //! Completion attests real full scans and a drained actual stream, not row provenance. use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module}; use crate::qsa_prompt_attention_select::{ - DeviceCaps, PoolPresence, PromptAttnKernel, SelectSwitches, Shapes, VARIANT_ENTRIES, select, + DeviceCaps, PoolPresence, PromptAttnKernel, SelectSwitches, SelectionArrays, Shapes, VARIANT_ENTRIES, select, }; use crate::qsa_prompt_kv::{QsaKvSnapshot, QsaPromptKv, QsaPromptStage, checked}; use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; +/// The selection arrays of the INT8 prompt path: stride 2051, ids and steps present. +const QWEN_SELECTION: SelectionArrays = SelectionArrays { cap: 2051, have_ids_and_steps: true }; /// Actual whole borrowed producer buffers; never a selection/finite certificate. pub struct QsaAttentionInputs<'loan, 'buffers> { pub(crate) q: &'loan DeviceBuffer<'buffers>, diff --git a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2.rs b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2.rs index b91a4784..e29c6c0c 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention/impl_qsapromptattention_2.rs @@ -151,7 +151,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { ) -> Result> { let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps(); let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] }; - let kernel = select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, switches) + let kernel = select(PoolPresence::int8(), Shapes::QWEN, QWEN_SELECTION, device, switches) .ok_or(Error::UnsupportedQwenOperation)?; self.attend_kernel(kernel, w, stage, kv, snapshot, inputs) } @@ -163,7 +163,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { pub(crate) fn selected_kernel(&self) -> Result { let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps(); let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] }; - select(PoolPresence::int8(), Shapes::QWEN, 2051, true, device, self.switches) + select(PoolPresence::int8(), Shapes::QWEN, QWEN_SELECTION, device, self.switches) .ok_or(Error::UnsupportedQwenOperation) } pub(in super::super) fn ensure_variants(&mut self) -> Result<()> { diff --git a/crates/cuda-model/src/mmq_original_prefill_misc.rs b/crates/cuda-model/src/mmq_original_prefill_misc.rs index 8e73e524..4eed5290 100644 --- a/crates/cuda-model/src/mmq_original_prefill_misc.rs +++ b/crates/cuda-model/src/mmq_original_prefill_misc.rs @@ -39,17 +39,19 @@ pub enum GatherNative { /// `copy1_kernel` over bytes. Copy1 { na: i64, nc: i64, blocks: u32 }, } +/// The five device addresses of one `gather_native`: the three sources and the two destinations. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GatherAddrs { + pub gate: u64, + pub up: u64, + pub down: u64, + pub gu_dst: u64, + pub d_dst: u64, +} /// `gather_native(gate, up, gu_half_bytes, down, d_bytes, gu_dst, d_dst)`: every address and both byte counts /// 16-aligned selects the `uint4` copy, otherwise the byte copy; grid `blocks(2 * na + nc)`. -pub fn gather_native_plan( - gate: u64, - up: u64, - gu_half_bytes: u64, - down: u64, - d_bytes: u64, - gu_dst: u64, - d_dst: u64, -) -> GatherNative { +pub fn gather_native_plan(addrs: GatherAddrs, gu_half_bytes: u64, d_bytes: u64) -> GatherNative { + let GatherAddrs { gate, up, down, gu_dst, d_dst } = addrs; let a16 = (gate | up | down | gu_dst | d_dst | gu_half_bytes | d_bytes) % 16 == 0; if a16 { let (na, nc) = ((gu_half_bytes / 16) as i64, (d_bytes / 16) as i64); @@ -152,7 +154,9 @@ mod tests { #[test] fn gather_native_picks_the_copy_width_like_the_original() { - let g = |gate, up, half, down, d, gu_dst, d_dst| gather_native_plan(gate, up, half, down, d, gu_dst, d_dst); + let g = |gate, up, half, down, d, gu_dst, d_dst| { + gather_native_plan(GatherAddrs { gate, up, down, gu_dst, d_dst }, half, d) + }; // Q2_0 expert of the IQ packs: gate/up half 1280/2 rows... aligned everywhere: uint4 copy assert_eq!( g(0x1000, 0x2000, 640 * 1280, 0x3000, 2560 * 160, 0x4000, 0x5000), diff --git a/crates/cuda-model/src/original_expert_slots.rs b/crates/cuda-model/src/original_expert_slots.rs index 2de48f00..5d14609a 100644 --- a/crates/cuda-model/src/original_expert_slots.rs +++ b/crates/cuda-model/src/original_expert_slots.rs @@ -15,6 +15,16 @@ pub struct OriginalExpertSlots { admitted: usize, } +/// What `choose_loan` is asked for: the requested chunk, the auto mode with its bounds, the lend percentage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LoanRequest { + pub requested: usize, + pub auto: bool, + pub auto_max: usize, + pub context: usize, + pub lend_percent: usize, +} + fn vec_of(count: usize, value: T) -> Result> { let mut result = Vec::new(); result.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; @@ -179,13 +189,10 @@ impl OriginalExpertSlots { /// `needed` computes Original's real bytes_needed for each candidate chunk. pub fn choose_loan( &self, - requested: usize, - auto: bool, - auto_max: usize, - context: usize, - lend_percent: usize, + request: LoanRequest, mut needed: impl FnMut(usize) -> Result, ) -> Result> { + let LoanRequest { requested, auto, auto_max, context, lend_percent } = request; if auto { self.choose_auto_loan(auto_max, context, lend_percent, &mut needed) } else { diff --git a/crates/cuda-model/src/original_prefill_schedule.rs b/crates/cuda-model/src/original_prefill_schedule.rs index fe765a4e..6544a9d2 100644 --- a/crates/cuda-model/src/original_prefill_schedule.rs +++ b/crates/cuda-model/src/original_prefill_schedule.rs @@ -176,6 +176,13 @@ pub struct StreamConfig { pub stream_all_min: usize, } +/// The stream configuration and the expert source one chunk is planned against. +#[derive(Clone, Copy)] +pub struct WalkCtx<'a> { + pub cfg: &'a StreamConfig, + pub src: &'a SourceView<'a>, +} + /// Persistent planner: `stage_live` outlives chunks and layers exactly as `m.stage_live` does. pub struct Planner { stage_live: Vec, @@ -212,6 +219,7 @@ pub struct TraceReport { mod tests; mod impl_default_for_ringpolicy; +pub use impl_default_for_ringpolicy::FuseFlags; #[allow(unused_imports)] pub use impl_default_for_ringpolicy::chunks; #[allow(unused_imports)] diff --git a/crates/cuda-model/src/original_prefill_schedule/impl_default_for_ringpolicy.rs b/crates/cuda-model/src/original_prefill_schedule/impl_default_for_ringpolicy.rs index 9c630a4d..5dbe5a2a 100644 --- a/crates/cuda-model/src/original_prefill_schedule/impl_default_for_ringpolicy.rs +++ b/crates/cuda-model/src/original_prefill_schedule/impl_default_for_ringpolicy.rs @@ -88,10 +88,19 @@ impl PleReadAhead { // ---------------------------------------------------------------- hyper-connection write fusion +/// The three switches of the fuse rule: the PLE path, `gr_unfused()` and `cvec().covers(l)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FuseFlags { + pub ple_on: bool, + pub gr_unfused: bool, + pub cvec_covers: bool, +} + /// `fuse` of one half after its write: `!gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && /// !(half == 1 && cvec().covers(l))`, `nl = half == 0 ? l : l + 1`. A fused write also computes the next half's norm /// (`normed = true`), so the next read skips `gr_norm_rs`. -pub fn fuse_after_half(l: usize, half: usize, le: usize, ple_on: bool, gr_unfused: bool, cvec_covers: bool) -> bool { +pub fn fuse_after_half(l: usize, half: usize, le: usize, flags: FuseFlags) -> bool { + let FuseFlags { ple_on, gr_unfused, cvec_covers } = flags; let nl = if half == 0 { l } else { l + 1 }; !gr_unfused && nl < le && !(half == 1 && nl == 1 && ple_on) && !(half == 1 && cvec_covers) } diff --git a/crates/cuda-model/src/original_prefill_schedule/impl_planner.rs b/crates/cuda-model/src/original_prefill_schedule/impl_planner.rs index 3e1fcdaf..16a40134 100644 --- a/crates/cuda-model/src/original_prefill_schedule/impl_planner.rs +++ b/crates/cuda-model/src/original_prefill_schedule/impl_planner.rs @@ -44,15 +44,15 @@ impl Planner { pub fn plan_chunk( &mut self, chunk_index: usize, - cfg: &StreamConfig, - src: &SourceView<'_>, - lb: usize, - le: usize, + ctx: WalkCtx<'_>, + layers: std::ops::Range, orders: &[Vec], ) -> Result<(), PlanError> { + let WalkCtx { cfg, src } = ctx; + let (lb, le) = (layers.start, layers.end); check_config(cfg)?; self.push(SchedOp::Chunk(chunk_index)); - let stream_all = cfg.ring > STAGE && cfg.rows >= cfg.stream_all_min; + let stream_all = is_stream_all(cfg); let seq = chunk_sequence(src, lb, le, stream_all); if stream_all && !seq.jobs.is_empty() { self.push(SchedOp::StagerStart(seq.jobs.clone())); @@ -62,7 +62,7 @@ impl Planner { self.issue_until(&mut st, cfg.ring); } for l in lb..le { - self.plan_layer(&mut st, (cfg, src), l, &orders[l - lb], stream_all)?; + self.plan_layer(&mut st, ctx, l, &orders[l - lb])?; } if stream_all { self.push(SchedOp::StagerFinish); // chunk_stager_done, destroyed with the chunk @@ -74,11 +74,12 @@ impl Planner { fn plan_layer( &mut self, st: &mut IssueState<'_>, - (cfg, src): (&StreamConfig, &SourceView<'_>), + ctx: WalkCtx<'_>, l: usize, order: &[usize], - stream_all: bool, ) -> Result<(), PlanError> { + let WalkCtx { cfg, src } = ctx; + let stream_all = is_stream_all(cfg); if order.windows(2).any(|w| w[0] >= w[1]) { return Err(PlanError::OrderNotAscending); } @@ -89,7 +90,7 @@ impl Planner { if stream_all { self.streamed_walk(st, src, l, order); } else { - self.staged_walk(cfg, src, l, order); + self.staged_walk(ctx, l, order); } self.push(SchedOp::Combine); if !stream_all { @@ -130,7 +131,8 @@ impl Planner { } /// The `!stream_all` layer: lookahead `STAGE - 1` staging through the 8 routed-only slots. - pub(super) fn staged_walk(&mut self, cfg: &StreamConfig, src: &SourceView<'_>, l: usize, order: &[usize]) { + pub(super) fn staged_walk(&mut self, ctx: WalkCtx<'_>, l: usize, order: &[usize]) { + let src = ctx.src; let n = order.len(); let (job_of, jobs) = staging_jobs(src, l, order); if !jobs.is_empty() { @@ -144,7 +146,7 @@ impl Planner { while staged < n && staged <= j + lookahead { let e = order[staged]; if !src.is_resident(l, e) { - stage_of[staged] = Some(self.stage_copy(cfg, src, (l, e), &mut stage_next, job_of[staged])); + stage_of[staged] = Some(self.stage_copy(ctx, (l, e), &mut stage_next, job_of[staged])); } staged += 1; } @@ -156,12 +158,12 @@ impl Planner { /// job); returns the slot. fn stage_copy( &mut self, - cfg: &StreamConfig, - src: &SourceView<'_>, + ctx: WalkCtx<'_>, (l, e): (usize, usize), stage_next: &mut usize, job: Option, ) -> usize { + let WalkCtx { cfg, src } = ctx; let slot = *stage_next; *stage_next = (*stage_next + 1) % STAGE; if (src.pinned)(l, e) { @@ -200,6 +202,11 @@ impl Planner { } } +/// Whether the chunk takes the `stream_all` sequence: a ring beyond `STAGE` and enough rows. +fn is_stream_all(cfg: &StreamConfig) -> bool { + cfg.ring > STAGE && cfg.rows >= cfg.stream_all_min +} + fn check_config(cfg: &StreamConfig) -> Result<(), PlanError> { if cfg.ring > RING_MAX || cfg.ring == 0 || cfg.stager_ring == 0 { return Err(PlanError::RingTooLarge); diff --git a/crates/cuda-model/src/original_prefill_schedule/tests.rs b/crates/cuda-model/src/original_prefill_schedule/tests.rs index a1e709f5..66222bdf 100644 --- a/crates/cuda-model/src/original_prefill_schedule/tests.rs +++ b/crates/cuda-model/src/original_prefill_schedule/tests.rs @@ -61,7 +61,9 @@ fn plan_golden_scenario(sc: &Value, name: &str) -> Planner { let cfg = golden_stream_config(p); let mut planner = Planner::new(); for chunk in 0..u(&p["chunks"]) { - planner.plan_chunk(chunk, &cfg, &view, lb, le, &orders).unwrap_or_else(|e| panic!("{name}: {e:?}")); + planner + .plan_chunk(chunk, WalkCtx { cfg: &cfg, src: &view }, lb..le, &orders) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); } planner } @@ -107,15 +109,23 @@ fn golden_fuse_rule_matches_the_extracted_original() { for row in table { let r: Vec = row.as_array().unwrap().iter().map(u).collect(); let (le, ple_on, unfused, cvec, l, half, want) = (r[0], r[1] != 0, r[2] != 0, r[3] != 0, r[4], r[5], r[6] != 0); - assert_eq!(fuse_after_half(l, half, le, ple_on, unfused, cvec), want, "{r:?}"); + assert_eq!( + fuse_after_half(l, half, le, FuseFlags { ple_on, gr_unfused: unfused, cvec_covers: cvec }), + want, + "{r:?}" + ); fused += usize::from(want); } assert!(fused > 0 && fused < table.len()); // the Rust executor's selection: `fused && index != 0 && index != 47` for the FFN half, always for the attention // half for l in 0..48 { - assert!(fuse_after_half(l, 0, 48, true, false, false)); - assert_eq!(fuse_after_half(l, 1, 48, true, false, false), l != 0 && l != 47, "layer {l}"); + assert!(fuse_after_half(l, 0, 48, FuseFlags { ple_on: true, gr_unfused: false, cvec_covers: false })); + assert_eq!( + fuse_after_half(l, 1, 48, FuseFlags { ple_on: true, gr_unfused: false, cvec_covers: false }), + l != 0 && l != 47, + "layer {l}" + ); } } @@ -211,7 +221,7 @@ fn safe_trace() -> Vec { let cfg = StreamConfig { ring: 16, stager_ring: 16, rows: 2048, stream_all_min: 1024 }; let orders = vec![(0..40).collect::>(), (0..40).collect::>()]; let mut planner = Planner::new(); - planner.plan_chunk(0, &cfg, &view, 0, 2, &orders).unwrap(); + planner.plan_chunk(0, WalkCtx { cfg: &cfg, src: &view }, 0..2, &orders).unwrap(); planner.ops.clone() } @@ -270,7 +280,7 @@ fn staged_path_never_uses_more_than_eight_slots_and_keeps_the_lookahead() { let cfg = StreamConfig { ring: 384, stager_ring: 16, rows: 100, stream_all_min: 1024 }; let order: Vec = (0..64).collect(); let mut planner = Planner::new(); - planner.plan_chunk(0, &cfg, &view, 0, 3, &vec![order.clone(); 3]).unwrap(); + planner.plan_chunk(0, WalkCtx { cfg: &cfg, src: &view }, 0..3, &vec![order.clone(); 3]).unwrap(); assert!(planner.ops.iter().all(|o| match o { SchedOp::H2d { slot, .. } | SchedOp::RecordCopied(slot) | SchedOp::ComputeWaitCopied(slot) => *slot < STAGE, _ => true, @@ -290,8 +300,17 @@ fn rejects_unsorted_or_out_of_range_routing() { let view = SourceView { n_layers: 1, n_expert: 4, cache_present: false, resident: &none, pinned: &none, transient: &none }; let cfg = StreamConfig { ring: 8, stager_ring: 16, rows: 10, stream_all_min: 1024 }; - assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![2, 1]]), Err(PlanError::OrderNotAscending)); - assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![0, 4]]), Err(PlanError::RoutedIdOutOfRange)); + assert_eq!( + Planner::new().plan_chunk(0, WalkCtx { cfg: &cfg, src: &view }, 0..1, &[vec![2, 1]]), + Err(PlanError::OrderNotAscending) + ); + assert_eq!( + Planner::new().plan_chunk(0, WalkCtx { cfg: &cfg, src: &view }, 0..1, &[vec![0, 4]]), + Err(PlanError::RoutedIdOutOfRange) + ); let big = StreamConfig { ring: 513, ..cfg }; - assert_eq!(Planner::new().plan_chunk(0, &big, &view, 0, 1, &[vec![]]), Err(PlanError::RingTooLarge)); + assert_eq!( + Planner::new().plan_chunk(0, WalkCtx { cfg: &big, src: &view }, 0..1, &[vec![]]), + Err(PlanError::RingTooLarge) + ); } diff --git a/crates/cuda-model/src/qsa_prompt_attention_select.rs b/crates/cuda-model/src/qsa_prompt_attention_select.rs index efbb96d1..7405ed02 100644 --- a/crates/cuda-model/src/qsa_prompt_attention_select.rs +++ b/crates/cuda-model/src/qsa_prompt_attention_select.rs @@ -74,6 +74,14 @@ pub struct Shapes { pub head_dim: usize, } +/// The per-query selection arrays: `cap` is the stride of `ids [n_q, cap]`, `have_ids_and_steps` the null test of the +/// `ids` and `steps` arrays. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SelectionArrays { + pub cap: i64, + pub have_ids_and_steps: bool, +} + /// The current device: compute capability with its minor and the opt-in shared-memory limit /// (`cudaDevAttrMaxSharedMemoryPerBlockOptin`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/cuda-model/src/qsa_prompt_attention_select/impl_poolpresence.rs b/crates/cuda-model/src/qsa_prompt_attention_select/impl_poolpresence.rs index e9c1c81c..e4aca8ca 100644 --- a/crates/cuda-model/src/qsa_prompt_attention_select/impl_poolpresence.rs +++ b/crates/cuda-model/src/qsa_prompt_attention_select/impl_poolpresence.rs @@ -186,11 +186,11 @@ fn int8_kernel(pools: &PoolPresence, switches: &SelectSwitches, turing: bool) -> pub fn select( pools: PoolPresence, shapes: Shapes, - cap: i64, - have_ids_and_steps: bool, + selection: SelectionArrays, device: DeviceCaps, switches: SelectSwitches, ) -> Option { + let SelectionArrays { cap, have_ids_and_steps } = selection; let cc = if switches.qsa_warp_arm { 75 } else { 10 * device.cc_major + device.cc_minor }; if cc < 75 { return None; diff --git a/crates/cuda-model/src/qsa_prompt_attention_select/tests.rs b/crates/cuda-model/src/qsa_prompt_attention_select/tests.rs index 63639eb4..baa5fcd6 100644 --- a/crates/cuda-model/src/qsa_prompt_attention_select/tests.rs +++ b/crates/cuda-model/src/qsa_prompt_attention_select/tests.rs @@ -8,8 +8,12 @@ const TURING: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 5, max_shared_opt const VOLTA: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 0, max_shared_optin: 98_304 }; const NONE: SelectSwitches = SelectSwitches { qsa_warp_arm: false, prompt_attn_v1: false }; +fn sel(cap: i64, have_ids_and_steps: bool) -> SelectionArrays { + SelectionArrays { cap, have_ids_and_steps } +} + fn pick(p: PoolPresence, d: DeviceCaps, s: SelectSwitches) -> Option { - select(p, Shapes::QWEN, 2051, true, d, s) + select(p, Shapes::QWEN, sel(2051, true), d, s) } #[test] @@ -73,11 +77,11 @@ fn assert_geometry_and_shared_arms() { use PromptAttnKernel::*; // geometry and selection arrays let bad = Shapes { n_head: 24, n_head_kv: 4, head_dim: 256 }; - assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), bad, sel(2051, true), BLACKWELL, NONE), None); let bad = Shapes { head_dim: 128, ..Shapes::QWEN }; - assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); - assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 0, true, BLACKWELL, NONE), None); - assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 2051, false, BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), bad, sel(2051, true), BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, sel(0, true), BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, sel(2051, false), BLACKWELL, NONE), None); // the dynamic shared memory opt-in must cover the FP16 kernel's 54288 bytes let small = DeviceCaps { max_shared_optin: 49_152, ..BLACKWELL }; assert_eq!(pick(PoolPresence::fp16(), small, NONE), None); diff --git a/crates/engine-core/src/conversation/binding.rs b/crates/engine-core/src/conversation/binding.rs index c245d141..c95d5565 100644 --- a/crates/engine-core/src/conversation/binding.rs +++ b/crates/engine-core/src/conversation/binding.rs @@ -8,8 +8,8 @@ use super::cache::{ConversationCheckpoint, ConversationKvReuse, SavedConversatio use super::manager::SessionEngine; use super::model::{ConvError, ConvResult, ModelGeometry, QsaDesc, SessionSpec, StateMemory}; use super::snapshot::{ - ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, snapshot_save, - snapshot_validate, + ConversationView, RestoreOutcome, SnapshotSession, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, + snapshot_save, snapshot_validate, }; use super::state::{checkpoint_restore, checkpoint_save}; @@ -57,7 +57,8 @@ impl SessionEngine for DeviceEngine<'_, D> { reuse: ConversationKvReuse, reused_bytes: &mut usize, ) -> ConvResult { - snapshot_save(view, self.session, self.geometry, self.draft, self.device, reuse, Some(reused_bytes)) + let session = SnapshotSession { ss: self.session, g: self.geometry, draft: self.draft }; + snapshot_save(view, session, self.device, reuse, Some(reused_bytes)) } fn snapshot_validate(&mut self, image: &SavedConversation) -> ConvResult<()> { diff --git a/crates/engine-core/src/conversation/golden_manager.rs b/crates/engine-core/src/conversation/golden_manager.rs index 831bbf66..f82dd43f 100644 --- a/crates/engine-core/src/conversation/golden_manager.rs +++ b/crates/engine-core/src/conversation/golden_manager.rs @@ -10,7 +10,7 @@ use super::cache::{ConversationCheckpoint, ConversationImageKey, ConversationKvR use super::manager::{ConversationManager, ConversationOptions, RequestStart, SessionEngine}; use super::model::{ConvError, ConvResult}; use super::snapshot::{ConversationView, RestoreOutcome}; -use crate::prompt::{PromptOptions, PromptPath, PromptPlan}; +use crate::prompt::{PlanLimits, PromptOptions, PromptPath, PromptPlan, ResumePoint}; use serde_json::Value; const PAYLOAD: usize = 100; @@ -117,10 +117,11 @@ fn assert_start(start: &RequestStart, want: &Value, ctx: &str) -> Option<(i64, b restored } -/// The request being replayed: its prompt ids and image keys. +/// The request being replayed: its prompt ids and image keys, and the action it is cancelled at (negative: never). struct Replay<'a> { ids: &'a [i32], images: &'a [ConversationImageKey], + stop_after: i64, } /// Run the prompt plan; true when the request was cancelled part way. @@ -129,9 +130,9 @@ fn run_plan( engine: &mut Synthetic, replay: &Replay<'_>, plan: PromptPlan, - stop_after: i64, ctx: &str, ) -> bool { + let stop_after = replay.stop_after; for (actions, action) in plan.enumerate() { if action.path == PromptPath::FinalSeed { break; @@ -201,6 +202,12 @@ fn synthetic_of(req: &Value) -> Synthetic { } } +/// The prompt plan of a request that starts as `start` says. +fn plan_of<'a>(prompt: &'a [u32], start: &RequestStart, options: PromptOptions, ctx: &str) -> PromptPlan<'a> { + let resume = ResumePoint { resume: start.resume, reread_to: start.reread_to }; + PromptPlan::new(prompt, resume, None, PlanLimits::new(options, 256)).unwrap_or_else(|e| panic!("{ctx}: {e:?}")) +} + /// Replay one request of a trace; returns its path index and whether it was cancelled. fn replay_request( mgr: &mut ConversationManager, @@ -218,10 +225,9 @@ fn replay_request( .unwrap_or_else(|e| panic!("{ctx}: {e}")); let restored = assert_start(&start, want, ctx); let prompt: Vec = ids.iter().map(|&i| i as u32).collect(); - let plan = PromptPlan::new(&prompt, start.resume, start.reread_to, None, plan_options, 256) - .unwrap_or_else(|e| panic!("{ctx}: {e:?}")); - let replay = Replay { ids: &ids, images: &images }; - let cancelled = run_plan(mgr, &mut engine, &replay, plan, req["stop_after"].as_i64().unwrap(), ctx); + let plan = plan_of(&prompt, &start, plan_options, ctx); + let replay = Replay { ids: &ids, images: &images, stop_after: req["stop_after"].as_i64().unwrap() }; + let cancelled = run_plan(mgr, &mut engine, &replay, plan, ctx); let generated = req["gen"].as_i64().unwrap() as usize; let consumed_len = if cancelled { 0 } else { ids.len() + generated - 1 }; finish_replay(mgr, &replay, cancelled, generated); diff --git a/crates/engine-core/src/conversation/kv.rs b/crates/engine-core/src/conversation/kv.rs index 5c9401fa..cc9421ea 100644 --- a/crates/engine-core/src/conversation/kv.rs +++ b/crates/engine-core/src/conversation/kv.rs @@ -10,7 +10,7 @@ use super::cache::ConversationKv; use super::checked::{add, product}; use super::model::{ ConvError, ConvResult, IDX_BLOCK, KV_HYBRID, KV_ROTATED, KvLayer, KvPool, ModelGeometry, PAGE_SIZE, - Q4_0_BLOCK_BYTES, QsaDesc, StateMemory, StateRegion, fail, + Q4_0_BLOCK_BYTES, QsaDesc, RingBlocks, StateMemory, StateRegion, fail, }; #[derive(Clone, Copy, Debug)] @@ -26,6 +26,17 @@ struct Layout { value_scales: usize, } +/// Which layer of which session state a K/V image is saved from, restored into or verified against: the layer, its +/// QSA descriptor, the model geometry, the token count and whether the indexer rows travel too. +#[derive(Clone, Copy)] +pub struct KvTarget<'a> { + pub layer: KvLayer, + pub st: &'a QsaDesc, + pub g: &'a ModelGeometry, + pub upto: i64, + pub index: bool, +} + struct Verifier<'a> { mem: &'a mut dyn StateMemory, buffer: Vec, diff --git a/crates/engine-core/src/conversation/kv/kv_save_fn.rs b/crates/engine-core/src/conversation/kv/kv_save_fn.rs index 0ba7d855..9e861bbe 100644 --- a/crates/engine-core/src/conversation/kv/kv_save_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_save_fn.rs @@ -87,18 +87,14 @@ fn capture_layer( /// only for storage retained from an image actually restored into this /// session, bounded by every subsequent rewrite: equal token IDs alone do not /// establish that its K/V bytes are unchanged. -#[allow(clippy::too_many_arguments)] pub fn kv_save( image: &mut ConversationKv, - layer: KvLayer, - st: &QsaDesc, - g: &ModelGeometry, - upto: i64, - index: bool, + target: KvTarget<'_>, unchanged_tokens: i64, mem: &mut dyn StateMemory, reused_bytes: Option<&mut usize>, ) -> ConvResult<()> { + let KvTarget { layer, st, g, upto, index } = target; let l = layout(st, g, upto, index)?; valid(st, &l, upto)?; if unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells { @@ -159,15 +155,8 @@ fn restore_buffer( /// Write the image into the layer; refills streamed residency afterwards. /// The caller synchronises the device before and after the whole session. -pub fn kv_restore( - image: &ConversationKv, - layer: KvLayer, - st: &QsaDesc, - g: &ModelGeometry, - upto: i64, - index: bool, - mem: &mut dyn StateMemory, -) -> ConvResult<()> { +pub fn kv_restore(image: &ConversationKv, target: KvTarget<'_>, mem: &mut dyn StateMemory) -> ConvResult<()> { + let KvTarget { layer, st, g, upto, index } = target; kv_validate(image, st, g, upto, index)?; for (buffer, pool) in image.buffers().into_iter().zip(KvPool::ALL) { restore_buffer(buffer, (layer, pool), mem)?; @@ -181,7 +170,8 @@ pub fn kv_restore( if st.kv_mode == 2 && upto > 0 { let end = (upto + PAGE_SIZE - 1) / PAGE_SIZE; let format = st.kv_format().ok_or_else(|| ConvError("conversation snapshot: hybrid ring".into()))?; - mem.restore_ring(layer, format, (end - st.n_slots).max(0), end, st.n_slots).map_err(residency)?; + let blocks = RingBlocks { begin: (end - st.n_slots).max(0), end, slots: st.n_slots }; + mem.restore_ring(layer, format, blocks).map_err(residency)?; } Ok(()) } diff --git a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs index 6a6d6daf..f3aa962c 100644 --- a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs @@ -28,15 +28,8 @@ fn verify_ring( /// Diagnostic read-back after a synchronised restore: compares the /// authoritative bytes (and the resident draft-ring pages), fingerprinting the /// authoritative payload only (FNV-1a 64). Never changes model state. -pub fn kv_verify( - image: &ConversationKv, - layer: KvLayer, - st: &QsaDesc, - g: &ModelGeometry, - upto: i64, - index: bool, - mem: &mut dyn StateMemory, -) -> ConvResult { +pub fn kv_verify(image: &ConversationKv, target: KvTarget<'_>, mem: &mut dyn StateMemory) -> ConvResult { + let KvTarget { layer, st, g, upto, index } = target; kv_validate(image, st, g, upto, index)?; let mut v = Verifier { mem, buffer: vec![0; 65536], hash: 1469598103934665603, error: None }; for (saved, pool) in image.buffers().into_iter().zip(KvPool::ALL) { diff --git a/crates/engine-core/src/conversation/manager_tests.rs b/crates/engine-core/src/conversation/manager_tests.rs index 25182e05..140cde80 100644 --- a/crates/engine-core/src/conversation/manager_tests.rs +++ b/crates/engine-core/src/conversation/manager_tests.rs @@ -12,11 +12,13 @@ use super::binding::{DeviceEngine, SessionDevice}; use super::cache::ConversationImageKey; use super::manager::{ConversationManager, ConversationOptions, RequestStart}; -use super::model::{IdxKind, KvLayer, KvPool, ModelGeometry, SessionShape, SessionSpec, StateMemory, StateRegion}; -use super::snapshot_tests::{Fixture, kv_region}; +use super::model::{ + IdxKind, KvLayer, KvPool, ModelGeometry, RingBlocks, SessionShape, SessionSpec, StateMemory, StateRegion, +}; +use super::snapshot_tests::{Fixture, FixtureGeometry, kv_region}; use super::state::state_sizes; use super::testing::HostMemory; -use crate::prompt::{PromptOptions, PromptPath, PromptPlan}; +use crate::prompt::{PlanLimits, PromptOptions, PromptPath, PromptPlan, ResumePoint}; const TURN: i32 = 248045; const MAX_CELLS: usize = 256; @@ -69,6 +71,8 @@ use hash_fn::pat; use hash_fn::pattern; mod impl_sessiondevice_for_simdevice; #[allow(unused_imports)] +use impl_sessiondevice_for_simdevice::Req; +#[allow(unused_imports)] use impl_sessiondevice_for_simdevice::chat; #[allow(unused_imports)] use impl_sessiondevice_for_simdevice::gen_tokens; diff --git a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs index 64187391..7b275101 100644 --- a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs +++ b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs @@ -16,7 +16,8 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { for salt in 1..=4 { runs.push(( salt, - w.request(&chat(salt, 16 + salt as usize, &[9]), &[], true, &gen_tokens(salt, 4), None, 8).unwrap(), + w.request(Req::new(&chat(salt, 16 + salt as usize, &[9]), &[], true), &gen_tokens(salt, 4), None, 8) + .unwrap(), )); } // 4 chats: the live one is chat 4; parked are the two most recent others. @@ -26,7 +27,7 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { // chat 1 (evicted) comes back: nothing to restore let mut again = runs[0].1.consumed.clone(); again.extend([TURN, 5]); - let r = w.request(&again, &[], true, &gen_tokens(9, 3), None, 8).unwrap(); + let r = w.request(Req::new(&again, &[], true), &gen_tokens(9, 3), None, 8).unwrap(); assert_eq!(r.start.restored, None); assert_eq!(r.start.resume, 0); } @@ -34,14 +35,14 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { #[test] fn an_incompatible_parked_image_is_discarded_and_the_request_falls_back() { let mut w = world(options(), false); - let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + let ra = w.request(Req::new(&chat(1, 20, &[10]), &[], true), &gen_tokens(1, 6), None, 8).unwrap(); + w.request(Req::new(&chat(2, 18, &[14]), &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 1); // The runtime geometry changes under the parked image. w.g.n_expert = 256; let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2]); - let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 8).unwrap(); + let r = w.request(Req::new(&a2, &[], true), &gen_tokens(3, 4), None, 8).unwrap(); assert_eq!(r.start.restored, None, "invalid image never restores"); assert_eq!(r.start.resume, 0); let events = w.mgr.take_events(); @@ -53,8 +54,8 @@ fn a_failed_restore_transfer_is_fatal_to_the_request() { // Measure the device copies `begin_request` performs for A/B/A, then fail the last one. let scenario = |fail_last: Option| { let mut w = world(options(), false); - let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + let ra = w.request(Req::new(&chat(1, 20, &[10]), &[], true), &gen_tokens(1, 6), None, 8).unwrap(); + w.request(Req::new(&chat(2, 18, &[14]), &[], true), &gen_tokens(2, 6), None, 8).unwrap(); let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2]); w.dev.mem.reset_counters(); @@ -79,16 +80,16 @@ fn a_failed_restore_transfer_is_fatal_to_the_request() { fn switching_steering_invalidates_checkpoints_and_isolates_parked_images() { let mut w = world(options(), false); let p = chat(1, 20, &[10, 10]); - let r1 = w.request(&p, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); + let r1 = w.request(Req::new(&p, &[], true), &gen_tokens(1, 6), None, 64).unwrap(); assert!(!w.mgr.checkpoints().is_empty()); let mut same = r1.consumed.clone(); same.extend([TURN, 3, 4]); - let r2 = w.request(&same, &[], false, &gen_tokens(2, 4), None, 64).unwrap(); + let r2 = w.request(Req::new(&same, &[], false), &gen_tokens(2, 4), None, 64).unwrap(); assert_eq!(r2.start.resume, 0, "a different steering mode never reuses the session"); assert!(!w.mgr.cvec_cached()); assert_eq!(w.dev.steering.last(), Some(&false)); // The old (steered) conversation was parked with its own steering mode. - let r3 = w.request(&same, &[], true, &gen_tokens(3, 4), None, 64).unwrap(); + let r3 = w.request(Req::new(&same, &[], true), &gen_tokens(3, 4), None, 64).unwrap(); assert_eq!(r3.start.restored.map(|(t, _)| t), Some(r1.consumed.len())); assert_eq!(w.dev.steering.last(), Some(&true)); } @@ -97,12 +98,12 @@ fn switching_steering_invalidates_checkpoints_and_isolates_parked_images() { fn a_cancelled_prompt_keeps_its_checkpoints_but_not_a_live_session() { let mut w = world(options(), false); let p = chat(1, 100, &[30]); - let cancelled = w.request(&p, &[], true, &gen_tokens(1, 4), Some(1), 8).unwrap(); + let cancelled = w.request(Req::new(&p, &[], true), &gen_tokens(1, 4), Some(1), 8).unwrap(); assert!(cancelled.consumed.is_empty()); assert!(!w.mgr.live_ok(), "the session is between two chunks: nothing to continue from"); assert!(w.mgr.checkpoints().iter().any(|c| c.ids.len() > 8), "checkpoints taken while reading survive"); let kept = w.mgr.checkpoints().last().unwrap().ids.len(); - let r = w.request(&p, &[], true, &gen_tokens(2, 4), None, 8).unwrap(); + let r = w.request(Req::new(&p, &[], true), &gen_tokens(2, 4), None, 8).unwrap(); assert_eq!(r.start.resume, kept, "a retry mounts the deepest surviving checkpoint"); assert!(!r.start.from_live); } @@ -116,7 +117,7 @@ fn periodic_checkpoints_follow_the_chunk_stride() { // No turn tokens inside: only periodic checkpoints can appear. let mut p = vec![TURN]; p.extend(1..=120); - w.request(&p, &[], true, &gen_tokens(1, 3), None, 1 << 20).unwrap(); + w.request(Req::new(&p, &[], true), &gen_tokens(1, 3), None, 1 << 20).unwrap(); let lens: Vec = w.mgr.checkpoints().iter().map(|c| c.ids.len()).collect(); assert!(!lens.is_empty()); assert!(lens.iter().all(|&l| l < p.len())); @@ -128,11 +129,11 @@ fn the_reread_check_zeroes_and_reads_a_checkpoint_again() { o.reread_checkpoints = true; let mut w = world(o, false); let p1 = chat(5, 16, &[10, 12]); - w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64).unwrap(); + w.request(Req::new(&p1, &[], true), &gen_tokens(1, 4), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); let mut p2 = p1[..turn_at].to_vec(); p2.extend([TURN, 9, 9, 9, 9]); - let r = w.request(&p2, &[], true, &gen_tokens(2, 3), None, 64).unwrap(); + let r = w.request(Req::new(&p2, &[], true), &gen_tokens(2, 3), None, 64).unwrap(); assert_eq!(r.start.reread_to, Some(turn_at)); assert_eq!(r.start.read_from, 0); } @@ -142,15 +143,15 @@ fn pictures_are_part_of_the_resume_identity() { let mut w = world(options(), false); let mut p = chat(1, 20, &[10]); let img = ConversationImageKey { start: 3, hash: 99 }; - let r1 = w.request(&p, &[img], true, &gen_tokens(1, 4), None, 64).unwrap(); + let r1 = w.request(Req::new(&p, &[img], true), &gen_tokens(1, 4), None, 64).unwrap(); p = r1.consumed.clone(); p.extend([TURN, 4]); - let same = w.request(&p, &[img], true, &gen_tokens(2, 3), None, 64).unwrap(); + let same = w.request(Req::new(&p, &[img], true), &gen_tokens(2, 3), None, 64).unwrap(); assert!(same.start.from_live && same.start.resume > 0); let other = ConversationImageKey { start: 3, hash: 100 }; let mut p2 = same.consumed.clone(); p2.extend([TURN, 5]); - let changed = w.request(&p2, &[other], true, &gen_tokens(3, 3), None, 64).unwrap(); + let changed = w.request(Req::new(&p2, &[other], true), &gen_tokens(3, 3), None, 64).unwrap(); assert_eq!(changed.start.resume, 0, "same pad tokens, different pixels: nothing is reused"); } @@ -158,10 +159,10 @@ fn pictures_are_part_of_the_resume_identity() { fn the_ple_history_window_is_restored_with_the_checkpoint() { let mut w = world(options(), true); let p1 = chat(6, 16, &[10, 12]); - w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64).unwrap(); + w.request(Req::new(&p1, &[], true), &gen_tokens(1, 4), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); let mut p2 = p1[..turn_at].to_vec(); p2.extend([TURN, 1, 2, 3, 4]); - let r = w.request(&p2, &[], true, &gen_tokens(2, 3), None, 64).unwrap(); + let r = w.request(Req::new(&p2, &[], true), &gen_tokens(2, 3), None, 64).unwrap(); assert_eq!(r.start.resume, turn_at); } diff --git a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs index 71f6b957..1ec11497 100644 --- a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs +++ b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs @@ -10,13 +10,13 @@ use super::*; fn a_continuing_chat_reuses_the_live_session_without_a_copy() { let mut w = world(options(), false); let p1 = chat(1, 20, &[10]); - let r1 = w.request(&p1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + let r1 = w.request(Req::new(&p1, &[], true), &gen_tokens(1, 6), None, 8).unwrap(); assert_eq!((r1.start.resume, r1.start.from_live), (0, false)); // Next request: the history as the client re-renders it, plus a new turn. let mut p2 = r1.consumed.clone(); p2.push(TURN); p2.extend([7, 8, 9]); - let r2 = w.request(&p2, &[], true, &gen_tokens(2, 5), None, 8).unwrap(); + let r2 = w.request(Req::new(&p2, &[], true), &gen_tokens(2, 5), None, 8).unwrap(); assert!(r2.start.from_live, "continues the live session"); assert_eq!(r2.start.resume, r1.consumed.len()); assert!(r2.start.restored.is_none()); @@ -28,10 +28,10 @@ fn a_continuing_chat_reuses_the_live_session_without_a_copy() { fn an_identical_prompt_still_reads_its_last_token() { let mut w = world(options(), false); let p = chat(2, 12, &[8]); - let first = w.request(&p, &[], true, &gen_tokens(1, 1), None, 8).unwrap(); + let first = w.request(Req::new(&p, &[], true), &gen_tokens(1, 1), None, 8).unwrap(); // gen of one token commits nothing: the session holds exactly the prompt. assert_eq!(first.consumed, p); - let second = w.request(&p, &[], true, &gen_tokens(2, 3), None, 8).unwrap(); + let second = w.request(Req::new(&p, &[], true), &gen_tokens(2, 3), None, 8).unwrap(); assert!(second.start.resume < p.len(), "the last token always starts the first verify window"); } @@ -39,14 +39,14 @@ fn an_identical_prompt_still_reads_its_last_token() { fn a_rewritten_tail_resumes_from_the_turn_boundary_checkpoint() { let mut w = world(options(), false); let p1 = chat(3, 16, &[10, 12]); - let r1 = w.request(&p1, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); + let r1 = w.request(Req::new(&p1, &[], true), &gen_tokens(1, 6), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); assert!(w.mgr.checkpoints().iter().any(|c| c.ids.len() == turn_at), "checkpoint at the last turn boundary"); // The client re-renders the last turn differently (e.g. dropped thinking). let mut p2 = p1[..turn_at].to_vec(); p2.push(TURN); p2.extend([42, 43, 44, 45, 46]); - let r2 = w.request(&p2, &[], true, &gen_tokens(2, 4), None, 64).unwrap(); + let r2 = w.request(Req::new(&p2, &[], true), &gen_tokens(2, 4), None, 64).unwrap(); assert!(!r2.start.from_live); assert_eq!(r2.start.resume, turn_at, "restored the checkpoint at the turn boundary"); assert!(r1.consumed.len() > turn_at); @@ -64,7 +64,7 @@ fn the_shared_root_is_pinned_while_other_checkpoints_rotate() { // Every chat shares the system prompt (same salt for it) via a common prefix. let mut shared = chat(1, system, &[]); shared.extend_from_slice(&ids[1 + system..]); - w.request(&shared, &[], true, &gen_tokens(1, 4), None, 8).unwrap(); + w.request(Req::new(&shared, &[], true), &gen_tokens(1, 4), None, 8).unwrap(); let checks = w.mgr.checkpoints(); assert!(checks.len() <= 3, "chain capacity honoured"); let root = checks.first().expect("a checkpoint exists"); @@ -78,7 +78,7 @@ fn the_shared_root_is_pinned_while_other_checkpoints_rotate() { // A brand-new chat sharing only the system prompt mounts through the root. let mut fresh = chat(1, system, &[]); fresh.extend([TURN, 5, 6, 7, 8, 9, 10]); - let r = w.request(&fresh, &[], true, &gen_tokens(3, 3), None, 8).unwrap(); + let r = w.request(Req::new(&fresh, &[], true), &gen_tokens(3, 3), None, 8).unwrap(); assert_eq!(r.start.resume, root_len.unwrap(), "new chats read only what follows the pinned root"); assert!(!r.start.from_live); } @@ -87,9 +87,9 @@ fn the_shared_root_is_pinned_while_other_checkpoints_rotate() { fn switching_between_conversations_parks_and_restores_exactly() { let mut w = world(options(), false); let a1 = chat(1, 20, &[10]); - let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + let ra = w.request(Req::new(&a1, &[], true), &gen_tokens(1, 6), None, 8).unwrap(); let b1 = chat(2, 18, &[14]); - let rb = w.request(&b1, &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + let rb = w.request(Req::new(&b1, &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert!(rb.start.restored.is_none() && rb.start.resume == 0); assert_eq!(w.mgr.cache().size(), 1, "A was parked when B took over"); let events = w.mgr.take_events(); @@ -100,7 +100,7 @@ fn switching_between_conversations_parks_and_restores_exactly() { // Back to A: its next turn. let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2, 3, 4]); - let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 8).unwrap(); + let r = w.request(Req::new(&a2, &[], true), &gen_tokens(3, 4), None, 8).unwrap(); assert_eq!(r.start.restored.map(|(tokens, _)| tokens), Some(ra.consumed.len()), "A restored from RAM"); assert_eq!(r.start.resume, ra.consumed.len()); assert!(r.start.from_live); @@ -108,7 +108,7 @@ fn switching_between_conversations_parks_and_restores_exactly() { // And B again. let mut b2 = rb.consumed.clone(); b2.extend([TURN, 9, 9, 9]); - let r = w.request(&b2, &[], true, &gen_tokens(4, 4), None, 8).unwrap(); + let r = w.request(Req::new(&b2, &[], true), &gen_tokens(4, 4), None, 8).unwrap(); assert_eq!(r.start.restored.map(|(tokens, _)| tokens), Some(rb.consumed.len())); } @@ -120,15 +120,15 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { // the tokens it names. let mut w = world(options(), false); let a1 = chat(1, 20, &[10]); - let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + let ra = w.request(Req::new(&a1, &[], true), &gen_tokens(1, 6), None, 8).unwrap(); let b1 = chat(2, 18, &[14]); - let rb = w.request(&b1, &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + let rb = w.request(Req::new(&b1, &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().retained_bytes(), 0, "nothing was restored yet"); let r = restore_a_keeping_its_kv(&mut w, &ra); // a third conversation takes the session from A (resume 0): A is parked, and the retained image is consumed by A's // own park only let c1 = chat(3, 16, &[12]); - let rc = w.request(&c1, &[], true, &gen_tokens(4, 6), None, 8).unwrap(); + let rc = w.request(Req::new(&c1, &[], true), &gen_tokens(4, 6), None, 8).unwrap(); assert_eq!(rc.start.resume, 0); assert_eq!(w.mgr.cache().retained_bytes(), 0, "C never inherits A's retained K/V"); let events = w.mgr.take_events(); @@ -146,7 +146,7 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { fn restore_a_keeping_its_kv(w: &mut World, ra: &Run) -> Run { let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2, 3, 4]); - let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 8).unwrap(); + let r = w.request(Req::new(&a2, &[], true), &gen_tokens(3, 4), None, 8).unwrap(); assert!(r.start.restored.is_some()); assert!(w.mgr.cache().retained_bytes() > 0, "the restore retained A's K/V"); w.mgr.take_events(); @@ -156,7 +156,7 @@ fn restore_a_keeping_its_kv(w: &mut World, ra: &Run) -> Run { fn assert_comes_back_with_its_own_cells(w: &mut World, conv: &[i32], tag: i32) { let mut next = conv.to_vec(); next.extend([TURN, tag, tag, tag]); - let back = w.request(&next, &[], true, &gen_tokens(tag, 3), None, 8).unwrap(); + let back = w.request(Req::new(&next, &[], true), &gen_tokens(tag, 3), None, 8).unwrap(); assert_eq!(back.start.restored.map(|(tokens, _)| tokens).unwrap_or(back.start.resume), conv.len(), "tag {tag}"); } @@ -164,13 +164,13 @@ fn assert_comes_back_with_its_own_cells(w: &mut World, conv: &[i32], tag: i32) { fn a_parked_conversation_restores_through_its_checkpoint_when_the_tail_was_rewritten() { let mut w = world(options(), false); let a1 = chat(1, 20, &[10, 10]); - let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); + let ra = w.request(Req::new(&a1, &[], true), &gen_tokens(1, 6), None, 64).unwrap(); let turn_at = a1.iter().rposition(|&t| t == TURN).unwrap(); let b1 = chat(2, 18, &[14]); - w.request(&b1, &[], true, &gen_tokens(2, 6), None, 64).unwrap(); + w.request(Req::new(&b1, &[], true), &gen_tokens(2, 6), None, 64).unwrap(); let mut a2 = a1[..turn_at].to_vec(); a2.extend([TURN, 77, 78, 79, 80]); - let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 64).unwrap(); + let r = w.request(Req::new(&a2, &[], true), &gen_tokens(3, 4), None, 64).unwrap(); assert_eq!(r.start.restored, Some((turn_at, false)), "restored the parked image, mounted its checkpoint"); assert_eq!(r.start.resume, turn_at); assert!(ra.consumed.len() > turn_at); @@ -181,12 +181,12 @@ fn parking_is_off_by_default_and_the_live_session_is_simply_replaced() { let mut off = options(); off.conversation_cache_bytes = 0; let mut w = world(off, false); - let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + let ra = w.request(Req::new(&chat(1, 20, &[10]), &[], true), &gen_tokens(1, 6), None, 8).unwrap(); + w.request(Req::new(&chat(2, 18, &[14]), &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 0); let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1]); - let r = w.request(&a2, &[], true, &gen_tokens(3, 3), None, 8).unwrap(); + let r = w.request(Req::new(&a2, &[], true), &gen_tokens(3, 3), None, 8).unwrap(); assert_eq!((r.start.resume, r.start.restored), (0, None), "A is gone and is read again"); } @@ -197,8 +197,8 @@ fn physical_memory_admission_gates_parking() { o.conversation_cache_min_free_bytes = 128 << 20; let mut w = world(o, false); w.dev.available = available; - w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + w.request(Req::new(&chat(1, 20, &[10]), &[], true), &gen_tokens(1, 6), None, 8).unwrap(); + w.request(Req::new(&chat(2, 18, &[14]), &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 0, "unknown or short RAM never parks ({available:?})"); let events = w.mgr.take_events(); assert!(events.iter().any(|e| e.contains("physical RAM admission")), "{events:?}"); @@ -207,7 +207,7 @@ fn physical_memory_admission_gates_parking() { o.conversation_cache_min_free_bytes = 128 << 20; let mut w = world(o, false); w.dev.available = Some(10 * GIB); - w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + w.request(Req::new(&chat(1, 20, &[10]), &[], true), &gen_tokens(1, 6), None, 8).unwrap(); + w.request(Req::new(&chat(2, 18, &[14]), &[], true), &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 1); } diff --git a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs index 5b1b9951..e9b16c9c 100644 --- a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs +++ b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs @@ -191,7 +191,7 @@ impl StateMemory for SimDevice { fn reset_streaming_residency(&mut self, layer: KvLayer) -> Result<(), String> { self.mem.reset_streaming_residency(layer) } - fn restore_ring(&mut self, layer: KvLayer, format: i32, b0: i64, b1: i64, slots: i64) -> Result<(), String> { - self.mem.restore_ring(layer, format, b0, b1, slots) + fn restore_ring(&mut self, layer: KvLayer, format: i32, blocks: RingBlocks) -> Result<(), String> { + self.mem.restore_ring(layer, format, blocks) } } diff --git a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs index e7ffd319..1c1d0962 100644 --- a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs +++ b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs @@ -73,8 +73,9 @@ pub(super) fn world(options: ConversationOptions, ple: bool) -> World { let g = world_geometry(); let mut mem = HostMemory::new(); let pages = (MAX_CELLS / PAGE) as i64; - let main = Fixture::with_geometry(&mut mem, KvLayer::Main(0), 0, 0, g, pages); - let draft = Fixture::with_geometry(&mut mem, KvLayer::Draft, 0, 2, g, pages); + let geometry = FixtureGeometry { g, n_pages: pages }; + let main = Fixture::with_geometry(&mut mem, KvLayer::Main(0), 0, 0, geometry); + let draft = Fixture::with_geometry(&mut mem, KvLayer::Draft, 0, 2, geometry); let z = state_sizes(&g).unwrap(); mem.put(StateRegion::Gdn, vec![0; z.gdn]); mem.put(StateRegion::PleHist, vec![0; if ple { z.ple } else { 0 }]); @@ -114,6 +115,20 @@ pub(super) fn chat(salt: i32, system: usize, turns: &[usize]) -> Vec { ids } +/// A request to replay: its prompt ids, image keys and steering flag. +#[derive(Clone, Copy)] +pub(super) struct Req<'a> { + ids: &'a [i32], + imgs: &'a [ConversationImageKey], + cvec: bool, +} + +impl<'a> Req<'a> { + pub(super) fn new(ids: &'a [i32], imgs: &'a [ConversationImageKey], cvec: bool) -> Self { + Self { ids, imgs, cvec } + } +} + impl World { /// Read the prompt per the plan with the manager's checkpoints; the position reached, or `None` when the request /// was cancelled after `stop_after` actions. @@ -147,20 +162,20 @@ impl World { /// finish. `stop_after` cancels after that many prompt actions. pub(super) fn request( &mut self, - ids: &[i32], - imgs: &[ConversationImageKey], - cvec: bool, + req: Req<'_>, gen_tokens: &[i32], stop_after: Option, root_min: usize, ) -> Result { + let Req { ids, imgs, cvec } = req; let mut engine = DeviceEngine { device: &mut self.dev, geometry: &self.g, session: &self.ss, draft: &self.draft }; let start = self.mgr.begin_request(&mut engine, ids, imgs, cvec).map_err(|e| e.0)?; let resume = if start.reread_to.is_some() { 0 } else { start.resume }; self.dev.assert_prefix_state(ids, resume, "state after begin_request"); let prompt: Vec = ids.iter().map(|&i| i as u32).collect(); - let plan = PromptPlan::new(&prompt, start.resume, start.reread_to, None, prompt_options(root_min), 256) + let resume = ResumePoint { resume: start.resume, reread_to: start.reread_to }; + let plan = PromptPlan::new(&prompt, resume, None, PlanLimits::new(prompt_options(root_min), 256)) .map_err(|e| format!("{e:?}"))?; let Some(at) = self.read_plan(ids, imgs, plan, (start.read_from, stop_after))? else { self.mgr.finish_request(Vec::new(), imgs, true); diff --git a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs index 8c8c3812..f5e5493e 100644 --- a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs +++ b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs @@ -94,7 +94,7 @@ fn random_request( let stop = (rng.below(8) == 0).then(|| rng.below(3) as usize); let generated = gen_tokens(step, 1 + rng.below(8) as usize); let ctx = format!("seed {seed} step {step}"); - let run = w.request(&ids, &[], cvec, &generated, stop, 8).unwrap_or_else(|e| panic!("{ctx}: {e}")); + let run = w.request(Req::new(&ids, &[], cvec), &generated, stop, 8).unwrap_or_else(|e| panic!("{ctx}: {e}")); cov.paths[resume_path(&run.start)] += 1; cov.parks += w.mgr.take_events().iter().filter(|e| e.contains("parked ")).count(); let live = !run.consumed.is_empty(); diff --git a/crates/engine-core/src/conversation/model.rs b/crates/engine-core/src/conversation/model.rs index e32d985e..77e4645b 100644 --- a/crates/engine-core/src/conversation/model.rs +++ b/crates/engine-core/src/conversation/model.rs @@ -307,6 +307,14 @@ pub fn fail(message: &str) -> ConvResult { Err(ConvError(format!("conversation snapshot: {message}"))) } +/// The host blocks `[begin, end)` of a drafter ring and the number of ring slots they land in (`block % slots`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RingBlocks { + pub begin: i64, + pub end: i64, + pub slots: i64, +} + /// The abstract device. Every method that can fail returns the backend's /// message, which the snapshot code wraps with the original's prefix. pub trait StateMemory { @@ -323,12 +331,5 @@ pub trait StateMemory { fn reset_streaming_residency(&mut self, layer: KvLayer) -> Result<(), String>; /// `kv_ring_restore`: copy host blocks `[begin, end)` into the ring slots /// (`block % n_slots`) of a drafter ring. - fn restore_ring( - &mut self, - layer: KvLayer, - format: i32, - begin_block: i64, - end_block: i64, - n_slots: i64, - ) -> Result<(), String>; + fn restore_ring(&mut self, layer: KvLayer, format: i32, blocks: RingBlocks) -> Result<(), String>; } diff --git a/crates/engine-core/src/conversation/snapshot.rs b/crates/engine-core/src/conversation/snapshot.rs index 4126ac8f..ecf5ebdf 100644 --- a/crates/engine-core/src/conversation/snapshot.rs +++ b/crates/engine-core/src/conversation/snapshot.rs @@ -10,7 +10,7 @@ use super::cache::{ ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, SavedConversation, }; use super::checked::{add, product}; -use super::kv::{kv_bytes, kv_capture_bytes, kv_restore, kv_save, kv_validate}; +use super::kv::{KvTarget, kv_bytes, kv_capture_bytes, kv_restore, kv_save, kv_validate}; use super::model::{ConvError, ConvResult, KvLayer, ModelGeometry, QsaDesc, SessionSpec, StateMemory, fail}; use super::state::{ StateSizes, checkpoint_restore, checkpoint_save, checkpoint_targets, checkpoint_validate, image_keys, session_sizes, @@ -27,6 +27,14 @@ pub struct ConversationView<'a> { pub cvec: bool, } +/// The session a snapshot is captured from: its carve, the model geometry and the draft's QSA state. +#[derive(Clone, Copy)] +pub struct SnapshotSession<'a> { + pub ss: &'a SessionSpec, + pub g: &'a ModelGeometry, + pub draft: &'a QsaDesc, +} + /// Outcome of [`snapshot_restore`]. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RestoreOutcome { @@ -236,22 +244,25 @@ fn begin_capture( fn capture_kv( captured: &mut SavedConversation, view: &ConversationView<'_>, - (ss, g, draft): (&SessionSpec, &ModelGeometry, &QsaDesc), + session: SnapshotSession<'_>, mem: &mut dyn StateMemory, unchanged: i64, ) -> ConvResult { + let SnapshotSession { ss, g, draft } = session; let layers = ss.owned_qsa(); let upto = view.ids.len() as i64; let mut reused = 0usize; for j in 0..layers { let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; - kv_save(&mut captured.kv[j], KvLayer::Main(j), st, g, upto, true, unchanged, mem, Some(&mut reused))?; + let target = KvTarget { layer: KvLayer::Main(j), st, g, upto, index: true }; + kv_save(&mut captured.kv[j], target, unchanged, mem, Some(&mut reused))?; } // The draft's final cell may not have been computed when the output cap was // reached. Refresh that page even when the main prefix continued unchanged. let draft_unchanged = (unchanged - 1).max(0); let draft_kv = &mut captured.kv[layers]; - kv_save(draft_kv, KvLayer::Draft, draft, g, upto, false, draft_unchanged, mem, Some(&mut reused))?; + let target = KvTarget { layer: KvLayer::Draft, st: draft, g, upto, index: false }; + kv_save(draft_kv, target, draft_unchanged, mem, Some(&mut reused))?; Ok(reused) } @@ -259,21 +270,19 @@ fn capture_kv( /// Builds into a new object so a failure cannot publish a partial snapshot. /// `reuse` is consumed, including on failure. The caller admits the estimate /// first; the active session is never modified by capture. -#[allow(clippy::too_many_arguments)] pub fn snapshot_save( view: &ConversationView<'_>, - ss: &SessionSpec, - g: &ModelGeometry, - draft: &QsaDesc, + session: SnapshotSession<'_>, mem: &mut dyn StateMemory, reuse: ConversationKvReuse, reused_bytes: Option<&mut usize>, ) -> ConvResult { + let SnapshotSession { ss, g, draft } = session; snapshot_capture_bytes(&reuse, view, ss, g, draft)?; synchronize(mem)?; let (mut captured, unchanged) = begin_capture(view, ss, g, reuse)?; checkpoint_save(&mut captured.live, ss, g, mem)?; - let reused = capture_kv(&mut captured, view, (ss, g, draft), mem, unchanged)?; + let reused = capture_kv(&mut captured, view, session, mem, unchanged)?; if let Some(total) = reused_bytes { *total += reused; } @@ -343,9 +352,10 @@ pub fn snapshot_restore( let restore = |mem: &mut dyn StateMemory| -> ConvResult<()> { for j in 0..ss.owned_qsa() { let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; - kv_restore(&image.kv[j], KvLayer::Main(j), st, g, upto, true, mem)?; + kv_restore(&image.kv[j], KvTarget { layer: KvLayer::Main(j), st, g, upto, index: true }, mem)?; } - kv_restore(&image.kv[ss.owned_qsa()], KvLayer::Draft, draft, g, upto, false, mem)?; + let target = KvTarget { layer: KvLayer::Draft, st: draft, g, upto, index: false }; + kv_restore(&image.kv[ss.owned_qsa()], target, mem)?; checkpoint_restore(&image.live, ss, g, mem) }; match restore(mem) { diff --git a/crates/engine-core/src/conversation/snapshot_tests.rs b/crates/engine-core/src/conversation/snapshot_tests.rs index 4a370516..468e72bc 100644 --- a/crates/engine-core/src/conversation/snapshot_tests.rs +++ b/crates/engine-core/src/conversation/snapshot_tests.rs @@ -6,20 +6,27 @@ use super::cache::{ ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, SavedConversation, }; -use super::kv::{kv_bytes, kv_restore, kv_save, kv_verify}; +use super::kv::{KvTarget, kv_bytes, kv_restore, kv_save, kv_verify}; use super::model::{ IDX_BLOCK, IdxKind, KV_F16, KV_INT8, KV_Q4, KV_VALUE_INT8, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, SessionSpec, StateRegion, StreamMap, }; use super::snapshot::{ - ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, snapshot_save, - snapshot_validate, + ConversationView, RestoreOutcome, SnapshotSession, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, + snapshot_save, snapshot_validate, }; use super::state::{checkpoint_restore, checkpoint_save, checkpoint_validate, session_sizes, state_sizes}; use super::testing::HostMemory; pub(super) const HYBRID: i32 = 3; +/// The model geometry of a fixture and the number of four-cell pages of its layer (`max_cells = 4 * n_pages`). +#[derive(Clone, Copy)] +pub(super) struct FixtureGeometry { + pub(super) g: ModelGeometry, + pub(super) n_pages: i64, +} + /// The C++ `Fixture`: one layer's pools (device slots plus host pools for a /// streamed layer) registered in a [`HostMemory`]. pub(super) struct Fixture { diff --git a/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs index 811b3ab2..8f03a3a5 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs @@ -273,7 +273,8 @@ impl Fx { fn readback(&mut self) -> ConvResult { let draft = self.image.kv.last().unwrap(); - kv_verify(draft, KvLayer::Draft, &self.draft.st, &self.g, 9, false, &mut self.mem) + let target = KvTarget { layer: KvLayer::Draft, st: &self.draft.st, g: &self.g, upto: 9, index: false }; + kv_verify(draft, target, &mut self.mem) } fn restore_and_readback(&mut self) { @@ -303,7 +304,8 @@ impl Fx { self.mem.copied_bytes = 0; let live_view = view_of(&self.image); let (ss, g, st) = (&self.ss, &self.g, &self.draft.st); - let full = snapshot_save(&live_view, ss, g, st, &mut self.mem, Default::default(), None) + let session = SnapshotSession { ss, g, draft: st }; + let full = snapshot_save(&live_view, session, &mut self.mem, Default::default(), None) .expect("full capture through host transfer backend"); let full_copies = self.mem.copied_bytes; let reuse = Self::reuse_of(&full); @@ -311,7 +313,7 @@ impl Fx { .expect("incremental capture admission without transfers"); self.mem.copied_bytes = 0; let mut reused = 0; - let incremental = snapshot_save(&live_view, ss, g, st, &mut self.mem, reuse, Some(&mut reused)) + let incremental = snapshot_save(&live_view, session, &mut self.mem, reuse, Some(&mut reused)) .expect("incremental capture through host backend"); assert!( reused > 0 && self.mem.copied_bytes + reused == full_copies, @@ -330,6 +332,7 @@ impl Fx { fn malformed_reuse(&mut self, full: &SavedConversation) { let live_view = view_of(&self.image); let (ss, g, st) = (&self.ss, &self.g, &self.draft.st); + let session = SnapshotSession { ss, g, draft: st }; let mut malformed = Self::reuse_of(full); malformed.kv.last_mut().unwrap().k.pop_back().unwrap(); self.mem.copy_calls = 0; @@ -345,7 +348,7 @@ impl Fx { let reuse = Self::reuse_of(full); self.mem.fail_copy = self.mem.copy_calls + 1; assert!( - snapshot_save(&live_view, ss, g, st, &mut self.mem, reuse, None).is_err(), + snapshot_save(&live_view, session, &mut self.mem, reuse, None).is_err(), "incremental capture copy failure is reported (nothing is published)" ); } diff --git a/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs index a2811872..0f9e0524 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs @@ -99,7 +99,8 @@ impl Session { fn save(&mut self, ids: &[i32]) -> ConvResult { let view = mk_view(ids, &self.images, &self.checkpoints); - snapshot_save(&view, &self.ss, &self.g, &self.draft.st, &mut self.mem, Default::default(), None) + let session = SnapshotSession { ss: &self.ss, g: &self.g, draft: &self.draft.st }; + snapshot_save(&view, session, &mut self.mem, Default::default(), None) } fn restore(&mut self, image: &SavedConversation) -> RestoreOutcome { @@ -151,7 +152,8 @@ impl Session { let (ss, g, st) = (&self.ss, &self.g, &self.draft.st); let peak = snapshot_capture_bytes(&reuse, &view, ss, g, st).expect("admit incremental capture peak"); let mut reused = 0usize; - let incremental = snapshot_save(&view, ss, g, st, &mut self.mem, reuse, Some(&mut reused)) + let session = SnapshotSession { ss, g, draft: st }; + let incremental = snapshot_save(&view, session, &mut self.mem, reuse, Some(&mut reused)) .expect("capture with retained pages"); (peak, incremental, reused) } @@ -183,11 +185,16 @@ impl Session { assert_eq!(dirty >= 4, reused > 0, "only complete unchanged pages or rows are retained"); assert_eq!(incremental.kv[0].v.first_address(), original, "growth never reallocates the retained payload"); assert_eq!(self.restore(&incremental), RestoreOutcome::Restored, "restore segmented incremental snapshot"); - kv_verify(incremental.kv.last().unwrap(), KvLayer::Draft, &self.draft.st, &self.g, 70, false, &mut self.mem) - .expect("incremental draft authoritative and ring read-back"); + self.verify_draft(incremental.kv.last().unwrap(), 70); ids.truncate(65); } + /// Read the draft's authoritative bytes and its ring back from the device after a restore of `upto` tokens. + fn verify_draft(&mut self, image: &ConversationKv, upto: i64) { + let target = KvTarget { layer: KvLayer::Draft, st: &self.draft.st, g: &self.g, upto, index: false }; + kv_verify(image, target, &mut self.mem).expect("incremental draft authoritative and ring read-back"); + } + fn assert_checkpoint_rebuild(&mut self, a: &SavedConversation) { checkpoint_restore(&a.checkpoints[0], &self.ss, &self.g, &mut self.mem) .expect("restore early running checkpoint"); diff --git a/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs index 5d5a4752..83b38c8d 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs @@ -16,12 +16,14 @@ struct Level { impl Level { fn save(&mut self, upto: i64, what: &str) -> ConversationKv { let mut kv = ConversationKv::default(); - kv_save(&mut kv, self.f.layer, &self.f.st, &self.f.g, upto, self.index, 0, &mut self.mem, None).expect(what); + let target = KvTarget { layer: self.f.layer, st: &self.f.st, g: &self.f.g, upto, index: self.index }; + kv_save(&mut kv, target, 0, &mut self.mem, None).expect(what); kv } fn restore(&mut self, image: &ConversationKv, upto: i64) -> ConvResult<()> { - kv_restore(image, self.f.layer, &self.f.st, &self.f.g, upto, self.index, &mut self.mem) + let target = KvTarget { layer: self.f.layer, st: &self.f.st, g: &self.f.g, upto, index: self.index }; + kv_restore(image, target, &mut self.mem) } fn reject_hybrid_streaming(&mut self) { @@ -31,8 +33,9 @@ impl Level { let bytes = kv_bytes(&self.f.st, &self.f.g, 9, true); assert_eq!(bytes, 0, "hybrid streaming/ring rejected without block-mover abort"); let mut invalid = ConversationKv::default(); + let target = KvTarget { layer, st: &self.f.st, g: &self.f.g, upto: 9, index: true }; assert!( - kv_save(&mut invalid, layer, &self.f.st, &self.f.g, 9, true, 0, &mut self.mem, None).is_err(), + kv_save(&mut invalid, target, 0, &mut self.mem, None).is_err(), "hybrid streaming/ring capture fails closed" ); } @@ -43,8 +46,9 @@ impl Level { let (layer, index) = (self.f.layer, self.index); for bad in [-1i64, 97, i64::MAX] { let mut invalid = ConversationKv::default(); + let target = KvTarget { layer, st: &self.f.st, g: &self.f.g, upto: bad, index }; assert!( - kv_save(&mut invalid, layer, &self.f.st, &self.f.g, bad, index, 0, &mut self.mem, None).is_err(), + kv_save(&mut invalid, target, 0, &mut self.mem, None).is_err(), "reject invalid save extent before allocation" ); assert!(self.restore(&invalid, bad).is_err(), "reject invalid restore extent before copying"); @@ -116,7 +120,8 @@ impl Level { fn cycle(&mut self, upto: i64) { let a = self.restore_round_trip(upto); let (layer, index) = (self.f.layer, self.index); - kv_verify(&a, layer, &self.f.st, &self.f.g, upto, index, &mut self.mem) + let target = KvTarget { layer, st: &self.f.st, g: &self.f.g, upto, index }; + kv_verify(&a, target, &mut self.mem) .expect("verify restored authoritative and resident bytes without rewriting them"); if self.mode == 1 { assert!(self.mem.page_tables[&layer].iter().all(|&x| x == -1), "stale VRAM pages invalidated"); diff --git a/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs index 11838bbe..07be6e63 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs @@ -152,7 +152,7 @@ fn alloc_pools(a: &mut Alloc<'_>, st: &mut QsaDesc, d: &Dims, (fmt, sizes): (i32 impl Fixture { pub(in super::super) fn new(mem: &mut HostMemory, layer: KvLayer, fmt: i32, mode: i32) -> Self { - Self::with_geometry(mem, layer, fmt, mode, ModelGeometry::default(), 24) + Self::with_geometry(mem, layer, fmt, mode, FixtureGeometry { g: ModelGeometry::default(), n_pages: 24 }) } /// `n_pages` four-cell pages of the layer's K/V (`max_cells = 4 * n_pages`). @@ -161,9 +161,9 @@ impl Fixture { layer: KvLayer, fmt: i32, mode: i32, - g: ModelGeometry, - n_pages: i64, + geometry: FixtureGeometry, ) -> Self { + let FixtureGeometry { g, n_pages } = geometry; let mut st = fixture_desc(fmt, mode, n_pages); let d = fixture_dims(&g, &st, fmt); let mut sizes = fixture_sizes(&d, &st, fmt); diff --git a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs index 943bccc0..b5e4061d 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs @@ -199,7 +199,8 @@ fn golden_layer_layouts_and_payload_hashes_match_the_original() { let ctx = format!("fmt {fmt} mode {mode} rot {rot} upto {upto}"); assert_eq!(kv_bytes(&f.st, &f.g, upto, index) as u64, case["bytes"].as_u64().unwrap(), "{ctx}: kv_bytes"); let mut image = ConversationKv::default(); - let saved = kv_save(&mut image, f.layer, &f.st, &f.g, upto, index, 0, mem, None); + let target = KvTarget { layer: f.layer, st: &f.st, g: &f.g, upto, index }; + let saved = kv_save(&mut image, target, 0, mem, None); assert_eq!(saved.is_ok(), case["ok"].as_bool().unwrap(), "{ctx}: save outcome"); if saved.is_ok() { assert_kv(&case["image"], &image, &ctx); diff --git a/crates/engine-core/src/conversation/testing.rs b/crates/engine-core/src/conversation/testing.rs index d9ec2574..f539ca56 100644 --- a/crates/engine-core/src/conversation/testing.rs +++ b/crates/engine-core/src/conversation/testing.rs @@ -4,7 +4,7 @@ //! It exercises the real control flow without a device; it is not a claim //! about hardware-failure recovery. -use super::model::{KvLayer, StateMemory, StateRegion}; +use super::model::{KvLayer, RingBlocks, StateMemory, StateRegion}; use std::collections::HashMap; #[derive(Default)] @@ -121,14 +121,7 @@ impl StateMemory for HostMemory { Ok(()) } - fn restore_ring( - &mut self, - layer: KvLayer, - _format: i32, - begin_block: i64, - end_block: i64, - n_slots: i64, - ) -> Result<(), String> { + fn restore_ring(&mut self, layer: KvLayer, _format: i32, blocks: RingBlocks) -> Result<(), String> { let pages = *self.ring_pages.get(&layer).ok_or("not a ring layer")?; for pool in [ super::model::KvPool::K, @@ -136,7 +129,7 @@ impl StateMemory for HostMemory { super::model::KvPool::KScale, super::model::KvPool::VScale, ] { - self.restore_ring_pool(layer, pool, pages, (begin_block, end_block, n_slots)); + self.restore_ring_pool(layer, pool, pages, (blocks.begin, blocks.end, blocks.slots)); } Ok(()) } diff --git a/crates/engine-core/src/prefix_cache/store.rs b/crates/engine-core/src/prefix_cache/store.rs index 50f5ff0b..4b9f36ff 100644 --- a/crates/engine-core/src/prefix_cache/store.rs +++ b/crates/engine-core/src/prefix_cache/store.rs @@ -155,6 +155,19 @@ pub struct Candidate { frontier: bool, } +/// The payloads of a node being inserted: its recurrent state and the blocks the store did not hold yet. +pub struct NodePayload { + pub state: N, + pub blocks: Vec<(usize, B)>, +} + +/// The tail of a tail node: the cells after the last full block, and the end (in tokens) of the tail node that must +/// stay standing when this one supersedes the others of its history (`None`: none is kept). +pub struct KeptTail { + pub tail: B, + pub keep_end: Option, +} + struct Scored { key: u64, /// Expected tokens saved per byte freed (the order victims are taken in). diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs index 28a2543d..3c37f6b1 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs @@ -175,11 +175,14 @@ impl PrefixStore { &mut self, candidate: Candidate, tokens: &[i32], - state: N, - blocks: Vec<(usize, B)>, - tail: Option, - keep_end: Option, + payload: NodePayload, + tail: Option>, ) -> Result<(), Reject> { + let NodePayload { state, blocks } = payload; + let (tail, keep_end) = match tail { + Some(KeptTail { tail, keep_end }) => (Some(tail), keep_end), + None => (None, None), + }; if !self.candidate_fits(&candidate, tokens, &blocks) { return Err(Reject::Mismatch); } diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs index 76e987b7..5be7de66 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs @@ -56,7 +56,7 @@ impl PrefixStore { if candidate.tail_len != 0 { return Err(Reject::Mismatch); } - self.insert(candidate, tokens, state, blocks, None, None) + self.insert(candidate, tokens, NodePayload { state, blocks }, None) } /// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same @@ -66,11 +66,10 @@ impl PrefixStore { &mut self, candidate: Candidate, tokens: &[i32], - state: N, - blocks: Vec<(usize, B)>, + payload: NodePayload, tail: B, ) -> Result<(), Reject> { - self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None) + self.commit_tail_keeping(candidate, tokens, payload, KeptTail { tail, keep_end: None }) } /// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a @@ -81,15 +80,13 @@ impl PrefixStore { &mut self, candidate: Candidate, tokens: &[i32], - state: N, - blocks: Vec<(usize, B)>, - tail: B, - keep_end: Option, + payload: NodePayload, + tail: KeptTail, ) -> Result<(), Reject> { if candidate.tail_len == 0 { return Err(Reject::Mismatch); } - self.insert(candidate, tokens, state, blocks, Some(tail), keep_end) + self.insert(candidate, tokens, payload, Some(tail)) } /// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues). diff --git a/crates/engine-core/src/prefix_cache/store/tests.rs b/crates/engine-core/src/prefix_cache/store/tests.rs index 095917c5..e838db4e 100644 --- a/crates/engine-core/src/prefix_cache/store/tests.rs +++ b/crates/engine-core/src/prefix_cache/store/tests.rs @@ -52,7 +52,8 @@ fn put_tail(s: &mut PrefixStore, t: &[i32], len: usize) -> Con match s.consider_tail(prefix, true, STATE, BLOCK) { Consider::Admit(c) => { let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); - s.commit_tail(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2)).unwrap(); + s.commit_tail(c, prefix, NodePayload { state: Payload(STATE), blocks: blocks_in }, Payload(BLOCK / 2)) + .unwrap(); s.check_invariants(); Consider::Exists } @@ -66,7 +67,9 @@ fn put_tail_keeping(s: &mut PrefixStore, t: &[i32], len: usize match s.consider_tail(prefix, true, STATE, BLOCK) { Consider::Admit(c) => { let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); - s.commit_tail_keeping(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2), Some(keep)).unwrap(); + let payload = NodePayload { state: Payload(STATE), blocks: blocks_in }; + let tail = KeptTail { tail: Payload(BLOCK / 2), keep_end: Some(keep) }; + s.commit_tail_keeping(c, prefix, payload, tail).unwrap(); s.check_invariants(); } other => panic!("not admitted: {other:?}"), diff --git a/crates/engine-core/src/prompt.rs b/crates/engine-core/src/prompt.rs index 1b9eb5d4..575b9e86 100644 --- a/crates/engine-core/src/prompt.rs +++ b/crates/engine-core/src/prompt.rs @@ -25,6 +25,36 @@ pub struct PromptOptions { pub grid: usize, } +/// Where a request restarts: the authenticated `resume` position and the optional end of the re-read prefix. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ResumePoint { + pub resume: usize, + pub reread_to: Option, +} + +impl ResumePoint { + /// A request read from its first token, without a re-read. + pub const START: Self = Self { resume: 0, reread_to: None }; + + /// Resume at `resume` without a re-read. + pub const fn at(resume: usize) -> Self { + Self { resume, reread_to: None } + } +} + +/// What the planner admits: the options and the admitted chunk capacity. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct PlanLimits { + pub options: PromptOptions, + pub admitted_capacity: usize, +} + +impl PlanLimits { + pub const fn new(options: PromptOptions, admitted_capacity: usize) -> Self { + Self { options, admitted_capacity } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PromptPath { Batched { diff --git a/crates/engine-core/src/prompt/grid_tests.rs b/crates/engine-core/src/prompt/grid_tests.rs index dd609bf7..8ab87a24 100644 --- a/crates/engine-core/src/prompt/grid_tests.rs +++ b/crates/engine-core/src/prompt/grid_tests.rs @@ -3,7 +3,7 @@ use super::*; fn cuts(tokens: &[u32], resume: usize, o: PromptOptions, capacity: usize) -> Vec<(usize, usize)> { - PromptPlan::new(tokens, resume, None, None, o, capacity) + PromptPlan::new(tokens, ResumePoint::at(resume), None, PlanLimits::new(o, capacity)) .unwrap() .filter(|a| a.path != PromptPath::FinalSeed) .map(|a| (a.first, a.count)) @@ -60,7 +60,11 @@ fn a_grid_must_be_a_multiple_of_256_within_the_admitted_capacity() { (512, 256, false), ] { let o = PromptOptions { grid, force_batched: true, ..PromptOptions::original_mode17(262144) }; - assert_eq!(PromptPlan::new(&tokens, 0, None, None, o, capacity).is_ok(), ok, "grid {grid} capacity {capacity}"); + assert_eq!( + PromptPlan::new(&tokens, ResumePoint::START, None, PlanLimits::new(o, capacity)).is_ok(), + ok, + "grid {grid} capacity {capacity}" + ); } } diff --git a/crates/engine-core/src/prompt/impl_promptoptions.rs b/crates/engine-core/src/prompt/impl_promptoptions.rs index d183d6bd..4ef0a0a8 100644 --- a/crates/engine-core/src/prompt/impl_promptoptions.rs +++ b/crates/engine-core/src/prompt/impl_promptoptions.rs @@ -130,27 +130,25 @@ impl<'a> PromptPlan<'a> { pub fn new_in_context( serving_cells: u64, prompt: &'a [u32], - resume: usize, - reread_to: Option, + resume: ResumePoint, embedding_rows: Option<&'a [bool]>, - options: PromptOptions, - admitted_capacity: usize, + limits: PlanLimits, ) -> Result { - if options.context_tokens as u64 > serving_cells { + if limits.options.context_tokens as u64 > serving_cells { return Err(PlanError::InvalidInput); } - Self::new(prompt, resume, reread_to, embedding_rows, options, admitted_capacity) + Self::new(prompt, resume, embedding_rows, limits) } /// `resume` and `reread_to` are scheduler operands, not certificates. /// Existing real session/draft restore must authenticate them first. pub fn new( prompt: &'a [u32], - resume: usize, - reread_to: Option, + resume: ResumePoint, embedding_rows: Option<&'a [bool]>, - options: PromptOptions, - admitted_capacity: usize, + limits: PlanLimits, ) -> Result { + let ResumePoint { resume, reread_to } = resume; + let PlanLimits { options, admitted_capacity } = limits; if !prompt_is_valid(prompt, (resume, embedding_rows), &options, (admitted_capacity, reread_to)) { return Err(PlanError::InvalidInput); } diff --git a/crates/engine-core/src/prompt/tests.rs b/crates/engine-core/src/prompt/tests.rs index f030f6d2..b9a22ef2 100644 --- a/crates/engine-core/src/prompt/tests.rs +++ b/crates/engine-core/src/prompt/tests.rs @@ -57,14 +57,9 @@ fn original_segment(actions: &mut Vec, at: &mut usize, to: usize, } } -fn original( - tokens: &[u32], - resume: usize, - reread: Option, - pictures: Option<&[bool]>, - o: PromptOptions, - cap: usize, -) -> Vec { +fn original(tokens: &[u32], resume: ResumePoint, pictures: Option<&[bool]>, limits: PlanLimits) -> Vec { + let ResumePoint { resume, reread_to: reread } = resume; + let PlanLimits { options: o, admitted_capacity: cap } = limits; let n = tokens.len(); let turn = original_turn(tokens, resume, o); let from = if reread.is_some() { 0 } else { resume }; @@ -93,13 +88,17 @@ fn sanitized_frame() -> Vec { } fn assert_plan_matches_original(frame: &[u32], options: PromptOptions) { - let baseline = original(frame, 0, None, None, options, 8192); - assert_eq!(baseline, PromptPlan::new(frame, 0, None, None, options, 8192).unwrap().collect::>()); + let baseline = original(frame, ResumePoint::START, None, PlanLimits::new(options, 8192)); + assert_eq!( + baseline, + PromptPlan::new(frame, ResumePoint::START, None, PlanLimits::new(options, 8192)).unwrap().collect::>() + ); } fn assert_first_frame_plan(frame: &[u32], o: PromptOptions) { - let baseline = original(frame, 0, None, None, o, 8192); - let candidate: Vec<_> = PromptPlan::new(frame, 0, None, None, o, 8192).unwrap().collect(); + let baseline = original(frame, ResumePoint::START, None, PlanLimits::new(o, 8192)); + let candidate: Vec<_> = + PromptPlan::new(frame, ResumePoint::START, None, PlanLimits::new(o, 8192)).unwrap().collect(); assert_eq!(baseline, candidate); assert_eq!( candidate.iter().map(|a| (a.first, a.count, a.path)).collect::>(), @@ -114,8 +113,11 @@ fn assert_first_frame_plan(frame: &[u32], o: PromptOptions) { fn assert_sweep_case_matches_original(tokens: &[u32], resume: usize, reread: Option, options: PromptOptions) { let n = tokens.len(); - let baseline = original(tokens, resume, reread, None, options, 8192); - let candidate: Vec<_> = PromptPlan::new(tokens, resume, reread, None, options, 8192).unwrap().collect(); + let baseline = original(tokens, ResumePoint { resume, reread_to: reread }, None, PlanLimits::new(options, 8192)); + let candidate: Vec<_> = + PromptPlan::new(tokens, ResumePoint { resume, reread_to: reread }, None, PlanLimits::new(options, 8192)) + .unwrap() + .collect(); assert_eq!(baseline, candidate); assert_eq!(candidate.last().unwrap().first, n - 1); assert!(candidate.iter().all(|a| a.count > 0 && a.first + a.count <= n)); @@ -164,10 +166,12 @@ fn assert_auto_capacity_and_request_capacity() { } fn assert_invalid_plans_are_refused(frame: &[u32], pictures: &[bool], o: PromptOptions) { - assert!(PromptPlan::new(frame, 202, None, None, o, 8192).is_err()); - assert!(PromptPlan::new(frame, 0, Some(1), None, o, 8192).is_err()); - assert!(PromptPlan::new(frame, 0, None, Some(&pictures[..201]), o, 8192).is_err()); - assert!(PromptPlan::new(frame, 0, None, None, o, 0).is_err()); + assert!(PromptPlan::new(frame, ResumePoint::at(202), None, PlanLimits::new(o, 8192)).is_err()); + assert!( + PromptPlan::new(frame, ResumePoint { resume: 0, reread_to: Some(1) }, None, PlanLimits::new(o, 8192)).is_err() + ); + assert!(PromptPlan::new(frame, ResumePoint::START, Some(&pictures[..201]), PlanLimits::new(o, 8192)).is_err()); + assert!(PromptPlan::new(frame, ResumePoint::START, None, PlanLimits::new(o, 0)).is_err()); assert!(choose_auto_capacity(262144, 8192, 128, 85, |_| Ok(1)).unwrap().is_none()); } @@ -179,8 +183,13 @@ fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { assert_sweep_matches_original(o); let mut pictures = vec![false; 202]; pictures[199] = true; - let baseline = original(&frame, 0, None, Some(&pictures), o, 8192); - assert_eq!(baseline, PromptPlan::new(&frame, 0, None, Some(&pictures), o, 8192).unwrap().collect::>()); + let baseline = original(&frame, ResumePoint::START, Some(&pictures), PlanLimits::new(o, 8192)); + assert_eq!( + baseline, + PromptPlan::new(&frame, ResumePoint::START, Some(&pictures), PlanLimits::new(o, 8192)) + .unwrap() + .collect::>() + ); assert_auto_capacity_and_request_capacity(); for options in [PromptOptions { root_min: 1, ..o }, PromptOptions { short_read: 0, ..o }] { assert_plan_matches_original(&frame, options); @@ -220,7 +229,7 @@ impl PromptRunner for Recorder { } fn recorded_drive(tokens: &[u32], resume: usize, o: PromptOptions) -> (Recorder, DriveSummary) { - let plan = PromptPlan::new(tokens, resume, None, None, o, 8192).unwrap(); + let plan = PromptPlan::new(tokens, ResumePoint::at(resume), None, PlanLimits::new(o, 8192)).unwrap(); let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; let s = drive(plan, 8192, &mut r).unwrap(); (r, s) @@ -271,19 +280,19 @@ fn drive_stops_on_cancel_runner_error_and_contract_violations() { let tokens = vec![7; 20000]; let mut r = Recorder { log: vec![], stop_after: Some(1), fail_on: None }; assert_eq!( - drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), + drive(PromptPlan::new(&tokens, ResumePoint::START, None, PlanLimits::new(o, 8192)).unwrap(), 8192, &mut r), Err(DriveError::Cancelled { at: 8192 }) ); assert_eq!(r.log.len(), 1); let mut r = Recorder { log: vec![], stop_after: None, fail_on: Some("batched") }; assert_eq!( - drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), + drive(PromptPlan::new(&tokens, ResumePoint::START, None, PlanLimits::new(o, 8192)).unwrap(), 8192, &mut r), Err(DriveError::Runner("batched failed")) ); // an executor built for a smaller capacity than the plan was admitted with let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; assert_eq!( - drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 4096, &mut r), + drive(PromptPlan::new(&tokens, ResumePoint::START, None, PlanLimits::new(o, 8192)).unwrap(), 4096, &mut r), Err(DriveError::Contract("batched chunk exceeds the admitted capacity")) ); assert!(r.log.is_empty()); diff --git a/crates/engine-core/src/spec/adaptive.rs b/crates/engine-core/src/spec/adaptive.rs index ea02738d..a61273fd 100644 --- a/crates/engine-core/src/spec/adaptive.rs +++ b/crates/engine-core/src/spec/adaptive.rs @@ -163,6 +163,13 @@ pub struct AdaptivePolicy { meas_ms: f64, } +/// How a recorded round was drawn: from the lookup drafter, and as an exploration round. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RoundFlags { + pub lookup: bool, + pub explored: bool, +} + /// Counters of what rounds did, kept by the controller for every policy (fixed windows included) and printed per /// request by `LELEKA_SPEC_STATS=1`. #[derive(Clone, Debug, Default)] diff --git a/crates/engine-core/src/spec/adaptive/impl_specstats.rs b/crates/engine-core/src/spec/adaptive/impl_specstats.rs index 1f05ffe2..274e5846 100644 --- a/crates/engine-core/src/spec/adaptive/impl_specstats.rs +++ b/crates/engine-core/src/spec/adaptive/impl_specstats.rs @@ -4,7 +4,8 @@ use super::*; impl SpecStats { - pub fn record(&mut self, t: usize, accepted: usize, lookup: bool, explored: bool, ms: f64) { + pub fn record(&mut self, t: usize, accepted: usize, flags: RoundFlags, ms: f64) { + let RoundFlags { lookup, explored } = flags; self.rounds += 1; self.tokens += accepted as u64 + 1; self.offered += (t - 1) as u64; diff --git a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs index 17a274c4..097a9fea 100644 --- a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs +++ b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs @@ -96,8 +96,8 @@ fn a_trace_is_reproducible() { #[test] fn stats_line_reports_the_histograms() { let mut s = SpecStats::default(); - s.record(4, 3, false, false, 50.0); - s.record(6, 0, true, true, 60.0); + s.record(4, 3, RoundFlags { lookup: false, explored: false }, 50.0); + s.record(6, 0, RoundFlags { lookup: true, explored: true }, 60.0); let l = s.line(); assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}"); assert!(l.contains("accepted=3/8"), "{l}"); diff --git a/crates/engine-core/src/spec/policy.rs b/crates/engine-core/src/spec/policy.rs index 01519986..b495ea6d 100644 --- a/crates/engine-core/src/spec/policy.rs +++ b/crates/engine-core/src/spec/policy.rs @@ -11,6 +11,15 @@ pub struct Pick { pub lookup: bool, pub t: usize, } +/// What a verified round did, as `observe` learns from it: drawn from the lookup drafter or not, the rows verified +/// (`t`), the drafts accepted and the lookup match length. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RoundOutcome { + pub lookup: bool, + pub t: usize, + pub accepted: usize, + pub matched: usize, +} #[derive(Clone)] pub struct DraftPolicy { max_t: usize, @@ -98,7 +107,8 @@ impl DraftPolicy { } p } - pub fn observe(&mut self, lookup: bool, t: usize, accepted: usize, matched: usize, round_ms: f64) -> Result<()> { + pub fn observe(&mut self, round: RoundOutcome, round_ms: f64) -> Result<()> { + let RoundOutcome { lookup, t, accepted, matched } = round; if !(1..=MAX_T).contains(&t) || accepted >= t || !round_ms.is_finite() { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/conversation/original.rs b/crates/engine-qwen35-cuda/src/conversation/original.rs index f5f5e4dc..5c658bdd 100644 --- a/crates/engine-qwen35-cuda/src/conversation/original.rs +++ b/crates/engine-qwen35-cuda/src/conversation/original.rs @@ -8,8 +8,8 @@ use super::binding::SessionDevice; use super::model::{ - HostPools, IdxKind, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, SessionSpec, StateMemory, StateRegion, - StreamMap, + HostPools, IdxKind, KvLayer, KvPool, ModelGeometry, QsaDesc, RingBlocks, SessionShape, SessionSpec, StateMemory, + StateRegion, StreamMap, }; use leleka_cuda_driver::{ OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalSessionBytes, @@ -197,8 +197,8 @@ impl StateMemory for OriginalDevice { } } - fn restore_ring(&mut self, l: KvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<(), String> { - self.session.restore_ring(layer(l), format, begin, end, slots).map_err(text) + fn restore_ring(&mut self, l: KvLayer, format: i32, blocks: RingBlocks) -> Result<(), String> { + self.session.restore_ring(layer(l), format, blocks.begin, blocks.end, blocks.slots).map_err(text) } } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs index a174df8a..6bc8f12d 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke_conv.rs @@ -78,7 +78,7 @@ pub(super) fn serve_once( /// on how the prompt is split (a root boundary is only cut when reading from 0, a resume point is a boundary the /// full read does not have), so different chunks may flip a near tie, with or without the cache. pub(super) fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option, every: usize, cache: bool) -> bool { - use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; + use crate::backend::original_prompt::{PlanLimits, PromptOptions, PromptPath, PromptPlan, ResumePoint}; let options = PromptOptions { short_read: 64, force_batched: true, ..PromptOptions::original_mode17(16_384) }; let options = if cache { crate::qwen_forward::original_serve_stack::ConversationConfig { @@ -91,7 +91,7 @@ pub(super) fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option| -> Vec<(usize, usize)> { - PromptPlan::new(prompt, resume, reread_to, None, options, capacity) + PromptPlan::new(prompt, ResumePoint { resume, reread_to }, None, PlanLimits::new(options, capacity)) .map(|plan| plan.filter(|a| a.path != PromptPath::FinalSeed).map(|a| (a.first, a.count)).collect()) .unwrap_or_default() }; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs index 19d2d3b9..260c31dc 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs @@ -4,7 +4,7 @@ use super::super::routed_source_descriptor_fn::validate_rows_finite; use super::super::routed_source_descriptor_fn::{check_matrix_tensor, check_moe_metadata, selected_expert}; #[allow(unused_imports)] use super::*; -use leleka_model_format::qwen4exp::Qwen4ExpArtifact; +use leleka_model_format::qwen4exp::{Qwen4ExpArtifact, RowRange}; /// One expert matrix of a layer, admitted against its expected kind, shape and extent. fn moe_matrix( @@ -143,7 +143,12 @@ impl ModelBinding { bytes.resize(key.bytes, 0); let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; let bytes = artifact - .read_expert_rows_owned(tensor_role, u64::from(expert), 0, key.rows as u64, bytes.into_boxed_slice()) + .read_expert_rows_owned( + tensor_role, + u64::from(expert), + RowRange { first: 0, count: key.rows as u64 }, + bytes.into_boxed_slice(), + ) .map_err(|_| E::Read)?; if bytes.len() != key.bytes { return Err(E::Read); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs index 9e38f90c..bb260ede 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs @@ -3,7 +3,7 @@ use super::super::routed_source_descriptor_fn::{check_matrix_tensor, selected_expert, validate_rows_finite}; #[allow(unused_imports)] use super::*; -use leleka_model_format::qwen4exp::Qwen4ExpArtifact; +use leleka_model_format::qwen4exp::{Qwen4ExpArtifact, RowRange}; /// A selected expert's rows from the resident bank, finite-checked by the proven encoded validators. fn read_resident_block( @@ -16,7 +16,12 @@ fn read_resident_block( // The same final owner, full finite loop and later H2D still apply. bytes.resize(limit, 0); let bytes = artifact - .read_expert_rows_owned(matrix.role, u64::from(id), first as u64, count as u64, bytes.into_boxed_slice()) + .read_expert_rows_owned( + matrix.role, + u64::from(id), + RowRange { first: first as u64, count: count as u64 }, + bytes.into_boxed_slice(), + ) .map_err(|_| E::Read)?; if bytes.len() != limit { return Err(E::Read); @@ -41,7 +46,12 @@ fn stream_block( Ok(()) }; match expert { - Some(id) => artifact.stream_expert_rows(matrix.role, u64::from(id), first as u64, count as u64, consume), + Some(id) => artifact.stream_expert_rows( + matrix.role, + u64::from(id), + RowRange { first: first as u64, count: count as u64 }, + consume, + ), None => artifact.stream_rows(matrix.role, first as u64, count as u64, consume), } .map_err(|_| E::Read)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs index 49c74040..f976e654 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs @@ -1,7 +1,7 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). use super::*; -use crate::backend::original_prompt::{PromptPath, PromptPlan}; +use crate::backend::original_prompt::{PlanLimits, PromptPath, PromptPlan, ResumePoint}; /// A device whose state is the token list it holds; points are copies of it. A restore is only possible /// to a point that is a prefix of what the device holds (the positional-cell rule). @@ -87,7 +87,13 @@ fn read_batched_chunks( let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); + let plan = PromptPlan::new( + &tokens, + ResumePoint { resume: start.resume, reread_to: start.reread_to }, + None, + PlanLimits::new(options, 256), + ) + .unwrap(); for action in plan { if action.path == PromptPath::FinalSeed { break; @@ -172,7 +178,13 @@ fn read_chunks( let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); + let plan = PromptPlan::new( + &tokens, + ResumePoint { resume: start.resume, reread_to: start.reread_to }, + None, + PlanLimits::new(options, 256), + ) + .unwrap(); for action in plan.take(chunks) { assert_eq!(d.held.len(), action.first); d.held.extend_from_slice(&prompt[action.first..action.first + action.count]); @@ -287,7 +299,7 @@ fn a_one_token_prompt_starts_empty_reads_nothing_and_checkpoints_nothing() { let tokens = [first[0] as u32]; let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, 0, None, None, options, 256).unwrap(); + let plan = PromptPlan::new(&tokens, ResumePoint::START, None, PlanLimits::new(options, 256)).unwrap(); assert!(plan.into_iter().all(|a| a.path == PromptPath::FinalSeed)); c.finish(true); // the buffer was zeroed for it, so the displaced conversation's checkpoints (cells that are gone) are dropped diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs index 2bf76ad2..87d91fbe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs @@ -2,7 +2,7 @@ #[allow(unused_imports)] use super::*; -use crate::prefix_cache::store::Candidate; +use crate::prefix_cache::store::{Candidate, KeptTail, NodePayload}; use std::ops::ControlFlow; /// Which kind of checkpoint position a verdict is about: a grid point, or a request-end tail of that many tokens. @@ -259,7 +259,7 @@ impl PrefixServe { let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); let park_ms = self.clock.since(started).as_secs_f64() * 1e3; self.store - .commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end) + .commit_tail_keeping(candidate, tokens, NodePayload { state, blocks }, KeptTail { tail, keep_end }) .map_err(|_| Error::IdentityMismatch)?; self.park_ms_request += park_ms; self.admitted_request += 1; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs index 967117ef..c2d47e1c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs @@ -1,7 +1,7 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). use super::*; -use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; +use crate::backend::original_prompt::{PlanLimits, PromptOptions, PromptPath, PromptPlan, ResumePoint}; pub(super) const G: usize = 256; @@ -166,7 +166,7 @@ fn read_chunks(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); let options = grid_options(s, resume); let mut chunks = 0; - for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { + for action in PromptPlan::new(&tokens, ResumePoint::at(resume), None, PlanLimits::new(options, 1024)).unwrap() { if action.path == PromptPath::FinalSeed { break; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index 4e08bd2c..cd0351d0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -49,7 +49,7 @@ use super::{ }, }, }; -use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; +use crate::backend::original_prompt::{PlanError, PlanLimits, PromptOptions, PromptPath, PromptPlan, ResumePoint}; use crate::model_binding::qwen4exp_input::ModelBinding; use leleka_context::memory_plan::KvFormat; use leleka_cuda_driver::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs index 5739e980..6d18fe76 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs @@ -235,11 +235,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let plan = PromptPlan::new_in_context( crate::qwen_forward::contract::serving_cells(), tokens, - resume, - reread_to, + ResumePoint { resume, reread_to }, None, - options, - capacity, + PlanLimits::new(options, capacity), ) .map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs index 2a81171d..0aca6d5b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs @@ -1,7 +1,7 @@ //! `FakeStack`: the request-level seams of the stack over the scripted device. use super::super::{ - PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ServeDevice, ServeError, - ServeRequest, original_serve_residency, plan_error, run_request, + PlanLimits, PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ResumePoint, + ServeDevice, ServeError, ServeRequest, original_serve_residency, plan_error, run_request, }; use super::{FakeBlock, FakeDevice, FakeState, GRID, VOCAB}; use crate::backend::original_prompt::PromptAction; @@ -107,11 +107,9 @@ impl FakeStack { let plan = PromptPlan::new_in_context( crate::qwen_forward::contract::serving_cells(), tokens, - resume, + ResumePoint::at(resume), None, - None, - options, - self.capacity, + PlanLimits::new(options, self.capacity), ); plan.map_err(plan_error).map_err(SpecError::Forward) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs index 6ab34691..a9bb7440 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_parts.rs @@ -4,6 +4,8 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::original_spec_adaptive::RoundFlags; +use crate::qwen_forward::original_spec_policy::RoundOutcome; /// The round's final result from the draft stage, the adaptive join and the drain, in the order of precedence of the /// Original. @@ -213,6 +215,19 @@ impl OriginalSpecController { Ok(()) } + /// The fixed-width draft policy learns from the round; a refusal ends the request. + fn observe_fixed(&mut self, round: &RoundFacts, ms: f64) -> SpecResult<()> { + let outcome = + RoundOutcome { lookup: round.from_lookup, t: round.t, accepted: round.accepted, matched: round.matched }; + if let Err(e) = self.policy.observe(outcome, ms) { + if let Some(r) = self.request.as_mut() { + r.finished = true; + } + return Err(crate::qwen_forward::contract::Error::from(e).into()); + } + Ok(()) + } + /// The timed round's observation: the adaptive policy (and its next plan), or the fixed-width draft policy. fn observe_round(&mut self, round: &RoundFacts, ms: f64, drafts_after: usize) -> SpecResult<()> { match (self.adaptive.as_mut(), round.choice.as_ref()) { @@ -225,19 +240,15 @@ impl OriginalSpecController { } _ => { if self.adaptive.is_none() { - if let Err(e) = self.policy.observe(round.from_lookup, round.t, round.accepted, round.matched, ms) { - if let Some(r) = self.request.as_mut() { - r.finished = true; - } - return Err(crate::qwen_forward::contract::Error::from(e).into()); - } + self.observe_fixed(round, ms)?; } if trace_enabled() { trace_fixed(round, ms, drafts_after); } } } - self.stats.record(round.t, round.accepted, round.from_lookup, round.choice.is_some_and(|c| c.explored), ms); + let flags = RoundFlags { lookup: round.from_lookup, explored: round.choice.is_some_and(|c| c.explored) }; + self.stats.record(round.t, round.accepted, flags, ms); Ok(()) } } diff --git a/crates/gptoss/src/quant_probes.rs b/crates/gptoss/src/quant_probes.rs index 54ddf6d8..033a5ece 100644 --- a/crates/gptoss/src/quant_probes.rs +++ b/crates/gptoss/src/quant_probes.rs @@ -165,7 +165,8 @@ fn kar_reconstruct( let encoded = kar::encode_with_boundaries(values, BLOCK as u16, boundaries, levels).map_err(&invalid)?; let planes: Vec<&[u32]> = encoded.planes.iter().map(Vec::as_slice).collect(); let mut decoded = vec![0.0f32; values.len()]; - kar::decode_range(&encoded.scales, book, &planes, BLOCK as u16, 0, &mut decoded).map_err(&invalid)?; + let prefix = kar::KarPrefix { scales: &encoded.scales, book, planes: &planes, group: BLOCK as u16 }; + kar::decode_range(&prefix, 0, &mut decoded).map_err(&invalid)?; Ok(decoded) } diff --git a/crates/kar-codec/src/lib.rs b/crates/kar-codec/src/lib.rs index 8616e42d..5758cd0b 100644 --- a/crates/kar-codec/src/lib.rs +++ b/crates/kar-codec/src/lib.rs @@ -200,18 +200,30 @@ fn pair_sums>(values: &[T]) -> Vec { values.as_chunks::<2>().0.iter().map(|pair| pair[0] + pair[1]).collect() } -/// Decode a bounded range from a selected KAR prefix. `book` is the f16 table -/// for exactly `planes.len()` levels; `start` is a flat element index. +/// A selected KAR prefix as the decoder reads it: the f16 group scales, the f16 `book` for exactly `planes.len()` +/// levels, the bit planes and the group size. +#[derive(Clone, Copy)] +pub struct KarPrefix<'a> { + pub scales: &'a [u16], + pub book: &'a [u16], + pub planes: &'a [&'a [u32]], + pub group: u16, +} + +/// Decode a bounded range from a selected KAR prefix; `start` is a flat element index. pub fn decode_range( - scales: &[u16], - book: &[u16], - planes: &[&[u32]], - group: u16, + prefix: &KarPrefix<'_>, start: usize, output: &mut [f32], ) -> Result<(), String> { + let KarPrefix { + scales, + book, + planes, + group, + } = *prefix; let group = usize::from(group); - check_decoder_input(scales, book, planes, group, start, output.len())?; + check_decoder_input(prefix, start, output.len())?; for (relative, value) in output.iter_mut().enumerate() { let position = start + relative; let mut index = 0usize; @@ -225,14 +237,14 @@ pub fn decode_range( } /// The geometry, range and finiteness checks of `decode_range`, in its order. -fn check_decoder_input( - scales: &[u16], - book: &[u16], - planes: &[&[u32]], - group: usize, - start: usize, - len: usize, -) -> Result<(), String> { +fn check_decoder_input(prefix: &KarPrefix<'_>, start: usize, len: usize) -> Result<(), String> { + let KarPrefix { + scales, + book, + planes, + group, + } = *prefix; + let group = usize::from(group); if !decoder_geometry_ok(book, planes, group) { return Err("invalid KAR decoder geometry or book".into()); } diff --git a/crates/model-format/examples/kar_cases.rs b/crates/model-format/examples/kar_cases.rs index 127c01dc..2b19f124 100644 --- a/crates/model-format/examples/kar_cases.rs +++ b/crates/model-format/examples/kar_cases.rs @@ -280,7 +280,7 @@ fn multiply_problem(rng: &mut Rng) -> Product { let w: Vec = (0..cols * rows).map(|_| genf(rng)).collect(); let x: Vec = (0..cols * tokens).map(|_| genf(rng)).collect(); let mut out = vec![0f32; (rows * tokens) as usize]; - let status = kernel_multiply(&w, &x, cols, rows, tokens, &mut out); + let status = kernel_multiply(&w, &x, MultiplyDims::new(cols, rows, tokens), &mut out); Product { cols, rows, tokens, w, x, out, status } } diff --git a/crates/model-format/src/gguf/index_parse.rs b/crates/model-format/src/gguf/index_parse.rs index e542e521..ae5c6de2 100644 --- a/crates/model-format/src/gguf/index_parse.rs +++ b/crates/model-format/src/gguf/index_parse.rs @@ -67,14 +67,8 @@ impl MetadataFields { Ok(()) } - fn into_summary( - self, - tensors: u64, - metadata: u64, - data_start: u64, - size: u64, - types: BTreeMap, - ) -> Summary { + fn into_summary(self, counts: HeaderCounts, data_start: u64, size: u64, types: BTreeMap) -> Summary { + let HeaderCounts { tensors, metadata } = counts; Summary { tensors, metadata, @@ -98,6 +92,13 @@ impl MetadataFields { } } +/// The tensor and metadata entry counts of the header. +#[derive(Clone, Copy)] +struct HeaderCounts { + tensors: u64, + metadata: u64, +} + pub(super) fn parse_index( cursor: &mut Cursor, size: u64, @@ -113,7 +114,7 @@ pub(super) fn parse_index( assign_byte_counts(&mut tensor_index, size, data_start, fields.alignment)?; } fields.check_split()?; - let summary = fields.into_summary(tensors, metadata, data_start, size, types); + let summary = fields.into_summary(HeaderCounts { tensors, metadata }, data_start, size, types); Ok(TensorIndex { summary, tensors: tensor_index }) } diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 9511dff9..dc07237c 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -53,7 +53,24 @@ pub struct KarTensorSource { pub plane_stride_bytes: u32, } -type ScalarDecoder = fn(&[u16], &[u16], &[&[u32]], u16, usize, &mut [f32]) -> Result<(), String>; +/// A selected KAR prefix as the scalar decoder reads it: the f16 group scales, the f16 book of exactly +/// `planes.len()` levels, the bit planes and the group size. +#[derive(Clone, Copy)] +pub struct DecodeSource<'a> { + pub scales: &'a [u16], + pub book: &'a [u16], + pub planes: &'a [&'a [u32]], + pub group: u16, +} + +/// `count` tensor elements from the flat element index `start`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ElementRange { + pub start: usize, + pub count: usize, +} + +type ScalarDecoder = fn(&DecodeSource<'_>, usize, &mut [f32]) -> Result<(), String>; pub struct KarInspection { summary: KarSummary, file: File, diff --git a/crates/model-format/src/kar/decode_record_range.rs b/crates/model-format/src/kar/decode_record_range.rs index f7c0dabc..32a7e8c7 100644 --- a/crates/model-format/src/kar/decode_record_range.rs +++ b/crates/model-format/src/kar/decode_record_range.rs @@ -7,10 +7,10 @@ pub(super) fn decode_record_range( file: &mut File, record: &[u8; RECORD_BYTES], level: u8, - start: usize, - count: usize, + range: ElementRange, decoder: ScalarDecoder, ) -> Result, String> { + let ElementRange { start, count } = range; let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; let end = start.checked_add(count).ok_or("KAR decode range overflow")?; if count == 0 || count > 1_000_000 || end > elements { @@ -80,7 +80,8 @@ fn decode_nested( let mut output = Vec::new(); output.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; output.resize(count, 0.0); - decoder(&scales, &book, &plane_refs, window.group, start - window.base_element, &mut output)?; + let source = DecodeSource { scales: &scales, book: &book, planes: &plane_refs, group: window.group }; + decoder(&source, start - window.base_element, &mut output)?; Ok(output) } diff --git a/crates/model-format/src/kar/impl_std_fmt_display.rs b/crates/model-format/src/kar/impl_std_fmt_display.rs index 6ae6d7c9..05dbdffd 100644 --- a/crates/model-format/src/kar/impl_std_fmt_display.rs +++ b/crates/model-format/src/kar/impl_std_fmt_display.rs @@ -166,14 +166,13 @@ impl KarInspection { &mut self, name: &str, level: u8, - start: usize, - count: usize, + range: ElementRange, decoder: ScalarDecoder, ) -> Result, KarError> { let index = self.sources.iter().position(|s| s.name == name).ok_or(KarError::Range("KAR tensor not found"))?; let record: [u8; RECORD_BYTES] = self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES].try_into().expect("validated directory"); - decode_record_range(&mut self.file, &record, level, start, count, decoder).map_err(typed) + decode_record_range(&mut self.file, &record, level, range, decoder).map_err(typed) } /// Trusted-owner contract, not an OS/stat check: the caller establishes that /// the retained inode has been immutable since inspection and remains so diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs index 4b870fb7..e584cee5 100644 --- a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs @@ -88,16 +88,8 @@ impl VerifiedKarPleArtifact { // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and // reads the // other fifteen here too when it was served from memory. - let packets = read_rows_parallel( - self.row_handles(), - &self.parts, - self.archive_bytes(), - self.identity.as_ref(), - rows, - 8, - 2, - true, - )?; + let fan_out = FanOut { max_threads: 8, min_rows_per_thread: 2, warm_probe: true }; + let packets = read_rows_parallel(self.archive_view(), rows, fan_out)?; let mut out = [KarPleRowPacket { payload: [0; 50], partition: 0 }; 16]; out.copy_from_slice(&packets); Ok(out) @@ -110,16 +102,17 @@ impl VerifiedKarPleArtifact { /// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill /// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk). pub fn read_rows_batch(&self, rows: &[u64]) -> Result, KarError> { - read_rows_parallel( - self.row_handles(), - &self.parts, - self.archive_bytes(), - self.identity.as_ref(), - rows, - 32, - 512, - false, - ) + let fan_out = FanOut { max_threads: 32, min_rows_per_thread: 512, warm_probe: false }; + read_rows_parallel(self.archive_view(), rows, fan_out) + } + /// The archive as the row reads see it: the handles of its own (opened on first use) and the verified state. + fn archive_view(&self) -> ArchiveView<'_> { + ArchiveView { + files: self.row_handles(), + parts: &self.parts, + archive_bytes: self.archive_bytes(), + identity: self.identity.as_ref(), + } } /// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread /// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead. diff --git a/crates/model-format/src/kar/independent_handles.rs b/crates/model-format/src/kar/independent_handles.rs index 10cd74fb..fb63761e 100644 --- a/crates/model-format/src/kar/independent_handles.rs +++ b/crates/model-format/src/kar/independent_handles.rs @@ -32,29 +32,42 @@ pub(super) fn reopen_independent(file: &File) -> std::io::Result { impl KarPleRowReader { /// `max_threads` positional-read threads at most (one per 512 rows). pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result, KarError> { - read_rows_parallel( - &self.files, - &self.parts, - self.archive_bytes, - self.identity.as_ref(), - rows, - max_threads, - 512, - false, - ) + let archive = ArchiveView { + files: &self.files, + parts: &self.parts, + archive_bytes: self.archive_bytes, + identity: self.identity.as_ref(), + }; + read_rows_parallel(archive, rows, FanOut { max_threads, min_rows_per_thread: 512, warm_probe: false }) } } -#[allow(clippy::too_many_arguments)] + +/// The verified archive PLE rows are read from: handles of its own, the partition table, the pinned length and, for an +/// ordinary file, the state it had when it was verified. +#[derive(Clone, Copy)] +pub(super) struct ArchiveView<'a> { + pub(super) files: &'a [File], + pub(super) parts: &'a [VerifiedPart], + pub(super) archive_bytes: u64, + pub(super) identity: Option<&'a crate::verify_stamp::FileIdentity>, +} + +/// How a row read is spread over threads: the most threads, the fewest rows worth a thread, and whether the first row +/// is timed to find out that a warm file needs no threads. +#[derive(Clone, Copy)] +pub(super) struct FanOut { + pub(super) max_threads: usize, + pub(super) min_rows_per_thread: usize, + pub(super) warm_probe: bool, +} + pub(super) fn read_rows_parallel( - files: &[File], - parts: &[VerifiedPart], - archive_bytes: u64, - identity: Option<&crate::verify_stamp::FileIdentity>, + archive: ArchiveView<'_>, rows: &[u64], - max_threads: usize, - min_rows_per_thread: usize, - warm_probe: bool, + fan_out: FanOut, ) -> Result, KarError> { + let ArchiveView { files, parts, archive_bytes, identity } = archive; + let FanOut { max_threads, min_rows_per_thread, warm_probe } = fan_out; let Some(first) = files.first() else { return Err(KarError::Io(std::io::ErrorKind::NotFound.into())); }; diff --git a/crates/model-format/src/kar/row_read_tests.rs b/crates/model-format/src/kar/row_read_tests.rs index da33a1c5..991d757f 100644 --- a/crates/model-format/src/kar/row_read_tests.rs +++ b/crates/model-format/src/kar/row_read_tests.rs @@ -73,28 +73,41 @@ fn check_probe_paths( // the file is in the page cache: the probe takes the single-thread path (or, on a loaded machine, falls // back to threads; the packets are the same either way) COLD_SKIP.store(0, Ordering::Relaxed); - let probed = read_rows_parallel(files, parts, total, None, rows, 8, 2, true).unwrap(); + let probed = read_rows_parallel(view(files, parts, total, None), rows, fan(true)).unwrap(); assert!(same(&probed, reference), "case {case}: probing read"); // after a cold verdict the next calls skip the probe and read in parallel COLD_SKIP.store(3, Ordering::Relaxed); - let parallel = read_rows_parallel(files, parts, total, None, rows, 8, 2, true).unwrap(); + let parallel = read_rows_parallel(view(files, parts, total, None), rows, fan(true)).unwrap(); assert!(same(¶llel, reference), "case {case}: parallel read after a cold verdict"); assert_eq!(COLD_SKIP.load(Ordering::Relaxed), 2, "a skipped probe uses up one of the skip calls"); - let unprobed = read_rows_parallel(files, parts, total, None, rows, 8, 2, false).unwrap(); + let unprobed = read_rows_parallel(view(files, parts, total, None), rows, fan(false)).unwrap(); assert!(same(&unprobed, reference), "case {case}: no probe"); } +fn view<'a>( + files: &'a [File], + parts: &'a [VerifiedPart], + archive_bytes: u64, + identity: Option<&'a crate::verify_stamp::FileIdentity>, +) -> ArchiveView<'a> { + ArchiveView { files, parts, archive_bytes, identity } +} + +fn fan(warm_probe: bool) -> FanOut { + FanOut { max_threads: 8, min_rows_per_thread: 2, warm_probe } +} + /// The refusals are the same as before: a row outside the table, a changed archive length. fn check_refusals(files: &[File], parts: &[VerifiedPart], total: u64) { let bad = vec![PLE_ROWS; 16]; - assert!(matches!(read_rows_parallel(files, parts, total, None, &bad, 8, 2, true), Err(KarError::Range(_)))); + assert!(matches!(read_rows_parallel(view(files, parts, total, None), &bad, fan(true)), Err(KarError::Range(_)))); assert!(matches!( - read_rows_parallel(files, parts, total + 1, None, &[1, 2], 8, 2, true), + read_rows_parallel(view(files, parts, total + 1, None), &[1, 2], fan(true)), Err(KarError::Integrity(_)) )); // a row beyond the partitions' last row is a range error on the probe path as well let beyond: Vec = (0..16).map(|i| 1500 + i).collect(); - assert!(read_rows_parallel(files, parts, total, None, &beyond, 8, 2, true).is_err()); + assert!(read_rows_parallel(view(files, parts, total, None), &beyond, fan(true)).is_err()); } #[cfg(unix)] @@ -104,15 +117,15 @@ fn an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified() { let id = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); let files = vec![file.try_clone().unwrap()]; let rows: Vec = vec![3, 999, 1000, 1400]; - let ok = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false).unwrap(); - let reference = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); + let ok = read_rows_parallel(view(&files, &parts, total, Some(&id)), &rows, fan(false)).unwrap(); + let reference = read_rows_parallel(view(&files, &parts, total, None), &rows, fan(false)).unwrap(); assert!(same(&ok, &reference), "the check changes no byte that is returned"); // a sealed memfd has no identity to compare: the length check alone assert!(check_archive_state(&file, total, None).is_ok()); assert!( matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length")) ); - let id2 = check_touched_file(&file, &files, (&parts, total), &rows, &path, &id); + let id2 = check_touched_file(&file, view(&files, &parts, total, None), &rows, &path, &id); check_chmod_and_reader(&file, files, (parts, total), (&rows, &path), (id2, &reference)); let _ = std::fs::remove_file(path); } @@ -122,22 +135,22 @@ fn an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified() { #[cfg(unix)] fn check_touched_file( file: &File, - files: &[File], - (parts, total): (&[VerifiedPart], u64), + archive: ArchiveView<'_>, rows: &[u64], path: &std::path::Path, id: &crate::verify_stamp::FileIdentity, ) -> crate::verify_stamp::FileIdentity { + let total = archive.archive_bytes; std::thread::sleep(std::time::Duration::from_millis(30)); let handle = std::fs::OpenOptions::new().write(true).open(path).unwrap(); handle.set_modified(std::time::SystemTime::now()).unwrap(); drop(handle); - let refused = read_rows_parallel(files, parts, total, Some(id), rows, 8, 2, false); + let refused = read_rows_parallel(ArchiveView { identity: Some(id), ..archive }, rows, fan(false)); assert!(matches!(refused, Err(KarError::Integrity(m)) if m.contains("changed since it was verified"))); assert!(matches!(check_archive_state(file, total, Some(id)), Err(KarError::Integrity(_)))); let id2 = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); assert_ne!(*id, id2); - assert!(read_rows_parallel(files, parts, total, Some(&id2), rows, 8, 2, false).is_ok()); + assert!(read_rows_parallel(ArchiveView { identity: Some(&id2), ..archive }, rows, fan(false)).is_ok()); id2 } diff --git a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs index f1696bed..682bd15d 100644 --- a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs +++ b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs @@ -119,10 +119,25 @@ fn decode_element(p: &DecodeParams, packet: &[u8], book: &[f32; 32], i: u32, out 0 } +/// The launch shape of `leleka_kar_multiply_f32`: `columns` per row, `rows` of the weight matrix, `tokens` of input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MultiplyDims { + pub columns: u32, + pub rows: u32, + pub tokens: u32, +} + +impl MultiplyDims { + pub const fn new(columns: u32, rows: u32, tokens: u32) -> Self { + Self { columns, rows, tokens } + } +} + /// Literal model of `leleka_kar_multiply_f32`: one block per (row, token), /// 256 lanes striding the columns with separately rounded multiply/add, then /// the fixed 128..1 shared-memory tree. Output is `[token][row]`. -pub fn kernel_multiply(weights: &[f32], input: &[f32], columns: u32, rows: u32, tokens: u32, out: &mut [f32]) -> u32 { +pub fn kernel_multiply(weights: &[f32], input: &[f32], dims: MultiplyDims, out: &mut [f32]) -> u32 { + let MultiplyDims { columns, rows, tokens } = dims; let (cols, nrows) = (columns as usize, rows as usize); if !multiply_args_ok(weights, input, (columns, rows, tokens), out.len()) { return STATUS_BAD_ARGUMENT; diff --git a/crates/model-format/src/kar_levels/expert_scratch.rs b/crates/model-format/src/kar_levels/expert_scratch.rs index 5037e425..0016cf01 100644 --- a/crates/model-format/src/kar_levels/expert_scratch.rs +++ b/crates/model-format/src/kar_levels/expert_scratch.rs @@ -27,7 +27,9 @@ pub fn cpu_reference_mlp(rows: &[GpuRows; 3], packets: &[Vec; 3], input: &[f return Err(KarLevelsError::NonFinite); } let mut out = vec![0f32; r.shape.rows as usize]; - if model::kernel_multiply(&weights, x, r.shape.columns, r.shape.rows, 1, &mut out) != 0 { + if model::kernel_multiply(&weights, x, model::MultiplyDims::new(r.shape.columns, r.shape.rows, 1), &mut out) + != 0 + { return Err(KarLevelsError::NonFinite); } Ok(out) diff --git a/crates/model-format/src/pinned_arena_plan.rs b/crates/model-format/src/pinned_arena_plan.rs index 0d914814..93447321 100644 --- a/crates/model-format/src/pinned_arena_plan.rs +++ b/crates/model-format/src/pinned_arena_plan.rs @@ -56,6 +56,13 @@ pub struct PinDecision { pub cap_why: &'static str, pub capped: bool, } +/// The cap the slice registration ran under: whether one applied, its size in bytes and where it came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SliceLimit<'a> { + pub limited: bool, + pub limit: u64, + pub why: &'a str, +} #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct SlicedPin { pub slice_starts: Vec, @@ -65,6 +72,23 @@ pub struct SlicedPin { // -------------------------------------------------------------------------------- parallel expert load +/// How the expert reads are issued: the worker threads and the bytes per read. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ReadPlan { + pub threads: usize, + pub chunk: u64, +} + +/// The uniform layout of `load_experts`: `layers` ranges of `blobs_per_layer` blobs of `blob_bytes` each. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ExpertLayout { + pub blob_bytes: u64, + pub blobs_per_layer: u64, + pub layers: u64, +} + #[derive(Clone, Debug, Default)] pub struct LoadStats { pub seconds: f64, diff --git a/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs index 1cd2a572..a309ae40 100644 --- a/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs +++ b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs @@ -214,12 +214,11 @@ pub fn pin_sliced(bounds: &[u64], limit: Option, mut register: impl FnMut(u pub fn sliced_note( decision: &PinDecision, refusal: &str, - limited: bool, - limit: u64, - limit_why: &str, + slice_limit: SliceLimit<'_>, pinned: &SlicedPin, previous_note: &str, ) -> String { + let SliceLimit { limited, limit, why: limit_why } = slice_limit; let mut note = String::new(); if decision.capped { let _ = write!(note, "cudaHostRegister limited to {} GiB {}; ", decision.cap >> 30, decision.cap_why); diff --git a/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs index 9dc0a6e3..24e2aea9 100644 --- a/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs +++ b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs @@ -5,18 +5,11 @@ use super::*; /// `load_experts`: `layers` uniform ranges of `blobs_per_layer * blob_bytes`. #[cfg(unix)] -pub fn load_experts( - path: &std::path::Path, - dst: &mut [u8], - blob_bytes: u64, - blobs_per_layer: u64, - layers: u64, - threads: usize, - chunk: u64, -) -> LoadStats { +pub fn load_experts(path: &std::path::Path, dst: &mut [u8], layout: ExpertLayout, plan: ReadPlan) -> LoadStats { + let ExpertLayout { blob_bytes, blobs_per_layer, layers } = layout; let n = (blobs_per_layer * blob_bytes) as u64; let off: Vec = (0..layers).map(|l| l * blobs_per_layer * blob_bytes).collect(); - load_experts_ranges(path, dst, &off, &vec![n; layers as usize], threads, chunk) + load_experts_ranges(path, dst, &off, &vec![n; layers as usize], plan) } /// `load_experts_ranges`: reads layer `L` (`layer_bytes[L]` bytes at file offset `layer_off[L]`) into /// `dst[layer_off[L]..]` @@ -28,9 +21,9 @@ pub fn load_experts_ranges( dst: &mut [u8], layer_off: &[u64], layer_bytes: &[u64], - threads: usize, - chunk: u64, + plan: ReadPlan, ) -> LoadStats { + let ReadPlan { threads, chunk } = plan; let mut st = LoadStats { ok: true, layers: layer_off.len() as u64, bytes: layer_bytes.iter().sum(), ..Default::default() }; let t0 = std::time::Instant::now(); diff --git a/crates/model-format/src/pinned_arena_plan/tests.rs b/crates/model-format/src/pinned_arena_plan/tests.rs index 7e5dd966..9c9e0046 100644 --- a/crates/model-format/src/pinned_arena_plan/tests.rs +++ b/crates/model-format/src/pinned_arena_plan/tests.rs @@ -146,17 +146,25 @@ fn assert_slices_stop_at_the_refusal_and_the_limit() { assert_eq!(r.slice_starts.last(), Some(&40), "slice 50..60 would pass the limit"); } +const GPU_BUDGET: &str = "the GPU's shared-memory budget"; + fn assert_the_constructors_note() { let gib = 1u64 << 30; let capped = decide_pin(64 * gib, 10, 0, 24); let pinned = SlicedPin { slice_starts: vec![0], registered_bytes: 24 * gib, registered_slices: 24 }; assert_eq!( - sliced_note(&capped, "", false, 0, "", &pinned, "MAP_PRIVATE"), + sliced_note(&capped, "", SliceLimit { limited: false, limit: 0, why: "" }, &pinned, "MAP_PRIVATE"), "cudaHostRegister limited to 24 GiB by STRATA_ARENA_PIN_GIB; 24 slices pinned (24 GiB); MAP_PRIVATE" ); let refused = decide_pin(64 * gib, 10, 0, -1); assert_eq!( - sliced_note(&refused, "out of memory", true, 26 * gib, "the GPU's shared-memory budget", &pinned, "n"), + sliced_note( + &refused, + "out of memory", + SliceLimit { limited: true, limit: 26 * gib, why: GPU_BUDGET }, + &pinned, + "n" + ), "cudaHostRegister of the whole arena FAILED (out of memory); slices capped at 26.0 GiB (the GPU's \ shared-memory budget; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); 24 slices pinned (24 GiB); n" ); @@ -194,7 +202,7 @@ fn write_random_file(path: &std::path::Path) -> Vec { fn assert_layers_match_a_serial_read(path: &std::path::Path, file: &[u8], threads: usize, chunk: u64) { let (off, len) = (LAYER_OFFSETS, LAYER_LENGTHS); let mut dst = vec![0xeeu8; 100_000]; - let stats = load_experts_ranges(path, &mut dst, &off, &len, threads, chunk); + let stats = load_experts_ranges(path, &mut dst, &off, &len, ReadPlan { threads, chunk }); assert!(stats.ok, "{}", stats.error); assert_eq!(stats.layers, 5); assert_eq!(stats.bytes, len.iter().sum::()); @@ -213,7 +221,12 @@ fn assert_layers_match_a_serial_read(path: &std::path::Path, file: &[u8], thread #[cfg(unix)] fn assert_uniform_wrapper_reads_the_prefix(path: &std::path::Path, file: &[u8]) { let mut dst = vec![0u8; 50_000]; - let stats = load_experts(path, &mut dst, 1000, 10, 5, 4, 3000); + let stats = load_experts( + path, + &mut dst, + ExpertLayout { blob_bytes: 1000, blobs_per_layer: 10, layers: 5 }, + ReadPlan { threads: 4, chunk: 3000 }, + ); assert!(stats.ok); assert_eq!(&dst[..], &file[..50_000]); } @@ -221,7 +234,7 @@ fn assert_uniform_wrapper_reads_the_prefix(path: &std::path::Path, file: &[u8]) #[cfg(unix)] fn assert_short_read_names_the_layer_and_offset(path: &std::path::Path) { let mut dst = vec![0u8; 200_000]; - let stats = load_experts_ranges(path, &mut dst, &[0, 150_000], &[1000, 1000], 2, 512); + let stats = load_experts_ranges(path, &mut dst, &[0, 150_000], &[1000, 1000], ReadPlan { threads: 2, chunk: 512 }); assert!(!stats.ok && stats.seconds < 0.0); assert_eq!(stats.error, "short read in layer 1: got 0 of 512 B at offset 150000"); } @@ -229,9 +242,9 @@ fn assert_short_read_names_the_layer_and_offset(path: &std::path::Path) { #[cfg(unix)] fn assert_bad_windows_are_refused_before_any_read(path: &std::path::Path) { let mut dst = vec![0u8; 1000]; - assert!(!load_experts_ranges(path, &mut dst, &[0, 500], &[600, 100], 1, 64).ok); - assert!(!load_experts_ranges(path, &mut dst, &[900], &[200], 1, 64).ok); - assert!(!load_experts_ranges(&temp("missing"), &mut dst, &[0], &[10], 1, 64).ok); + assert!(!load_experts_ranges(path, &mut dst, &[0, 500], &[600, 100], ReadPlan { threads: 1, chunk: 64 }).ok); + assert!(!load_experts_ranges(path, &mut dst, &[900], &[200], ReadPlan { threads: 1, chunk: 64 }).ok); + assert!(!load_experts_ranges(&temp("missing"), &mut dst, &[0], &[10], ReadPlan { threads: 1, chunk: 64 }).ok); } #[cfg(unix)] diff --git a/crates/model-format/src/qwen4exp.rs b/crates/model-format/src/qwen4exp.rs index 00ed2d3a..434f6044 100644 --- a/crates/model-format/src/qwen4exp.rs +++ b/crates/model-format/src/qwen4exp.rs @@ -162,6 +162,13 @@ pub struct ResolvedTensor { file_size: u64, } +/// `count` rows of an expert matrix from row `first`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RowRange { + pub first: u64, + pub count: u64, +} + /// A row table inside a verified shard, readable by position. #[derive(Debug)] pub struct RowTableSource { diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs index 354434b3..3e350efd 100644 --- a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs @@ -116,12 +116,11 @@ impl Qwen4ExpArtifact { &mut self, role: TensorRole, expert: u64, - first: u64, - count: u64, + rows: RowRange, bytes: Box<[u8]>, ) -> Result, BindingError> { let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; - let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; + let range = plan_stream_rows(tensor, role, rows.first, rows.count, Some(expert))?; if range.1 != bytes.len() as u64 { return Err(BindingError::Range("owned_expert_extent")); } @@ -165,12 +164,11 @@ impl Qwen4ExpArtifact { &mut self, role: TensorRole, expert: u64, - first: u64, - count: u64, + rows: RowRange, consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; - let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; + let range = plan_stream_rows(tensor, role, rows.first, rows.count, Some(expert))?; self.shards[tensor.shard as usize] .stream_tensor(tensor.tensor_number, range.0, range.1, consume) .map_err(BindingError::Io) diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs index aaa5f274..ba5026ff 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs @@ -4,6 +4,13 @@ #[allow(unused_imports)] use super::*; +/// The memory the admission saw: `MemAvailable` bytes observed and the headroom kept for the future. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct MemoryReading { + observed: usize, + headroom: u64, +} + impl Qwen4ExpArtifact { /// Explicit fresh-owner load; called before publishing a selected binding. /// No tensor finite admission is performed on unused expert banks. @@ -18,7 +25,8 @@ impl Qwen4ExpArtifact { let observed = admit_plan(source_bytes, metadata)?; let (charged, remaining) = self.load_banks(plan, &mut banks, metadata, source_bytes)?; self.verify_loaded_banks(&banks, remaining)?; - let report = self.bank_report(source_bytes, charged, observed, FUTURE_HEADROOM, false); + let report = + self.bank_report(source_bytes, charged, MemoryReading { observed, headroom: FUTURE_HEADROOM }, false); Ok(self.publish_banks(banks, report)) } @@ -92,10 +100,10 @@ impl Qwen4ExpArtifact { &self, source_bytes: usize, charged: usize, - observed: usize, - headroom: u64, + memory: MemoryReading, file_mapped: bool, ) -> ResidentExpertSourceReport { + let MemoryReading { observed, headroom } = memory; ResidentExpertSourceReport { source_bytes: source_bytes as u64, charged_bytes: charged as u64, @@ -147,7 +155,7 @@ impl Qwen4ExpArtifact { if banks.len() != BANKS { return Err(ResidentExpertSourceError::Geometry); } - let report = self.bank_report(source_bytes, source_bytes, 0, 0, true); + let report = self.bank_report(source_bytes, source_bytes, MemoryReading { observed: 0, headroom: 0 }, true); Ok(self.publish_banks(banks, report)) } diff --git a/crates/model-format/tests/kar_crc_slicing.rs b/crates/model-format/tests/kar_crc_slicing.rs index 891524e1..eef27bdd 100644 --- a/crates/model-format/tests/kar_crc_slicing.rs +++ b/crates/model-format/tests/kar_crc_slicing.rs @@ -107,15 +107,35 @@ fn outcome(result: Result<(), KarError>) -> String { Err(error) => format!("{error:?}"), } } -fn compare_stream( - bytes: &[u8], - sections: &[Section], +/// What the integrity stream verifies: the sections, the byte count and the pinned digest. +struct IntegrityStream<'a> { + sections: &'a [Section], expected_bytes: u64, - pin: &[u8; 32], + pin: &'a [u8; 32], +} + +impl<'a> IntegrityStream<'a> { + fn new(sections: &'a [Section], expected_bytes: u64, pin: &'a [u8; 32]) -> Self { + Self { sections, expected_bytes, pin } + } +} + +/// How the test reader hands the bytes out: at most `chunk` per read, failing at offset `fail_at` when set. +#[derive(Clone, Copy)] +struct ReaderPlan { chunk: usize, fail_at: Option, - expected: &str, -) { +} + +impl ReaderPlan { + fn new(chunk: usize, fail_at: Option) -> Self { + Self { chunk, fail_at } + } +} + +fn compare_stream(bytes: &[u8], case: IntegrityStream<'_>, reader: ReaderPlan, expected: &str) { + let IntegrityStream { sections, expected_bytes, pin } = case; + let ReaderPlan { chunk, fail_at } = reader; let reader = || Counted { bytes, position: 0, limit: chunk, fail_at, calls: 0 }; let mut old = reader(); let old_result = outcome(scalar_integrity_stream(&mut old, sections, expected_bytes, pin, &mut vec![0; chunk])); @@ -221,22 +241,27 @@ impl StreamCase<'_> { fn assert_sha_precedes_crc(&self, chunk: usize) { let (bytes, pin) = (self.bytes, &self.pin); let good = crc_sections(bytes); - compare_stream(bytes, &good, 187, pin, chunk, None, "ok"); + compare_stream(bytes, IntegrityStream::new(&good, 187, pin), ReaderPlan::new(chunk, None), "ok"); let mut bad = crc_sections(bytes); bad[0].crc32 ^= 1; bad[6].crc32 ^= 1; - compare_stream(bytes, &bad, 187, pin, chunk, None, CRC_FAILURE); + compare_stream(bytes, IntegrityStream::new(&bad, 187, pin), ReaderPlan::new(chunk, None), CRC_FAILURE); let mut wrong_pin = self.pin; wrong_pin[31] ^= 1; - compare_stream(bytes, &bad, 187, &wrong_pin, chunk, None, SHA_FAILURE); + compare_stream(bytes, IntegrityStream::new(&bad, 187, &wrong_pin), ReaderPlan::new(chunk, None), SHA_FAILURE); let mut metadata_bad = bytes.to_vec(); metadata_bad[3] ^= 1; - compare_stream(&metadata_bad, &good, 187, pin, chunk, None, SHA_FAILURE); + compare_stream(&metadata_bad, IntegrityStream::new(&good, 187, pin), ReaderPlan::new(chunk, None), SHA_FAILURE); let mut payload_bad = bytes.to_vec(); payload_bad[186] ^= 1; - compare_stream(&payload_bad, &good, 187, pin, chunk, None, SHA_FAILURE); - compare_stream(&bytes[..186], &bad, 187, pin, chunk, None, SHA_FAILURE); - compare_stream(&self.domain[..188], &bad, 187, pin, chunk, None, SHA_FAILURE); + compare_stream(&payload_bad, IntegrityStream::new(&good, 187, pin), ReaderPlan::new(chunk, None), SHA_FAILURE); + compare_stream(&bytes[..186], IntegrityStream::new(&bad, 187, pin), ReaderPlan::new(chunk, None), SHA_FAILURE); + compare_stream( + &self.domain[..188], + IntegrityStream::new(&bad, 187, pin), + ReaderPlan::new(chunk, None), + SHA_FAILURE, + ); } /// A read failure wins over a CRC mismatch; bad section bounds are refused before any read. @@ -247,14 +272,19 @@ impl StreamCase<'_> { bad[6].crc32 ^= 1; // Even an already detected CRC mismatch cannot hide a later read failure. for at in [0, 17, 18, 33, 186, 187] { - compare_stream(bytes, &bad, 187, pin, chunk, Some(at), READ_FAILURE); + compare_stream(bytes, IntegrityStream::new(&bad, 187, pin), ReaderPlan::new(chunk, Some(at)), READ_FAILURE); } let mut invalid = crc_sections(bytes); invalid[1].offset += 1; - compare_stream(bytes, &invalid, 187, pin, chunk, Some(0), RANGE_FAILURE); + compare_stream(bytes, IntegrityStream::new(&invalid, 187, pin), ReaderPlan::new(chunk, Some(0)), RANGE_FAILURE); let mut overflow = crc_sections(bytes); overflow[6].bytes = u64::MAX; - compare_stream(bytes, &overflow, 187, pin, chunk, Some(0), RANGE_FAILURE); + compare_stream( + bytes, + IntegrityStream::new(&overflow, 187, pin), + ReaderPlan::new(chunk, Some(0)), + RANGE_FAILURE, + ); } } @@ -274,7 +304,12 @@ fn original_first_crc_slicing_states_tails_splits_and_stream_precedence() { case.assert_read_failures_and_bad_bounds(chunk); stream_comparisons += 15; } - compare_stream(bytes, &crc_sections(bytes), 187, &case.pin, 0, None, "Range(\"KAR integrity buffer is empty\")"); + compare_stream( + bytes, + IntegrityStream::new(&crc_sections(bytes), 187, &case.pin), + ReaderPlan::new(0, None), + "Range(\"KAR integrity buffer is empty\")", + ); stream_comparisons += 1; assert_eq!(comparisons, 163792); assert_eq!(stream_comparisons, 196); diff --git a/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs b/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs index 3e929654..281589c9 100644 --- a/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs +++ b/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs @@ -43,7 +43,7 @@ fn assert_mutation_fails_closed(name: &str, bad: &DecodeParams, good: &DecodePar #[test] fn corrupt_launch_parameters_fail_closed_before_any_write() { let mut rng = Rng(0xbad); - let f = fixture(&mut rng, "t", &[500], 64, 3, 2, 3); + let f = fixture(&mut rng, "t", &[500], Nesting::new(64, 3, 2, 3)); let plan = plan_window(&f.record, 3, 37, 301).unwrap(); let packet = stage_packet(&plan, &f.archive).unwrap(); let good = plan.params; @@ -74,7 +74,7 @@ fn assert_ranges_touching_the_poisoned_group_are_flagged(f: &Fixture, r: &KarNes } fn assert_nan_book_flags_only_its_own_level(rng: &mut Rng) { - let mut g = fixture(rng, "t", &[256], 32, 3, 2, 3); + let mut g = fixture(rng, "t", &[256], Nesting::new(32, 3, 2, 3)); let gr = g.record.clone(); let at = gr.books_offset as usize; // first entry of the level-1 table let level2 = gr.books_offset as usize + 2 * 2; // first entry of level-2 table @@ -91,7 +91,7 @@ fn assert_nan_book_flags_only_its_own_level(rng: &mut Rng) { #[test] fn nonfinite_scales_and_books_flag_exactly_when_the_oracle_rejects() { let mut rng = Rng(0xf1f1); - let mut f = fixture(&mut rng, "t", &[256], 32, 3, 2, 3); + let mut f = fixture(&mut rng, "t", &[256], Nesting::new(32, 3, 2, 3)); let r = f.record.clone(); // Poison group 5 (elements 160..192) with an Inf scale. let at = (r.scales_offset + 5 * 2) as usize; @@ -109,7 +109,7 @@ fn nonfinite_scales_and_books_flag_exactly_when_the_oracle_rejects() { fn rows_and_experts_decode_like_flat_ranges_for_unaligned_row_lengths() { let mut rng = Rng(0xe4e4); // [cols=20, rows=7, experts=5]: rows are not word aligned. - let f = fixture(&mut rng, "experts", &[20, 7, 5], 32, 5, 2, 5); + let f = fixture(&mut rng, "experts", &[20, 7, 5], Nesting::new(32, 5, 2, 5)); for level in MIN_LEVEL..=MAX_LEVEL { for expert in 0..5u64 { let (first_row, rows) = expert_rows(&f.record, expert).unwrap(); @@ -127,7 +127,7 @@ fn rows_and_experts_decode_like_flat_ranges_for_unaligned_row_lengths() { assert!(plan_rows(&f.record, 2, 34, 2).is_err()); // rows 34,35 -> 35 rows total assert!(plan_rows(&f.record, 2, 0, 0).is_err()); assert!(plan_rows(&f.record, 2, u64::MAX, 2).is_err()); - let two_d = fixture(&mut rng, "m", &[20, 7], 32, 2, 2, 2); + let two_d = fixture(&mut rng, "m", &[20, 7], Nesting::new(32, 2, 2, 2)); assert!(expert_rows(&two_d.record, 0).is_err()); } @@ -137,7 +137,7 @@ fn assert_integer_multiply_is_exact() { let weights: Vec = (0..cols * rows).map(|i| (i % 7) as f32 - 3.0).collect(); let input: Vec = (0..cols * tokens).map(|i| (i % 5) as f32 - 2.0).collect(); let mut out = vec![0f32; (rows * tokens) as usize]; - assert_eq!(kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), 0); + assert_eq!(kernel_multiply(&weights, &input, MultiplyDims::new(cols, rows, tokens), &mut out), 0); for t in 0..tokens as usize { for r in 0..rows as usize { let exact: i64 = (0..cols as usize) @@ -157,7 +157,7 @@ fn assert_float_multiply_is_close_to_f64() { let w: Vec = (0..cols * rows).map(|_| (rng.below(2001) as f32 - 1000.0) / 640.0).collect(); let x: Vec = (0..cols).map(|_| (rng.below(2001) as f32 - 1000.0) / 512.0).collect(); let mut y = vec![0f32; rows as usize]; - assert_eq!(kernel_multiply(&w, &x, cols, rows, 1, &mut y), 0); + assert_eq!(kernel_multiply(&w, &x, MultiplyDims::new(cols, rows, 1), &mut y), 0); for r in 0..rows as usize { let (mut reference, mut mass) = (0f64, 0f64); for c in 0..cols as usize { @@ -181,7 +181,7 @@ fn multiply_model_order_is_lane_strided_then_fixed_tree() { // Lanes 0,1,2 hold 2^24, 2, 1. Tree: (p0 + p2) + p1 = (2^24 + 1 -> 2^24) + 2. // Left-to-right over lanes would give (2^24 + 2) + 1 -> 2^24 + 4. let mut out = [0f32]; - assert_eq!(kernel_multiply(&[big, 2.0, 1.0], &[1f32; 3], 3, 1, 1, &mut out), 0); + assert_eq!(kernel_multiply(&[big, 2.0, 1.0], &[1f32; 3], MultiplyDims::new(3, 1, 1), &mut out), 0); assert_eq!(out[0], big + 2.0); // Columns stride by 256 within a lane: lane 0 sums columns 0, 256, 512 in // order, so 2^24 absorbs the two trailing 1.0 terms one at a time. @@ -190,7 +190,7 @@ fn multiply_model_order_is_lane_strided_then_fixed_tree() { weights[256] = 1.0; weights[512] = 1.0; let mut out = [0f32]; - assert_eq!(kernel_multiply(&weights, &vec![1f32; 513], 513, 1, 1, &mut out), 0); + assert_eq!(kernel_multiply(&weights, &vec![1f32; 513], MultiplyDims::new(513, 1, 1), &mut out), 0); assert_eq!(out[0], big); } @@ -199,18 +199,21 @@ fn multiply_model_flags_nonfinite_and_bad_shapes() { let mut out = [0f32; 2]; let weights = [f32::NAN, 1.0, 1.0, 1.0]; let input = [1.0, 1.0]; - assert_eq!(kernel_multiply(&weights, &input, 2, 2, 1, &mut out), STATUS_NONFINITE_OUTPUT); + assert_eq!(kernel_multiply(&weights, &input, MultiplyDims::new(2, 2, 1), &mut out), STATUS_NONFINITE_OUTPUT); for (cols, rows, tokens) in [(0, 2, 1), (2, 0, 1), (2, 2, 0), (2, 2, MAX_TOKENS + 1)] { - assert_eq!(kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), STATUS_BAD_ARGUMENT); + assert_eq!( + kernel_multiply(&weights, &input, MultiplyDims::new(cols, rows, tokens), &mut out), + STATUS_BAD_ARGUMENT + ); } // Buffers shorter than the declared geometry are refused, not read. - assert_eq!(kernel_multiply(&weights[..3], &input, 2, 2, 1, &mut out), STATUS_BAD_ARGUMENT); + assert_eq!(kernel_multiply(&weights[..3], &input, MultiplyDims::new(2, 2, 1), &mut out), STATUS_BAD_ARGUMENT); } #[test] fn decode_then_multiply_matches_oracle_decode_then_multiply() { let mut rng = Rng(0xd0d0); - let f = fixture(&mut rng, "ffn", &[48, 10, 3], 32, 4, 2, 4); + let f = fixture(&mut rng, "ffn", &[48, 10, 3], Nesting::new(32, 4, 2, 4)); let x: Vec = (0..48 * 2).map(|_| (rng.below(65) as f32 - 32.0) / 16.0).collect(); for level in [2u8, 3, 4] { let (first, rows) = expert_rows(&f.record, 2).unwrap(); @@ -219,10 +222,10 @@ fn decode_then_multiply_matches_oracle_decode_then_multiply() { let mut weights = vec![0f32; 480]; assert_eq!(kernel_decode(&plan.window.params, &packet, &mut weights), 0); let mut got = vec![0f32; 20]; - assert_eq!(kernel_multiply(&weights, &x, 48, 10, 2, &mut got), 0); + assert_eq!(kernel_multiply(&weights, &x, MultiplyDims::new(48, 10, 2), &mut got), 0); let oracle_weights = oracle(&f.archive, &f.record, level, 2 * 480, 480).unwrap(); let mut want = vec![0f32; 20]; - kernel_multiply(&oracle_weights, &x, 48, 10, 2, &mut want); + kernel_multiply(&oracle_weights, &x, MultiplyDims::new(48, 10, 2), &mut want); assert_bits_eq(&got, &want, &format!("L{level}")); } } diff --git a/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs b/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs index 28fcf611..63319c5f 100644 --- a/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs +++ b/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs @@ -48,7 +48,7 @@ fn random_record(rng: &mut Rng, level: u8, round: u32) -> RandomRecord { let stored = rng.range(u64::from(level), 5) as u8; let min = rng.range(2, u64::from(level)) as u8; let max = rng.range(u64::from(level), u64::from(stored)) as u8; - let fixture = fixture(rng, "t", &[n], group, stored, min, max); + let fixture = fixture(rng, "t", &[n], Nesting::new(group, stored, min, max)); RandomRecord { fixture, n, group } } @@ -112,7 +112,7 @@ fn alignment_edge_windows(n: u64) -> Vec<(u64, u64)> { fn kernel_matches_oracle_on_alignment_edges_and_partial_last_group() { let mut rng = Rng(0x000e_d9e5); // n = 200 with group 96: groups of 96, 96, and a last group holding 8. - let f = fixture(&mut rng, "edge", &[200], 96, 5, 2, 5); + let f = fixture(&mut rng, "edge", &[200], Nesting::new(96, 5, 2, 5)); let edges = alignment_edge_windows(200); for level in MIN_LEVEL..=MAX_LEVEL { for &(start, count) in &edges { @@ -128,7 +128,7 @@ fn kernel_matches_oracle_on_alignment_edges_and_partial_last_group() { fn multi_block_ranges_cross_block_boundaries_exactly() { let mut rng = Rng(0xb10c_b10c); let n = 5 * u64::from(BLOCK_THREADS) + 77; - let f = fixture(&mut rng, "blocks", &[n], 64, 4, 2, 4); + let f = fixture(&mut rng, "blocks", &[n], Nesting::new(64, 4, 2, 4)); for level in [2u8, 3, 4] { for (start, count) in [(0u64, n), (13, n - 13), (255, 258), (256, 256), (511, 3)] { let (plan, got, status) = run_kernel(&f, level, start, count); @@ -145,8 +145,8 @@ fn overlay_selected_levels_decode_from_their_own_archive() { let mut rng = Rng(0x0e71_a7e5); // Base stores 2 planes (dial 2..=2); overlay re-encodes the same tensor // at 4 planes (dial 3..=4). A loader picks (archive, level) per tensor. - let base = fixture(&mut rng, "w", &[777], 32, 2, 2, 2); - let overlay = fixture(&mut rng, "w", &[777], 32, 4, 3, 4); + let base = fixture(&mut rng, "w", &[777], Nesting::new(32, 2, 2, 2)); + let overlay = fixture(&mut rng, "w", &[777], Nesting::new(32, 4, 3, 4)); let (_, base_out, s0) = run_kernel(&base, 2, 100, 400); assert_eq!(s0, 0); assert_bits_eq(&base_out, &oracle(&base.archive, &base.record, 2, 100, 400).unwrap(), "base L2"); @@ -183,7 +183,7 @@ fn assert_levels_outside_the_dial_are_refused(f: &Fixture) { fn assert_levels_above_the_stored_planes_and_nesting_are_refused(rng: &mut Rng) { // A well-formed record whose dial allows 5 but stores only 4 is impossible; // a stored-4 record asked for 5 is rejected before the dial check. - let mut four = fixture(rng, "t", &[100], 32, 4, 2, 4); + let mut four = fixture(rng, "t", &[100], Nesting::new(32, 4, 2, 4)); assert_eq!( plan_window(&four.record, 5, 0, 8).unwrap_err(), KernelModelError::Rejected("KAR level exceeds the planes stored in the record") @@ -198,7 +198,7 @@ fn assert_levels_above_the_stored_planes_and_nesting_are_refused(rng: &mut Rng) #[test] fn level_bounds_dial_and_stored_planes_are_enforced() { let mut rng = Rng(7); - let f = fixture(&mut rng, "t", &[100], 32, 4, 3, 4); + let f = fixture(&mut rng, "t", &[100], Nesting::new(32, 4, 3, 4)); assert_levels_outside_the_dial_are_refused(&f); assert_levels_above_the_stored_planes_and_nesting_are_refused(&mut rng); for level in 2..=4 { @@ -209,7 +209,7 @@ fn level_bounds_dial_and_stored_planes_are_enforced() { #[test] fn range_bounds_are_enforced_without_overflow() { let mut rng = Rng(8); - let f = fixture(&mut rng, "t", &[100], 32, 3, 2, 3); + let f = fixture(&mut rng, "t", &[100], Nesting::new(32, 3, 2, 3)); assert!(plan_window(&f.record, 2, 0, 100).is_ok()); assert!(plan_window(&f.record, 2, 99, 1).is_ok()); for (start, count) in [ @@ -304,7 +304,7 @@ fn plan_ranges_are_in_bounds_aligned_disjoint_and_minimal() { for _ in 0..80 { let group = [32u32, 64, 96, 256][rng.below(4) as usize]; let n = rng.range(1, 4000); - let f = fixture(&mut rng, "t", &[n], group, level, 2, level); + let f = fixture(&mut rng, "t", &[n], Nesting::new(group, level, 2, level)); let start = rng.below(n); let count = rng.range(1, n - start); let plan = plan_window(&f.record, level, start, count).unwrap(); diff --git a/crates/model-format/tests/kar_kernel_model/mod.rs b/crates/model-format/tests/kar_kernel_model/mod.rs index fb3562a8..b9fe86ec 100644 --- a/crates/model-format/tests/kar_kernel_model/mod.rs +++ b/crates/model-format/tests/kar_kernel_model/mod.rs @@ -120,7 +120,23 @@ fn nested_record(name: &str, dims: &[u64], g: &Geometry) -> KarNestedRecord { /// Build a section laid out exactly as the inspector's formulas require, with /// random finite scales/books/planes and random garbage in every padding gap. -fn fixture(rng: &mut Rng, name: &str, dims: &[u64], group: u32, stored: u8, min: u8, max: u8) -> Fixture { +/// The nested shape of a fixture: the group size, the planes stored and the dial range (`min..=max` planes). +#[derive(Clone, Copy)] +struct Nesting { + group: u32, + stored: u8, + min: u8, + max: u8, +} + +impl Nesting { + fn new(group: u32, stored: u8, min: u8, max: u8) -> Self { + Self { group, stored, min, max } + } +} + +fn fixture(rng: &mut Rng, name: &str, dims: &[u64], nesting: Nesting) -> Fixture { + let Nesting { group, stored, min, max } = nesting; let g = geometry(dims, group, stored, (min, max)); let archive = random_archive(rng, &g); // Plane words stay random, padding bytes after them stay garbage. @@ -145,13 +161,11 @@ fn oracle_has_nonfinite(scales: &[u16], book: &[u16], group: usize, span: std::o // --------------------------------------------------------------- oracle /// `control-plane/src/kar_codec.rs::decode_range`, transcribed. fn oracle_decode_range( - scales: &[u16], - book: &[u16], - planes: &[&[u32]], - group: u16, + source: &crate::kar::DecodeSource<'_>, start: usize, output: &mut [f32], ) -> std::result::Result<(), String> { + let crate::kar::DecodeSource { scales, book, planes, group } = *source; let group = usize::from(group); if !oracle_geometry_is_valid(group, planes, book) { return Err("invalid KAR decoder geometry or book".into()); @@ -240,7 +254,8 @@ fn oracle( let planes = oracle_planes(archive, r, level, &w); let refs: Vec<&[u32]> = planes.iter().map(Vec::as_slice).collect(); let mut out = vec![0f32; count]; - oracle_decode_range(&scales, &book, &refs, r.group as u16, start - w.base_element, &mut out)?; + let source = crate::kar::DecodeSource { scales: &scales, book: &book, planes: &refs, group: r.group as u16 }; + oracle_decode_range(&source, start - w.base_element, &mut out)?; Ok(out) } diff --git a/crates/model-format/tests/kar_levels/mod.rs b/crates/model-format/tests/kar_levels/mod.rs index 3847ebbf..85b738fc 100644 --- a/crates/model-format/tests/kar_levels/mod.rs +++ b/crates/model-format/tests/kar_levels/mod.rs @@ -32,7 +32,8 @@ fn record_layout(dims: &[u64], group: u32, stored: u8, section_offset: u64) -> R RecordLayout { n_elements, n_padded, scales_bytes, books_offset, books_bytes, planes_offset, stride, end } } -fn record(name: &str, dims: &[u64], group: u32, stored: u8, min: u8, max: u8, section_offset: u64) -> KarNestedRecord { +fn record(spec: Spec<'_>, section_offset: u64) -> KarNestedRecord { + let (name, dims, group, stored, min, max) = spec; let l = record_layout(dims, group, stored, section_offset); let record = KarNestedRecord { name: name.into(), @@ -64,8 +65,8 @@ type Spec<'a> = (&'a str, &'a [u64], u32, u8, u8, u8); pub(super) fn archive(sha: u8, specs: &[Spec]) -> ArchiveView { let mut offset = 1024u64; let mut records = Vec::new(); - for (name, dims, group, stored, min, max) in specs { - let r = record(name, dims, *group, *stored, *min, *max, offset); + for spec in specs { + let r = record(*spec, offset); offset = (offset + r.section_bytes).div_ceil(256) * 256; records.push(r); } diff --git a/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs b/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs index 50319f00..b07524e9 100644 --- a/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs +++ b/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs @@ -148,7 +148,7 @@ fn inconsistent_overlays_are_rejected_before_any_selection() { let same = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 3, 4)]); assert!(KarLevelSelector::new(base(), Some(same), policy).is_err()); // Duplicate names and sections that run past the archive are refused. - let r = record(EXPERT, &[64, 32], 32, 2, 2, 2, 1024); + let r = record((EXPERT, &[64, 32], 32, 2, 2, 2), 1024); assert!(ArchiveView::from_records([1; 32], 1 << 20, vec![r.clone(), r.clone()]).is_err()); assert!(ArchiveView::from_records([1; 32], 1100, vec![r]).is_err()); } diff --git a/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs b/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs index 53167d92..f476e325 100644 --- a/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs +++ b/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs @@ -67,7 +67,7 @@ fn assert_stream_reads_the_archive_once_and_decodes_the_literals(bytes: &[u8], i assert_eq!(input.eof, 1); } inspection.verify_integrity(bytes.len() as u64, &pin).unwrap(); - let row = inspection.decode_range("fixture.part0", 2, 0, 160, scalar).unwrap(); + let row = inspection.decode_range("fixture.part0", 2, ElementRange { start: 0, count: 160 }, scalar).unwrap(); for (i, value) in row.iter().enumerate() { assert_eq!(value.to_bits(), EXPECTED[i / 32][i % 4]); } diff --git a/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs b/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs index 5d60d8b3..aa8f57df 100644 --- a/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs +++ b/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs @@ -16,7 +16,9 @@ fn literal_rows_and_partition_books_decode_exactly_in_requested_order() { assert_eq!(inspected.summary().archive_bytes, 1280); assert_eq!(inspected.tensor_sources()[0].dimensions, [160, 2]); for part in [1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1] { - let row = inspected.decode_range(&format!("fixture.part{part}"), 2, 0, 160, scalar).unwrap(); + let row = inspected + .decode_range(&format!("fixture.part{part}"), 2, ElementRange { start: 0, count: 160 }, scalar) + .unwrap(); let expected: Vec = (0..160) .map(|i| { let bits = EXPECTED[i / 32][i % 4]; @@ -28,17 +30,17 @@ fn literal_rows_and_partition_books_decode_exactly_in_requested_order() { } #[test] fn literal_scale_plane_packet_fields_and_cross_group_range_are_preserved() { - fn fields(s: &[u16], b: &[u16], p: &[&[u32]], g: u16, start: usize, o: &mut [f32]) -> Result<(), String> { - assert_eq!(s, SCALES); - assert_eq!(b, BOOKS[0]); - assert_eq!(p[0], [0xcccc_cccc; 5]); - assert_eq!(p[1], [0xaaaa_aaaa; 5]); - scalar(s, b, p, g, start, o) + fn fields(source: &DecodeSource<'_>, start: usize, o: &mut [f32]) -> Result<(), String> { + assert_eq!(source.scales, SCALES); + assert_eq!(source.book, BOOKS[0]); + assert_eq!(source.planes[0], [0xcccc_cccc; 5]); + assert_eq!(source.planes[1], [0xaaaa_aaaa; 5]); + scalar(source, start, o) } let f = Fixture::new(&tiny_archive()); let mut reader = f.inspect(); - reader.decode_range("fixture.part0", 2, 0, 160, fields).unwrap(); - let got = reader.decode_range("fixture.part0", 2, 31, 3, scalar).unwrap(); + reader.decode_range("fixture.part0", 2, ElementRange { start: 0, count: 160 }, fields).unwrap(); + let got = reader.decode_range("fixture.part0", 2, ElementRange { start: 31, count: 3 }, scalar).unwrap(); assert_eq!(got.iter().map(|v| v.to_bits()).collect::>(), [0x40000000, 0xc0800000, 0xbf800000]); } @@ -50,7 +52,7 @@ fn asymmetric_plane_bytes_low_high_bits_and_negative_zero_scale_are_exact() { put16(&mut b, 770, 0x8000); payload_integrity(&mut b); let fixture = Fixture::new(&b); - let got = fixture.inspect().decode_range("fixture.part0", 2, 0, 64, scalar).unwrap(); + let got = fixture.inspect().decode_range("fixture.part0", 2, ElementRange { start: 0, count: 64 }, scalar).unwrap(); let mut wanted = [0xc000_0000u32; 64]; wanted[0] = 0x3f00_0000; wanted[15] = 0xbf00_0000; @@ -73,7 +75,7 @@ fn range_overflow_empty_huge_unknown_and_unstored_level_refuse_before_decoder() ("fixture.part0", 0, 0, 1), ("fixture.part0", 3, 0, 1), ] { - assert!(r.decode_range(name, level, start, count, unexpected_decoder).is_err()); + assert!(r.decode_range(name, level, ElementRange { start, count }, unexpected_decoder).is_err()); } } #[test] @@ -84,7 +86,7 @@ fn retained_descriptor_reads_original_after_path_replacement() { std::fs::rename(&f.path, f.directory.join("retained.kar")).unwrap(); std::fs::write(&f.path, b"different object").unwrap(); r.verify_payloads().unwrap(); - let got = r.decode_range("fixture.part0", 2, 0, 4, scalar).unwrap(); + let got = r.decode_range("fixture.part0", 2, ElementRange { start: 0, count: 4 }, scalar).unwrap(); assert_eq!(got.iter().map(|v| v.to_bits()).collect::>(), EXPECTED[0]); // This proves same-descriptor reads, not protection against same-inode writes. } @@ -179,7 +181,7 @@ fn selected_nonfinite_scale_and_any_book_entry_refuse_scalar_publication() { let f = Fixture::new(&b); let mut r = f.inspect(); r.verify_payloads().unwrap(); - assert!(r.decode_range("fixture.part0", 2, 0, 160, scalar).is_err()); + assert!(r.decode_range("fixture.part0", 2, ElementRange { start: 0, count: 160 }, scalar).is_err()); } } } diff --git a/crates/model-format/tests/kar_ple/mod.rs b/crates/model-format/tests/kar_ple/mod.rs index 48d28fa4..7f620983 100644 --- a/crates/model-format/tests/kar_ple/mod.rs +++ b/crates/model-format/tests/kar_ple/mod.rs @@ -185,14 +185,8 @@ fn f16(bits: u16) -> f32 { } f32::from_bits(sign | ((u32::from(exponent) + 112) << 23) | (fraction << 13)) } -fn scalar( - scales: &[u16], - book: &[u16], - planes: &[&[u32]], - group: u16, - start: usize, - out: &mut [f32], -) -> Result<(), String> { +fn scalar(source: &DecodeSource<'_>, start: usize, out: &mut [f32]) -> Result<(), String> { + let DecodeSource { scales, book, planes, group } = *source; if group != 32 || planes.len() != 2 || book.len() != 4 || scales.iter().chain(book).any(|w| w & 0x7c00 == 0x7c00) { return Err("independent finite L2 oracle domain".into()); } @@ -204,7 +198,7 @@ fn scalar( } Ok(()) } -fn unexpected_decoder(_: &[u16], _: &[u16], _: &[&[u32]], _: u16, _: usize, _: &mut [f32]) -> Result<(), String> { +fn unexpected_decoder(_: &DecodeSource<'_>, _: usize, _: &mut [f32]) -> Result<(), String> { panic!("invalid range reached scalar decoder") } fn profile(bytes: &[u8]) -> KarPleProfileSpec { @@ -239,7 +233,7 @@ impl KarInspection { let record: [u8; RECORD_BYTES] = self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES].try_into().ok()?; let mut file = self.file.try_clone().ok()?; - decode_record_range(&mut file, &record, level, start, count, scalar).ok() + decode_record_range(&mut file, &record, level, ElementRange { start, count }, scalar).ok() } } diff --git a/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs b/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs index 94a70ade..790835e8 100644 --- a/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs +++ b/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs @@ -72,7 +72,7 @@ fn every_expert_first_tail_and_last_span_stays_in_its_own_encoded_plane() { for (first, count) in SPANS { let mut actual = Vec::new(); artifact - .stream_expert_rows(EXPERT, expert, first, count, |chunk| { + .stream_expert_rows(EXPERT, expert, RowRange { first, count }, |chunk| { assert!(!chunk.is_empty() && chunk.len() <= 65536); actual.extend_from_slice(chunk); Ok(()) @@ -132,7 +132,7 @@ fn assert_expert_rows_refused( ) { assert!( artifact - .stream_expert_rows(role, expert, span.0, span.1, |_| { + .stream_expert_rows(role, expert, RowRange { first: span.0, count: span.1 }, |_| { *calls += 1; Ok(()) }) diff --git a/crates/quant-core/src/iq3_s.rs b/crates/quant-core/src/iq3_s.rs index 34eb2f37..9c16b59d 100644 --- a/crates/quant-core/src/iq3_s.rs +++ b/crates/quant-core/src/iq3_s.rs @@ -47,20 +47,36 @@ fn decode_quartet_pair( let high_bit = usize::from((high >> part) & 1) << 8; let grid = IQ3S_GRID[low | high_bit].to_le_bytes(); let first = 32 * subblock + 8 * quartet_pair; - store_signed_grid(output, first, 4 * half, grid, signs, scale); + let entry = SignedGrid { + grid, + signs, + scale, + }; + store_signed_grid(output, first, 4 * half, entry); } } +/// One grid entry's four magnitudes with the sign bits and the scale they are stored under. +#[derive(Clone, Copy)] +struct SignedGrid { + grid: [u8; 4], + signs: u8, + scale: f32, +} + /// Four magnitudes of one grid entry, scaled and signed by bits `first_local..` of `signs`, stored at `first + local`. #[inline(always)] fn store_signed_grid( output: &mut [f32; BLOCK_ELEMENTS], first: usize, first_local: usize, - grid: [u8; 4], - signs: u8, - scale: f32, + entry: SignedGrid, ) { + let SignedGrid { + grid, + signs, + scale, + } = entry; for (within, magnitude) in grid.iter().enumerate() { let local = first_local + within; let value = scale * f32::from(*magnitude); diff --git a/crates/sampler-ref/src/coupled.rs b/crates/sampler-ref/src/coupled.rs index 4ab63548..c9f488b9 100644 --- a/crates/sampler-ref/src/coupled.rs +++ b/crates/sampler-ref/src/coupled.rs @@ -95,6 +95,23 @@ pub fn accepted_drafts(window: &[i32], picks: &[i32]) -> usize { a } +/// The draft head: the maps between token ids and the head's subset entries, the vocabulary size they cover and the +/// request's sampler parameters. +#[derive(Clone, Copy)] +pub struct DraftHead<'a> { + pub sub_to_id: Option<&'a [i32]>, + pub id_to_sub: Option<&'a [i32]>, + pub id_vocab: usize, + pub params: &'a SamplerParams, +} + +/// Draft `j` of a chain over a history ring of capacity `cap`: it is written to `ring[cap + j]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RingSlot { + pub cap: i32, + pub j: i32, +} + /// What `coupled_draft_sample` produces for one draft. #[derive(Clone, Copy, Debug, PartialEq)] pub struct DraftSample { @@ -110,15 +127,14 @@ pub struct DraftSample { /// in place for draft `j`, over the ring window `[cap + j - h, cap + j)`. Each /// distinct subset entry is penalised once, with the count of its token id over /// the whole window. A history token outside the subset has no logit here. -pub fn coupled_penalize( - logits: &mut [f32], - id_to_sub: Option<&[i32]>, - id_vocab: usize, - p: &SamplerParams, - ring: &[i32], - cap: i32, - j: i32, -) { +pub fn coupled_penalize(logits: &mut [f32], head: &DraftHead<'_>, ring: &[i32], slot: RingSlot) { + let DraftHead { + id_to_sub, + id_vocab, + params: p, + .. + } = *head; + let RingSlot { cap, j } = slot; let h = coupled_hist_len(p.penalty_last_n, cap); if h <= 0 { return; @@ -154,20 +170,16 @@ fn subset_slot(v: i32, id_to_sub: Option<&[i32]>, id_vocab: usize, nv: usize) -> /// Writes the id to `ring[cap + j]` and returns it with its probability. /// Greedy parameters take the argmax with probability 1 (the Original never /// launches this for greedy, "defensively" it picks entry 0). -#[allow(clippy::too_many_arguments)] pub fn coupled_draft_sample( logits: &mut [f32], - sub_to_id: Option<&[i32]>, - id_to_sub: Option<&[i32]>, - id_vocab: usize, - params: &SamplerParams, + head: &DraftHead<'_>, ring: &mut [i32], - cap: i32, - j: i32, + slot: RingSlot, step_rec0: i32, ) -> DraftSample { - coupled_penalize(logits, id_to_sub, id_vocab, params, ring, cap, j); - let mut p = *params; + coupled_penalize(logits, head, ring, slot); + let RingSlot { cap, j } = slot; + let mut p = *head.params; p.counter = coupled_draft_counter(i64::from(step_rec0)); let k = sampled_k(p.top_k, logits.len()); debug_assert!(k <= MAX_SELECT); @@ -175,7 +187,7 @@ pub fn coupled_draft_sample( let sel = select_topk(logits, k); let pick = draft_pick(&sel, &p); let s = pick.token; - let id = sub_to_id.map_or(s, |m| m[s as usize]); + let id = head.sub_to_id.map_or(s, |m| m[s as usize]); ring[(cap + j) as usize] = id; DraftSample { id, @@ -328,7 +340,14 @@ mod tests { ring[(cap - 3) as usize..cap as usize].copy_from_slice(&[3, 5, 3]); let cell = 99i64; let mut l = logits.clone(); - let d = coupled_draft_sample(&mut l, None, None, nv, &p, &mut ring, cap, 0, cell as i32); + let head = DraftHead { + sub_to_id: None, + id_to_sub: None, + id_vocab: nv, + params: &p, + }; + let slot = RingSlot { cap, j: 0 }; + let d = coupled_draft_sample(&mut l, &head, &mut ring, slot, cell as i32); assert_eq!(ring[cap as usize], d.id); // the target's verify row: history row = the same window, counter = cell + 1 let hist = &ring[(cap - 4) as usize..cap as usize]; diff --git a/crates/sampler-ref/tests/oracle.rs b/crates/sampler-ref/tests/oracle.rs index 8a8b67e2..8d8ad88b 100644 --- a/crates/sampler-ref/tests/oracle.rs +++ b/crates/sampler-ref/tests/oracle.rs @@ -7,8 +7,8 @@ use leleka_sampler_ref::chain::{ SamplerParams, penalised_logits, penalty_window, sample_row, sampled_k, select_topk, }; use leleka_sampler_ref::coupled::{ - coupled_draft_cell, coupled_draft_counter, coupled_draft_sample, coupled_hist_base, - coupled_hist_len, coupled_hist_start, penalty_rows, + DraftHead, RingSlot, coupled_draft_cell, coupled_draft_counter, coupled_draft_sample, + coupled_hist_base, coupled_hist_len, coupled_hist_start, penalty_rows, }; use leleka_sampler_ref::philox::philox_uniform; use serde_json::Value; @@ -193,17 +193,13 @@ fn check_coupled_case(case: &Value) -> bool { let sub_to_id = ints(&case["sub_to_id"]); let id_to_sub = ints(&case["id_to_sub"]); let mut ring = ints(&case["ring"]); - let got = coupled_draft_sample( - &mut logits, - (!sub_to_id.is_empty()).then_some(&sub_to_id[..]), - (!id_to_sub.is_empty()).then_some(&id_to_sub[..]), + let head = DraftHead { + sub_to_id: (!sub_to_id.is_empty()).then_some(&sub_to_id[..]), + id_to_sub: (!id_to_sub.is_empty()).then_some(&id_to_sub[..]), id_vocab, - &p, - &mut ring, - cap, - j, - step0, - ); + params: &p, + }; + let got = coupled_draft_sample(&mut logits, &head, &mut ring, RingSlot { cap, j }, step0); let e = &case["expect"]; assert_eq!(got.id, e["id"].as_i64().unwrap() as i32); assert_eq!(got.sub_index, e["sub"].as_i64().unwrap() as i32); diff --git a/crates/sampler-ref/tests/serve_loop.rs b/crates/sampler-ref/tests/serve_loop.rs index 1cd662ae..7754e29e 100644 --- a/crates/sampler-ref/tests/serve_loop.rs +++ b/crates/sampler-ref/tests/serve_loop.rs @@ -11,7 +11,7 @@ use leleka_sampler_ref::{ chain::{SamplerParams, sample_row}, - coupled::{COUPLED_HIST_CAP, coupled_draft_cell, coupled_draft_sample}, + coupled::{COUPLED_HIST_CAP, DraftHead, RingSlot, coupled_draft_cell, coupled_draft_sample}, serve::{ServeSampling, settle_window, window_rows}, }; @@ -111,6 +111,13 @@ struct SpecRun { accepted: usize, } +/// Draft `j` of a chain, drawn at KV cell `cell`. +#[derive(Clone, Copy)] +struct DraftStep { + j: usize, + cell: i64, +} + /// The state of the mode-17 serve loop, generate.cpp's `while (!cancelled && produced_n < max_new)`. struct SpecLoop<'a> { sampling: &'a ServeSampling, @@ -184,7 +191,14 @@ impl<'a> SpecLoop<'a> { } /// One coupled draft: the subset head sees only the ids of its subset. - fn coupled(&self, params: &SamplerParams, ring: &mut [i32], logits: Vec, j: usize, cell: i64) -> (i32, f32) { + fn coupled( + &self, + params: &SamplerParams, + ring: &mut [i32], + logits: Vec, + step: DraftStep, + ) -> (i32, f32) { + let DraftStep { j, cell } = step; let (mut l, map): (Vec, Option<&[i32]>) = if self.spec.subset { let picked = self.sub_to_id.iter().map(|&id| logits[id as usize]).collect(); (picked, Some(&self.sub_to_id[..])) @@ -192,8 +206,17 @@ impl<'a> SpecLoop<'a> { (logits, None) }; let inv = self.spec.subset.then_some(&self.id_to_sub[..]); - let (cap, j, step) = (COUPLED_HIST_CAP, j as i32, cell as i32); - let d = coupled_draft_sample(&mut l, map, inv, V, params, ring, cap, j, step); + let head = DraftHead { + sub_to_id: map, + id_to_sub: inv, + id_vocab: V, + params, + }; + let slot = RingSlot { + cap: COUPLED_HIST_CAP, + j: j as i32, + }; + let d = coupled_draft_sample(&mut l, &head, ring, slot, cell as i32); (d.id, d.prob) } @@ -201,7 +224,7 @@ impl<'a> SpecLoop<'a> { let cell = coupled_draft_cell(self.p, a as i32, j as i32); let logits = draft_logits(ctx, cell, self.spec.noise); match self.sampling.draft_params() { - Some(params) => self.coupled(params, ring, logits, j, cell), + Some(params) => self.coupled(params, ring, logits, DraftStep { j, cell }), None => argmax_draft(&logits), } } diff --git a/crates/tokenizer/src/gguf_bpe.rs b/crates/tokenizer/src/gguf_bpe.rs index a3239a3f..aaae02a7 100644 --- a/crates/tokenizer/src/gguf_bpe.rs +++ b/crates/tokenizer/src/gguf_bpe.rs @@ -40,6 +40,14 @@ pub enum TokenizerError { Unsupported(String), } +/// The ids of the special tokens the model declares (`None`: the file declares none). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SpecialIds { + pub bos: Option, + pub eos: Option, + pub pad: Option, +} + pub struct GgufBpe { /// Token text in the byte-as-character form, indexed by id. tokens: Vec, diff --git a/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs b/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs index 9ce9990d..3eb0822d 100644 --- a/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs +++ b/crates/tokenizer/src/gguf_bpe/impl_ggufbpe.rs @@ -11,14 +11,12 @@ impl GgufBpe { let merges = build::string_list(g, "tokenizer.ggml.merges")?; let types = build::token_types(g, tokens.len())?; let special_id = |key: &str| g.get_u64(key).and_then(|v| u32::try_from(v).ok()); - Self::from_parts( - &tokens, - &types, - &merges, - special_id("tokenizer.ggml.bos_token_id"), - special_id("tokenizer.ggml.eos_token_id"), - special_id("tokenizer.ggml.padding_token_id"), - ) + let specials = SpecialIds { + bos: special_id("tokenizer.ggml.bos_token_id"), + eos: special_id("tokenizer.ggml.eos_token_id"), + pad: special_id("tokenizer.ggml.padding_token_id"), + }; + Self::from_parts(&tokens, &types, &merges, specials) } /// Build from the vocabulary pieces (`merges` are `"left right"` strings). @@ -26,10 +24,9 @@ impl GgufBpe { tokens: &[&str], types: &[i64], merges: &[&str], - bos: Option, - eos: Option, - pad: Option, + special_ids: SpecialIds, ) -> Result { + let SpecialIds { bos, eos, pad } = special_ids; let vocabulary = build::vocabulary(tokens, types, merges)?; let is_special = build::special_flags(types); let specials = build::special_matcher(tokens, types)?; diff --git a/crates/tokenizer/src/gguf_bpe/tests.rs b/crates/tokenizer/src/gguf_bpe/tests.rs index d641e28a..3ab2a0b0 100644 --- a/crates/tokenizer/src/gguf_bpe/tests.rs +++ b/crates/tokenizer/src/gguf_bpe/tests.rs @@ -29,7 +29,7 @@ fn tiny() -> GgufBpe { ]; let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); let m: Vec<&str> = merges.iter().map(String::as_str).collect(); - GgufBpe::from_parts(&t, &types, &m, None, None, None).unwrap() + GgufBpe::from_parts(&t, &types, &m, SpecialIds::default()).unwrap() } #[test] @@ -140,10 +140,10 @@ fn bad_vocabularies_are_refused() { let all: Vec = chars.iter().map(|c| c.to_string()).collect(); let t: Vec<&str> = all.iter().map(String::as_str).collect(); let ok_types = vec![1i64; t.len()]; - assert!(GgufBpe::from_parts(&t, &ok_types, &[], None, None, None).is_ok()); - assert!(GgufBpe::from_parts(&t[1..], &ok_types[1..], &[], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types[1..], &[], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &["nospace"], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &["zz yy"], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &[], Some(9999), None, None).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &[], SpecialIds::default()).is_ok()); + assert!(GgufBpe::from_parts(&t[1..], &ok_types[1..], &[], SpecialIds::default()).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types[1..], &[], SpecialIds::default()).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &["nospace"], SpecialIds::default()).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &["zz yy"], SpecialIds::default()).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &[], SpecialIds { bos: Some(9999), ..SpecialIds::default() }).is_err()); } diff --git a/crates/worker-protocol/src/lib.rs b/crates/worker-protocol/src/lib.rs index 25dd682e..d9d70e31 100644 --- a/crates/worker-protocol/src/lib.rs +++ b/crates/worker-protocol/src/lib.rs @@ -48,7 +48,11 @@ thing" } fn assert_done_line_round_trips(finish: Finish) { - let line = lines::done_line(12, 300, 45.12, 88.26, finish, 200); + let phases = lines::PhaseMs { + prompt_ms: 45.12, + decode_ms: 88.26, + }; + let line = lines::done_line(12, 300, phases, finish, 200); let Some(Event::Done(done)) = parse_line(&line).unwrap() else { panic!("{line}") }; diff --git a/crates/worker-protocol/src/lines.rs b/crates/worker-protocol/src/lines.rs index b04ea35e..2337b0b7 100644 --- a/crates/worker-protocol/src/lines.rs +++ b/crates/worker-protocol/src/lines.rs @@ -24,15 +24,25 @@ pub fn error_line(message: &str) -> String { format!("ERR {}\n", message.replace(['\r', '\n'], " ")) } +/// The milliseconds a request spent reading its prompt and decoding. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PhaseMs { + pub prompt_ms: f64, + pub decode_ms: f64, +} + /// The terminal line of a request. The draft and expert counters are zero: this worker has neither. pub fn done_line( generated: u64, prompt_tokens: u64, - prompt_ms: f64, - decode_ms: f64, + phases: PhaseMs, finish: Finish, reused: u64, ) -> String { + let PhaseMs { + prompt_ms, + decode_ms, + } = phases; let mut line = String::new(); write!( line, @@ -54,7 +64,11 @@ mod tests { assert_eq!(token_line(42), "T 42\n"); assert_eq!(progress_line(64, 4096), "PP 64 4096\n"); assert_eq!(error_line("bad\nthing"), "ERR bad thing\n"); - let done = done_line(12, 300, 45.12, 88.26, Finish::Stop, 200); + let phases = PhaseMs { + prompt_ms: 45.12, + decode_ms: 88.26, + }; + let done = done_line(12, 300, phases, Finish::Stop, 200); assert_eq!(done, "DONE 12 300 45.1 88.3 stop 0 0 200 0 0\n"); // at least five fields; reused is the field the control plane reads at index 7 let fields: Vec<&str> = done.split_whitespace().skip(1).collect();