feat(mtp): RT directory reader and closed-profile load plan for the Original MTP loader

Add original_mtp_rt (dense.txt/dense.bin/experts.bin/draft_vocab.bin host side
of MtpDrafter::load/bind with fail-closed extents, finiteness and file checks)
and turn original_mtp_loader into a load plan over captured geometry/session
inputs, admitting the retained ring against the Original KV-mode plan.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:57:20 +02:00
co-authored by Claude Sonnet 5.5
parent 8651f784ef
commit 06af3114fc
3 changed files with 1408 additions and 13 deletions
+1
View File
@@ -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};
+396 -13
View File
@@ -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<T> = std::result::Result<T, LoaderError>;
@@ -273,8 +296,368 @@ pub(crate) fn bind_bytes(input: BindInputs) -> PlanResult<u64> {
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<Self> {
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<u64>, head_row_bytes: u64) -> PlanResult<u64> {
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<u64>) -> PlanResult<CoupledPlan> {
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<KvPlan> {
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::<u64>(), 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);
}
}
File diff suppressed because it is too large Load Diff