From 32a4aef83cdd9a80a7ea3a9b52e02fb9751eb59d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:37:02 +0200 Subject: [PATCH 1/4] fix(mtp): feed full-forward the MLP hyper-connection, shared-expert gate/up/down and final mixer roles in driver order full_forward_weights handed OriginalMtpRetainedFullWeights::retain the roles in the wrong order: slots 3..6 (read by mlp_gr as the MLP hyper-connection: norm, down, up, inject) got the ATTENTION hyper-connection tensors, slots 12..14 (final mixer norm/down/up) got the MLP hyper-connection tensors, and slots 8..10 (shared expert gate, up, down per record_forward) got down, gate, up. The driver only checks byte extents and allows identical aliases, and these tensors have equal sizes, so the permutation passed every check and would run silently with the wrong weights: garbage drafts (zero acceptance, only speed lost, never correctness). mlp_hyper_connection inject and hyper_connection_mixer tensors were never used at all. Pin the order in one table (FULL_FORWARD_ROLES) with a name-level test against mtp.cpp record_forward. Co-Authored-By: Claude Sonnet 5.5 --- .../cache_original_mtp_weights.rs | 66 ++++++++++++++----- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/cache_original_mtp_weights.rs b/crates/leleka-runtime/src/qwen_forward/cache_original_mtp_weights.rs index 6a996ffd..00789bd4 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_original_mtp_weights.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_original_mtp_weights.rs @@ -149,23 +149,10 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{ if (kind,rows,columns)!=expected{return Err(Error::InvalidDimension);} Ok(owner) }; - let roles=[ - acquire(MtpRole::QueryProjection,(MtpKind::Q8_0,12288,2560))?, - acquire(MtpRole::QueryNorm,(MtpKind::F32,1,256))?, - acquire(MtpRole::AttentionOutput,(MtpKind::Q8_0,2560,6144))?, - acquire(MtpRole::AttentionNorm,(MtpKind::F32,1,10240))?, - acquire(MtpRole::AttentionDown,(MtpKind::Bf16,320,10240))?, - acquire(MtpRole::AttentionUp,(MtpKind::Bf16,10240,320))?, - acquire(MtpRole::AttentionInject,(MtpKind::Bf16,4,10240))?, - acquire(MtpRole::Router,(MtpKind::Bf16,512,2560))?, - acquire(MtpRole::SharedDown,(MtpKind::Q8_0,2560,640))?, - acquire(MtpRole::SharedGate,(MtpKind::Q8_0,640,2560))?, - acquire(MtpRole::SharedUp,(MtpKind::Q8_0,640,2560))?, - acquire(MtpRole::SharedScalar,(MtpKind::Bf16,1,2560))?, - acquire(MtpRole::FfnNorm,(MtpKind::F32,1,10240))?, - acquire(MtpRole::FfnDown,(MtpKind::Bf16,320,10240))?, - acquire(MtpRole::FfnUp,(MtpKind::Bf16,10240,320))?, - ]; + let roles=FULL_FORWARD_ROLES.map(|(role,expected)|acquire(role,expected)); + let mut acquired=Vec::new();acquired.try_reserve_exact(roles.len()).map_err(|_|Error::InputAllocation)?; + for role in roles{acquired.push(role?);} + let roles:[Rc>;15]=acquired.try_into().map_err(|_|Error::InvalidDimension)?; let experts=self.expert_bank(binding,context)?; // Literal bind: with a draft_vocab subset the draft head is the gathered // rows (`dhead_`, `n_dvocab_` of them), else the native head itself. @@ -185,6 +172,32 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{ } } +/// Role order of `OriginalMtpRetainedFullWeights::retain` (driver `FULL_EXTENTS`; +/// consumed by `plan`/`mlp_gr`/`final_gr`), i.e. mtp.cpp `record_forward(full)`: +/// 0 q_proj, 1 q_norm, 2 o_proj, 3..6 the MLP hyper-connection (hc_norm, down, +/// up, block_inject), 7 router, 8 shared gate, 9 shared up, 10 shared down, +/// 11 shared-expert gate scalar, 12..14 the final mixer (hc_norm, down, up). +/// The attention hyper-connection is the prefix's. Several of these have equal +/// byte extents (gate/up/down, the two hyper-connections), so the driver's +/// extent and alias checks cannot catch a permutation: the order is pinned here. +const FULL_FORWARD_ROLES:[(MtpRole,(MtpKind,usize,usize));15]=[ + (MtpRole::QueryProjection,(MtpKind::Q8_0,12288,2560)), + (MtpRole::QueryNorm,(MtpKind::F32,1,256)), + (MtpRole::AttentionOutput,(MtpKind::Q8_0,2560,6144)), + (MtpRole::FfnNorm,(MtpKind::F32,1,10240)), + (MtpRole::FfnDown,(MtpKind::Bf16,320,10240)), + (MtpRole::FfnUp,(MtpKind::Bf16,10240,320)), + (MtpRole::FfnInject,(MtpKind::Bf16,4,10240)), + (MtpRole::Router,(MtpKind::Bf16,512,2560)), + (MtpRole::SharedGate,(MtpKind::Q8_0,640,2560)), + (MtpRole::SharedUp,(MtpKind::Q8_0,640,2560)), + (MtpRole::SharedDown,(MtpKind::Q8_0,2560,640)), + (MtpRole::SharedScalar,(MtpKind::Bf16,1,2560)), + (MtpRole::FinalNorm,(MtpKind::F32,1,10240)), + (MtpRole::FinalDown,(MtpKind::Bf16,320,10240)), + (MtpRole::FinalUp,(MtpKind::Bf16,10240,320)), +]; + fn rt_kind(kind:MtpKind)->Result{ 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)} @@ -203,6 +216,25 @@ mod rt_contract_tests{ assert_eq!(rt_kind(MtpKind::Q2_0).err(),Some(Error::InvalidDimension)); } + /// mtp.cpp record_forward(full) tensor names, in the driver's role order. + #[test] + fn full_forward_role_order_matches_mtp_cpp_tensor_names(){ + let names:Vec<&str>=FULL_FORWARD_ROLES.iter().map(|(role,_)|rt_dense_name(*role).unwrap()).collect(); + assert_eq!(names,[ + "self_attn.q_proj.weight","self_attn.q_norm.weight","self_attn.o_proj.weight", + "mlp_hyper_connection.hc_norm.weight","mlp_hyper_connection.input_mix_weight_down.weight", + "mlp_hyper_connection.input_mix_weight_up.weight","mlp_hyper_connection.block_inject_weight.weight", + "mlp.gate.weight", + "mlp.shared_expert.gate_proj.weight","mlp.shared_expert.up_proj.weight","mlp.shared_expert.down_proj.weight", + "mlp.shared_expert_gate.weight", + "hyper_connection_mixer.hc_norm.weight","hyper_connection_mixer.input_mix_weight_down.weight", + "hyper_connection_mixer.input_mix_weight_up.weight", + ]); + for (role,expected) in FULL_FORWARD_ROLES{ + assert_eq!(rt_dense_shape(role),Some(expected)); + } + } + #[test] fn every_contract_role_has_a_unique_rt_name_kind_and_shape(){ let roles=rt_dense_roles(); From 95ce8042314cf711e2d8de33b2a40e0ca47dd8be Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:40:30 +0200 Subject: [PATCH 2/4] fix(mtp): accept the real draft ring slot count in prefix_commands prefix_commands (used by prepare_round and prepare_step, i.e. every draft) required ring.slots == MTP_ORIGINAL_WINDOW / 4 == 8192. The ring that the shared layout creates has (window + 4 * max_t + 64) / 4 = 8208 + max_t slots (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 cells per slot), or 65536 for the fully-resident retry, so the check failed with InvalidQwenShape for every configuration and no round or step graph could ever be prepared. Accept exactly those two counts. Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/src/mtp_original_full_forward.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/cuda-driver/src/mtp_original_full_forward.rs b/crates/cuda-driver/src/mtp_original_full_forward.rs index 82e939a3..7b12bf0d 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward.rs @@ -1910,7 +1910,10 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { || t > self.inner.max_t || t > scalar.max_t || t > ring.max_t - || ring.slots != MTP_ORIGINAL_WINDOW / 4 + // Window ring (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 per + // slot) or the Original fully-resident retry (one slot per page). + || (ring.slots != (MTP_ORIGINAL_WINDOW + 4 * ring.max_t + 64).div_ceil(4) + && ring.slots != MTP_ORIGINAL_MAX_CELLS / 4) || step_row .checked_add(t) .is_none_or(|n| n > 2 * self.inner.max_t) From 78195fd3a709c0995d3272d7ce26942d7fb39f2b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:40:31 +0200 Subject: [PATCH 3/4] harden(mtp): open RT files with O_NOFOLLOW|O_NONBLOCK on Linux open_regular lstat'ed then opened by path; a dense.txt/dense.bin/experts.bin swapped for a symlink or FIFO between the two steps was followed (or blocked the loader). The control-plane preflight already opens with these flags. Co-Authored-By: Claude Sonnet 5.5 --- crates/cuda-driver/src/original_mtp_rt.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs index 85427575..3aec48f6 100644 --- a/crates/cuda-driver/src/original_mtp_rt.rs +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -298,6 +298,19 @@ fn open_regular(path: &Path) -> Option { if link.file_type().is_symlink() || !link.is_file() { return None; } + // The lstat above and this open are separate steps: on Linux the open itself + // refuses a symlink swapped in between (O_NOFOLLOW) and cannot block on a + // FIFO swapped in (O_NONBLOCK; a regular file is unaffected). + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + let file = { + use std::os::unix::fs::OpenOptionsExt; + fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + .ok()? + }; + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] let file = File::open(path).ok()?; file.metadata().ok()?.is_file().then_some(file) } From b91368fc701e58ea7ce2245df0d1d567f4f02d40 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 16:46:30 +0200 Subject: [PATCH 4/4] fix(mtp): correct the shared-arena role map of the full-forward tail and the scalar injection Two table errors in the Original-literal physical layout, both invisible to type and extent checks and both reached only on the GPU: 1. Layout::full_role mapped tail buffers 8, 9, 10 (hit_dst, parts, hit_slot) to roles 34, 35, 36. Role 35 (hit_dst_) is 40 bytes and 36 (hit_count_) 16, but tail 9 (the 102400-byte expert parts) and tail 10 (40 bytes) were placed there, so FullOwned::handle returned InvalidSize for them and no round or step program could be planned. Map them to 35, 31 (parts_), 34. 2. Layout::scalar mapped the attention hyper-connection injection (scalar 10) to inj2_ (role 14), the very buffer the tail uses as the MLP half's inject_out (tail 20). mlp_gr passes the attention inject as inj_prev and the MLP inject as inject_out, so the fused GR kernels read and wrote the same 4 floats concurrently. Map scalar 10 to inj_ (role 13), as Original. Add pure tests (red before, green after) that every tail buffer fits its role without overlap and that the scalar and tail views share only the step/pos records, which Original shares too. Co-Authored-By: Claude Sonnet 5.5 --- .../src/mtp_original_full_forward.rs | 82 +++++++++++++++++++ .../src/mtp_original_physical_layout.rs | 11 ++- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/cuda-driver/src/mtp_original_full_forward.rs b/crates/cuda-driver/src/mtp_original_full_forward.rs index 7b12bf0d..b73d7def 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward.rs @@ -2707,3 +2707,85 @@ mod session_coupling; pub use session_coupling::{ OriginalMtpRopeForm, OriginalMtpSessionPlan, OriginalMtpSessionResources, }; + +#[cfg(test)] +mod role_map_tests { + use super::*; + + /// `handle()` places every legacy TailLayout buffer at a literal MtpDrafter + /// role of the shared physical arena (`Layout::full_role`). Each mapped span + /// must fit its role and no two may overlap; a permuted table (hit_dst / parts + /// / hit_slot once pointed at roles 34..36) makes `handle` fail for every draft. + /// The scalar (prefix) view and the tail view address one arena. The only + /// legitimate sharing is Original's own: `step_` and `pos_` (scalar 13/14 = + /// tail 31/32). Anything else overlapping (it once happened to the two + /// injection buffers) is a data race between the two halves of a round. + #[test] + fn scalar_and_tail_views_share_only_step_and_position_records() { + for t in 1..=8 { + let tail = TailLayout::new(248_320, t, true).expect("tail layout"); + let arena = physical_layout::Layout::new(t).expect("physical layout"); + let view = arena.scalar(); + let sizes = Scratch::new(t).expect("scalar layout").sizes; + let mut scalar: Vec<(usize, usize, usize)> = Vec::new(); + for (index, size) in sizes.iter().copied().enumerate() { + assert!(size <= arena_role_size(&arena, view.offsets[index]), "scalar {index}"); + scalar.push((index, view.offsets[index], size)); + } + let mut tails: Vec<(usize, usize, usize)> = Vec::new(); + for (index, size) in tail.sizes.iter().copied().enumerate() { + if let Some((role, offset)) = physical_layout::Layout::full_role(index) { + tails.push((index, arena.offsets[role] + offset, size)); + } + } + for (i, a) in scalar.iter().enumerate() { + for b in &scalar[..i] { + assert!(a.1 + a.2 <= b.1 || b.1 + b.2 <= a.1, "scalar {} and {} overlap", a.0, b.0); + } + for b in &tails { + let overlap = a.1 < b.1 + b.2 && b.1 < a.1 + a.2; + let intended = matches!((a.0, b.0), (13, 31) | (14, 32)); + assert!(!overlap || intended, "T={t}: scalar {} overlaps tail {}", a.0, b.0); + } + } + } + } + + fn arena_role_size(arena: &physical_layout::Layout, offset: usize) -> usize { + let role = arena.offsets.iter().position(|o| *o == offset).expect("role start"); + arena.sizes[role] + } + + #[test] + fn tail_buffers_fit_their_physical_roles_without_overlap() { + for t in 1..=8 { + for coupled in [false, true] { + let tail = TailLayout::new(248_320, t, coupled).expect("tail layout"); + let arena = physical_layout::Layout::new(t).expect("physical layout"); + let mut spans: Vec<(usize, usize, usize, usize)> = Vec::new(); + for (index, size) in tail.sizes.iter().copied().enumerate() { + let Some((role, offset)) = physical_layout::Layout::full_role(index) else { + continue; + }; + assert!( + offset + size <= arena.sizes[role], + "T={t} tail {index} needs {size} at {offset} of role {role} ({})", + arena.sizes[role] + ); + spans.push((index, role, offset, size)); + } + for (i, a) in spans.iter().enumerate() { + for b in &spans[..i] { + assert!( + a.1 != b.1 || a.2 + a.3 <= b.2 || b.2 + b.3 <= a.2, + "T={t} tail {} and {} overlap in role {}", + a.0, + b.0, + a.1 + ); + } + } + } + } + } +} diff --git a/crates/cuda-driver/src/mtp_original_physical_layout.rs b/crates/cuda-driver/src/mtp_original_physical_layout.rs index ea87e4f3..42a14184 100644 --- a/crates/cuda-driver/src/mtp_original_physical_layout.rs +++ b/crates/cuda-driver/src/mtp_original_physical_layout.rs @@ -149,9 +149,11 @@ impl Layout { Some((27, 0)), Some((28, 0)), Some((29, 0)), - Some((34, 0)), + // 8 hit_dst, 9 parts, 10 hit_slot: the order `plan` hands moe_group + // (hit_dst, hit_slot) and moe_grouped_s2/combine (parts). Some((35, 0)), - Some((36, 0)), + Some((31, 0)), + Some((34, 0)), Some((30, 0)), Some((37, 0)), Some((38, 0)), @@ -182,7 +184,10 @@ impl Layout { } pub(super) fn scalar(&self) -> Scratch { - let roles = [5usize, 6, 7, 8, 9, 10, 11, 18, 15, 16, 14, 12, 0, 1, 2, 19]; + // Index 10 is the attention hyper-connection's injection: Original `inj_` + // (role 13). Role 14 (`inj2_`) is the MLP half's, which the tail owns + // (`full_role(20)`); sharing it raced inject_out against inj_prev. + let roles = [5usize, 6, 7, 8, 9, 10, 11, 18, 15, 16, 13, 12, 0, 1, 2, 19]; let mut sizes = [0; 16]; let mut offsets = [0; 16]; for (out, role) in roles.into_iter().enumerate() {