prompt path: optional alias of the token table onto the native embedding's mapped host copy (EXPERIMENTAL, LELEKA_PROMPT_EMBED_ALIAS=1; -324 MiB VRAM, -322 MiB pinned RAM)
OriginalPromptEmbedding::load and OriginalNativeOutput::load(.., true) both stream the GGUF TokenEmbedding tensor (IQ4_XS, 248,320 rows of 1,360 B): the first uploads a 324 MiB copy to VRAM for the prompt path and the MTP prefill, the second keeps the same bytes in a pinned host mapping that the decode gather reads over PCIe. Vanilla keeps one (mapped). With the switch on, OriginalNativeEmbed::table_alias() hands the prompt path a borrowed DeviceBuffer over that mapping (not charged, frees nothing), the native head and embedding open first, and the stack closes the prompt table before the native embedding it aliases. Off by default: the drafter gathers a row per draft step over PCIe beside the expert staging traffic and the effect on decode is unmeasured; the A/B job has an arm for it and slots-id.sh a bitwise-identity arm. Tests: the switch is opt-in; a CUDA test of a borrowed alias over a cuMemHostAlloc block (reads the host bytes, costs no device memory, survives drop; passes on the RTX 3080 laptop); an sm_120-only test of table_alias itself (ignored, for the server). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
981c7aad42
commit
521bfc91d5
@@ -1262,6 +1262,22 @@ impl<'ctx> OriginalNativeEmbed<'ctx> {
|
||||
pub fn is_mapped(&self) -> bool {
|
||||
self.inner.mapped.is_some()
|
||||
}
|
||||
/// A non-owning whole-table [`DeviceBuffer`] over this embedding's table: the pinned host copy as the device sees it (kernels
|
||||
/// read the rows over PCIe, as the decode gather does) or, when pinning failed, the device copy. It frees nothing and is not
|
||||
/// charged to the context, so a second owner of the same token table (the prompt path's) costs no VRAM. The caller must
|
||||
/// stop using it before `close` and must not write through it.
|
||||
pub fn table_alias(&self) -> Result<DeviceBuffer<'ctx>> {
|
||||
self.inner.validate(self.inner.context)?;
|
||||
let bytes = self.bytes();
|
||||
let handle = crate::ffi::BufferHandle::registered_bank_alias(self.inner.address()?, bytes)?;
|
||||
Ok(DeviceBuffer {
|
||||
context: self.inner.context,
|
||||
handle: Some(handle),
|
||||
bytes,
|
||||
_thread: std::marker::PhantomData,
|
||||
borrowed: true,
|
||||
})
|
||||
}
|
||||
pub fn gather_one<'a>(
|
||||
&'a self,
|
||||
stream: &'a mut OriginalGpuStream<'ctx>,
|
||||
@@ -2149,3 +2165,72 @@ pub(crate) fn head_assets_sealed() -> [(&'static str, bool); 3] {
|
||||
("native_head.sampler", sampler_asset().is_some()),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
mod alias_tests {
|
||||
use super::*;
|
||||
|
||||
fn payload(bytes: usize) -> Vec<u8> {
|
||||
(0..bytes).map(|k| (k as u8).wrapping_mul(7).wrapping_add((k >> 8) as u8)).collect()
|
||||
}
|
||||
|
||||
/// Needs any CUDA device: `cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored mapped_table_alias`.
|
||||
/// The alias `table_alias` returns is exactly a borrowed `DeviceBuffer` over a `cuMemHostAlloc` block's device pointer.
|
||||
#[test]
|
||||
#[ignore = "needs a CUDA device"]
|
||||
fn mapped_table_alias_reads_the_host_bytes_and_costs_no_device_memory() {
|
||||
let driver = crate::Driver::load().unwrap();
|
||||
let context = driver.device(0).unwrap().create_context(256 << 20).unwrap();
|
||||
let bytes = 1360 * 1024;
|
||||
let expected = payload(bytes);
|
||||
let guard = context.enter().unwrap();
|
||||
let mapped = MappedAllocation::new(bytes);
|
||||
guard.finish().unwrap();
|
||||
let mut mapped = mapped.unwrap();
|
||||
mapped.write(0, &expected).unwrap();
|
||||
let handle = crate::ffi::BufferHandle::registered_bank_alias(mapped.address(0, bytes).unwrap(), bytes).unwrap();
|
||||
let alias = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true };
|
||||
assert_eq!(context.allocated_bytes(), 0, "an alias is not charged");
|
||||
let mut back = vec![0u8; bytes];
|
||||
alias.copy_to(&mut back).unwrap();
|
||||
assert!(back == expected, "the device reads the host copy through the alias");
|
||||
// dropping or releasing an alias frees nothing: a second alias of the same block still reads it
|
||||
drop(alias);
|
||||
let again = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true };
|
||||
let mut back = vec![0u8; bytes];
|
||||
again.copy_to(&mut back).unwrap();
|
||||
assert!(back == expected);
|
||||
again.release().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
let guard = context.enter().unwrap();
|
||||
let closed = mapped.close();
|
||||
guard.finish().unwrap();
|
||||
closed.unwrap();
|
||||
}
|
||||
|
||||
/// Needs an sm_120 device (the sealed IQ PTX of the head/embedding): run on the 5090 server.
|
||||
#[test]
|
||||
#[ignore = "needs an sm_120 CUDA device (sealed PTX)"]
|
||||
fn native_embed_table_alias_reads_the_same_bytes_and_costs_no_device_memory() {
|
||||
let driver = crate::Driver::load().unwrap();
|
||||
let context = driver.device(0).unwrap().create_context(256 << 20).unwrap();
|
||||
// IQ4_XS (kind 23): 2560 columns are 10 blocks of 136 bytes = 1,360 bytes a row
|
||||
let (kind, n, vocab) = (23u32, 2560usize, 1024usize);
|
||||
let row = native_head_row_bytes(kind, n).unwrap();
|
||||
assert_eq!(row, 1360);
|
||||
let expected = payload(row * vocab);
|
||||
let embed = context.original_native_embed(kind, n, vocab, &expected).unwrap();
|
||||
let charged = context.allocated_bytes();
|
||||
let alias = embed.table_alias().unwrap();
|
||||
assert_eq!(alias.len(), expected.len());
|
||||
assert_eq!(context.allocated_bytes(), charged, "an alias is not charged");
|
||||
let mut back = vec![0u8; expected.len()];
|
||||
alias.copy_to(&mut back).unwrap();
|
||||
assert!(back == expected, "the alias reads the table's bytes");
|
||||
// it is a legal prompt-path table of this layout
|
||||
crate::OriginalMtpEmbedding::native(&alias, kind as i32, row, vocab).unwrap();
|
||||
drop(alias);
|
||||
assert_eq!(context.allocated_bytes(), charged);
|
||||
embed.close().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,22 @@ impl<'ctx> OriginalPromptEmbedding<'ctx>{
|
||||
table.copy_from_owned(source).map_err(driver_error)?;
|
||||
Ok(Self{binding:binding.identity(),context,table:Some(std::rc::Rc::new(table)),kind,row_bytes,vocabulary,failed:false})
|
||||
}
|
||||
/// `LELEKA_PROMPT_EMBED_ALIAS=1` (EXPERIMENTAL, off by default): the prompt path reads the same token table through the mapped
|
||||
/// host copy the native embedding already holds, instead of a second 324 MiB copy in VRAM (and a second 322 MiB read at load).
|
||||
/// Prefill gathers 8192 rows of 1,360 B per chunk (11 MB over PCIe); the MTP drafter's per-round row is one more.
|
||||
pub(in crate::qwen_forward) fn alias_enabled()->bool{
|
||||
alias_requested(std::env::var("LELEKA_PROMPT_EMBED_ALIAS").ok().as_deref())
|
||||
}
|
||||
/// The same table, aliased onto `native` (its mapped host copy or device fallback). Identity is checked against the binding's own
|
||||
/// layout so a different tensor can never be aliased. `native` must outlive every use: close this owner first.
|
||||
pub(in crate::qwen_forward) fn alias_native(binding:&ModelBinding,context:&'ctx Context<'ctx>,native:&leleka_cuda_driver::OriginalNativeEmbed<'ctx>)->Result<Self>{
|
||||
let(kind,row_bytes,vocabulary,bytes)=binding.native_embedding_layout().map_err(|_|Error::InputRead)?;
|
||||
let kind=i32::try_from(kind).map_err(|_|Error::InvalidDimension)?;
|
||||
if i64::from(native.kind())!=i64::from(kind)||native.bytes()!=bytes{return Err(Error::IdentityMismatch);}
|
||||
let table=native.table_alias().map_err(driver_error)?;
|
||||
OriginalMtpEmbedding::native(&table,kind,row_bytes,vocabulary).map_err(driver_error)?;
|
||||
Ok(Self{binding:binding.identity(),context,table:Some(std::rc::Rc::new(table)),kind,row_bytes,vocabulary,failed:false})
|
||||
}
|
||||
pub(in crate::qwen_forward) fn borrow(&self,binding:&ModelBinding,context:&Context<'ctx>)->Result<OriginalMtpEmbedding<'_, 'ctx>>{
|
||||
if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);}
|
||||
if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch);}
|
||||
@@ -45,3 +61,16 @@ impl<'ctx> OriginalPromptEmbedding<'ctx>{
|
||||
Some(table)=>match std::rc::Rc::try_unwrap(table){Ok(table)=>table.release().map_err(driver_error),Err(_)=>Ok(())},None=>Ok(())}}
|
||||
}
|
||||
impl Drop for OriginalPromptEmbedding<'_>{fn drop(&mut self){let _=self.close_inner();}}
|
||||
|
||||
/// The switch's reading: only an explicit yes turns the alias on.
|
||||
fn alias_requested(value:Option<&str>)->bool{matches!(value,Some("1"|"on"|"yes"))}
|
||||
#[cfg(test)]
|
||||
mod tests{
|
||||
use super::alias_requested;
|
||||
#[test]
|
||||
fn the_token_table_alias_is_opt_in(){
|
||||
assert!(!alias_requested(None));
|
||||
for off in ["","0","off","no","true","2"]{assert!(!alias_requested(Some(off)),"{off}");}
|
||||
for on in ["1","on","yes"]{assert!(alias_requested(Some(on)),"{on}");}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,8 +404,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
let layout = prefill_layout_options(config.capacity, max_cells, &blobs);
|
||||
|
||||
vram_note(context, "open begin");
|
||||
let embedding = staged!("embedding table", context, OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?);
|
||||
// The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy
|
||||
// of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor).
|
||||
let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?);
|
||||
let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() {
|
||||
OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))?
|
||||
} else {
|
||||
OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?
|
||||
});
|
||||
let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() {
|
||||
Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?),
|
||||
None => None,
|
||||
@@ -888,8 +894,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
drop((session, pool, kar));
|
||||
note(moe.close());
|
||||
note(dense.close());
|
||||
note(output.close());
|
||||
// the prompt path's token table may alias the native embedding's mapped copy: it goes first
|
||||
note(embedding.close());
|
||||
note(output.close());
|
||||
first.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user