diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b06179af..d4b1e5b0 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -59,6 +59,7 @@ mod mtp_dense_kv; mod original_mtp_actor; mod original_mtp_coupled; mod original_mtp_loader; +mod original_mtp_rt; mod original_session_state; mod qwen_dispatch; pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead}; diff --git a/crates/cuda-driver/src/original_mtp_loader.rs b/crates/cuda-driver/src/original_mtp_loader.rs index b9b0313b..3537489c 100644 --- a/crates/cuda-driver/src/original_mtp_loader.rs +++ b/crates/cuda-driver/src/original_mtp_loader.rs @@ -1,15 +1,22 @@ -//! Private, unselected load-time port of Original `core/mtp.cpp:80–415`. +//! Load-time port of Original `core/mtp.cpp:80-415` (`MtpDrafter::load`/`bind`). //! -//! Contract: this module owns only checked resource plans and read ranges. It -//! never mints loaded weights, a KV snapshot, a CUDA completion or model binding. -//! The selected IO/driver loader is NOT implemented: `select_operations` always -//! refuses. Root must connect the actual retained source/device/session owners -//! and preserve the stage/error/cleanup order below before selecting this leaf. +//! This file is the pure half: checked resource plans, the captured +//! geometry/session/device inputs of `load` (`OriginalMtpCapture`), and the +//! admission of the retained ring against the Original KV-mode plan. It reads +//! no file and touches no CUDA object. Its callers are +//! `original_mtp_rt` (RT directory bytes), `original_mtp_bank` (device banks and +//! the nine-name check), `original_mtp_draft_head` (optional `draft_vocab.bin` +//! head gather) and the runtime assembly that binds those to the genuine +//! `mtp_original_full_*` / session owners. //! //! Original dense.bin is a whole-file fread after 64-bit seek/tell. Only //! experts.bin uses the 64 MiB initialized chunk, then synchronous H2D per chunk; -//! this is not a 64 MiB libc stream-buffer/setvbuf policy. No source file is opened -//! here. No digest, numeric, device-budget or finite admission is bypassed. +//! this is not a 64 MiB libc stream-buffer/setvbuf policy. +//! +//! The Rust owners are closed to the shipped profile (256K cells, fixed 32768 +//! window, INT8 ring, 512 experts); `OriginalMtpLoadPlan::new` refuses any +//! capture outside it instead of silently planning something the retained +//! owners cannot represent. //! //! Trace: imported mtp.cpp SHA256 //! 71d8a93f6edc18916a5df9954cba372833f3cfd4efd952e2aedaed089a8d3fb4; @@ -25,7 +32,23 @@ pub(crate) const COUPLED_HISTORY: u64 = 4096; pub(crate) enum LoaderError { Geometry, Overflow, - MissingOperations, + /// `load` step 1: `max_t < 1 || max_t > kVerifyMaxT`. + MaxTOutOfRange, + /// A capture value the closed retained owners cannot represent. + ClosedProfile(&'static str), + /// The retained ring's actual mode contradicts the Original KV plan. + RingMode, +} +impl LoaderError { + pub(crate) fn message(self) -> String { + match self { + Self::MaxTOutOfRange => "mtp: max_t out of range".into(), + Self::Geometry => "mtp: invalid geometry".into(), + Self::Overflow => "mtp: resource size overflow".into(), + Self::ClosedProfile(what) => format!("mtp: unsupported {what} for the retained Original owners"), + Self::RingMode => "mtp: the draft K/V ring does not match the planned KV mode".into(), + } + } } type PlanResult = std::result::Result; @@ -273,8 +296,368 @@ pub(crate) fn bind_bytes(input: BindInputs) -> PlanResult { Ok(bytes) } -/// Explicit absence of operational IO/CUDA/session ownership dependencies. -/// A plan is not a loader; Root must not turn this refusal into a Loaded receipt. -pub(crate) fn select_operations() -> PlanResult<()> { - Err(LoaderError::MissingOperations) +/// The shipped profile every retained owner is closed to. The first six equal +/// `OriginalSessionGeometry::original()` (asserted in tests on Linux); the last +/// two equal `MTP_ORIGINAL_MAX_CELLS` / `MTP_ORIGINAL_WINDOW`. +pub(crate) const PROFILE_N_EXPERT: u64 = 512; +pub(crate) const PROFILE_TOP_K: u64 = 10; +pub(crate) const PROFILE_HEADS: u64 = 24; +pub(crate) const PROFILE_KV_HEADS: u64 = 2; +pub(crate) const PROFILE_HEAD_DIM: u64 = 256; +pub(crate) const PROFILE_INDEX_DIM: u64 = 128; +pub(crate) const CLOSED_MAX_CELLS: u64 = 262_144; +pub(crate) const CLOSED_WINDOW: i64 = 32_768; +pub(crate) const VOCABULARY_LIMIT: u64 = 262_144; + +/// Original startup globals the draft state reads (`qsa_*` settings), resolved +/// once by the operator adapter, never inferred during load. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OriginalMtpKvStartup { + pub resident_cells: u64, + pub ring_off: bool, + pub main_off: bool, + pub int8: bool, + pub hybrid: bool, + pub q4: bool, + pub int8_rotated: bool, +} + +/// Everything `MtpDrafter::load`/`bind` capture from `ModelGeometry`, +/// `SessionState`, the current device and the call arguments. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OriginalMtpCapture { + /// `cudaGetDevice` at load: the drafter lives on this device. + pub device: i32, + /// `g.n_expert` and `ss.k`. + pub n_expert: u64, + pub top_k: u64, + /// `ss.qsa_states[ss.qsa_primary()].max_cells`. + pub max_cells: u64, + pub max_t: u64, + /// `load(..., window)`; Original default 32768. + pub window: i64, + /// `output.weight` `ne1` (checked at bind). + pub vocabulary: u64, + pub kv: OriginalMtpKvStartup, + /// `coupled_draft_env()` preference. + pub coupled_requested: bool, +} + +/// The planned resources of one load. Immutable; admission against the actual +/// ring and the reserve for `bind` are methods so no caller recomputes them. +#[derive(Debug, Clone, Copy)] +pub(crate) struct OriginalMtpLoadPlan { + capture: OriginalMtpCapture, + kv_inputs: KvInputs, + bank: WeightBankPlan, + kv: KvPlan, + staging: [u64; 6], +} +impl OriginalMtpLoadPlan { + pub(crate) fn new(capture: OriginalMtpCapture, dense_file_bytes: u64) -> PlanResult { + if capture.max_t < 1 || capture.max_t > 8 { + return Err(LoaderError::MaxTOutOfRange); + } + if capture.device < 0 { + return Err(LoaderError::ClosedProfile("device ordinal")); + } + if capture.n_expert != PROFILE_N_EXPERT { + return Err(LoaderError::ClosedProfile("expert count")); + } + if capture.top_k != PROFILE_TOP_K { + return Err(LoaderError::ClosedProfile("routed expert count")); + } + if capture.max_cells != CLOSED_MAX_CELLS { + return Err(LoaderError::ClosedProfile("session cell capacity")); + } + if capture.window != CLOSED_WINDOW { + return Err(LoaderError::ClosedProfile("draft attention window")); + } + if capture.vocabulary == 0 || capture.vocabulary > VOCABULARY_LIMIT { + return Err(LoaderError::ClosedProfile("vocabulary")); + } + let kv = capture.kv; + // The retained draft state is the INT8 owner; whole-Q4 or F16 draft + // KV have no retained representation. + if kv.q4 || !(kv.int8 || kv.hybrid) { + return Err(LoaderError::ClosedProfile("draft K/V format")); + } + let kv_inputs = KvInputs { + max_cells: capture.max_cells, + max_t: capture.max_t, + requested_window: capture.window, + resident_cells: kv.resident_cells, + ring_off: kv.ring_off, + main_off: kv.main_off, + heads: PROFILE_HEADS, + kv_heads: PROFILE_KV_HEADS, + head_dim: PROFILE_HEAD_DIM, + index_dim: PROFILE_INDEX_DIM, + int8: kv.int8, + hybrid: kv.hybrid, + q4: kv.q4, + int8_rotated: kv.int8_rotated, + }; + let plan = kv_inputs.plan()?; + // The retained owner first attempts the window ring over pinned host + // pages and only then (pin failure) the fully resident state. A plan + // that starts resident or streamed has no retained counterpart. + if plan.mode != KvMode::WindowRing { + return Err(LoaderError::ClosedProfile("draft K/V mode")); + } + Ok(Self { + capture, + kv_inputs, + bank: WeightBankPlan::new(dense_file_bytes, capture.n_expert)?, + kv: plan, + staging: mapped_staging(capture.max_t, PROFILE_HEADS)?, + }) + } + pub(crate) fn capture(&self) -> &OriginalMtpCapture { + &self.capture + } + pub(crate) fn weight_bank(&self) -> &WeightBankPlan { + &self.bank + } + pub(crate) fn kv(&self) -> &KvPlan { + &self.kv + } + pub(crate) fn staging(&self) -> &[u64; 6] { + &self.staging + } + /// The effective window `first_needed()` uses (`window_` of mtp.cpp:222). + pub(crate) fn effective_window(&self) -> i64 { + self.kv.effective_window as i64 + } + /// `bind_bytes` with the capture's `max_t`/vocabulary/coupled preference. + /// Neither the logits nor a subset are owned before bind, so this is the + /// literal upper estimate the startup reserve subtracts. + pub(crate) fn bind_reserve(&self, observed_subset_file_bytes: Option, head_row_bytes: u64) -> PlanResult { + bind_bytes(BindInputs { + max_t: self.capture.max_t, + vocabulary: self.capture.vocabulary, + head_row_bytes, + logits_already_owned: false, + subset_already_owned: false, + observed_subset_file_bytes, + coupled_enabled: self.capture.coupled_requested, + coupled_params_already_owned: false, + }) + } + /// `setup_coupled` plan for the real subset width (None = whole vocabulary). + pub(crate) fn coupled(&self, subset_vocabulary: Option) -> PlanResult { + coupled_plan(self.capture.coupled_requested, self.capture.max_t, self.capture.vocabulary, subset_vocabulary) + } + /// Admit the retained ring's ACTUAL mode: the window ring is the planned + /// path; a fully resident ring is the Original retry (`ring = -1`) after a + /// mapped-host failure, and its plan is returned instead. + pub(crate) fn admit_ring(&self, fully_resident: bool) -> PlanResult { + if fully_resident { self.kv_inputs.fully_resident_retry() } else { Ok(self.kv) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kv() -> OriginalMtpKvStartup { + OriginalMtpKvStartup { + resident_cells: 20480, + ring_off: false, + main_off: false, + int8: true, + hybrid: false, + q4: false, + int8_rotated: false, + } + } + fn capture() -> OriginalMtpCapture { + OriginalMtpCapture { + device: 0, + n_expert: 512, + top_k: 10, + max_cells: 262_144, + max_t: 4, + window: 32_768, + vocabulary: 248_320, + kv: kv(), + coupled_requested: false, + } + } + + /// `StateLayout::new` of mtp_original_ring_state.rs, restated as numbers. + fn ring_state_bytes(max_t: u64, resident: bool) -> u64 { + let slots = if resident { 262_144 / 4 } else { (32_768 + 4 * max_t + 64).div_ceil(4) }; + let pooled = if resident { 262_144 / 4 + 2 } else { 2 }; + let raw = slots * 4224 + 128 + 65_536 * 4 + 1536 + 512 + pooled * 512 + 16 + 32 + 96; + raw.div_ceil(16) * 16 + 256 + } + + #[test] + fn plan_accepts_the_shipped_profile_and_matches_the_retained_ring_layout() { + for max_t in 1..=8 { + let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { max_t, ..capture() }, 116_099_072).unwrap(); + let kv = plan.kv(); + assert_eq!(kv.mode, KvMode::WindowRing); + assert_eq!(kv.format, KvFormat::Int8 { rotated: false }); + assert_eq!(kv.slots, (32_768 + 4 * max_t + 64).div_ceil(4)); + assert_eq!(kv.pooled_rows, 2); + assert_eq!(kv.effective_window, 32_768); + assert_eq!(plan.effective_window(), 32_768); + assert_eq!(kv.state_device_allocation, ring_state_bytes(max_t, false), "T={max_t}"); + assert_eq!(kv.authoritative_host_allocation, kv.pages * 4 * 1056 + 1024); + assert_eq!(plan.staging()[0], max_t * 4 + 64); + assert_eq!(plan.weight_bank().device_bytes, 116_099_072 + 707_788_800); + // the pinned-host retry plan equals the fully resident retained layout + let retry = plan.admit_ring(true).unwrap(); + assert_eq!(retry.mode, KvMode::Resident); + assert_eq!(retry.slots, 65_536); + assert_eq!(retry.state_device_allocation, ring_state_bytes(max_t, true), "T={max_t}"); + assert_eq!(retry.authoritative_host_allocation, 0); + assert_eq!(plan.admit_ring(false).unwrap().mode, KvMode::WindowRing); + } + } + + #[test] + fn hybrid_selects_int8_and_whole_q4_is_refused_for_the_retained_owner() { + let hybrid = OriginalMtpKvStartup { int8: false, hybrid: true, int8_rotated: true, ..kv() }; + let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: hybrid, ..capture() }, 1).unwrap(); + assert_eq!(plan.kv().format, KvFormat::Int8 { rotated: true }); + for refused in [ + OriginalMtpKvStartup { q4: true, ..kv() }, + OriginalMtpKvStartup { int8: false, hybrid: false, ..kv() }, + ] { + assert_eq!( + OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: refused, ..capture() }, 1).unwrap_err(), + LoaderError::ClosedProfile("draft K/V format") + ); + } + } + + #[test] + fn captures_outside_the_closed_profile_are_refused_with_a_reason() { + let cases: [(OriginalMtpCapture, LoaderError); 12] = [ + (OriginalMtpCapture { max_t: 0, ..capture() }, LoaderError::MaxTOutOfRange), + (OriginalMtpCapture { max_t: 9, ..capture() }, LoaderError::MaxTOutOfRange), + (OriginalMtpCapture { device: -1, ..capture() }, LoaderError::ClosedProfile("device ordinal")), + (OriginalMtpCapture { n_expert: 256, ..capture() }, LoaderError::ClosedProfile("expert count")), + (OriginalMtpCapture { top_k: 8, ..capture() }, LoaderError::ClosedProfile("routed expert count")), + (OriginalMtpCapture { max_cells: 131_072, ..capture() }, LoaderError::ClosedProfile("session cell capacity")), + (OriginalMtpCapture { window: 0, ..capture() }, LoaderError::ClosedProfile("draft attention window")), + (OriginalMtpCapture { window: 16_384, ..capture() }, LoaderError::ClosedProfile("draft attention window")), + (OriginalMtpCapture { vocabulary: 0, ..capture() }, LoaderError::ClosedProfile("vocabulary")), + (OriginalMtpCapture { vocabulary: 262_145, ..capture() }, LoaderError::ClosedProfile("vocabulary")), + // resident (no ring: kv streaming off) and streamed-main plans have no retained owner + ( + OriginalMtpCapture { kv: OriginalMtpKvStartup { ring_off: true, ..kv() }, ..capture() }, + LoaderError::ClosedProfile("draft K/V mode"), + ), + ( + OriginalMtpCapture { kv: OriginalMtpKvStartup { resident_cells: 0, ..kv() }, ..capture() }, + LoaderError::ClosedProfile("draft K/V mode"), + ), + ]; + for (input, expected) in cases { + assert_eq!(OriginalMtpLoadPlan::new(input, 1).unwrap_err(), expected, "{input:?}"); + assert!(expected.message().starts_with("mtp: ")); + } + assert_eq!(LoaderError::MaxTOutOfRange.message(), "mtp: max_t out of range"); + } + + #[test] + fn bank_plan_counts_expert_chunks_like_the_original_loop() { + let plan = WeightBankPlan::new(116_099_072, 512).unwrap(); + assert_eq!(plan.expert_device_bytes, 707_788_800); + assert_eq!(plan.device_bytes, 823_887_872); + assert_eq!(plan.expert_host_peak, 64 << 20); + let reads: Vec<_> = plan.expert_reads().collect(); + assert_eq!(reads.len(), 11); + assert!(reads[..10].iter().all(|r| r.bytes == 64 << 20)); + assert_eq!(reads[10].bytes, 707_788_800 - 10 * (64 << 20)); + assert_eq!(reads.iter().map(|r| r.bytes).sum::(), 707_788_800); + assert!(reads.windows(2).all(|w| w[0].offset + w[0].bytes == w[1].offset)); + assert_eq!(WeightBankPlan::new(1, 0).unwrap().expert_reads().count(), 0); + assert_eq!(WeightBankPlan::new(u64::MAX, 1).unwrap_err(), LoaderError::Overflow); + assert_eq!(WeightBankPlan::new(0, u64::MAX).unwrap_err(), LoaderError::Overflow); + } + + #[test] + fn bind_reserve_is_the_literal_upper_estimate() { + let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + let logits = 4 * 248_320 * 4; + assert_eq!(plan.bind_reserve(None, 1440).unwrap(), logits); + // a valid subset file adds the gathered rows plus the id list; invalid sizes are ignored + assert_eq!(plan.bind_reserve(Some(400), 1440).unwrap(), logits + 100 * 1440 + 400); + for ignored in [0, 3, 6] { + assert_eq!(plan.bind_reserve(Some(ignored), 1440).unwrap(), logits); + } + let coupled = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); + assert_eq!( + coupled.bind_reserve(None, 1440).unwrap(), + logits + 248_320 * 4 + (4096 + 4) * 4 + 64 * 64 * 8 + 4096 + ); + } + + #[test] + fn coupled_setup_plan_follows_setup_coupled() { + let off = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + assert!(matches!(off.coupled(None).unwrap(), CoupledPlan::Off)); + let on = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); + match on.coupled(None).unwrap() { + CoupledPlan::Allocate { params, ring, scratch, inverse_map, mapped_params, mapped_history, device_total } => { + assert_eq!((params, ring, mapped_params, mapped_history), (64, (4096 + 4) * 4, 64, 4096 * 4)); + assert_eq!(scratch, 61 * 64 * 8); // ceil(248320 / 4096) = 61 split lists + assert_eq!(inverse_map, 0); + assert_eq!(device_total, params + ring + scratch); + } + other => panic!("{other:?}"), + } + match on.coupled(Some(1000)).unwrap() { + CoupledPlan::Allocate { scratch, inverse_map, .. } => { + assert_eq!(scratch, 64 * 8 / 1); // one split list + assert_eq!(inverse_map, 248_320 * 4); + } + other => panic!("{other:?}"), + } + // 65 lists or a zero-width subset: successful argmax fallback, not coupled-ready + assert!(matches!( + coupled_plan(true, 4, 262_145, None).unwrap(), + CoupledPlan::ArgmaxVocabularyTooWide + )); + assert!(matches!(coupled_plan(true, 4, 10, Some(0)).unwrap(), CoupledPlan::ArgmaxVocabularyTooWide)); + assert!(matches!(coupled_plan(true, 4, 262_144, None).unwrap(), CoupledPlan::Allocate { .. })); + assert_eq!(coupled_plan(true, 0, 10, None).unwrap_err(), LoaderError::Geometry); + assert_eq!(coupled_plan(false, 9, 10, None).unwrap_err(), LoaderError::Geometry); + } + + #[test] + fn staging_and_kv_geometry_validation() { + let s = mapped_staging(4, 24).unwrap(); + assert_eq!(s, [80, 192, 4 * 24 * 8 + 64, 64, 80, 80]); + assert_eq!(mapped_staging(0, 24).unwrap_err(), LoaderError::Geometry); + assert_eq!(mapped_staging(4, 0).unwrap_err(), LoaderError::Geometry); + let base = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + assert_eq!(base.kv_inputs.plan().unwrap().mode, KvMode::WindowRing); + for bad in [ + KvInputs { head_dim: 128, ..base.kv_inputs }, + KvInputs { heads: 25, ..base.kv_inputs }, + KvInputs { max_cells: 0, ..base.kv_inputs }, + KvInputs { max_t: 9, ..base.kv_inputs }, + KvInputs { index_dim: 0, ..base.kv_inputs }, + ] { + assert_eq!(bad.plan().unwrap_err(), LoaderError::Geometry); + } + // window 0 with a resident budget streams the main KV, as mtp.cpp does + let streamed = KvInputs { requested_window: 0, ..base.kv_inputs }.plan().unwrap(); + assert_eq!(streamed.mode, KvMode::Streamed); + assert_eq!(streamed.slots, 20_480 / 4); + assert!(streamed.authoritative_host_allocation > 0); + // overflow stays an error rather than a wrap + let huge = KvInputs { max_cells: u64::MAX / 2, ..base.kv_inputs }; + assert!(huge.plan().is_err()); + // the orders are documented once each + assert_eq!(LOAD_ORDER.len(), 11); + assert_eq!(RELEASE_ORDER.len(), 13); + assert_eq!(REQUIRED_Q8_NAMES.len(), 9); + } } diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs new file mode 100644 index 00000000..85427575 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -0,0 +1,1011 @@ +//! Host half of Original `MtpDrafter::load` (core/mtp.cpp:143-205) and the file +//! reads of `bind` (:380-415): the `tools/mtp_rt.py` runtime directory. +//! +//! Directory layout (engine/strata/tools/mtp_rt.py): `dense.txt` one line per +//! tensor `name kind rows cols offset bytes` (kind q8_0|bf16|f32), `dense.bin` +//! every indexed tensor 256-aligned, `experts.bin` 512 routed expert blobs, +//! optional `draft_vocab.bin` int32 token ids. +//! +//! This file owns bytes and arithmetic only: no CUDA object, no device pointer, +//! no readiness claim. Device placement is `original_mtp_loader`. +//! +//! Literal Original behaviour kept: the `getline` index loop (empty lines are +//! skipped, a short line is "malformed"); the first-match `f32/bf16/q8` lookup +//! by kind; the whole-file `dense.bin` read; the `experts.bin` chunk loop that +//! reads exactly `n_expert * BLOB` bytes and ignores trailing bytes; the nine +//! required q8_0 names checked only after both banks; `draft_vocab.bin` is +//! silently ignored when absent, shorter than 4 bytes or not a multiple of 4. +//! +//! Deliberate fail-closed differences (Original trusts the offline tool): the +//! index is bounded (64 KiB, 128 tensors) and ASCII; every extent must be +//! inside `dense.bin` with exact `rows * row_bytes` byte counts; duplicate names +//! and unknown kinds are refused; regular non-symlink files only; dense values +//! and expert scale halves must be finite; draft-vocab ids must lie inside the +//! vocabulary (the device gather would otherwise read out of bounds). + +use std::{ + fs::{self, File}, + io::Read, + path::{Path, PathBuf}, +}; + +pub(crate) const INDEX_LIMIT: u64 = 64 * 1024; +pub(crate) const MAX_TENSORS: usize = 128; +/// Bound for the whole-file `dense.bin` read. The shipped file is ~111 MiB. +pub(crate) const DENSE_LIMIT: u64 = 1 << 30; +pub(crate) const DRAFT_VOCAB_MAX_IDS: u64 = 262_144; +/// Scale halves of one expert blob start here (mtp_rt.py `blob_of`: codes then +/// f16 scales); the first 1,228,800 bytes are Q2_0 gate/up codes. +pub(crate) const EXPERT_SCALE_OFFSET: u64 = 1_228_800; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum RtError { + CannotOpenIndex { directory: String }, + IndexTooLarge, + IndexNotAscii, + MalformedLine(String), + TooManyTensors, + InvalidName(String), + DuplicateTensor(String), + UnknownKind(String), + Geometry(String), + OutOfRange(String), + NonFinite(String), + CannotReadDense, + DenseTooLarge, + CannotOpenExperts, + ExpertsTruncated, + ExpertSizeOverflow, + MissingRequired(&'static str), + DraftVocabTooLarge, + DraftVocabOutOfRange, + Host, +} + +impl RtError { + /// Original error text where `mtp.cpp` has one, otherwise an `mtp:` text in + /// the same style. Never contains file contents beyond the offending line. + pub(crate) fn message(&self) -> String { + match self { + Self::CannotOpenIndex { directory } => { + format!("mtp: cannot open {directory}/dense.txt (run tools/mtp_rt.py)") + } + Self::MalformedLine(line) => format!("mtp: malformed dense.txt line: {line}"), + Self::CannotReadDense => "mtp: cannot read dense.bin".into(), + Self::CannotOpenExperts => "mtp: cannot open experts.bin".into(), + Self::ExpertsTruncated => "mtp: experts.bin is truncated".into(), + Self::MissingRequired(name) => format!("mtp: {name} is missing (q8_0)"), + Self::IndexTooLarge => "mtp: dense.txt exceeds 64 KiB".into(), + Self::IndexNotAscii => "mtp: dense.txt must be ASCII".into(), + Self::TooManyTensors => "mtp: dense.txt lists more than 128 tensors".into(), + Self::InvalidName(name) => format!("mtp: invalid tensor name in dense.txt: {name}"), + Self::DuplicateTensor(name) => format!("mtp: duplicate tensor in dense.txt: {name}"), + Self::UnknownKind(name) => format!("mtp: unsupported kind for tensor {name}"), + Self::Geometry(name) => format!("mtp: inconsistent geometry for tensor {name}"), + Self::OutOfRange(name) => format!("mtp: tensor {name} extends beyond dense.bin"), + Self::NonFinite(name) => format!("mtp: non-finite values in {name}"), + Self::DenseTooLarge => "mtp: dense.bin is too large".into(), + Self::ExpertSizeOverflow => "mtp: the expert bank size overflows".into(), + Self::DraftVocabTooLarge => "mtp: draft_vocab.bin is too large".into(), + Self::DraftVocabOutOfRange => { + "mtp: draft_vocab.bin holds an id outside the vocabulary".into() + } + Self::Host => "mtp: host allocation failed".into(), + } + } +} +type RtResult = std::result::Result; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OriginalMtpTensorKind { + F32, + Bf16, + Q8_0, +} +impl OriginalMtpTensorKind { + fn parse(text: &str) -> Option { + match text { + "f32" => Some(Self::F32), + "bf16" => Some(Self::Bf16), + "q8_0" => Some(Self::Q8_0), + _ => None, + } + } + pub fn index_name(self) -> &'static str { + match self { + Self::F32 => "f32", + Self::Bf16 => "bf16", + Self::Q8_0 => "q8_0", + } + } + /// Bytes of one row of `columns` elements; q8_0 needs whole 32-blocks. + pub(crate) fn row_bytes(self, columns: u64) -> Option { + match self { + Self::F32 => columns.checked_mul(4), + Self::Bf16 => columns.checked_mul(2), + Self::Q8_0 if columns % 32 == 0 => (columns / 32).checked_mul(34), + Self::Q8_0 => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct TensorEntry { + pub name: String, + pub kind: OriginalMtpTensorKind, + pub rows: u64, + pub columns: u64, + pub offset: u64, + pub bytes: u64, +} + +/// Parsed `dense.txt`; extents are not yet checked against `dense.bin`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DenseIndex { + tensors: Vec, +} + +fn digits(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +impl DenseIndex { + /// `std::getline` loop of mtp.cpp:157-166. An empty line is skipped; any + /// other line must hold six fields (`is >> name kind rows cols off bytes`). + pub(crate) fn parse(text: &str) -> RtResult { + if !text.is_ascii() { + return Err(RtError::IndexNotAscii); + } + let mut tensors: Vec = Vec::new(); + for line in text.split('\n') { + if line.is_empty() { + continue; + } + let malformed = || RtError::MalformedLine(line.chars().take(200).collect()); + let mut fields = line.split_ascii_whitespace(); + let (name, kind, rows, columns, offset, bytes) = ( + fields.next().ok_or_else(malformed)?, + fields.next().ok_or_else(malformed)?, + fields.next().ok_or_else(malformed)?, + fields.next().ok_or_else(malformed)?, + fields.next().ok_or_else(malformed)?, + fields.next().ok_or_else(malformed)?, + ); + // Original ignores trailing tokens; a fixed six-field format + // leaves no legitimate producer for them. + if fields.next().is_some() { + return Err(malformed()); + } + let numbers = [rows, columns, offset, bytes].map(digits); + let [Some(rows), Some(columns), Some(offset), Some(bytes)] = numbers else { + return Err(malformed()); + }; + if tensors.len() >= MAX_TENSORS { + return Err(RtError::TooManyTensors); + } + if name.len() > 180 + || !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b)) + { + return Err(RtError::InvalidName(name.chars().take(64).collect())); + } + if tensors.iter().any(|t| t.name == name) { + return Err(RtError::DuplicateTensor(name.to_owned())); + } + let kind = OriginalMtpTensorKind::parse(kind) + .ok_or_else(|| RtError::UnknownKind(name.to_owned()))?; + tensors.push(TensorEntry { + name: name.to_owned(), + kind, + rows, + columns, + offset, + bytes, + }); + } + Ok(Self { tensors }) + } + + pub(crate) fn tensors(&self) -> &[TensorEntry] { + &self.tensors + } + + /// Extent validation Original omits: shape/byte consistency and containment + /// in the actual `dense.bin` length. Runs before any device allocation. + pub(crate) fn validate_extents(&self, dense_bytes: u64) -> RtResult<()> { + for t in &self.tensors { + let row = t.kind.row_bytes(t.columns); + if t.rows == 0 + || t.columns == 0 + || t.rows > i32::MAX as u64 + || t.columns > i32::MAX as u64 + || row.and_then(|row| row.checked_mul(t.rows)) != Some(t.bytes) + { + return Err(RtError::Geometry(t.name.clone())); + } + if t.offset + .checked_add(t.bytes) + .is_none_or(|end| end > dense_bytes) + { + return Err(RtError::OutOfRange(t.name.clone())); + } + } + Ok(()) + } + + /// `f32()/bf16()/q8()` of mtp.cpp:131-141: first entry with this name AND + /// this kind. Names are unique after `parse`, so "first" is the only one. + pub(crate) fn find(&self, name: &str, kind: OriginalMtpTensorKind) -> Option<&TensorEntry> { + self.tensors + .iter() + .find(|t| t.name == name && t.kind == kind) + } + + /// The nine-name check of mtp.cpp:204-205, in source order. Callers run it + /// only after both banks exist, as Original does. + pub(crate) fn check_required(&self, required: &[&'static str]) -> RtResult<()> { + for name in required { + if self.find(name, OriginalMtpTensorKind::Q8_0).is_none() { + return Err(RtError::MissingRequired(name)); + } + } + Ok(()) + } + + /// Slice of one tensor inside a validated `dense.bin` image. + pub(crate) fn slice<'a>(&self, entry: &TensorEntry, dense: &'a [u8]) -> RtResult<&'a [u8]> { + let start = + usize::try_from(entry.offset).map_err(|_| RtError::OutOfRange(entry.name.clone()))?; + let end = usize::try_from(entry.offset.saturating_add(entry.bytes)) + .map_err(|_| RtError::OutOfRange(entry.name.clone()))?; + dense + .get(start..end) + .ok_or_else(|| RtError::OutOfRange(entry.name.clone())) + } + + /// Finite admission of every indexed tensor (the runtime pack reader does + /// the same): bf16/q8 scale exponent not all-ones, f32 finite. + pub(crate) fn validate_finite(&self, dense: &[u8]) -> RtResult<()> { + for t in &self.tensors { + let bytes = self.slice(t, dense)?; + let finite = match t.kind { + OriginalMtpTensorKind::Bf16 => bytes + .chunks_exact(2) + .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7f80 != 0x7f80), + OriginalMtpTensorKind::F32 => bytes + .chunks_exact(4) + .all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()), + OriginalMtpTensorKind::Q8_0 => bytes + .chunks_exact(34) + .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00), + }; + if !finite { + return Err(RtError::NonFinite(t.name.clone())); + } + } + Ok(()) + } +} + +/// An opened regular file. Symlinked or special files are refused so a pack +/// directory cannot redirect a read (control-plane preflight does the same). +fn open_regular(path: &Path) -> Option { + let link = fs::symlink_metadata(path).ok()?; + if link.file_type().is_symlink() || !link.is_file() { + return None; + } + let file = File::open(path).ok()?; + file.metadata().ok()?.is_file().then_some(file) +} + +fn zeroed(bytes: usize) -> RtResult> { + let mut v = Vec::new(); + v.try_reserve_exact(bytes).map_err(|_| RtError::Host)?; + v.resize(bytes, 0); + Ok(v) +} + +pub(crate) fn read_index(directory: &Path) -> RtResult { + let open = || RtError::CannotOpenIndex { + directory: directory.display().to_string(), + }; + let file = open_regular(&directory.join("dense.txt")).ok_or_else(open)?; + if file.metadata().map_err(|_| open())?.len() > INDEX_LIMIT { + return Err(RtError::IndexTooLarge); + } + let mut bytes = Vec::new(); + file.take(INDEX_LIMIT + 1) + .read_to_end(&mut bytes) + .map_err(|_| open())?; + if bytes.len() as u64 > INDEX_LIMIT { + return Err(RtError::IndexTooLarge); + } + DenseIndex::parse(std::str::from_utf8(&bytes).map_err(|_| RtError::IndexNotAscii)?) +} + +/// Whole-file read (`read_file` of mtp.cpp:76-91): one allocation of the file +/// length and one read. Length comes from file metadata (64-bit, as the +/// seek/tell pair of the Original) and is bounded by `DENSE_LIMIT`. +pub(crate) fn read_dense(directory: &Path) -> RtResult> { + let file = open_regular(&directory.join("dense.bin")).ok_or(RtError::CannotReadDense)?; + let length = file.metadata().map_err(|_| RtError::CannotReadDense)?.len(); + if length > DENSE_LIMIT { + return Err(RtError::DenseTooLarge); + } + let mut blob = zeroed(usize::try_from(length).map_err(|_| RtError::DenseTooLarge)?)?; + let mut file = file; + file.read_exact(&mut blob) + .map_err(|_| RtError::CannotReadDense)?; + Ok(blob) +} + +/// `n_expert * BLOB` with checked arithmetic. +pub(crate) fn expert_bank_bytes(n_expert: u64, blob: u64) -> RtResult { + n_expert + .checked_mul(blob) + .ok_or(RtError::ExpertSizeOverflow) +} + +/// The absolute scale-half ranges of experts.bin inside `[offset, offset+len)` +/// must not hold an Inf/NaN f16. Offsets and lengths must be even. +pub(crate) fn expert_scales_finite(offset: u64, chunk: &[u8], blob: u64) -> bool { + if blob <= EXPERT_SCALE_OFFSET || offset % 2 != 0 || chunk.len() % 2 != 0 || blob % 2 != 0 { + return false; + } + let end = offset + chunk.len() as u64; + let mut at = offset; + while at < end { + let within = at % blob; + if within < EXPERT_SCALE_OFFSET { + at += EXPERT_SCALE_OFFSET - within; + continue; + } + let stop = (at - within + blob).min(end); + let from = (at - offset) as usize; + let to = (stop - offset) as usize; + if chunk[from..to] + .chunks_exact(2) + .any(|h| u16::from_le_bytes([h[0], h[1]]) & 0x7c00 == 0x7c00) + { + return false; + } + at = stop; + } + true +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum StreamError { + Rt(RtError), + Sink(E), +} + +/// `experts.bin` chunk loop of mtp.cpp:171-184. Open first, let the caller +/// allocate (`before_read`), then read `bytes` in `chunk_bytes` pieces, each +/// handed to `sink(offset, data)`; trailing file bytes are ignored. The chunk +/// vector is allocated in full even when `bytes` is smaller, as in Original. +pub(crate) fn stream_experts( + directory: &Path, + bytes: u64, + chunk_bytes: usize, + before_read: impl FnOnce() -> std::result::Result<(), E>, + mut sink: impl FnMut(u64, &[u8]) -> std::result::Result<(), E>, +) -> std::result::Result<(), StreamError> { + let mut file = open_regular(&directory.join("experts.bin")) + .ok_or(StreamError::Rt(RtError::CannotOpenExperts))?; + before_read().map_err(StreamError::Sink)?; + if chunk_bytes == 0 { + return Err(StreamError::Rt(RtError::Host)); + } + let mut chunk = zeroed(chunk_bytes).map_err(StreamError::Rt)?; + let mut offset = 0u64; + while offset < bytes { + let n = (chunk.len() as u64).min(bytes - offset); + let piece = &mut chunk[..n as usize]; + file.read_exact(piece) + .map_err(|_| StreamError::Rt(RtError::ExpertsTruncated))?; + sink(offset, piece).map_err(StreamError::Sink)?; + offset += n; + } + Ok(()) +} + +pub(crate) fn draft_vocab_path(directory: &Path) -> PathBuf { + directory.join("draft_vocab.bin") +} + +/// `bind_bytes` probe (mtp.cpp:259-266): `fopen` succeeded -> `ftell` size. +pub(crate) fn observed_draft_vocab_bytes(directory: &Path) -> Option { + Some( + open_regular(&draft_vocab_path(directory))? + .metadata() + .ok()? + .len(), + ) +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum DraftVocab { + /// Missing, unreadable, shorter than one id or not a multiple of 4 bytes. + Absent, + Subset(Vec), +} + +/// `bind` reads `draft_vocab.bin` (mtp.cpp:393-396). Original ignores a file +/// that is unreadable or malformed in size; a valid-size file is a subset. +pub(crate) fn read_draft_vocab(directory: &Path) -> RtResult { + let Some(mut file) = open_regular(&draft_vocab_path(directory)) else { + return Ok(DraftVocab::Absent); + }; + let Ok(length) = file.metadata().map(|m| m.len()) else { + return Ok(DraftVocab::Absent); + }; + if length < 4 || length % 4 != 0 { + return Ok(DraftVocab::Absent); + } + if length / 4 > DRAFT_VOCAB_MAX_IDS { + return Err(RtError::DraftVocabTooLarge); + } + let mut raw = zeroed(length as usize)?; + if file.read_exact(&mut raw).is_err() { + return Ok(DraftVocab::Absent); + } + Ok(DraftVocab::Subset( + raw.chunks_exact(4) + .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(), + )) +} + +/// Every id must name a vocabulary row before the device gather reads it. +pub(crate) fn validate_subset(ids: &[i32], vocabulary: usize) -> RtResult<()> { + if ids.is_empty() + || vocabulary == 0 + || ids.iter().any(|&id| id < 0 || id as usize >= vocabulary) + { + return Err(RtError::DraftVocabOutOfRange); + } + Ok(()) +} + +#[cfg(test)] +pub(crate) mod fixtures { + //! Synthetic RT directories. Names, kinds and 256-byte placement follow + //! tools/mtp_rt.py and control-plane/src/mtp_pack.rs (REQUIRED/OPTIONAL); + //! dimensions are scaled down so tests stay small. + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + /// (name, kind, rows, columns) with the real names and tiny shapes. + pub(crate) const TENSORS: &[(&str, &str, u64, u64)] = &[ + ("fc_embedding.weight", "q8_0", 2, 64), + ("fc_hidden.weight", "q8_0", 2, 64), + ("self_attn.q_proj.weight", "q8_0", 3, 32), + ("self_attn.k_proj.weight", "q8_0", 1, 32), + ("self_attn.v_proj.weight", "q8_0", 1, 32), + ("self_attn.o_proj.weight", "q8_0", 2, 96), + ("mlp.shared_expert.gate_proj.weight", "q8_0", 1, 64), + ("mlp.shared_expert.up_proj.weight", "q8_0", 1, 64), + ("mlp.shared_expert.down_proj.weight", "q8_0", 2, 32), + ( + "attn_hyper_connection.block_inject_weight.weight", + "bf16", + 4, + 8, + ), + ("mlp.gate.weight", "bf16", 5, 8), + ("attn_hyper_connection.hc_norm.weight", "f32", 1, 16), + ("self_attn.k_norm.weight", "f32", 1, 8), + ]; + + pub(crate) struct TempDir(pub PathBuf); + impl TempDir { + pub(crate) fn new(tag: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "leleka-mtp-rt-{tag}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + pub(crate) fn tensor_bytes(kind: &str, rows: u64, columns: u64) -> u64 { + match kind { + "q8_0" => rows * (columns / 32) * 34, + "bf16" => rows * columns * 2, + _ => rows * columns * 4, + } + } + + /// Returns `(dense.txt, dense.bin)` with deterministic finite payloads. + pub(crate) fn dense() -> (String, Vec) { + let mut text = String::new(); + let mut blob: Vec = Vec::new(); + for (index, (name, kind, rows, columns)) in TENSORS.iter().enumerate() { + blob.resize(blob.len().div_ceil(256) * 256, 0); + let bytes = tensor_bytes(kind, *rows, *columns); + text.push_str(&format!( + "{name} {kind} {rows} {columns} {} {bytes}\n", + blob.len() + )); + let at = blob.len(); + blob.resize(at + bytes as usize, 0); + for (i, b) in blob[at..].iter_mut().enumerate() { + *b = (index * 7 + i) as u8; + } + // Keep every scale/exponent field finite: clear the top byte bits. + match *kind { + "f32" => blob[at..].chunks_exact_mut(4).for_each(|w| w[3] = 0x3f), + "bf16" => blob[at..].chunks_exact_mut(2).for_each(|w| w[1] = 0x3f), + _ => blob[at..].chunks_exact_mut(34).for_each(|w| w[1] = 0x3c), + } + } + (text, blob) + } + + /// `experts` expert blobs of `blob` bytes with finite scale halves. + pub(crate) fn experts(experts: usize, blob: usize) -> Vec { + let mut bytes = vec![0x11u8; experts * blob]; + for e in 0..experts { + let scales = &mut bytes[e * blob + EXPERT_SCALE_OFFSET as usize..(e + 1) * blob]; + scales.chunks_exact_mut(2).for_each(|h| { + h[0] = 0x00; + h[1] = 0x3c; + }); + } + bytes + } + + pub(crate) fn write(dir: &TempDir, name: &str, bytes: &[u8]) { + fs::write(dir.0.join(name), bytes).unwrap(); + } +} + +#[cfg(test)] +mod tests { + use super::fixtures::*; + use super::*; + + const REQUIRED: &[&str] = &[ + "fc_embedding.weight", + "fc_hidden.weight", + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", + "mlp.shared_expert.down_proj.weight", + ]; + + #[test] + fn parses_getline_loop_and_skips_empty_lines() { + let (text, blob) = dense(); + let index = DenseIndex::parse(&format!("\n{text}\n\n")).unwrap(); + assert_eq!(index.tensors().len(), TENSORS.len()); + index.validate_extents(blob.len() as u64).unwrap(); + index.check_required(REQUIRED).unwrap(); + let q = index + .find("self_attn.q_proj.weight", OriginalMtpTensorKind::Q8_0) + .unwrap(); + assert_eq!((q.rows, q.columns, q.bytes), (3, 32, 102)); + assert_eq!(q.offset % 256, 0); + // kind-specific lookup: a bf16 tensor is not a q8 one. + assert!( + index + .find("mlp.gate.weight", OriginalMtpTensorKind::Q8_0) + .is_none() + ); + assert!( + index + .find("mlp.gate.weight", OriginalMtpTensorKind::Bf16) + .is_some() + ); + // CRLF and a missing final newline parse like std::getline + >>. + let crlf = text.replace('\n', "\r\n"); + assert_eq!( + DenseIndex::parse(&crlf).unwrap().tensors().len(), + TENSORS.len() + ); + assert_eq!( + DenseIndex::parse(text.trim_end()).unwrap().tensors().len(), + TENSORS.len() + ); + assert_eq!(DenseIndex::parse("").unwrap().tensors().len(), 0); + } + + #[test] + fn malformed_index_lines_carry_the_original_message() { + let (text, _) = dense(); + for bad in [ + "name q8_0 1 32 0\n".to_owned(), // five fields + "name q8_0 1 32 0 34 extra\n".to_owned(), // seven fields + "name q8_0 x 32 0 34\n".to_owned(), + "name q8_0 -1 32 0 34\n".to_owned(), + "name q8_0 +1 32 0 34\n".to_owned(), + " \n".to_owned(), // whitespace-only is not "empty" + format!("{text}tail\n"), + ] { + let error = DenseIndex::parse(&bad).unwrap_err(); + assert!( + matches!(error, RtError::MalformedLine(_)), + "{bad:?} -> {error:?}" + ); + assert!( + error + .message() + .starts_with("mtp: malformed dense.txt line: ") + ); + } + assert_eq!( + DenseIndex::parse("n é 1 1 0 1\n").unwrap_err(), + RtError::IndexNotAscii + ); + assert!(matches!( + DenseIndex::parse("a.b-c q8_0 1 32 0 34\n"), + Err(RtError::InvalidName(_)) + )); + assert!(matches!( + DenseIndex::parse("a q4 1 32 0 34\n"), + Err(RtError::UnknownKind(_)) + )); + assert!(matches!( + DenseIndex::parse("a f32 1 4 0 16\na bf16 1 4 256 8\n"), + Err(RtError::DuplicateTensor(_)) + )); + let many: String = (0..=MAX_TENSORS) + .map(|i| format!("t{i} f32 1 1 0 4\n")) + .collect(); + assert_eq!( + DenseIndex::parse(&many).unwrap_err(), + RtError::TooManyTensors + ); + } + + #[test] + fn extent_validation_is_exact_and_bounded() { + let (text, blob) = dense(); + let end = blob.len() as u64; + let index = DenseIndex::parse(&text).unwrap(); + assert!(index.validate_extents(end - 1).is_err()); + index.validate_extents(end + 5).unwrap(); + for edit in [ + ( + "self_attn.q_proj.weight q8_0 3 32", + "self_attn.q_proj.weight q8_0 3 31", + ), + ( + "self_attn.q_proj.weight q8_0 3 32", + "self_attn.q_proj.weight q8_0 0 32", + ), + ("mlp.gate.weight bf16 5 8", "mlp.gate.weight bf16 6 8"), + ("fc_hidden.weight q8_0 2 64", "fc_hidden.weight q8_0 2 32"), + ( + "self_attn.k_norm.weight f32 1 8", + "self_attn.k_norm.weight f32 2 8", + ), + ] { + let broken = DenseIndex::parse(&text.replacen(edit.0, edit.1, 1)).unwrap(); + assert!( + matches!(broken.validate_extents(end), Err(RtError::Geometry(_))), + "{edit:?}" + ); + } + let beyond = DenseIndex::parse("x f32 1 4 4294967296 16\n").unwrap(); + assert!(matches!( + beyond.validate_extents(end), + Err(RtError::OutOfRange(_)) + )); + let wrap = DenseIndex::parse("x f32 1 4 18446744073709551615 16\n").unwrap(); + assert!(matches!( + wrap.validate_extents(end), + Err(RtError::OutOfRange(_)) + )); + let huge = DenseIndex::parse("x q8_0 4294967296 32 0 1\n").unwrap(); + assert!(matches!( + huge.validate_extents(u64::MAX), + Err(RtError::Geometry(_)) + )); + } + + #[test] + fn required_names_are_checked_in_source_order_by_kind() { + let (text, _) = dense(); + for (i, name) in REQUIRED.iter().enumerate() { + // dropping the line and retyping it as bf16 both make it "missing (q8_0)" + let dropped: String = text + .lines() + .filter(|l| !l.starts_with(&format!("{name} "))) + .map(|l| format!("{l}\n")) + .collect(); + let retyped = text.replacen(&format!("{name} q8_0"), &format!("{name} bf16"), 1); + for broken in [dropped, retyped] { + let index = DenseIndex::parse(&broken).unwrap(); + let error = index.check_required(REQUIRED).unwrap_err(); + assert_eq!(error, RtError::MissingRequired(REQUIRED[i])); + assert_eq!(error.message(), format!("mtp: {name} is missing (q8_0)")); + } + } + // two missing: the FIRST in source order is reported. + let two = DenseIndex::parse( + &text + .lines() + .filter(|l| { + !l.starts_with("fc_hidden.weight ") && !l.starts_with("fc_embedding.weight ") + }) + .map(|l| format!("{l}\n")) + .collect::(), + ) + .unwrap(); + assert_eq!( + two.check_required(REQUIRED).unwrap_err(), + RtError::MissingRequired(REQUIRED[0]) + ); + } + + #[test] + fn finite_admission_rejects_each_dtype() { + let (text, blob) = dense(); + let index = DenseIndex::parse(&text).unwrap(); + index.validate_finite(&blob).unwrap(); + for (name, offset_in_tensor, bytes) in [ + ("fc_embedding.weight", 0usize, [0x00u8, 0x7c]), // q8 f16 scale = inf + ("mlp.gate.weight", 2, [0x80, 0x7f]), // bf16 inf + ("attn_hyper_connection.hc_norm.weight", 4, [0x00, 0x80]), // f32 bytes below + ] { + let entry = index.tensors().iter().find(|t| t.name == name).unwrap(); + let mut broken = blob.clone(); + let at = entry.offset as usize + offset_in_tensor; + if name.starts_with("attn_hyper") { + broken[at..at + 4].copy_from_slice(&f32::NAN.to_le_bytes()); + } else { + broken[at..at + 2].copy_from_slice(&bytes); + } + assert_eq!( + index.validate_finite(&broken).unwrap_err(), + RtError::NonFinite(name.to_owned()) + ); + } + assert!(matches!( + index.validate_finite(&blob[..blob.len() - 1]), + Err(RtError::OutOfRange(_)) + )); + } + + #[test] + fn index_and_dense_readers_follow_original_file_semantics() { + let dir = TempDir::new("read"); + let (text, blob) = dense(); + let missing = read_index(&dir.0).unwrap_err(); + assert!( + missing + .message() + .contains("/dense.txt (run tools/mtp_rt.py)") + ); + write(&dir, "dense.txt", text.as_bytes()); + assert_eq!(read_index(&dir.0).unwrap().tensors().len(), TENSORS.len()); + assert_eq!( + read_dense(&dir.0).unwrap_err().message(), + "mtp: cannot read dense.bin" + ); + write(&dir, "dense.bin", &blob); + assert_eq!(read_dense(&dir.0).unwrap(), blob); + write(&dir, "dense.bin", b""); + assert!(read_dense(&dir.0).unwrap().is_empty()); // n == 0 succeeds like Original + write(&dir, "dense.txt", &vec![b' '; INDEX_LIMIT as usize + 1]); + assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexTooLarge); + write(&dir, "dense.txt", "é".as_bytes()); + assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexNotAscii); + } + + #[cfg(unix)] + #[test] + fn symlinked_and_non_regular_files_are_refused() { + let dir = TempDir::new("link"); + let (text, blob) = dense(); + write(&dir, "real.bin", &blob); + std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("dense.bin")).unwrap(); + assert_eq!(read_dense(&dir.0).unwrap_err(), RtError::CannotReadDense); + write(&dir, "real.txt", text.as_bytes()); + std::os::unix::fs::symlink(dir.0.join("real.txt"), dir.0.join("dense.txt")).unwrap(); + assert!(matches!( + read_index(&dir.0), + Err(RtError::CannotOpenIndex { .. }) + )); + fs::create_dir(dir.0.join("experts.bin")).unwrap(); + let outcome = stream_experts::<()>(&dir.0, 4, 4, || Ok(()), |_, _| Ok(())); + assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); + } + + #[test] + fn expert_stream_matches_the_chunk_plan_and_ignores_trailing_bytes() { + let dir = TempDir::new("experts"); + let blob = 1_382_400usize; + let bank = experts(3, blob); + let mut file = bank.clone(); + file.extend_from_slice(b"trailing bytes Original never reads"); + write(&dir, "experts.bin", &file); + let total = bank.len() as u64; + for chunk in [2usize << 20, 1 << 20, 4 << 20] { + let mut seen = Vec::new(); + let mut stored = vec![0u8; bank.len()]; + let allocated = std::cell::Cell::new(false); + stream_experts::<()>( + &dir.0, + total, + chunk, + || { + allocated.set(true); + Ok(()) + }, + |offset, data| { + assert!(allocated.get(), "allocation precedes the first read"); + seen.push((offset, data.len() as u64)); + stored[offset as usize..offset as usize + data.len()].copy_from_slice(data); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(stored, bank); + let expected: Vec<_> = (0..total) + .step_by(chunk) + .map(|o| (o, (chunk as u64).min(total - o))) + .collect(); + assert_eq!(seen, expected); + } + } + + #[test] + fn expert_stream_error_paths_use_original_order_and_text() { + let dir = TempDir::new("experts-err"); + // open failure happens before the caller may allocate + let mut ran = false; + let outcome = stream_experts::<()>( + &dir.0, + 8, + 8, + || { + ran = true; + Ok(()) + }, + |_, _| Ok(()), + ); + assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); + assert!(!ran); + write(&dir, "experts.bin", &[7u8; 20]); + // allocation failure reported by the callback wins before any read + let mut reads = 0; + let outcome = stream_experts( + &dir.0, + 20, + 8, + || Err("alloc"), + |_, _| { + reads += 1; + Ok(()) + }, + ); + assert_eq!(outcome, Err(StreamError::Sink("alloc"))); + assert_eq!(reads, 0); + // truncated: 20 bytes present, 21 requested + let mut chunks = 0; + let outcome = stream_experts::<()>( + &dir.0, + 21, + 8, + || Ok(()), + |_, _| { + chunks += 1; + Ok(()) + }, + ); + assert_eq!(outcome, Err(StreamError::Rt(RtError::ExpertsTruncated))); + assert_eq!(chunks, 2); // two complete chunks were delivered before the short read + assert_eq!( + RtError::ExpertsTruncated.message(), + "mtp: experts.bin is truncated" + ); + // a sink failure stops the loop + let outcome = stream_experts( + &dir.0, + 20, + 8, + || Ok(()), + |o, _| if o == 8 { Err("h2d") } else { Ok(()) }, + ); + assert_eq!(outcome, Err(StreamError::Sink("h2d"))); + assert!(matches!( + stream_experts::<()>(&dir.0, 20, 0, || Ok(()), |_, _| Ok(())), + Err(StreamError::Rt(RtError::Host)) + )); + assert_eq!(expert_bank_bytes(512, 1_382_400).unwrap(), 707_788_800); + assert_eq!( + expert_bank_bytes(u64::MAX, 2), + Err(RtError::ExpertSizeOverflow) + ); + } + + #[test] + fn expert_scale_scan_handles_chunk_boundaries_inside_blobs() { + let blob = 1_382_400u64; + let bank = experts(2, blob as usize); + for chunk in [1_000_000usize, 777_776, 1_382_400, 2_764_800] { + let mut offset = 0usize; + while offset < bank.len() { + let end = (offset + chunk).min(bank.len()); + assert!(expert_scales_finite( + offset as u64, + &bank[offset..end], + blob + )); + offset = end; + } + } + // an Inf scale half in the second blob is found from any chunking + for chunk in [1_000_000usize, 777_776, 2_764_800] { + let mut broken = bank.clone(); + let at = blob as usize + EXPERT_SCALE_OFFSET as usize + 1000; + broken[at] = 0x00; + broken[at + 1] = 0x7c; + let mut found = false; + let mut offset = 0usize; + while offset < broken.len() { + let end = (offset + chunk).min(broken.len()); + found |= !expert_scales_finite(offset as u64, &broken[offset..end], blob); + offset = end; + } + assert!(found, "chunk {chunk}"); + } + // an Inf in the Q2 code region is not a scale and is never examined + let mut codes = bank.clone(); + codes[10] = 0x00; + codes[11] = 0x7c; + assert!(expert_scales_finite(0, &codes, blob)); + assert!(!expert_scales_finite(1, &bank[1..3], blob)); // odd offset refused + } + + #[test] + fn draft_vocab_follows_the_original_size_filter() { + let dir = TempDir::new("vocab"); + assert_eq!(read_draft_vocab(&dir.0).unwrap(), DraftVocab::Absent); + assert_eq!(observed_draft_vocab_bytes(&dir.0), None); + for bad in [&b""[..], &b"abc"[..], &b"abcdef"[..]] { + write(&dir, "draft_vocab.bin", bad); + assert_eq!(read_draft_vocab(&dir.0).unwrap(), DraftVocab::Absent); + // the bind_bytes probe still sees the file size (the caller filters) + assert_eq!(observed_draft_vocab_bytes(&dir.0), Some(bad.len() as u64)); + } + let ids = [5i32, 0, 9, 5]; + let raw: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); + write(&dir, "draft_vocab.bin", &raw); + assert_eq!( + read_draft_vocab(&dir.0).unwrap(), + DraftVocab::Subset(ids.to_vec()) + ); + validate_subset(&ids, 10).unwrap(); + assert_eq!(validate_subset(&ids, 9), Err(RtError::DraftVocabOutOfRange)); + assert_eq!( + validate_subset(&[-1], 10), + Err(RtError::DraftVocabOutOfRange) + ); + assert_eq!(validate_subset(&[], 10), Err(RtError::DraftVocabOutOfRange)); + write( + &dir, + "draft_vocab.bin", + &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], + ); + assert_eq!(read_draft_vocab(&dir.0), Err(RtError::DraftVocabTooLarge)); + } +}