feat(mtp): wire RT-directory MTP selection through the prompt executor and verified adapter
OriginalPromptExecutor::select_rt_mtp mirrors generate.cpp's --mtp branch: RT bank load, executor over the exact retained roles, native-head bind with the optional draft_vocab gather, shared scalar/full/ring layout, coupled setup and the loaded OriginalMtpActor. The retained-weights cache can now be built from an RT bank (kind/shape contract by name), full_forward_weights takes the real draft head, and draft_committed_mtp drives the actor's settings and coupled history instead of caller-supplied copies. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
0c1fc6173f
commit
92b8eca9e7
@@ -62,7 +62,7 @@ mod original_mtp_loader;
|
||||
mod original_mtp_rt;
|
||||
mod original_mtp_bank;
|
||||
pub use original_mtp_bank::{
|
||||
OriginalMtpLoadFailure, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind,
|
||||
OriginalMtpLoadFailure, original_mtp_draft_vocab_bytes, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind,
|
||||
};
|
||||
pub use original_mtp_actor::{
|
||||
ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings,
|
||||
@@ -70,7 +70,7 @@ pub use original_mtp_actor::{
|
||||
pub use original_mtp_loader::{
|
||||
CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat,
|
||||
KvMode as OriginalMtpKvMode, KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError,
|
||||
OriginalMtpCapture, OriginalMtpKvStartup, OriginalMtpLoadPlan,
|
||||
OriginalMtpCapture, OriginalMtpKvStartup, OriginalMtpLoadPlan, original_mtp_bind_reserve,
|
||||
WeightBankPlan as OriginalMtpWeightBankPlan,
|
||||
};
|
||||
#[cfg(all(
|
||||
|
||||
@@ -35,9 +35,9 @@ fn mismatch(what: &'static str) -> OriginalMtpLoadFailure {
|
||||
|
||||
/// `vram_` bookkeeping: the Original adds every allocation of `load`/`bind` to
|
||||
/// one counter. Here the figure is the context's own allocation ledger across
|
||||
/// the whole load, so it includes every owner (banks, ring, scratch arena,
|
||||
/// mapped-adjacent device buffers, subset head) and cannot be asserted by a
|
||||
/// caller.
|
||||
/// the assembly (ring, scratch arena, subset head, ...) plus the bytes of the
|
||||
/// banks the caller loaded earlier (`preloaded_bytes`, taken from the bank
|
||||
/// itself), so it cannot be asserted by a caller.
|
||||
pub struct OriginalMtpLoadMeter {
|
||||
allocated: usize,
|
||||
device: i32,
|
||||
@@ -53,6 +53,7 @@ impl OriginalMtpLoadMeter {
|
||||
self,
|
||||
context: &Context<'ctx>,
|
||||
draft_head: Option<&OriginalMtpDraftHead<'ctx>>,
|
||||
preloaded_bytes: u64,
|
||||
) -> std::result::Result<OriginalMtpLoadEvidence, OriginalMtpLoadFailure> {
|
||||
if context.is_poisoned() {
|
||||
return Err(inconsistent(Error::ContextPoisoned));
|
||||
@@ -62,8 +63,11 @@ impl OriginalMtpLoadMeter {
|
||||
.checked_sub(self.allocated)
|
||||
.filter(|_| context.device_ordinal() == self.device)
|
||||
.ok_or_else(|| mismatch("the load ledger is not monotonic on its device"))?;
|
||||
let vram = (vram as u64)
|
||||
.checked_add(preloaded_bytes)
|
||||
.ok_or_else(|| mismatch("the load ledger overflows"))?;
|
||||
Ok(OriginalMtpLoadEvidence {
|
||||
vram_bytes: vram as u64,
|
||||
vram_bytes: vram,
|
||||
device: self.device,
|
||||
draft_vocabulary: draft_head.map(OriginalMtpDraftHead::count),
|
||||
})
|
||||
|
||||
@@ -133,6 +133,10 @@ impl<'ctx> OriginalMtpRtBank<'ctx> {
|
||||
pub fn expert_count(&self) -> usize {
|
||||
self.expert_count
|
||||
}
|
||||
/// Length of `dense.bin` as loaded.
|
||||
pub fn dense_file_bytes(&self) -> u64 {
|
||||
self.dense_file_bytes
|
||||
}
|
||||
/// `vram_` of the Original after the two banks: `dense.bin` + experts.
|
||||
pub fn vram_bytes(&self) -> u64 {
|
||||
self.dense_file_bytes + self.experts.len() as u64
|
||||
@@ -284,3 +288,8 @@ impl<'ctx> Context<'ctx> {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Size probe of `rt/draft_vocab.bin` for `bind_bytes` (`fopen` + `ftell`).
|
||||
pub fn original_mtp_draft_vocab_bytes(directory: &Path) -> Option<u64> {
|
||||
rt::observed_draft_vocab_bytes(directory)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum LoaderError {
|
||||
RingMode,
|
||||
}
|
||||
impl LoaderError {
|
||||
pub(crate) fn message(self) -> String {
|
||||
pub fn message(self) -> String {
|
||||
match self {
|
||||
Self::MaxTOutOfRange => "mtp: max_t out of range".into(),
|
||||
Self::Geometry => "mtp: invalid geometry".into(),
|
||||
@@ -122,8 +122,8 @@ impl WeightBankPlan {
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ReadRange { pub offset: u64, pub bytes: u64 }
|
||||
pub(crate) struct ExpertReads { offset: u64, end: u64 }
|
||||
pub struct ReadRange { pub offset: u64, pub bytes: u64 }
|
||||
pub struct ExpertReads { offset: u64, end: u64 }
|
||||
impl Iterator for ExpertReads {
|
||||
type Item = ReadRange;
|
||||
fn next(&mut self) -> Option<ReadRange> {
|
||||
@@ -327,6 +327,23 @@ pub struct OriginalMtpKvStartup {
|
||||
pub int8_rotated: bool,
|
||||
}
|
||||
|
||||
impl OriginalMtpKvStartup {
|
||||
/// The shipped retained configuration: INT8 draft K/V (no hybrid, no Q4),
|
||||
/// window ring and main streaming enabled, `resident_cells` of resident
|
||||
/// budget (`qsa_set_kv_resident`; `qsa_kv_resident_min()` is 20480).
|
||||
pub fn ring_int8(resident_cells: u64) -> Self {
|
||||
Self {
|
||||
resident_cells,
|
||||
ring_off: false,
|
||||
main_off: false,
|
||||
int8: true,
|
||||
hybrid: false,
|
||||
q4: false,
|
||||
int8_rotated: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything `MtpDrafter::load`/`bind` capture from `ModelGeometry`,
|
||||
/// `SessionState`, the current device and the call arguments.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -348,6 +365,31 @@ pub struct OriginalMtpCapture {
|
||||
pub coupled_requested: bool,
|
||||
}
|
||||
|
||||
/// `MtpDrafter::bind_bytes` for the startup reserve (generate.cpp:2781), before
|
||||
/// any bank exists. `observed_subset_file_bytes` is the `draft_vocab.bin` size
|
||||
/// from `original_mtp_draft_vocab_bytes`; `head_row_bytes` the native head's
|
||||
/// bytes per vocabulary row. Only the captured `max_t`, vocabulary and coupled
|
||||
/// preference matter here; the rest of the capture is checked by `load`.
|
||||
pub fn original_mtp_bind_reserve(
|
||||
capture: &OriginalMtpCapture,
|
||||
observed_subset_file_bytes: Option<u64>,
|
||||
head_row_bytes: u64,
|
||||
) -> PlanResult<u64> {
|
||||
if capture.vocabulary == 0 || capture.vocabulary > VOCABULARY_LIMIT {
|
||||
return Err(LoaderError::ClosedProfile("vocabulary"));
|
||||
}
|
||||
bind_bytes(BindInputs {
|
||||
max_t: capture.max_t,
|
||||
vocabulary: capture.vocabulary,
|
||||
head_row_bytes,
|
||||
logits_already_owned: false,
|
||||
subset_already_owned: false,
|
||||
observed_subset_file_bytes,
|
||||
coupled_enabled: capture.coupled_requested,
|
||||
coupled_params_already_owned: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
@@ -438,16 +480,7 @@ impl OriginalMtpLoadPlan {
|
||||
/// Neither the logits nor a subset are owned before bind, so this is the
|
||||
/// literal upper estimate the startup reserve subtracts.
|
||||
pub 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,
|
||||
})
|
||||
original_mtp_bind_reserve(&self.capture, observed_subset_file_bytes, head_row_bytes)
|
||||
}
|
||||
/// Whether the retained full-forward layout must be built with the coupled
|
||||
/// resources: `setup_coupled` reaches device allocation for this subset
|
||||
@@ -609,6 +642,24 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_reserve_matches_the_plan_method_and_checks_its_inputs() {
|
||||
let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap();
|
||||
assert_eq!(
|
||||
original_mtp_bind_reserve(&capture(), Some(400), 1440).unwrap(),
|
||||
plan.bind_reserve(Some(400), 1440).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
original_mtp_bind_reserve(&OriginalMtpCapture { vocabulary: 0, ..capture() }, None, 1).unwrap_err(),
|
||||
LoaderError::ClosedProfile("vocabulary")
|
||||
);
|
||||
assert_eq!(
|
||||
original_mtp_bind_reserve(&OriginalMtpCapture { max_t: 0, ..capture() }, None, 1).unwrap_err(),
|
||||
LoaderError::Geometry
|
||||
);
|
||||
assert_eq!(OriginalMtpKvStartup::ring_int8(20480), kv());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coupled_setup_plan_follows_setup_coupled() {
|
||||
let off = OriginalMtpLoadPlan::new(capture(), 1).unwrap();
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) use ple::{PleMatrixRole, PleWeights};
|
||||
|
||||
#[path = "qwen4exp_mtp.rs"]
|
||||
mod mtp;
|
||||
pub(crate) use mtp::{MtpKind, MtpRole, MtpWeights};
|
||||
pub(crate) use mtp::{MtpKind, MtpRole, MtpWeights, pinned_dense_bytes, rt_dense_name, rt_dense_roles, rt_dense_shape};
|
||||
|
||||
#[path = "qwen4exp_moe_route.rs"]
|
||||
mod moe_route;
|
||||
|
||||
@@ -595,6 +595,42 @@ fn descriptor(role: MtpRole) -> &'static Descriptor {
|
||||
.expect("closed MTP role")
|
||||
}
|
||||
|
||||
/// RT-directory contract for a directory read by the Original-literal loader
|
||||
/// (`original_mtp_rt`): the normalized tensor names of tools/mtp_rt.py, with the
|
||||
/// kind and shape the retained MTP owners require. The pinned loader above
|
||||
/// additionally fixes offsets and digests; the Original does not, so only
|
||||
/// (kind, rows, columns) are part of this contract.
|
||||
/// `dense.bin` length of the pinned pack (the shipped RT profile).
|
||||
pub(crate) fn pinned_dense_bytes() -> u64 {
|
||||
DENSE_BYTES
|
||||
}
|
||||
pub(crate) fn rt_dense_roles() -> Vec<MtpRole> {
|
||||
DESCRIPTORS
|
||||
.iter()
|
||||
.filter(|d| {
|
||||
d.dense.is_some()
|
||||
&& !matches!(
|
||||
d.role,
|
||||
MtpRole::IndexProjection | MtpRole::IndexKeyNorm | MtpRole::IndexQueryNorm
|
||||
)
|
||||
})
|
||||
.map(|d| d.role)
|
||||
.collect()
|
||||
}
|
||||
pub(crate) fn rt_dense_name(role: MtpRole) -> Option<&'static str> {
|
||||
DESCRIPTORS
|
||||
.iter()
|
||||
.find(|d| d.role == role && d.dense.is_some())
|
||||
.map(|d| d.name)
|
||||
}
|
||||
pub(crate) fn rt_dense_shape(role: MtpRole) -> Option<(MtpKind, usize, usize)> {
|
||||
DESCRIPTORS
|
||||
.iter()
|
||||
.find(|d| d.role == role)
|
||||
.and_then(|d| d.dense)
|
||||
.map(|d| (d.kind, d.rows, d.columns))
|
||||
}
|
||||
|
||||
/// Validation-only receipt. This cannot construct a verified weights owner.
|
||||
struct MtpIndex;
|
||||
impl MtpIndex {
|
||||
@@ -1506,6 +1542,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn rt_contract_lists_the_consumed_dense_roles_by_name() {
|
||||
let roles = rt_dense_roles();
|
||||
assert_eq!(roles.len(), 26);
|
||||
assert!(!roles.contains(&MtpRole::ExpertDown) && !roles.contains(&MtpRole::IndexProjection));
|
||||
let mut names: Vec<_> = roles.iter().map(|r| rt_dense_name(*r).unwrap()).collect();
|
||||
assert!(names.contains(&"fc_embedding.weight"));
|
||||
assert!(names.contains(&"pre_fc_norm_hidden.weight"));
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), 26);
|
||||
assert_eq!(rt_dense_shape(MtpRole::QueryProjection), Some((MtpKind::Q8_0, 12288, 2560)));
|
||||
assert_eq!(rt_dense_shape(MtpRole::Router), Some((MtpKind::Bf16, 512, 2560)));
|
||||
assert_eq!(rt_dense_shape(MtpRole::KeyNorm), Some((MtpKind::F32, 1, 256)));
|
||||
assert_eq!(rt_dense_shape(MtpRole::ExpertGateUp), None);
|
||||
assert_eq!(rt_dense_name(MtpRole::ExpertDown), None);
|
||||
// every nine-name requirement of the Original loader is a q8_0 role here
|
||||
for name in ["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"] {
|
||||
let role = DESCRIPTORS.iter().find(|d| d.name == name).unwrap().role;
|
||||
assert_eq!(rt_dense_shape(role).unwrap().0, MtpKind::Q8_0, "{name}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn malformed_descriptor_input_never_becomes_index() {
|
||||
let good = index();
|
||||
for bad in [
|
||||
|
||||
@@ -2,10 +2,27 @@
|
||||
//! allocations, so a per-call matrix borrow can never outlive its weight bank.
|
||||
use super::*;
|
||||
use super::super::output_native::OriginalMtpNativeHead;
|
||||
use crate::model_binding::qwen4exp_input::{pinned_dense_bytes,rt_dense_name,rt_dense_roles,rt_dense_shape};
|
||||
#[derive(Clone)]
|
||||
struct RetainedDense<'ctx>{role:MtpRole,kind:MtpKind,rows:usize,columns:usize,buffer:Rc<DeviceBuffer<'ctx>>}
|
||||
/// Where the immutable roles came from. `Pinned` is the digest-frozen pack
|
||||
/// owned by the binding; `RtDirectory` is the Original-literal `--mtp DIR`
|
||||
/// load (`Context::original_mtp_rt_bank`), whose bytes are already resident and
|
||||
/// whose kinds/shapes were matched to the role contract at construction.
|
||||
#[derive(Clone,Copy,PartialEq,Eq)]
|
||||
enum WeightSource{Pinned,RtDirectory}
|
||||
/// Clones share the same device allocations (`Rc`); no buffer is duplicated.
|
||||
#[derive(Clone)]
|
||||
pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx>{
|
||||
binding:BindingIdentity,context:&'ctx Context<'ctx>,dense:Vec<RetainedDense<'ctx>>,
|
||||
experts:Rc<DeviceBuffer<'ctx>>,
|
||||
experts:Rc<DeviceBuffer<'ctx>>,source:WeightSource,
|
||||
/// `dense.bin` length and the device bytes this owner's load itself placed
|
||||
/// (0 for the pinned pack, whose bytes the MoE cache already charged).
|
||||
dense_file_bytes:u64,loaded_bytes:u64,
|
||||
/// Indexed RT tensors no role consumes (the optional indexer tensors, or
|
||||
/// extras). Original keeps the whole `dense.bin` resident, so they stay
|
||||
/// owned here for the life of the bank rather than being released early.
|
||||
extras:Vec<Rc<DeviceBuffer<'ctx>>>,
|
||||
}
|
||||
impl<'ctx> MoeWeightCache<'ctx>{
|
||||
pub(in crate::qwen_forward) fn retain_original_mtp_weights(&self,binding:&ModelBinding,
|
||||
@@ -23,21 +40,61 @@ impl<'ctx> MoeWeightCache<'ctx>{
|
||||
}
|
||||
let experts=Rc::clone(self.bank.as_ref().ok_or(Error::IdentityMismatch)?);
|
||||
if experts.len()!=707_788_800{return Err(Error::InvalidDimension);}
|
||||
Ok(RetainedOriginalMtpWeights{binding:binding.identity(),context:self.context,dense,experts})
|
||||
Ok(RetainedOriginalMtpWeights{binding:binding.identity(),context:self.context,dense,experts,source:WeightSource::Pinned,dense_file_bytes:pinned_dense_bytes(),loaded_bytes:0,extras:Vec::new()})
|
||||
}
|
||||
}
|
||||
impl<'ctx> RetainedOriginalMtpWeights<'ctx>{
|
||||
/// Original `MtpDrafter::load` weights, taken from the loaded RT bank.
|
||||
/// Every role of the contract must be present with exactly the retained
|
||||
/// kind and shape (the pinned path checks the same shapes through its
|
||||
/// descriptor table); unknown extra tensors stay in the bank, unused, as in
|
||||
/// Original. The bank's allocations are shared, never copied.
|
||||
pub(in crate::qwen_forward) fn from_rt_bank(binding:&ModelBinding,context:&'ctx Context<'ctx>,
|
||||
bank:&leleka_cuda_driver::OriginalMtpRtBank<'ctx>)->Result<Self>{
|
||||
bank.validate_context(context).map_err(driver_error)?;
|
||||
let roles=rt_dense_roles();
|
||||
let mut dense=Vec::new();dense.try_reserve_exact(roles.len()).map_err(|_|Error::InputAllocation)?;
|
||||
for role in roles{
|
||||
let name=rt_dense_name(role).ok_or(Error::IdentityMismatch)?;
|
||||
let(kind,rows,columns)=rt_dense_shape(role).ok_or(Error::IdentityMismatch)?;
|
||||
let tensor=bank.tensor(name,rt_kind(kind)?).ok_or(Error::InvalidDimension)?;
|
||||
if (tensor.rows(),tensor.columns())!=(rows,columns){return Err(Error::InvalidDimension);}
|
||||
dense.push(RetainedDense{role,kind,rows,columns,buffer:tensor.buffer()});
|
||||
}
|
||||
let experts=bank.experts();
|
||||
if bank.expert_count()!=512||experts.len()!=707_788_800{return Err(Error::InvalidDimension);}
|
||||
let mut extras=Vec::new();extras.try_reserve_exact(bank.tensors().len()).map_err(|_|Error::InputAllocation)?;
|
||||
for tensor in bank.tensors(){
|
||||
let buffer=tensor.buffer();
|
||||
if !dense.iter().any(|entry|Rc::ptr_eq(&entry.buffer,&buffer)){extras.push(buffer);}
|
||||
}
|
||||
Ok(Self{binding:binding.identity(),context,dense,experts,source:WeightSource::RtDirectory,dense_file_bytes:bank.dense_file_bytes(),loaded_bytes:bank.vram_bytes(),extras})
|
||||
}
|
||||
pub(in crate::qwen_forward) fn dense_file_bytes(&self)->u64{self.dense_file_bytes}
|
||||
pub(in crate::qwen_forward) fn loaded_bytes(&self)->u64{self.loaded_bytes}
|
||||
fn validate(&self,binding:&ModelBinding,context:&Context<'ctx>)->Result<()> {
|
||||
if self.context.is_poisoned(){return Err(Error::CudaExecution);}
|
||||
if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch);}
|
||||
binding.mtp_weights().map_err(binding_error)?.validate_sources(binding).map_err(binding_error)
|
||||
match self.source{
|
||||
WeightSource::Pinned=>binding.mtp_weights().map_err(binding_error)?.validate_sources(binding).map_err(binding_error),
|
||||
// The bank is device-resident and was matched at construction;
|
||||
// re-prove that every retained allocation still belongs to this context.
|
||||
WeightSource::RtDirectory=>{
|
||||
if self.experts.len()!=707_788_800||self.dense.iter().any(|entry|entry.buffer.len()==0)
|
||||
||self.extras.iter().any(|buffer|buffer.len()==0){return Err(Error::InvalidDimension);}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn matrix(&self,binding:&ModelBinding,context:&Context<'ctx>,role:MtpRole)
|
||||
->Result<(MtpKind,usize,usize,Rc<DeviceBuffer<'ctx>>)>{
|
||||
self.validate(binding,context)?;
|
||||
let entry=self.dense.iter().find(|entry|entry.role==role).ok_or(Error::IdentityMismatch)?;
|
||||
if binding.mtp_weights().map_err(binding_error)?.dense_shape(binding,role).map_err(binding_error)?
|
||||
!=(entry.kind,entry.rows,entry.columns){return Err(Error::IdentityMismatch);}
|
||||
let expected=match self.source{
|
||||
WeightSource::Pinned=>binding.mtp_weights().map_err(binding_error)?.dense_shape(binding,role).map_err(binding_error)?,
|
||||
WeightSource::RtDirectory=>rt_dense_shape(role).ok_or(Error::IdentityMismatch)?,
|
||||
};
|
||||
if expected!=(entry.kind,entry.rows,entry.columns){return Err(Error::IdentityMismatch);}
|
||||
Ok((entry.kind,entry.rows,entry.columns,Rc::clone(&entry.buffer)))
|
||||
}
|
||||
pub(in crate::qwen_forward) fn expert_bank(&self,binding:&ModelBinding,context:&Context<'ctx>)
|
||||
@@ -83,10 +140,10 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{
|
||||
&self,binding:&ModelBinding,context:&'ctx Context<'ctx>,
|
||||
prefix:Rc<leleka_cuda_driver::OriginalMtpRetainedPrefix<'ctx>>,
|
||||
head:&OriginalMtpNativeHead<'ctx>,id_vocab:usize,
|
||||
subset:Option<(Rc<DeviceBuffer<'ctx>>,Rc<DeviceBuffer<'ctx>>)>,
|
||||
draft_head:Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
|
||||
)->Result<Rc<leleka_cuda_driver::OriginalMtpRetainedFullWeights<'ctx>>>{
|
||||
self.validate(binding,context)?;
|
||||
if head.columns()!=2560{return Err(Error::InvalidDimension);}
|
||||
if head.columns()!=2560||id_vocab!=head.vocabulary(){return Err(Error::InvalidDimension);}
|
||||
let acquire=|role,expected|->Result<Rc<DeviceBuffer<'ctx>>>{
|
||||
let(kind,rows,columns,owner)=self.matrix(binding,context,role)?;
|
||||
if (kind,rows,columns)!=expected{return Err(Error::InvalidDimension);}
|
||||
@@ -110,8 +167,14 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{
|
||||
acquire(MtpRole::FfnUp,(MtpKind::Bf16,10240,320))?,
|
||||
];
|
||||
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.
|
||||
let(head_weights,head_rows,subset)=match draft_head{
|
||||
Some(draft)=>(draft.rows(),draft.count(),Some(draft.subset_pair())),
|
||||
None=>(head.weights(),head.vocabulary(),None),
|
||||
};
|
||||
let weights=leleka_cuda_driver::OriginalMtpRetainedFullWeights::retain(
|
||||
context,prefix,roles,experts,head.weights(),head.kind(),head.vocabulary(),id_vocab,subset,head.dispatch(),
|
||||
context,prefix,roles,experts,head_weights,head.kind(),head_rows,id_vocab,subset,head.dispatch(),
|
||||
).map_err(driver_error)?;
|
||||
self.validate(binding,context)?;
|
||||
Ok(Rc::new(weights))
|
||||
@@ -121,3 +184,8 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{
|
||||
.and_then(|n|n.checked_add(std::mem::size_of::<Self>())).ok_or(Error::Overflow)
|
||||
}
|
||||
}
|
||||
|
||||
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)}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use super::super::session::original_prompt::{OriginalPromptTxn,OriginalSessionCh
|
||||
use super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer;
|
||||
use super::super::output::OriginalPromptSample;
|
||||
use super::super::session::original_prompt::draft::{OriginalDraftSession,OriginalDraftCheckpoint};
|
||||
use super::super::original_mtp_full_owner::{OriginalMtpFullAssembly,OriginalMtpFullOwner};
|
||||
use super::super::output_native::OriginalNativeOutput;
|
||||
use super::super::original_mtp_full_owner::{OriginalMtpFullAssembly,OriginalMtpFullOwner,OriginalMtpLoadError,OriginalMtpRequest};
|
||||
use super::super::prompt_device_rows::{OriginalDraftKvPending,OriginalPromptDraftOutcome};
|
||||
#[path="original_prompt_embedding.rs"]
|
||||
pub(in crate::qwen_forward) mod embedding;
|
||||
@@ -30,6 +31,7 @@ pub(in crate::qwen_forward) struct OriginalPromptExecutor<'ctx>{
|
||||
// Installed only through `install_full_mtp`: this full owner and the
|
||||
// returned draft session share the literal MtpDrafter physical ring.
|
||||
mtp_full:Option<OriginalMtpFullOwner<'ctx>>,
|
||||
max_t:usize,
|
||||
layers:[Option<ResidentQsaLayer<'ctx>>;48],failed:bool,
|
||||
}
|
||||
enum Carrier<'w,'arena,'loan,'ctx>{
|
||||
@@ -42,13 +44,24 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
pub(in crate::qwen_forward) fn new(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,
|
||||
session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>,
|
||||
embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool,
|
||||
)->Result<Self>{
|
||||
// Pinned-pack source: the MoE cache already holds and charged the roles.
|
||||
let retained=moe.retain_original_mtp_weights(binding,context)?;
|
||||
Self::new_with_mtp_weights(binding,dense,session,context,retained,embedding,capacity,max_t,fused)
|
||||
}
|
||||
/// Same construction over any retained MTP role bank (the pinned pack, or
|
||||
/// the Original-literal RT directory bank of `select_rt_mtp`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn new_with_mtp_weights(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,
|
||||
session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,retained:RetainedOriginalMtpWeights<'ctx>,
|
||||
embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool,
|
||||
)->Result<Self>{
|
||||
if binding.layer_count()!=48||!(1..=8192).contains(&capacity)||!(1..=8).contains(&max_t)
|
||||
||dense.native_prompt_capacity(binding,context)?!=capacity
|
||||
||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);}
|
||||
let mut owner=Self{context,binding:binding.identity(),capacity,fused,prompt:None,gdn:None,qsa:None,
|
||||
transport:None,attention:None,mtp_prefill:None,mtp_scalar:None,mtp_scalar_weights:None,
|
||||
mtp_weights:None,mtp_full:None,layers:std::array::from_fn(|_|None),failed:false};
|
||||
mtp_weights:None,mtp_full:None,max_t,layers:std::array::from_fn(|_|None),failed:false};
|
||||
let result=(||{
|
||||
owner.prompt=Some(context.original_prompt_device(capacity,PleBf16Mode::HighOnly,GrNativeProfile::HighOnly).map_err(driver_error)?);
|
||||
owner.gdn=Some(context.original_gdn_prompt_device(capacity,GrNativeProfile::HighOnly).map_err(driver_error)?);
|
||||
@@ -56,7 +69,6 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
owner.transport=Some(context.original_qsa_resident_transport().map_err(driver_error)?);
|
||||
owner.attention=Some(context.original_qsa_resident_attention(capacity).map_err(driver_error)?);
|
||||
owner.mtp_prefill=Some(context.original_mtp_prefill().map_err(driver_error)?);
|
||||
let retained=moe.retain_original_mtp_weights(binding,context)?;
|
||||
owner.mtp_scalar_weights=Some(retained.scalar_prefill_weights(binding,context,embedding)?);
|
||||
owner.mtp_weights=Some(retained);
|
||||
owner.mtp_scalar=Some(context.original_mtp_scalar_prefill(max_t,capacity).map_err(driver_error)?);
|
||||
@@ -80,23 +92,74 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
/// session before it leaves the assembly, so callers cannot pair a full
|
||||
/// graph with a separately allocated MTP ring.
|
||||
pub(in crate::qwen_forward) fn install_full_mtp(&mut self,binding:&ModelBinding,
|
||||
session:&QwenSession<'ctx>,assembly:OriginalMtpFullAssembly<'ctx>,
|
||||
coupled:bool,max_t:usize)->Result<OriginalDraftSession<'ctx>>{
|
||||
session:&QwenSession<'ctx>,assembly:OriginalMtpFullAssembly<'ctx>)->Result<OriginalDraftSession<'ctx>>{
|
||||
if self.failed||self.context.is_poisoned()||!self.binding.matches(&binding.identity())
|
||||
||!std::ptr::eq(self.context,session.mtp_context()?)||self.mtp_full.is_some(){return Err(Error::IdentityMismatch);}
|
||||
assembly.draft.checkpoint(binding,session)?;
|
||||
assembly.owner.validate(binding,self.context,coupled,max_t)?;
|
||||
assembly.owner.validate(binding,self.context,self.max_t)?;
|
||||
self.mtp_full=Some(assembly.owner);
|
||||
Ok(assembly.draft)
|
||||
}
|
||||
/// The verifier adapter obtains the retained full drafter only after the
|
||||
/// prompt executor has installed its matching canonical draft session.
|
||||
/// The caller still borrows that ring through `with_pending_ring`, which
|
||||
/// keeps SessionState as the sole mutable authority for its snapshot.
|
||||
pub(in crate::qwen_forward) fn full_mtp_drafter(&mut self,binding:&ModelBinding,
|
||||
coupled:bool,max_t:usize)->Result<&mut leleka_cuda_driver::OriginalMtpDrafter<'ctx>>{
|
||||
self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?
|
||||
.drafter_mut(binding,self.context,coupled,max_t)
|
||||
/// Source-level MTP selection, the `--mtp DIR` branch of generate.cpp
|
||||
/// (`mtp.load` ... `mtp.bind`): load the RT directory banks (dense.txt,
|
||||
/// dense.bin, experts.bin, nine-name check), build the prompt executor over
|
||||
/// those exact retained roles, then bind the native head (optional
|
||||
/// draft_vocab subset), the shared scalar/full/ring layout, the coupled
|
||||
/// setup and the actor, and install the matching draft session.
|
||||
///
|
||||
/// Returns both owners; the draft session is the sole mutator of the
|
||||
/// ring, the executor holds the actor. Any failure releases everything
|
||||
/// built so far through the owners' own closure order.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn select_rt_mtp(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,
|
||||
session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>,
|
||||
output:&OriginalNativeOutput<'ctx>,rt_directory:&std::path::Path,capacity:usize,fused:bool,
|
||||
request:&OriginalMtpRequest)->std::result::Result<(Self,OriginalDraftSession<'ctx>),OriginalMtpLoadError>{
|
||||
if !(1..=8).contains(&request.max_t)||request.prompt_capacity!=capacity||binding.layer_count()!=48{
|
||||
return Err(Error::IdentityMismatch.into());}
|
||||
let bank=context.original_mtp_rt_bank(rt_directory,binding.expert_count() as usize)?;
|
||||
let retained=RetainedOriginalMtpWeights::from_rt_bank(binding,context,&bank)?;
|
||||
// The bank object is only a loader receipt: every allocation it holds is
|
||||
// shared with (or retained alongside) `retained`.
|
||||
drop(bank);
|
||||
let mut executor=Self::new_with_mtp_weights(binding,dense,session,context,retained.clone(),embedding,
|
||||
capacity,request.max_t,fused)?;
|
||||
let assembly=OriginalMtpFullOwner::assemble_rt(binding,session,context,&retained,embedding,output,request,rt_directory)?;
|
||||
let draft=executor.install_full_mtp(binding,session,assembly)?;
|
||||
Ok((executor,draft))
|
||||
}
|
||||
/// The loaded `MtpDrafter` of this executor. The caller still borrows the
|
||||
/// ring through the draft session (`with_pending_ring`,
|
||||
/// `with_mtp_transition_ring`), which keeps SessionState as the sole mutable
|
||||
/// authority for its snapshot.
|
||||
pub(in crate::qwen_forward) fn mtp_actor(&mut self,binding:&ModelBinding)
|
||||
->Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>>{
|
||||
let(context,max_t)=(self.context,self.max_t);
|
||||
self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t)
|
||||
}
|
||||
/// generate.cpp `mtp.set_prompt_len(n)`.
|
||||
pub(in crate::qwen_forward) fn set_mtp_prompt_len(&mut self,binding:&ModelBinding,n:i64)->Result<()> {
|
||||
self.mtp_actor(binding)?.set_prompt_len(n);Ok(())
|
||||
}
|
||||
/// generate.cpp `mtp.set_max_drafts(S_mtp - 1)`.
|
||||
pub(in crate::qwen_forward) fn set_mtp_max_drafts(&mut self,binding:&ModelBinding,k:i32)->Result<()> {
|
||||
self.mtp_actor(binding)?.set_max_drafts(k);Ok(())
|
||||
}
|
||||
/// `MtpDrafter::idle()`: drain its own capture stream, nothing else.
|
||||
pub(in crate::qwen_forward) fn mtp_idle(&mut self,binding:&ModelBinding)->Result<()> {
|
||||
self.mtp_actor(binding)?.idle().map_err(driver_error)
|
||||
}
|
||||
/// `MtpDrafter::device()`.
|
||||
pub(in crate::qwen_forward) fn mtp_device(&mut self,binding:&ModelBinding)->Result<i32> {
|
||||
Ok(self.mtp_actor(binding)?.device())
|
||||
}
|
||||
/// generate.cpp `if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume)`
|
||||
/// on the retained ring of the CURRENT, already restored target branch.
|
||||
pub(in crate::qwen_forward) fn mtp_kv_restore(&mut self,binding:&ModelBinding,
|
||||
session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,upto:i64)->Result<()> {
|
||||
let origin=session.target_origin()?;
|
||||
let actor=self.mtp_actor(binding)?;
|
||||
draft.with_mtp_current_ring(binding,session,&origin,|ring,prior|actor.kv_restore(ring,prior,upto).map_err(driver_error))
|
||||
}
|
||||
fn validate(&self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>)->Result<()> {
|
||||
if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);}
|
||||
|
||||
@@ -1,24 +1,79 @@
|
||||
//! Whole `MtpDrafter::init` ownership port for the selected Original path.
|
||||
//! The constructor follows the source acquisition order: immutable MTP roles,
|
||||
//! native output head, one shared scalar/full physical layout, then the sole
|
||||
//! draft-session ring. It performs no launch and does not manufacture a
|
||||
//! verifier receipt; the serving adapter supplies those at a later boundary.
|
||||
//! Whole `MtpDrafter::load` + `bind` ownership port for the selected Original path.
|
||||
//! The constructor follows the source acquisition order: immutable MTP roles
|
||||
//! (RT directory bank or the pinned pack), native output head, optional
|
||||
//! `draft_vocab.bin` head gather, one shared scalar/full physical layout, then
|
||||
//! the sole draft-session ring, and finally the loaded `OriginalMtpActor` that
|
||||
//! links `idle/device/kv_restore/set_*/draft*` to those owners. It performs no
|
||||
//! launch and does not manufacture a verifier receipt; the serving adapter
|
||||
//! supplies those at a later boundary.
|
||||
|
||||
use super::{contract::{Error,Result,Stage},executor::original_prompt::embedding::OriginalPromptEmbedding,
|
||||
moe_weight_cache::{MoeWeightCache,RetainedOriginalMtpWeights},output_native::OriginalNativeOutput,
|
||||
session::{QwenSession,original_prompt::draft::OriginalDraftSession}};
|
||||
use crate::model_binding::qwen4exp_input::{BindingIdentity,ModelBinding};
|
||||
use leleka_cuda_driver::{Context,DeviceBuffer,OriginalMtpDrafter,OriginalMtpRetainedFullWeights,
|
||||
use leleka_cuda_driver::{Context,OriginalMtpActor,OriginalMtpCapture,OriginalMtpDraftHead,OriginalMtpDrafter,
|
||||
OriginalMtpKvStartup,OriginalMtpLoadFailure,OriginalMtpLoadMeter,OriginalMtpLoadPlan,OriginalMtpPlanError,
|
||||
OriginalMtpRetainedPrefix};
|
||||
use std::rc::Rc;
|
||||
use std::{path::Path,rc::Rc};
|
||||
|
||||
/// Model-affine full MTP graphs and their immutable role bank. The canonical
|
||||
/// `OriginalDraftSession` receives the one ring created by the same driver
|
||||
/// shared-layout allocation; it is deliberately kept outside this owner so
|
||||
/// the genuine prompt/verification transaction remains its sole mutator.
|
||||
/// Everything `MtpDrafter::load(rt_dir, g, ss, max_t, err, window)` receives
|
||||
/// besides geometry (which comes from the binding) and the RT directory.
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub(in crate::qwen_forward) struct OriginalMtpRequest{
|
||||
pub(in crate::qwen_forward) max_t:usize,
|
||||
/// Prompt chunk capacity of the scalar-prefill records.
|
||||
pub(in crate::qwen_forward) prompt_capacity:usize,
|
||||
/// `coupled_draft_env()`: a preference, resolved against the real subset
|
||||
/// width into the actual layout by the load plan.
|
||||
pub(in crate::qwen_forward) coupled:bool,
|
||||
/// `load(..., window)`; Original default 32768.
|
||||
pub(in crate::qwen_forward) window:i64,
|
||||
pub(in crate::qwen_forward) kv:OriginalMtpKvStartup,
|
||||
}
|
||||
impl OriginalMtpRequest{
|
||||
/// Original defaults: window 32768 and the INT8 window-ring draft state.
|
||||
pub(in crate::qwen_forward) fn ring_int8(max_t:usize,prompt_capacity:usize,coupled:bool,resident_cells:u64)->Self{
|
||||
Self{max_t,prompt_capacity,coupled,window:leleka_cuda_driver::MTP_ORIGINAL_WINDOW as i64,
|
||||
kv:OriginalMtpKvStartup::ring_int8(resident_cells)}
|
||||
}
|
||||
}
|
||||
|
||||
/// A load refusal: the fixed runtime error plus, when the driver produced one,
|
||||
/// the Original `mtp: ...` text the caller may print as `strata generate: ...`.
|
||||
#[derive(Clone,Debug,Eq,PartialEq)]
|
||||
pub(in crate::qwen_forward) struct OriginalMtpLoadError{pub(in crate::qwen_forward) error:Error,pub(in crate::qwen_forward) message:Option<String>}
|
||||
impl From<Error> for OriginalMtpLoadError{fn from(error:Error)->Self{Self{error,message:None}}}
|
||||
impl From<OriginalMtpLoadFailure> for OriginalMtpLoadError{
|
||||
fn from(failure:OriginalMtpLoadFailure)->Self{
|
||||
let error=match failure.cause(){
|
||||
Some(leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation)=>Error::InputAllocation,
|
||||
Some(leleka_cuda_driver::Error::ContextMismatch)=>Error::IdentityMismatch,
|
||||
Some(leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize
|
||||
|leleka_cuda_driver::Error::ShapeMismatch{..})=>Error::InvalidDimension,
|
||||
Some(leleka_cuda_driver::Error::UnsupportedQwenOperation)=>Error::Unsupported(Stage::Session),
|
||||
Some(_)=>Error::CudaExecution,
|
||||
None=>Error::InputRead,
|
||||
};
|
||||
Self{error,message:Some(failure.message().to_owned())}
|
||||
}
|
||||
}
|
||||
fn plan_error(error:OriginalMtpPlanError)->OriginalMtpLoadError{
|
||||
let kind=match error{
|
||||
OriginalMtpPlanError::ClosedProfile(_)=>Error::Unsupported(Stage::Session),
|
||||
OriginalMtpPlanError::Overflow=>Error::Overflow,
|
||||
_=>Error::InvalidDimension,
|
||||
};
|
||||
OriginalMtpLoadError{error:kind,message:Some(error.message())}
|
||||
}
|
||||
|
||||
/// Model-affine full MTP graphs, their immutable role bank and the loaded
|
||||
/// actor. The canonical `OriginalDraftSession` receives the one ring created
|
||||
/// by the same driver shared-layout allocation; it is deliberately kept outside
|
||||
/// this owner so the genuine prompt/verification transaction remains its sole
|
||||
/// mutator.
|
||||
pub(in crate::qwen_forward) struct OriginalMtpFullOwner<'ctx>{
|
||||
binding:BindingIdentity,context:&'ctx Context<'ctx>,weights:Rc<OriginalMtpRetainedFullWeights<'ctx>>,
|
||||
drafter:Option<OriginalMtpDrafter<'ctx>>,max_t:usize,coupled:bool,failed:bool,
|
||||
binding:BindingIdentity,context:&'ctx Context<'ctx>,
|
||||
actor:Option<OriginalMtpActor<'ctx>>,max_t:usize,failed:bool,
|
||||
}
|
||||
|
||||
/// The only construction output accepted by the runtime. The graph owner and
|
||||
@@ -29,63 +84,133 @@ pub(in crate::qwen_forward) struct OriginalMtpFullAssembly<'ctx>{
|
||||
pub(in crate::qwen_forward) owner:OriginalMtpFullOwner<'ctx>,
|
||||
}
|
||||
|
||||
fn capture_of(binding:&ModelBinding,context:&Context<'_>,request:&OriginalMtpRequest,vocabulary:usize)->OriginalMtpCapture{
|
||||
OriginalMtpCapture{
|
||||
// `cudaGetDevice` at load, `g.n_expert`, `ss.k`, `max_cells` of the primary QSA state.
|
||||
device:context.device_ordinal(),n_expert:u64::from(binding.expert_count()),
|
||||
top_k:u64::from(binding.expert_used_count()),
|
||||
max_cells:u64::from(binding.input_constants().context_length()),
|
||||
max_t:request.max_t as u64,window:request.window,vocabulary:vocabulary as u64,
|
||||
kv:request.kv,coupled_requested:request.coupled,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalMtpFullOwner<'ctx>{
|
||||
/// Builds source-selected KAR/PLE MTP resources. `id_vocab` and an optional
|
||||
/// subset pair are the real model mapping inputs; `retain` rejects a fake
|
||||
/// head, incompatible vocabulary mapping, or any overlapping device range.
|
||||
/// `bind_bytes` for the startup reserve (generate.cpp `mtp.bind_bytes(...)`):
|
||||
/// computed from the real native head and the RT directory, before any
|
||||
/// device bank exists.
|
||||
pub(in crate::qwen_forward) fn bind_reserve(binding:&ModelBinding,context:&Context<'_>,
|
||||
output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:&Path)->Result<u64> {
|
||||
let head=output.mtp_head(binding)?;
|
||||
let capture=capture_of(binding,context,request,head.vocabulary());
|
||||
let row_bytes=leleka_cuda_driver::native_head_row_bytes(head.kind(),head.columns()).map_err(|_|Error::InvalidDimension)?;
|
||||
leleka_cuda_driver::original_mtp_bind_reserve(&capture,
|
||||
leleka_cuda_driver::original_mtp_draft_vocab_bytes(rt_directory),row_bytes as u64)
|
||||
.map_err(|e|plan_error(e).error)
|
||||
}
|
||||
|
||||
/// Literal `MtpDrafter::load` + `bind` from an RT directory. The caller
|
||||
/// has already loaded the bank into `retained` (`Context::original_mtp_rt_bank`
|
||||
/// then `RetainedOriginalMtpWeights::from_rt_bank`); `rt_directory` is read
|
||||
/// again here only for the optional `draft_vocab.bin`, exactly where
|
||||
/// `bind` reads it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn assemble_rt(binding:&ModelBinding,session:&QwenSession<'ctx>,
|
||||
context:&'ctx Context<'ctx>,retained:&RetainedOriginalMtpWeights<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>,
|
||||
output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:&Path)
|
||||
->std::result::Result<OriginalMtpFullAssembly<'ctx>,OriginalMtpLoadError>{
|
||||
Self::assemble_core(binding,session,context,retained,embedding,output,request,Some(rt_directory))
|
||||
}
|
||||
|
||||
/// Same assembly over the digest-pinned pack held by the MoE cache (no RT
|
||||
/// directory, hence no draft-vocab subset).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn assemble(binding:&ModelBinding,session:&QwenSession<'ctx>,
|
||||
context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>,
|
||||
output:&OriginalNativeOutput<'ctx>,max_t:usize,prompt_capacity:usize,coupled:bool,
|
||||
id_vocab:usize,subset:Option<(Rc<DeviceBuffer<'ctx>>,Rc<DeviceBuffer<'ctx>>)>)
|
||||
->Result<OriginalMtpFullAssembly<'ctx>>{
|
||||
if binding.layer_count()!=48||!(1..=8).contains(&max_t)||!(1..=8192).contains(&prompt_capacity)
|
||||
||!std::ptr::eq(context,session.mtp_context()?) {return Err(Error::IdentityMismatch);}
|
||||
output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest)
|
||||
->std::result::Result<OriginalMtpFullAssembly<'ctx>,OriginalMtpLoadError>{
|
||||
// Source keeps all MTP roles immutable for the life of cached graphs.
|
||||
let retained:RetainedOriginalMtpWeights<'ctx>=moe.retain_original_mtp_weights(binding,context)?;
|
||||
let retained=moe.retain_original_mtp_weights(binding,context)?;
|
||||
Self::assemble_core(binding,session,context,&retained,embedding,output,request,None)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn assemble_core(binding:&ModelBinding,session:&QwenSession<'ctx>,
|
||||
context:&'ctx Context<'ctx>,retained:&RetainedOriginalMtpWeights<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>,
|
||||
output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:Option<&Path>)
|
||||
->std::result::Result<OriginalMtpFullAssembly<'ctx>,OriginalMtpLoadError>{
|
||||
let(max_t,prompt_capacity)=(request.max_t,request.prompt_capacity);
|
||||
if binding.layer_count()!=48||!(1..=8).contains(&max_t)||!(1..=8192).contains(&prompt_capacity)
|
||||
||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch.into());}
|
||||
// Fresh ledger window: the bank's own bytes are added by `finish`.
|
||||
let meter=OriginalMtpLoadMeter::start(context);
|
||||
let head=output.mtp_head(binding)?;
|
||||
// geometry/session/device capture -> checked plan (refuses what the
|
||||
// retained owners cannot represent instead of planning around it)
|
||||
let plan=OriginalMtpLoadPlan::new(capture_of(binding,context,request,head.vocabulary()),retained.dense_file_bytes())
|
||||
.map_err(plan_error)?;
|
||||
// ---- bind: optional draft head (needs the main head's weights)
|
||||
let draft_head:Option<OriginalMtpDraftHead<'ctx>>=match rt_directory{
|
||||
Some(directory)=>{
|
||||
let weights=head.weights();
|
||||
context.original_mtp_draft_head(directory,&weights,head.kind(),head.columns(),head.vocabulary())?
|
||||
},
|
||||
None=>None,
|
||||
};
|
||||
let subset=draft_head.as_ref().map(|h|h.count() as u64);
|
||||
let coupled_layout=plan.coupled_layout(subset).map_err(plan_error)?;
|
||||
let scalar=retained.scalar_prefill_weights(binding,context,embedding)?;
|
||||
let prefix=Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?);
|
||||
let head=output.mtp_head(binding)?;
|
||||
let weights=retained.full_forward_weights(binding,context,prefix,&head,id_vocab,subset)?;
|
||||
let weights=retained.full_forward_weights(binding,context,prefix,&head,head.vocabulary(),draft_head.as_ref())?;
|
||||
// This returns exactly one main arena and mapped records shared by
|
||||
// scalar prefill and full forward, plus the matching physical KV ring.
|
||||
let (ring,scalar,full)=context.original_mtp_shared_layout_with_ring(
|
||||
Rc::clone(&weights),max_t,prompt_capacity,coupled).map_err(driver_error)?;
|
||||
let(ring,scalar,full)=context.original_mtp_shared_layout_with_ring(
|
||||
Rc::clone(&weights),max_t,prompt_capacity,coupled_layout).map_err(driver_error)?;
|
||||
let drafter=match OriginalMtpDrafter::new(full,scalar){
|
||||
Ok(value)=>value,
|
||||
Err(primary)=>{let close=ring.close().map_err(driver_error);return match close {Err(cleanup)=>Err(cleanup),Ok(())=>Err(driver_error(primary))};}
|
||||
Err(primary)=>{let close=ring.close().map_err(driver_error);return Err(match close {Err(cleanup)=>cleanup,Ok(())=>driver_error(primary)}.into());}
|
||||
};
|
||||
let evidence=match meter.finish(context,draft_head.as_ref(),retained.loaded_bytes()){
|
||||
Ok(value)=>value,
|
||||
Err(primary)=>{let _=drafter.close();let _=ring.close();return Err(primary.into());}
|
||||
};
|
||||
let actor=match OriginalMtpActor::adopt(context,plan,drafter,&ring,weights,evidence){
|
||||
Ok(value)=>value,
|
||||
Err(primary)=>{let _=ring.close();return Err(primary.into());}
|
||||
};
|
||||
let draft=match OriginalDraftSession::from_original_ring(binding,session,context,ring){
|
||||
Ok(value)=>value,
|
||||
Err(primary)=>{let close=drafter.close().map_err(driver_error);return match close {Err(cleanup)=>Err(cleanup),Ok(())=>Err(primary)};}
|
||||
Err(primary)=>{let _=actor.close();return Err(primary.into());}
|
||||
};
|
||||
Ok(OriginalMtpFullAssembly{draft,owner:Self{binding:binding.identity(),context,weights,
|
||||
drafter:Some(drafter),max_t,coupled,failed:false}})
|
||||
Ok(OriginalMtpFullAssembly{draft,owner:Self{binding:binding.identity(),context,actor:Some(actor),max_t,failed:false}})
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) fn validate(&self,binding:&ModelBinding,context:&Context<'ctx>,
|
||||
coupled:bool,max_t:usize)->Result<()> {
|
||||
if self.failed||self.coupled!=coupled||self.max_t!=max_t
|
||||
||!self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch);}
|
||||
self.weights.validate_context(context).map_err(driver_error)?;
|
||||
self.drafter.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver_error)
|
||||
max_t:usize)->Result<()> {
|
||||
if self.failed||self.max_t!=max_t||!self.binding.matches(&binding.identity())
|
||||
||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch);}
|
||||
self.actor.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver_error)
|
||||
}
|
||||
|
||||
/// The verified-session adapter loans the canonical ring from
|
||||
/// `OriginalDraftSession::with_pending_ring` and invokes this exact owner.
|
||||
/// `OriginalDraftSession::with_pending_ring` and invokes this exact actor.
|
||||
/// No public mutable ring reference escapes this module.
|
||||
pub(in crate::qwen_forward) fn drafter_mut(&mut self,binding:&ModelBinding,
|
||||
context:&Context<'ctx>,coupled:bool,max_t:usize)->Result<&mut OriginalMtpDrafter<'ctx>>{
|
||||
self.validate(binding,context,coupled,max_t)?;
|
||||
self.drafter.as_mut().ok_or(Error::IdentityMismatch)
|
||||
pub(in crate::qwen_forward) fn actor_mut(&mut self,binding:&ModelBinding,
|
||||
context:&Context<'ctx>,max_t:usize)->Result<&mut OriginalMtpActor<'ctx>>{
|
||||
self.validate(binding,context,max_t)?;
|
||||
self.actor.as_mut().ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
/// Read-only view for `device()`, `vram_bytes()`, `first_needed()`, plans.
|
||||
pub(in crate::qwen_forward) fn actor(&self)->Result<&OriginalMtpActor<'ctx>>{
|
||||
self.actor.as_ref().ok_or(Error::IdentityMismatch)
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) fn close(mut self)->Result<()> {self.close_inner()}
|
||||
fn close_inner(&mut self)->Result<()> {
|
||||
self.failed=true;
|
||||
// `weights` is an Rc bank. Dropping it after the drafter has closed
|
||||
// releases the final immutable loan in the same order as the source.
|
||||
self.drafter.take().map_or(Ok(()),|owner|owner.close().map_err(driver_error))
|
||||
// The actor drains its stream and closes the drafter before the retained
|
||||
// weights it holds are released, the same order as the source.
|
||||
self.actor.take().map_or(Ok(()),|owner|owner.close().map_err(driver_error))
|
||||
}
|
||||
}
|
||||
impl Drop for OriginalMtpFullOwner<'_>{fn drop(&mut self){let _=self.close_inner();}}
|
||||
|
||||
@@ -101,23 +101,35 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx>{
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
/// Literal source order: verifier completion -> target commit -> full MTP
|
||||
/// draft. This neither commits target state nor accepts tokens; both are
|
||||
/// already evidenced by `OriginalCommittedMtpReceipt`.
|
||||
/// already evidenced by `OriginalCommittedMtpReceipt`. `max_drafts` and
|
||||
/// the coupled request/history come from the loaded actor (`set_max_drafts`,
|
||||
/// `set_draft_sampling`, `set_draft_history`), as in `MtpDrafter::draft`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::qwen_forward) fn draft_committed_mtp(&mut self,binding:&ModelBinding,
|
||||
session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,
|
||||
receipt:OriginalCommittedMtpReceipt<'ctx>,max_t:usize,coupled:bool,max_drafts:i32,
|
||||
min_p:f32,policy:&OriginalMtpFullPolicy,coupled_history:Option<(SamplerParams,&[i32;4096])>)
|
||||
receipt:OriginalCommittedMtpReceipt<'ctx>,min_p:f32,policy:&OriginalMtpFullPolicy)
|
||||
->Result<OriginalMtpDraftReceipt<'ctx>>{
|
||||
receipt.validate(binding,session,self.context)?;
|
||||
if !min_p.is_finite()||max_drafts<0{return Err(Error::InvalidDimension);}
|
||||
let drafter=self.full_mtp_drafter(binding,coupled,max_t)?;
|
||||
if !min_p.is_finite(){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|{
|
||||
drafter.draft_from_verifier(ring,prior,receipt.window,receipt.selection,
|
||||
receipt.accepted_row,max_drafts,min_p,policy,coupled_history).map_err(driver_error)
|
||||
actor.draft_from_verifier(ring,prior,receipt.window,receipt.selection,
|
||||
receipt.accepted_row,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<()> {
|
||||
self.mtp_actor(binding)?.set_draft_sampling(params);Ok(())
|
||||
}
|
||||
/// `mtp.set_draft_history(consumed, n, next)` before the next draft.
|
||||
pub(in crate::qwen_forward) fn set_mtp_draft_history(&mut self,binding:&ModelBinding,
|
||||
tail:&[i32],next:i32)->Result<()> {
|
||||
self.mtp_actor(binding)?.set_draft_history(tail,next).map_err(driver_error)
|
||||
}
|
||||
}
|
||||
|
||||
fn driver_error(error:leleka_cuda_driver::Error)->Error{
|
||||
|
||||
Reference in New Issue
Block a user