diff --git a/crates/cuda-driver/src/mtp_original_full_forward.rs b/crates/cuda-driver/src/mtp_original_full_forward.rs index 51f93355..075d34e4 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) @@ -2705,3 +2708,85 @@ pub use session_coupling::{ OriginalMtpRopeForm, OriginalMtpSessionPlan, OriginalMtpSessionResources, }; pub(crate) use session_coupling::session_assets_sealed; + +#[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() { 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) } 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();