test(mtp): Root-only GPU proofs for the RT bank and draft-head gather; first-draft adapter; gap ledger

Add compile-checked ignored device tests (placement, Original ordering, budget
and non-finite refusals, gather widths), draft_first_committed_mtp, runtime
contract tests, and update PORT-GAPS-MODE17 row 1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:10:07 +02:00
co-authored by Claude Sonnet 5.5
parent 92b8eca9e7
commit 6be1e4e38e
6 changed files with 274 additions and 1 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate.
| Original source / function | Current Rust boundary | Required completion |
| --- | --- | --- |
| `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | `cuda-driver/src/original_mtp_loader.rs:278` always returns `MissingOperations`. `original_mtp_actor.rs:140` always returns operation-specific `Unselected`. Existing `mtp_original_full_*` implements genuine forward/graph owners, not an RT-directory loader. | Actual dense.txt/dense.bin/experts.bin loading, required-name check at original stage, real geometry/session/device capture, optional draft_vocab head gather, coupled setup and retained ring resume/idle linkage. Do not substitute configuration metadata for those owners. No actor reset exists upstream. |
| `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | SOURCE-COMPLETE, NOT GPU-RUN (2026-10-14, branch `claude/port-mtp-loader`). `original_mtp_rt.rs` reads dense.txt/dense.bin/experts.bin/draft_vocab.bin; `original_mtp_bank.rs` places them (Original order, nine-name check last); `original_mtp_loader.rs` plans geometry/session/KV/coupled and admits the retained ring; `original_mtp_draft_head.rs` gathers the subset head; `original_mtp_actor_loaded.rs` adopts the genuine drafter and links `idle/device/kv_restore/set_*/draft*/coupled`. Runtime: `RetainedOriginalMtpWeights::from_rt_bank`, `OriginalMtpFullOwner::assemble_rt`, `OriginalPromptExecutor::select_rt_mtp` and the actor-driven `draft_committed_mtp`/`draft_first_committed_mtp`. | Remaining is GPU-only evidence: run the ignored `original_mtp_bank_gpu` tests (`LELEKA_MTP_RT_BANK_GPU=yes`), a real-pack load, and compare drafts with the Original. Nothing above `select_rt_mtp` (serving backend, `OriginalSpecController`) calls it yet: rows 2-3. Not repeated: Original `cudaMemset(cring_, 0xff)`; the Original single-allocation `dense_` (each indexed tensor is its own allocation, same total bytes); `tensor_f32/bf16/q8` host accessors (roles are the retained `Rc<DeviceBuffer>` bank). |
| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. No concrete implementation of that combined verifier resource trait was found in `crates/`. | Implement retained whole 48-layer native window resources, actual projection/GR/GDN/QSA/MoE/head command recording, cache-slot/source lifetime and CPU pool/PCIe plan callbacks. Record all T graphs and real commit graph before `run`; existing scheduler alone is not the window producer. |
| `mtp.cpp` `draft/draft_first` and `verify.cpp` `run/commit/wait_commit`, used together by mode17 generation | `qwen_forward/original_spec_draft.rs` defines `OriginalDraftEngine` / `OriginalFirstDraftEngine`; `original_spec_controller.rs:20` defines `OriginalSpecEngine`. No concrete impl or production `OriginalSpecController::new` call was found. The real driver `OriginalMtpDrafter` and verifier receipt bridge already exist. | Bind the genuine verifier receipts, all-T residual catch-up, actual MTP ring/full seed, accepted-prefix replay/publication, adaptive work and BOTH checkpoint restoration to these traits; then select that controller in the actual serving owner. Preserve sampled history/counter and async commit event dependencies. |
| `include/strata/core/verify.hpp` `set_stage/set_next`; `src/core/verify.cpp:191,1054,1382,1412`; `core/on_device.hpp` | `OriginalVerifier` loops all 48 layers, has no next-stage owner or stage handoff fields. Context identity exists, but the unselected MTP actor cannot infer an actual current CUDA device ordinal. | Port stage bounds, mapped portable R+pending-bo+inject handoff, next-user CPU dispatch and last-stage head/sampling/final_R/commit forwarding. This is an absent multi-GPU mode17 leaf, not a single-device quality defect. |
@@ -293,3 +293,7 @@ impl<'ctx> Context<'ctx> {
pub fn original_mtp_draft_vocab_bytes(directory: &Path) -> Option<u64> {
rt::observed_draft_vocab_bytes(directory)
}
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "original_mtp_bank_gpu.rs"]
mod gpu_tests;
@@ -0,0 +1,185 @@
//! Root-only device proofs for the RT bank and the draft-head gather. They need
//! a CUDA device and run only with the enabling variable; on every other host
//! they are compile-checked, never executed. Synthetic payloads certify the
//! loader's placement/ordering/refusal behaviour, not model quality.
use super::*;
use crate::Driver;
use crate::original_mtp_rt::fixtures::{self as fx, TempDir};
const ENABLE: &str = "LELEKA_MTP_RT_BANK_GPU";
const BLOB: usize = EXPERT_BLOB_BYTES as usize;
fn read(buffer: &DeviceBuffer<'_>) -> Vec<u8> {
let mut bytes = vec![0; buffer.len()];
buffer.copy_to(&mut bytes).unwrap();
bytes
}
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn rt_bank_places_every_tensor_and_the_expert_chunks_exactly() {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(256 << 20).expect("context");
let dir = TempDir::new("bank-gpu");
let (text, blob) = fx::dense();
let experts = fx::experts(3, BLOB);
fx::write(&dir, "dense.txt", text.as_bytes());
fx::write(&dir, "dense.bin", &blob);
fx::write(&dir, "experts.bin", &experts);
let baseline = context.allocated_bytes();
let bank = context.original_mtp_rt_bank(&dir.0, 3).expect("bank");
assert_eq!(bank.device(), 0);
assert_eq!(bank.vram_bytes(), (blob.len() + experts.len()) as u64);
assert_eq!(
context.allocated_bytes() - baseline,
blob.len() + experts.len()
);
assert_eq!(bank.expert_count(), 3);
bank.validate_context(&context).unwrap();
assert_eq!(read(&bank.experts()), experts);
let index = rt::DenseIndex::parse(&text).unwrap();
for entry in index.tensors() {
let tensor = bank.tensor(&entry.name, entry.kind).expect(&entry.name);
assert_eq!(
(tensor.rows() as u64, tensor.columns() as u64),
(entry.rows, entry.columns)
);
assert_eq!(
read(&tensor.buffer()),
index.slice(entry, &blob).unwrap(),
"{}",
entry.name
);
}
// kind is part of the lookup: the q8 tensor is not a bf16 one
assert!(
bank.tensor("fc_hidden.weight", OriginalMtpTensorKind::Bf16)
.is_none()
);
drop(bank);
assert_eq!(context.allocated_bytes(), baseline);
// Original order: the nine-name check is LAST, after both banks were placed
// (so a missing name leaves no allocation behind once the failure drops).
let missing: String = text
.lines()
.filter(|l| !l.starts_with("self_attn.v_proj.weight "))
.map(|l| format!("{l}\n"))
.collect();
fx::write(&dir, "dense.txt", missing.as_bytes());
let error = context
.original_mtp_rt_bank(&dir.0, 3)
.err()
.expect("missing name");
assert_eq!(
error.message(),
"mtp: self_attn.v_proj.weight is missing (q8_0)"
);
assert_eq!(context.allocated_bytes(), baseline);
// truncated experts are found only after the dense bank was uploaded
fx::write(&dir, "dense.txt", text.as_bytes());
fx::write(&dir, "experts.bin", &experts[..experts.len() - 1]);
let error = context
.original_mtp_rt_bank(&dir.0, 3)
.err()
.expect("truncated");
assert_eq!(error.message(), "mtp: experts.bin is truncated");
assert_eq!(context.allocated_bytes(), baseline);
// an Inf scale half in the second chunk refuses before the checks run
let mut bad = experts.clone();
let at = BLOB + rt::EXPERT_SCALE_OFFSET as usize + 8;
bad[at] = 0x00;
bad[at + 1] = 0x7c;
fx::write(&dir, "experts.bin", &bad);
let error = context
.original_mtp_rt_bank(&dir.0, 3)
.err()
.expect("non-finite");
assert!(error.message().contains("non-finite"), "{error}");
// the budget refusal plays cudaMalloc's: Original text plus the sizes
let tight = device
.create_context(blob.len() + 16)
.expect("tight context");
fx::write(&dir, "experts.bin", &experts);
let error = tight.original_mtp_rt_bank(&dir.0, 3).err().expect("budget");
assert!(
error
.message()
.starts_with("mtp: dense weights allocation failed"),
"{error}"
);
assert_eq!(tight.allocated_bytes(), 0);
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn draft_head_gather_matches_a_host_gather_for_each_kernel_width() {
use crate::original_mtp_coupled::subset_inverse;
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(256 << 20).expect("context");
let dir = TempDir::new("head-gpu");
let vocabulary = 50usize;
let ids = [7i32, 3, 49, 3, 0];
// Q8_0 native head (kind 8): 2560 cols -> 2720 B rows (16-byte kernel),
// 64 cols -> 68 B (4-byte kernel), 32 cols -> 34 B (byte kernel).
for columns in [2560usize, 64, 32] {
let row_bytes = crate::native_head_row_bytes(8, columns).unwrap();
let host: Vec<u8> = (0..vocabulary * row_bytes)
.map(|i| (i * 31 + columns) as u8)
.collect();
let mut head = context.allocate(host.len()).unwrap();
head.copy_from(&host).unwrap();
// absent file: Original ignores it
assert!(
context
.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary)
.unwrap()
.is_none()
);
fx::write(
&dir,
"draft_vocab.bin",
&ids.iter().flat_map(|i| i.to_le_bytes()).collect::<Vec<_>>(),
);
let draft = context
.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary)
.unwrap()
.expect("subset head");
assert_eq!((draft.count(), draft.row_bytes()), (ids.len(), row_bytes));
let expected: Vec<u8> = ids
.iter()
.flat_map(|&id| host[id as usize * row_bytes..(id as usize + 1) * row_bytes].to_vec())
.collect();
assert_eq!(read(&draft.rows()), expected, "columns {columns}");
let ids_back: Vec<i32> = read(&draft.ids())
.chunks_exact(4)
.map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
assert_eq!(ids_back, ids);
let inverse: Vec<i32> = read(&draft.inverse())
.chunks_exact(4)
.map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
assert_eq!(inverse, subset_inverse(vocabulary, &ids).unwrap());
assert_eq!(inverse[3], 1, "first occurrence wins");
// an id outside the vocabulary never reaches the kernel
fx::write(&dir, "draft_vocab.bin", &50i32.to_le_bytes());
let error = context
.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary)
.err()
.expect("range");
assert!(error.message().contains("outside the vocabulary"));
std::fs::remove_file(dir.0.join("draft_vocab.bin")).unwrap();
}
assert!(!context.is_poisoned());
}
@@ -189,3 +189,33 @@ fn rt_kind(kind:MtpKind)->Result<leleka_cuda_driver::OriginalMtpTensorKind>{
use leleka_cuda_driver::OriginalMtpTensorKind as K;
match kind{MtpKind::Q8_0=>Ok(K::Q8_0),MtpKind::Bf16=>Ok(K::Bf16),MtpKind::F32=>Ok(K::F32),MtpKind::Q2_0=>Err(Error::InvalidDimension)}
}
#[cfg(test)]
mod rt_contract_tests{
use super::*;
use leleka_cuda_driver::OriginalMtpTensorKind as K;
#[test]
fn bank_kinds_map_one_to_one_and_q2_is_never_a_dense_kind(){
assert!(matches!(rt_kind(MtpKind::Q8_0),Ok(K::Q8_0)));
assert!(matches!(rt_kind(MtpKind::Bf16),Ok(K::Bf16)));
assert!(matches!(rt_kind(MtpKind::F32),Ok(K::F32)));
assert_eq!(rt_kind(MtpKind::Q2_0).err(),Some(Error::InvalidDimension));
}
#[test]
fn every_contract_role_has_a_unique_rt_name_kind_and_shape(){
let roles=rt_dense_roles();
assert_eq!(roles.len(),26);
let mut names=Vec::new();
for role in roles{
let name=rt_dense_name(role).unwrap();
let(kind,rows,columns)=rt_dense_shape(role).unwrap();
assert!(rt_kind(kind).is_ok()&&rows>0&&columns>0,"{name}");
names.push(name);
}
names.sort_unstable();names.dedup();
assert_eq!(names.len(),26);
assert_eq!(pinned_dense_bytes(),116_099_072);
}
}
@@ -225,3 +225,37 @@ fn driver_error(error:leleka_cuda_driver::Error)->Error{
_=>Error::CudaExecution,
}
}
#[cfg(test)]
mod tests{
use super::*;
#[test]
fn plan_refusals_map_to_fixed_errors_and_keep_the_original_text(){
let cases=[
(OriginalMtpPlanError::MaxTOutOfRange,Error::InvalidDimension,"mtp: max_t out of range"),
(OriginalMtpPlanError::Geometry,Error::InvalidDimension,"mtp: invalid geometry"),
(OriginalMtpPlanError::Overflow,Error::Overflow,"mtp: resource size overflow"),
(OriginalMtpPlanError::RingMode,Error::InvalidDimension,"mtp: the draft K/V ring does not match the planned KV mode"),
(OriginalMtpPlanError::ClosedProfile("draft attention window"),Error::Unsupported(Stage::Session),
"mtp: unsupported draft attention window for the retained Original owners"),
];
for(plan,error,text) in cases{
let mapped=plan_error(plan);
assert_eq!(mapped.error,error);
assert_eq!(mapped.message.as_deref(),Some(text));
}
// a runtime-only error carries no driver text
assert_eq!(OriginalMtpLoadError::from(Error::IdentityMismatch),
OriginalMtpLoadError{error:Error::IdentityMismatch,message:None});
}
#[test]
fn default_request_is_the_original_window_over_the_int8_ring(){
let request=OriginalMtpRequest::ring_int8(4,512,true,20480);
assert_eq!((request.max_t,request.prompt_capacity,request.coupled),(4,512,true));
assert_eq!(request.window,32768);
assert_eq!(request.kv,OriginalMtpKvStartup::ring_int8(20480));
assert!(request.kv.int8&&!request.kv.q4&&!request.kv.hybrid&&!request.kv.ring_off&&!request.kv.main_off);
}
}
@@ -120,6 +120,26 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
draft.publish_mtp_completion(binding,session,&receipt.before,&receipt.committed,&completed)?;
Ok(OriginalMtpDraftReceipt{binding:binding.identity(),context:self.context,origin:receipt.committed,completed})
}
/// generate.cpp `mtp.draft_first(o.spec, ss.R, x, p - 1, drafts, ...)`: the
/// first round after the prompt, from the single-row verifier window of the
/// final prompt seed (the Original repeat-row path), not `draft`'s catch-up.
/// Same order and receipts as `draft_committed_mtp`; `rows` is `T`.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn draft_first_committed_mtp(&mut self,binding:&ModelBinding,
session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,
receipt:OriginalCommittedMtpReceipt<'ctx>,rows:usize,min_p:f32,policy:&OriginalMtpFullPolicy)
->Result<OriginalMtpDraftReceipt<'ctx>>{
receipt.validate(binding,session,self.context)?;
if !min_p.is_finite()||receipt.accepted_row!=0||receipt.window.rows()!=1{return Err(Error::InvalidDimension);}
let actor=self.mtp_actor(binding)?;
if actor.settings().max_drafts()<0{return Err(Error::InvalidDimension);}
let completed=draft.with_mtp_transition_ring(binding,session,&receipt.before,&receipt.committed,|ring,prior|{
actor.draft_first_from_verifier(ring,prior,receipt.window,receipt.selection,rows,min_p,policy)
.map_err(driver_error)
})?;
draft.publish_mtp_completion(binding,session,&receipt.before,&receipt.committed,&completed)?;
Ok(OriginalMtpDraftReceipt{binding:binding.identity(),context:self.context,origin:receipt.committed,completed})
}
/// `mtp.set_draft_sampling(req_sp)` (a no-op unless coupled setup succeeded).
pub(in crate::qwen_forward) fn set_mtp_draft_sampling(&mut self,binding:&ModelBinding,
params:&SamplerParams)->Result<()> {