STRA-338 size2 cd3: mtp input workspace, original mtp ffi/mapped owners and logical prefix functions split into phases
This commit is contained in:
@@ -19,6 +19,31 @@ impl MtpInputCompletion<'_, '_> {
|
||||
Ok(self.values)
|
||||
}
|
||||
}
|
||||
/// The registered function of each of the three Qwen operations, in `OPERATIONS` order.
|
||||
fn qwen_functions(context: &Context<'_>) -> Result<[ffi::FunctionHandle; 3]> {
|
||||
let mut qwen = [None; 3];
|
||||
for (i, operation) in OPERATIONS.into_iter().enumerate() {
|
||||
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function);
|
||||
}
|
||||
Ok([
|
||||
qwen[0].ok_or(Error::ContextPoisoned)?,
|
||||
qwen[1].ok_or(Error::ContextPoisoned)?,
|
||||
qwen[2].ok_or(Error::ContextPoisoned)?,
|
||||
])
|
||||
}
|
||||
/// Little-endian host staging of the embedding row and the four hidden streams.
|
||||
fn stage_inputs(embedding: &[f32], streams: &[f32]) -> Result<(Vec<u8>, Vec<u8>)> {
|
||||
let mut e = staging(10240)?;
|
||||
let mut r = staging(40960)?;
|
||||
for (v, out) in embedding.iter().zip(e.as_chunks_mut::<4>().0) {
|
||||
out.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
for (v, out) in streams.iter().zip(r.as_chunks_mut::<4>().0) {
|
||||
out.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
Ok((e, r))
|
||||
}
|
||||
impl Context<'_> {
|
||||
pub fn mtp_input_workspace(&self) -> Result<MtpInputWorkspace<'_>> {
|
||||
MtpInputWorkspace::new(self)
|
||||
@@ -26,6 +51,21 @@ impl Context<'_> {
|
||||
}
|
||||
impl<'ctx> MtpInputWorkspace<'ctx> {
|
||||
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
|
||||
Self::admit(context)?;
|
||||
let mut owner = Self {
|
||||
context,
|
||||
buffers: std::array::from_fn(|_| None),
|
||||
module: None,
|
||||
kernels: None,
|
||||
generation: 0,
|
||||
failed: false,
|
||||
};
|
||||
if let Err(error) = owner.bring_up() {
|
||||
return combine(Err(error), owner.close());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
fn admit(context: &Context<'_>) -> Result<()> {
|
||||
if context.is_poisoned() || context.handle.is_none() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
@@ -38,54 +78,33 @@ impl<'ctx> MtpInputWorkspace<'ctx> {
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
let mut owner = Self {
|
||||
context,
|
||||
buffers: std::array::from_fn(|_| None),
|
||||
module: None,
|
||||
kernels: None,
|
||||
generation: 0,
|
||||
failed: false,
|
||||
};
|
||||
let result = (|| {
|
||||
for (i, size) in SIZES.into_iter().enumerate() {
|
||||
owner.buffers[i] = Some(context.allocate(size)?);
|
||||
}
|
||||
let guard = context.enter()?;
|
||||
let load = (|| {
|
||||
let (quant, project) = context.common_kernels(ProjectionKind::Dense(DenseFormat::Q8_0))?;
|
||||
let mut qwen = [None; 3];
|
||||
for (i, operation) in OPERATIONS.into_iter().enumerate() {
|
||||
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function);
|
||||
}
|
||||
let module = context.driver.api.load_mmq_resident()?;
|
||||
owner.module = Some(module);
|
||||
let finite = [
|
||||
context.driver.api.mmq_resident_function(module, 0)?,
|
||||
context.driver.api.mmq_resident_function(module, 1)?,
|
||||
];
|
||||
Ok(Kernels {
|
||||
qwen: [
|
||||
qwen[0].ok_or(Error::ContextPoisoned)?,
|
||||
qwen[1].ok_or(Error::ContextPoisoned)?,
|
||||
qwen[2].ok_or(Error::ContextPoisoned)?,
|
||||
],
|
||||
quant,
|
||||
project,
|
||||
guard: finite,
|
||||
})
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
owner.kernels = Some(combine(load, pop)?);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
return combine(Err(error), owner.close());
|
||||
Ok(())
|
||||
}
|
||||
fn bring_up(&mut self) -> Result<()> {
|
||||
let context = self.context;
|
||||
for (i, size) in SIZES.into_iter().enumerate() {
|
||||
self.buffers[i] = Some(context.allocate(size)?);
|
||||
}
|
||||
Ok(owner)
|
||||
let guard = context.enter()?;
|
||||
let load = self.load_kernels();
|
||||
let pop = guard.finish();
|
||||
if pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
self.kernels = Some(combine(load, pop)?);
|
||||
Ok(())
|
||||
}
|
||||
fn load_kernels(&mut self) -> Result<Kernels> {
|
||||
let context = self.context;
|
||||
let (quant, project) = context.common_kernels(ProjectionKind::Dense(DenseFormat::Q8_0))?;
|
||||
let qwen = qwen_functions(context)?;
|
||||
let module = context.driver.api.load_mmq_resident()?;
|
||||
self.module = Some(module);
|
||||
let finite = [
|
||||
context.driver.api.mmq_resident_function(module, 0)?,
|
||||
context.driver.api.mmq_resident_function(module, 1)?,
|
||||
];
|
||||
Ok(Kernels { qwen, quant, project, guard: finite })
|
||||
}
|
||||
pub(super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
|
||||
self.buffers[index].as_ref().ok_or(Error::ContextPoisoned)
|
||||
@@ -96,28 +115,33 @@ impl<'ctx> MtpInputWorkspace<'ctx> {
|
||||
}
|
||||
let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let mut handles = [first; 9];
|
||||
for (i, size) in SIZES.into_iter().enumerate() {
|
||||
let b = self.buffer(i)?;
|
||||
if !std::ptr::eq(self.context, b.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if b.bytes != size {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let h = b.handle.ok_or(Error::ContextPoisoned)?;
|
||||
h.validate_projection_extent(size, 4)?;
|
||||
for (j, prior) in handles.iter().take(i).enumerate() {
|
||||
if h.overlaps(size, *prior, SIZES[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
handles[i] = h;
|
||||
for i in 0..SIZES.len() {
|
||||
handles[i] = self.checked_handle(i, &handles[..i])?;
|
||||
}
|
||||
if self.context.allocated_bytes() > self.context.budget {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(handles)
|
||||
}
|
||||
/// The validated handle of owner `i`, disjoint from the handles of the owners before it.
|
||||
fn checked_handle(&self, i: usize, prior: &[ffi::BufferHandle]) -> Result<ffi::BufferHandle> {
|
||||
let size = SIZES[i];
|
||||
let b = self.buffer(i)?;
|
||||
if !std::ptr::eq(self.context, b.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if b.bytes != size {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let h = b.handle.ok_or(Error::ContextPoisoned)?;
|
||||
h.validate_projection_extent(size, 4)?;
|
||||
for (j, earlier) in prior.iter().enumerate() {
|
||||
if h.overlaps(size, *earlier, SIZES[j]) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
pub fn is_failed(&self) -> bool {
|
||||
self.failed || self.context.is_poisoned() || self.context.handle.is_none()
|
||||
}
|
||||
@@ -134,14 +158,7 @@ impl<'ctx> MtpInputWorkspace<'ctx> {
|
||||
return Err(Error::InvalidDriverValue("MTP input finite source"));
|
||||
}
|
||||
self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
|
||||
let mut e = staging(10240)?;
|
||||
let mut r = staging(40960)?;
|
||||
for (v, out) in embedding.iter().zip(e.as_chunks_mut::<4>().0) {
|
||||
out.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
for (v, out) in streams.iter().zip(r.as_chunks_mut::<4>().0) {
|
||||
out.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
let (e, r) = stage_inputs(embedding, streams)?;
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?;
|
||||
let mut weights = Vec::new();
|
||||
|
||||
@@ -57,24 +57,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
self.weight(weight, 10240)?;
|
||||
let workspace = &*self.workspace;
|
||||
let buffers = [workspace.buffer(0)?, weight, workspace.buffer(2)?];
|
||||
let operation = OPERATIONS[0];
|
||||
let (_, layout, handles) = admission(
|
||||
workspace.context,
|
||||
&buffers,
|
||||
Admission {
|
||||
operation,
|
||||
layout: Ok(operation.layout()),
|
||||
asset: qwen_ffi::asset(operation),
|
||||
epsilon: 0.0,
|
||||
in_place: false,
|
||||
},
|
||||
)?;
|
||||
let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[0];
|
||||
self.commands.push(Command::Qwen(
|
||||
f,
|
||||
operation,
|
||||
Box::new(Arguments::with_layout(operation, layout, handles, 0.0)),
|
||||
));
|
||||
queue_qwen(workspace, &mut self.commands, 0, buffers)?;
|
||||
self.finite(self.workspace.handles()?[2], 2560, 0)?;
|
||||
self.weights.push(weight);
|
||||
self.phase = 1;
|
||||
@@ -90,11 +73,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
quant_index: usize,
|
||||
) -> Result<()> {
|
||||
let w = self.weight(weight, 6_963_200)?;
|
||||
let shape = projection_shape(ProjectionSpec {
|
||||
kind: ProjectionKind::Dense(DenseFormat::Q8_0),
|
||||
rows: 2560,
|
||||
columns: 2560,
|
||||
})?;
|
||||
let shape = square_shape()?;
|
||||
projection_ranges(ProjectionKind::Dense(DenseFormat::Q8_0), &shape, [w, source, output])?;
|
||||
let handles = self.workspace.handles()?;
|
||||
let status = self.status(quant_index)?;
|
||||
@@ -128,25 +107,8 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
self.ready(2)?;
|
||||
self.weight(weight, 40960)?;
|
||||
let workspace = &*self.workspace;
|
||||
let operation = OPERATIONS[1];
|
||||
let buffers = [workspace.buffer(1)?, weight, workspace.buffer(4)?];
|
||||
let (_, layout, handles) = admission(
|
||||
workspace.context,
|
||||
&buffers,
|
||||
Admission {
|
||||
operation,
|
||||
layout: Ok(operation.layout()),
|
||||
asset: qwen_ffi::asset(operation),
|
||||
epsilon: 0.0,
|
||||
in_place: false,
|
||||
},
|
||||
)?;
|
||||
let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[1];
|
||||
self.commands.push(Command::Qwen(
|
||||
f,
|
||||
operation,
|
||||
Box::new(Arguments::with_layout(operation, layout, handles, 0.0)),
|
||||
));
|
||||
queue_qwen(workspace, &mut self.commands, 1, buffers)?;
|
||||
self.finite(self.workspace.handles()?[4], 10240, 3)?;
|
||||
self.weights.push(weight);
|
||||
self.phase = 3;
|
||||
@@ -182,32 +144,17 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
/// The broadcast stage: admit and queue the last Qwen kernel and its finite check.
|
||||
fn queue_broadcast(&mut self) -> Result<()> {
|
||||
self.ready(7)?;
|
||||
let workspace = &*self.workspace;
|
||||
let buffers = [workspace.buffer(5)?, workspace.buffer(3)?, workspace.buffer(6)?];
|
||||
queue_qwen(workspace, &mut self.commands, 2, buffers)?;
|
||||
self.finite(self.workspace.handles()?[6], 10240, 12)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn finish(mut self) -> Result<MtpInputCompletion<'lease, 'ctx>> {
|
||||
let admission = (|| {
|
||||
self.ready(7)?;
|
||||
let workspace = &*self.workspace;
|
||||
let operation = OPERATIONS[2];
|
||||
let buffers = [workspace.buffer(5)?, workspace.buffer(3)?, workspace.buffer(6)?];
|
||||
let (_, layout, handles) = admission(
|
||||
workspace.context,
|
||||
&buffers,
|
||||
Admission {
|
||||
operation,
|
||||
layout: Ok(operation.layout()),
|
||||
asset: qwen_ffi::asset(operation),
|
||||
epsilon: 0.0,
|
||||
in_place: false,
|
||||
},
|
||||
)?;
|
||||
let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[2];
|
||||
self.commands.push(Command::Qwen(
|
||||
f,
|
||||
operation,
|
||||
Box::new(Arguments::with_layout(operation, layout, handles, 0.0)),
|
||||
));
|
||||
self.finite(self.workspace.handles()?[6], 10240, 12)?;
|
||||
Ok(())
|
||||
})();
|
||||
let admission = self.queue_broadcast();
|
||||
if let Err(error) = admission {
|
||||
self.refusal.get_or_insert(error);
|
||||
}
|
||||
@@ -229,62 +176,97 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
pub(super) fn drain(mut self, final_output: bool) -> Result<Drained<'lease, 'ctx>> {
|
||||
let handles = self.workspace.handles()?;
|
||||
let generation = self.workspace.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
|
||||
let mut statuses = staging(52)?;
|
||||
let write_final = final_output && self.checks == 13;
|
||||
let mut final_staging = staging(if write_final { 40960 } else { 0 })?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(if write_final { 10240 } else { 0 }).map_err(|_| Error::HostAllocation)?;
|
||||
if write_final {
|
||||
values.resize(10240, 0.0);
|
||||
}
|
||||
let mut host = DrainStaging::new(final_output && self.checks == 13)?;
|
||||
if !self.commands.is_empty() {
|
||||
let f = self.workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.guard[0];
|
||||
let mut reset = ffi::MmqResidentArguments::zero(handles[8], 13);
|
||||
let context = self.workspace.context;
|
||||
let guard = context.enter().inspect_err(|_| {
|
||||
self.workspace.failed = true;
|
||||
context.poisoned.set(true);
|
||||
})?;
|
||||
let mut operation = context.driver.api.copy_from(handles[0], &self.embedding);
|
||||
if operation.is_ok() && self.phase >= 3 {
|
||||
operation = context.driver.api.copy_from(handles[1], &self.streams);
|
||||
}
|
||||
if operation.is_ok() {
|
||||
operation = context.driver.api.launch_mmq_resident(f, 13, &mut reset);
|
||||
}
|
||||
for command in &mut self.commands {
|
||||
if operation.is_err() {
|
||||
break;
|
||||
}
|
||||
operation = command.launch(context);
|
||||
}
|
||||
if operation.is_ok() {
|
||||
operation = context.driver.api.copy_to(handles[8], &mut statuses);
|
||||
}
|
||||
if operation.is_ok() && write_final {
|
||||
operation = context.driver.api.copy_to(handles[6], &mut final_staging);
|
||||
}
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.workspace.failed = true;
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((
|
||||
reset,
|
||||
self.commands,
|
||||
self.embedding,
|
||||
self.streams,
|
||||
statuses,
|
||||
final_staging,
|
||||
values,
|
||||
self.weights,
|
||||
));
|
||||
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain MTP input drain"));
|
||||
}
|
||||
combine(combine(operation, sync), pop)?;
|
||||
self.run_program(handles, &mut host)?;
|
||||
}
|
||||
let decoded = self.decode_witness(&host.statuses)?;
|
||||
let refusal = first_refusal(&decoded, self.checks);
|
||||
for (out, bytes) in host.values.iter_mut().zip(host.final_staging.as_chunks::<4>().0) {
|
||||
*out = f32::from_le_bytes(*bytes);
|
||||
}
|
||||
self.workspace.generation = generation;
|
||||
Ok(Drained {
|
||||
workspace: self.workspace,
|
||||
weights: self.weights,
|
||||
statuses: decoded,
|
||||
refusal,
|
||||
deferred: self.refusal,
|
||||
values: host.values.into_boxed_slice(),
|
||||
generation,
|
||||
})
|
||||
}
|
||||
/// Upload the inputs, run the whole program on the context, then read the status words (and the final
|
||||
/// streams) back after one completion fence.
|
||||
fn run_program(&mut self, handles: [ffi::BufferHandle; 9], host: &mut DrainStaging) -> Result<()> {
|
||||
let f = self.workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.guard[0];
|
||||
let mut reset = ffi::MmqResidentArguments::zero(handles[8], 13);
|
||||
let context = self.workspace.context;
|
||||
let guard = context.enter().inspect_err(|_| {
|
||||
self.workspace.failed = true;
|
||||
context.poisoned.set(true);
|
||||
})?;
|
||||
let mut operation = self.launch_program(context, handles, (f, &mut reset));
|
||||
if operation.is_ok() {
|
||||
operation = context.driver.api.copy_to(handles[8], &mut host.statuses);
|
||||
}
|
||||
if operation.is_ok() && host.write_final {
|
||||
operation = context.driver.api.copy_to(handles[6], &mut host.final_staging);
|
||||
}
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
self.settle_drain(host, reset, [operation, sync, pop])
|
||||
}
|
||||
fn launch_program(
|
||||
&mut self,
|
||||
context: &Context<'_>,
|
||||
handles: [ffi::BufferHandle; 9],
|
||||
(f, reset): (ffi::FunctionHandle, &mut ffi::MmqResidentArguments),
|
||||
) -> Result<()> {
|
||||
let mut operation = context.driver.api.copy_from(handles[0], &self.embedding);
|
||||
if operation.is_ok() && self.phase >= 3 {
|
||||
operation = context.driver.api.copy_from(handles[1], &self.streams);
|
||||
}
|
||||
if operation.is_ok() {
|
||||
operation = context.driver.api.launch_mmq_resident(f, 13, reset);
|
||||
}
|
||||
for command in &mut self.commands {
|
||||
if operation.is_err() {
|
||||
break;
|
||||
}
|
||||
operation = command.launch(context);
|
||||
}
|
||||
operation
|
||||
}
|
||||
fn settle_drain(
|
||||
&mut self,
|
||||
host: &mut DrainStaging,
|
||||
reset: ffi::MmqResidentArguments,
|
||||
[operation, sync, pop]: [Result<()>; 3],
|
||||
) -> Result<()> {
|
||||
let context = self.workspace.context;
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.workspace.failed = true;
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((
|
||||
reset,
|
||||
std::mem::take(&mut self.commands),
|
||||
std::mem::take(&mut self.embedding),
|
||||
std::mem::take(&mut self.streams),
|
||||
std::mem::take(&mut host.statuses),
|
||||
std::mem::take(&mut host.final_staging),
|
||||
std::mem::take(&mut host.values),
|
||||
std::mem::take(&mut self.weights),
|
||||
));
|
||||
return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain MTP input drain"));
|
||||
}
|
||||
combine(combine(operation, sync), pop)
|
||||
}
|
||||
/// The 13 status words; any bit outside the stage's allowed set, or any word past the checked prefix, is a
|
||||
/// corrupt witness that poisons the context.
|
||||
fn decode_witness(&mut self, statuses: &[u8]) -> Result<[u32; 13]> {
|
||||
let mut decoded = [0u32; 13];
|
||||
for (i, (out, bytes)) in decoded.iter_mut().zip(statuses.as_chunks::<4>().0).enumerate() {
|
||||
*out = u32::from_le_bytes(*bytes);
|
||||
@@ -295,24 +277,57 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
|
||||
return Err(Error::InvalidDriverValue("MTP input numeric witness"));
|
||||
}
|
||||
}
|
||||
let refusal = decoded.iter().take(self.checks).enumerate().find(|(_, s)| **s != 0).map(|(i, _)| {
|
||||
(
|
||||
if QUANT.contains(&i) { MtpInputRefusal::InvalidQ8Activation } else { MtpInputRefusal::NonFinite },
|
||||
STAGES[i],
|
||||
)
|
||||
});
|
||||
for (out, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) {
|
||||
*out = f32::from_le_bytes(*bytes);
|
||||
}
|
||||
self.workspace.generation = generation;
|
||||
Ok(Drained {
|
||||
workspace: self.workspace,
|
||||
weights: self.weights,
|
||||
statuses: decoded,
|
||||
refusal,
|
||||
deferred: self.refusal,
|
||||
values: values.into_boxed_slice(),
|
||||
generation,
|
||||
})
|
||||
Ok(decoded)
|
||||
}
|
||||
}
|
||||
/// Owned host staging of one drain: the status words and, for the final stage, the four output streams.
|
||||
struct DrainStaging {
|
||||
statuses: Vec<u8>,
|
||||
final_staging: Vec<u8>,
|
||||
values: Vec<f32>,
|
||||
write_final: bool,
|
||||
}
|
||||
impl DrainStaging {
|
||||
fn new(write_final: bool) -> Result<Self> {
|
||||
let statuses = staging(52)?;
|
||||
let final_staging = staging(if write_final { 40960 } else { 0 })?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(if write_final { 10240 } else { 0 }).map_err(|_| Error::HostAllocation)?;
|
||||
if write_final {
|
||||
values.resize(10240, 0.0);
|
||||
}
|
||||
Ok(Self { statuses, final_staging, values, write_final })
|
||||
}
|
||||
}
|
||||
/// The earliest set status word within the checked prefix, as a refusal with its stage name.
|
||||
fn first_refusal(decoded: &[u32; 13], checks: usize) -> Option<(MtpInputRefusal, &'static str)> {
|
||||
decoded.iter().take(checks).enumerate().find(|(_, s)| **s != 0).map(|(i, _)| {
|
||||
(if QUANT.contains(&i) { MtpInputRefusal::InvalidQ8Activation } else { MtpInputRefusal::NonFinite }, STAGES[i])
|
||||
})
|
||||
}
|
||||
/// Admit and queue the fixed Qwen kernel `which` over three buffers (input, weight or second input, output).
|
||||
fn queue_qwen(
|
||||
workspace: &MtpInputWorkspace<'_>,
|
||||
commands: &mut Vec<Command>,
|
||||
which: usize,
|
||||
buffers: [&DeviceBuffer<'_>; 3],
|
||||
) -> Result<()> {
|
||||
let operation = OPERATIONS[which];
|
||||
let (_, layout, handles) = admission(
|
||||
workspace.context,
|
||||
&buffers,
|
||||
Admission {
|
||||
operation,
|
||||
layout: Ok(operation.layout()),
|
||||
asset: qwen_ffi::asset(operation),
|
||||
epsilon: 0.0,
|
||||
in_place: false,
|
||||
},
|
||||
)?;
|
||||
let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[which];
|
||||
commands.push(Command::Qwen(f, operation, Box::new(Arguments::with_layout(operation, layout, handles, 0.0))));
|
||||
Ok(())
|
||||
}
|
||||
fn square_shape() -> Result<crate::ProjectionShape> {
|
||||
projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q8_0), rows: 2560, columns: 2560 })
|
||||
}
|
||||
|
||||
@@ -10,41 +10,47 @@ impl MtpInputWorkspace<'_> {
|
||||
let mut result = Ok(());
|
||||
for buffer in &mut self.buffers {
|
||||
if let Some(buffer) = buffer.take() {
|
||||
let release = if self.context.is_poisoned() {
|
||||
std::mem::forget(buffer);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
buffer.release()
|
||||
};
|
||||
if release.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, release);
|
||||
result = combine(result, retire_buffer(self.context, buffer));
|
||||
}
|
||||
}
|
||||
if let Some(module) = self.module.take() {
|
||||
let release = if self.context.is_poisoned() {
|
||||
self.context.retain_driver();
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
match self.context.enter() {
|
||||
Ok(guard) => {
|
||||
let unload = self.context.driver.api.unload(module);
|
||||
let pop = guard.finish();
|
||||
combine(unload, pop)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
};
|
||||
if release.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
self.context.retain_driver();
|
||||
}
|
||||
result = combine(result, release);
|
||||
result = combine(result, retire_module(self.context, module));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
fn retire_buffer(context: &Context<'_>, buffer: DeviceBuffer<'_>) -> Result<()> {
|
||||
let release = if context.is_poisoned() {
|
||||
std::mem::forget(buffer);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
buffer.release()
|
||||
};
|
||||
if release.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
release
|
||||
}
|
||||
fn retire_module(context: &Context<'_>, module: ffi::ModuleHandle) -> Result<()> {
|
||||
let release = if context.is_poisoned() {
|
||||
context.retain_driver();
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
match context.enter() {
|
||||
Ok(guard) => {
|
||||
let unload = context.driver.api.unload(module);
|
||||
let pop = guard.finish();
|
||||
combine(unload, pop)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
};
|
||||
if release.is_err() {
|
||||
context.poisoned.set(true);
|
||||
context.retain_driver();
|
||||
}
|
||||
release
|
||||
}
|
||||
impl Drop for MtpInputWorkspace<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.close_inner();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Changed input transport only. Original scalar calls finish FIRST.
|
||||
//! Synthetic weights do not certify a binding, frame, KV or model publication.
|
||||
use super::*;
|
||||
use crate::Driver;
|
||||
use crate::{Device, Driver};
|
||||
const ENABLE: &str = "LELEKA_STRA172_RUN_MTP_INPUT_PREFIX";
|
||||
#[derive(Default, Debug)]
|
||||
struct Report {
|
||||
@@ -25,6 +25,21 @@ fn original_first_mtp_input_prefix_products_status_order_and_cleanup() {
|
||||
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, foreign, budget) = open_contexts(&device);
|
||||
let operation = (|| {
|
||||
let mut report = run(&context, &foreign)?;
|
||||
refuse(budget.mtp_input_workspace(), Error::BudgetExceeded, &mut report)?;
|
||||
Ok(report)
|
||||
})();
|
||||
let allocated = [context.allocated_bytes(), foreign.allocated_bytes(), budget.allocated_bytes()];
|
||||
let poisoned = context.is_poisoned() || foreign.is_poisoned() || budget.is_poisoned();
|
||||
let cleanup = combine(combine(context.close(), foreign.close()), budget.close());
|
||||
let report = combine(operation, cleanup).expect("MTP input fixture and all Context cleanup");
|
||||
check_report(&report, allocated, poisoned);
|
||||
eprintln!("MTP-INPUT-PREFIX {report:?}; device_bytes={TOTAL}; statuses=13; cleanup=0; component_only=true");
|
||||
}
|
||||
/// The working, the foreign and the one-byte-short budget contexts; an earlier one is closed if a later fails.
|
||||
fn open_contexts<'d>(device: &Device<'d>) -> (Context<'d>, Context<'d>, Context<'d>) {
|
||||
let context = device.create_context(256 * 1024 * 1024).expect("Context");
|
||||
let foreign = match device.create_context(1024 * 1024) {
|
||||
Ok(value) => value,
|
||||
@@ -40,20 +55,10 @@ fn original_first_mtp_input_prefix_products_status_order_and_cleanup() {
|
||||
panic!("budget {primary:?}; cleanup={cleanup:?}");
|
||||
}
|
||||
};
|
||||
let operation = (|| {
|
||||
let mut report = run(&context, &foreign)?;
|
||||
refuse(budget.mtp_input_workspace(), Error::BudgetExceeded, &mut report)?;
|
||||
Ok(report)
|
||||
})();
|
||||
let allocated = context.allocated_bytes();
|
||||
let other = foreign.allocated_bytes();
|
||||
let budget_bytes = budget.allocated_bytes();
|
||||
let poisoned = context.is_poisoned() || foreign.is_poisoned() || budget.is_poisoned();
|
||||
let cleanup = combine(combine(context.close(), foreign.close()), budget.close());
|
||||
let report = combine(operation, cleanup).expect("MTP input fixture and all Context cleanup");
|
||||
assert_eq!(allocated, 0);
|
||||
assert_eq!(other, 0);
|
||||
assert_eq!(budget_bytes, 0);
|
||||
(context, foreign, budget)
|
||||
}
|
||||
fn check_report(report: &Report, allocated: [usize; 3], poisoned: bool) {
|
||||
assert_eq!(allocated, [0; 3]);
|
||||
assert!(!poisoned);
|
||||
assert_eq!(report.products, 80);
|
||||
assert_eq!(report.words, 358400);
|
||||
@@ -61,9 +66,7 @@ fn original_first_mtp_input_prefix_products_status_order_and_cleanup() {
|
||||
assert_eq!(report.witness_errors, 0);
|
||||
assert_eq!(report.numeric, 6);
|
||||
assert_eq!(report.guards, report.refusals);
|
||||
eprintln!("MTP-INPUT-PREFIX {report:?}; device_bytes={TOTAL}; statuses=13; cleanup=0; component_only=true");
|
||||
}
|
||||
|
||||
#[path = "mtp_input_workspace_gpu/bytes_fn.rs"]
|
||||
mod bytes_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -63,7 +63,7 @@ pub(super) fn refuse<T>(result: Result<T>, expected: Error, report: &mut Report)
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
// Independent original allocation/upload/projection/full readback sequence.
|
||||
/// Independent original allocation/upload/projection/full readback sequence.
|
||||
// H0..3 each use a real whole 10240B activation owner, not candidate subspans.
|
||||
pub(super) fn original(
|
||||
context: &Context<'_>,
|
||||
@@ -72,71 +72,119 @@ pub(super) fn original(
|
||||
weights: [&DeviceBuffer<'_>; 7],
|
||||
) -> Result<Observed> {
|
||||
let mut owned = Vec::new();
|
||||
let operation = (|| {
|
||||
owned.push(upload(context, &bytes(embedding))?);
|
||||
owned.push(upload(context, &bytes(streams))?);
|
||||
for size in [10240, 10240, 40960, 10240, 10240, 40960, 40960] {
|
||||
owned.push(context.allocate(size)?);
|
||||
}
|
||||
let mut products = Vec::new();
|
||||
let [e, r, en, e2, hn, h_input, h_output, h2, out] = owned.as_mut_slice() else {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
};
|
||||
context.mtp_embedding_norm_f32(e, weights[0], en)?;
|
||||
let value = read(en)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[0] }));
|
||||
}
|
||||
products.push(value);
|
||||
let spec = ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q8_0), rows: 2560, columns: 2560 };
|
||||
match context.project_q8_1(weights[1], en, e2, spec) {
|
||||
Err(Error::InvalidQ8Activation) => {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[1] }));
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
let value = read(e2)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[2] }));
|
||||
}
|
||||
products.push(value);
|
||||
context.mtp_hidden_norm_f32(r, weights[2], hn)?;
|
||||
let hidden = read(hn)?;
|
||||
if !full_finite(&hidden) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[3] }));
|
||||
}
|
||||
products.push(hidden.clone());
|
||||
let mut joined = Vec::new();
|
||||
for (i, weight) in weights[3..].iter().enumerate() {
|
||||
h_input.copy_from(&hidden[i * 10240..(i + 1) * 10240])?;
|
||||
match context.project_q8_1(weight, h_input, h_output, spec) {
|
||||
Err(Error::InvalidQ8Activation) => {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[4 + 2 * i] }));
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
let value = read(h_output)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[5 + 2 * i] }));
|
||||
}
|
||||
joined.extend_from_slice(&value);
|
||||
products.push(value);
|
||||
}
|
||||
h2.copy_from(&joined)?;
|
||||
context.mtp_broadcast_f32(h2, e2, out)?;
|
||||
let value = read(out)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[12] }));
|
||||
}
|
||||
products.push(value);
|
||||
Ok(Ok(products))
|
||||
})();
|
||||
let operation = original_products(context, (embedding, streams), weights, &mut owned);
|
||||
let mut cleanup = Ok(());
|
||||
for buffer in owned {
|
||||
cleanup = combine(cleanup, buffer.release());
|
||||
}
|
||||
combine(operation, cleanup)
|
||||
}
|
||||
type Step<T> = Result<std::result::Result<T, Numeric>>;
|
||||
macro_rules! numeric {
|
||||
($step:expr) => {
|
||||
match $step? {
|
||||
Ok(value) => value,
|
||||
Err(stop) => return Ok(Err(stop)),
|
||||
}
|
||||
};
|
||||
}
|
||||
const SPEC: ProjectionSpec =
|
||||
ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q8_0), rows: 2560, columns: 2560 };
|
||||
fn original_products<'a>(
|
||||
context: &'a Context<'_>,
|
||||
(embedding, streams): (&[f32], &[f32]),
|
||||
weights: [&DeviceBuffer<'_>; 7],
|
||||
owned: &mut Vec<DeviceBuffer<'a>>,
|
||||
) -> Result<Observed> {
|
||||
owned.push(upload(context, &bytes(embedding))?);
|
||||
owned.push(upload(context, &bytes(streams))?);
|
||||
for size in [10240, 10240, 40960, 10240, 10240, 40960, 40960] {
|
||||
owned.push(context.allocate(size)?);
|
||||
}
|
||||
let [e, r, en, e2, hn, h_input, h_output, h2, out] = owned.as_mut_slice() else {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
};
|
||||
let mut products = Vec::new();
|
||||
let (norm, projected) = numeric!(embedding_products(context, [e, en, e2], weights));
|
||||
products.push(norm);
|
||||
products.push(projected);
|
||||
let hidden = numeric!(hidden_norm_product(context, [r, hn], weights[2]));
|
||||
products.push(hidden.clone());
|
||||
let (mut projections, joined) =
|
||||
numeric!(hidden_projection_products(context, [h_input, h_output], &hidden, weights));
|
||||
products.append(&mut projections);
|
||||
products.push(numeric!(broadcast_product(context, [h2, e2, out], &joined)));
|
||||
Ok(Ok(products))
|
||||
}
|
||||
fn broadcast_product(context: &Context<'_>, [h2, e2, out]: [&mut DeviceBuffer<'_>; 3], joined: &[u8]) -> Step<Vec<u8>> {
|
||||
h2.copy_from(joined)?;
|
||||
context.mtp_broadcast_f32(h2, e2, out)?;
|
||||
let value = read(out)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[12] }));
|
||||
}
|
||||
Ok(Ok(value))
|
||||
}
|
||||
fn embedding_products(
|
||||
context: &Context<'_>,
|
||||
[e, en, e2]: [&mut DeviceBuffer<'_>; 3],
|
||||
weights: [&DeviceBuffer<'_>; 7],
|
||||
) -> Step<(Vec<u8>, Vec<u8>)> {
|
||||
context.mtp_embedding_norm_f32(e, weights[0], en)?;
|
||||
let norm = read(en)?;
|
||||
if !full_finite(&norm) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[0] }));
|
||||
}
|
||||
match context.project_q8_1(weights[1], en, e2, SPEC) {
|
||||
Err(Error::InvalidQ8Activation) => {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[1] }));
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
let projected = read(e2)?;
|
||||
if !full_finite(&projected) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[2] }));
|
||||
}
|
||||
Ok(Ok((norm, projected)))
|
||||
}
|
||||
fn hidden_norm_product(
|
||||
context: &Context<'_>,
|
||||
[r, hn]: [&mut DeviceBuffer<'_>; 2],
|
||||
weight: &DeviceBuffer<'_>,
|
||||
) -> Step<Vec<u8>> {
|
||||
context.mtp_hidden_norm_f32(r, weight, hn)?;
|
||||
let hidden = read(hn)?;
|
||||
if !full_finite(&hidden) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[3] }));
|
||||
}
|
||||
Ok(Ok(hidden))
|
||||
}
|
||||
/// The four hidden projections over whole 10240 B activation owners: their products and the joined bytes.
|
||||
fn hidden_projection_products(
|
||||
context: &Context<'_>,
|
||||
[h_input, h_output]: [&mut DeviceBuffer<'_>; 2],
|
||||
hidden: &[u8],
|
||||
weights: [&DeviceBuffer<'_>; 7],
|
||||
) -> Step<(Vec<Vec<u8>>, Vec<u8>)> {
|
||||
let mut products = Vec::new();
|
||||
let mut joined = Vec::new();
|
||||
for (i, weight) in weights[3..].iter().enumerate() {
|
||||
h_input.copy_from(&hidden[i * 10240..(i + 1) * 10240])?;
|
||||
match context.project_q8_1(weight, h_input, h_output, SPEC) {
|
||||
Err(Error::InvalidQ8Activation) => {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[4 + 2 * i] }));
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
let value = read(h_output)?;
|
||||
if !full_finite(&value) {
|
||||
return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[5 + 2 * i] }));
|
||||
}
|
||||
joined.extend_from_slice(&value);
|
||||
products.push(value);
|
||||
}
|
||||
Ok(Ok((products, joined)))
|
||||
}
|
||||
pub(super) fn queue<'a, 'ctx>(
|
||||
workspace: &'a mut MtpInputWorkspace<'ctx>,
|
||||
embedding: &[f32],
|
||||
@@ -165,15 +213,7 @@ pub(super) fn finite_case(
|
||||
let before = context.allocated_bytes();
|
||||
let completed = queue(workspace, &embedding, &streams, weights)?;
|
||||
report.witness_errors += usize::from(completed.numerical_refusal().is_some() || completed.statuses != [0; 13]);
|
||||
let mut actual = Vec::new();
|
||||
for index in [2usize, 3, 4] {
|
||||
actual.push(read(completed.workspace.buffer(index)?)?);
|
||||
}
|
||||
let h2 = read(completed.workspace.buffer(5)?)?;
|
||||
for chunk in h2.chunks_exact(10240) {
|
||||
actual.push(chunk.to_vec());
|
||||
}
|
||||
actual.push(read(completed.workspace.buffer(6)?)?);
|
||||
let actual = candidate_products(&*completed.workspace)?;
|
||||
for (old, actual) in old.iter().zip(&actual) {
|
||||
compare(old, actual, report);
|
||||
}
|
||||
@@ -182,3 +222,16 @@ pub(super) fn finite_case(
|
||||
usize::from(bytes(&final_values) != old[7] || context.allocated_bytes() != before || workspace.is_failed());
|
||||
Ok(())
|
||||
}
|
||||
/// The candidate's norms, projections and broadcast products, read back from its whole owners.
|
||||
fn candidate_products(workspace: &MtpInputWorkspace<'_>) -> Result<Vec<Vec<u8>>> {
|
||||
let mut actual = Vec::new();
|
||||
for index in [2usize, 3, 4] {
|
||||
actual.push(read(workspace.buffer(index)?)?);
|
||||
}
|
||||
let h2 = read(workspace.buffer(5)?)?;
|
||||
for chunk in h2.chunks_exact(10240) {
|
||||
actual.push(chunk.to_vec());
|
||||
}
|
||||
actual.push(read(workspace.buffer(6)?)?);
|
||||
Ok(actual)
|
||||
}
|
||||
|
||||
@@ -32,94 +32,147 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result<Report
|
||||
let mut workspace = None;
|
||||
let mut owned = Vec::new();
|
||||
let mut report = Report::default();
|
||||
let operation = (|| {
|
||||
let gamma_e = vec![1.0; 2560];
|
||||
let gamma_h = vec![1.0; 10240];
|
||||
let e = raw(11);
|
||||
let h = raw(79);
|
||||
for data in [bytes(&gamma_e), e.clone(), bytes(&gamma_h), h.clone()] {
|
||||
owned.push(upload(context, &data)?);
|
||||
}
|
||||
let mut en_bad = gamma_e.clone();
|
||||
en_bad[2559] = f32::INFINITY;
|
||||
owned.push(upload(context, &bytes(&en_bad))?);
|
||||
let en_quant = vec![1.0e30; 2560];
|
||||
owned.push(upload(context, &bytes(&en_quant))?);
|
||||
let mut hn_bad = gamma_h.clone();
|
||||
hn_bad[10239] = f32::NAN;
|
||||
owned.push(upload(context, &bytes(&hn_bad))?);
|
||||
let mut e_bad = e.clone();
|
||||
e_bad[6_963_166..6_963_168].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
owned.push(upload(context, &e_bad)?);
|
||||
let mut h_bad = h.clone();
|
||||
h_bad[..2].copy_from_slice(&0x7e00u16.to_le_bytes());
|
||||
owned.push(upload(context, &h_bad)?);
|
||||
owned.push(upload(foreign, &bytes(&gamma_e))?);
|
||||
owned.push(context.allocate(10236)?);
|
||||
workspace = Some(context.mtp_input_workspace()?);
|
||||
let ws = workspace.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
report.witness_errors += usize::from(ws.allocated_bytes() != TOTAL);
|
||||
let good = [&owned[0], &owned[1], &owned[2], &owned[3], &owned[3], &owned[3], &owned[3]];
|
||||
for case in [0usize, 1, 2, 0] {
|
||||
finite_case(ws, context, good, case, &mut report)?;
|
||||
}
|
||||
for (weight, index, error, stage) in [
|
||||
(4usize, 0usize, MtpInputRefusal::NonFinite, STAGES[0]),
|
||||
(5, 0, MtpInputRefusal::InvalidQ8Activation, STAGES[1]),
|
||||
(6, 2, MtpInputRefusal::NonFinite, STAGES[3]),
|
||||
(7, 1, MtpInputRefusal::NonFinite, STAGES[2]),
|
||||
(8, 6, MtpInputRefusal::NonFinite, STAGES[11]),
|
||||
] {
|
||||
let mut bad = good;
|
||||
bad[index] = &owned[weight];
|
||||
numeric_case(ws, context, bad, Numeric { error, stage }, &mut report)?;
|
||||
finite_case(ws, context, good, 1, &mut report)?;
|
||||
}
|
||||
let (embedding, streams) = inputs(0);
|
||||
refuse(ws.begin(&embedding[..2559], &streams), Error::InvalidQwenShape, &mut report)?;
|
||||
let mut bad_input = embedding.clone();
|
||||
bad_input[2559] = f32::INFINITY;
|
||||
refuse(ws.begin(&bad_input, &streams), Error::InvalidDriverValue("MTP input finite source"), &mut report)?;
|
||||
let mut empty = ws.begin(&embedding, &streams)?;
|
||||
refuse(empty.hidden_norm(&owned[2]), Error::InvalidQwenShape, &mut report)?;
|
||||
refuse(empty.drain_prefix(), Error::InvalidQwenShape, &mut report)?;
|
||||
let mut first = ws.begin(&embedding, &streams)?;
|
||||
refuse(first.embedding_norm(&owned[9]), Error::ContextMismatch, &mut report)?;
|
||||
refuse(first.drain_prefix(), Error::ContextMismatch, &mut report)?;
|
||||
let mut short = ws.begin(&embedding, &streams)?;
|
||||
refuse(short.embedding_norm(&owned[10]), Error::InvalidQwenShape, &mut report)?;
|
||||
refuse(short.drain_prefix(), Error::InvalidQwenShape, &mut report)?;
|
||||
// Earlier genuine full EN finite refusal beats a later real foreign E.
|
||||
let old = original(
|
||||
context,
|
||||
&embedding,
|
||||
&streams,
|
||||
[&owned[4], &owned[1], &owned[2], &owned[3], &owned[3], &owned[3], &owned[3]],
|
||||
)?;
|
||||
report.witness_errors +=
|
||||
usize::from(old != Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[0] }));
|
||||
let mut prefix = ws.begin(&embedding, &streams)?;
|
||||
prefix.embedding_norm(&owned[4])?;
|
||||
refuse(prefix.embedding_projection(&owned[9]), Error::ContextMismatch, &mut report)?;
|
||||
report.witness_errors += usize::from(prefix.drain_prefix()? != Some(MtpInputRefusal::NonFinite));
|
||||
report.numeric += 1;
|
||||
// Finite earlier work preserves the later actual extent error after drain.
|
||||
let mut prefix = ws.begin(&embedding, &streams)?;
|
||||
prefix.embedding_norm(&owned[0])?;
|
||||
prefix.embedding_projection(&owned[1])?;
|
||||
prefix.hidden_norm(&owned[2])?;
|
||||
for _ in 0..3 {
|
||||
prefix.hidden_projection(&owned[3])?;
|
||||
}
|
||||
refuse(prefix.hidden_projection(&owned[10]), Error::InvalidQwenShape, &mut report)?;
|
||||
refuse(prefix.drain_prefix(), Error::InvalidQwenShape, &mut report)?;
|
||||
finite_case(ws, context, good, 0, &mut report)?;
|
||||
Ok(report)
|
||||
})();
|
||||
let operation = run_cases(context, foreign, (&mut workspace, &mut owned), &mut report);
|
||||
let mut cleanup = workspace.take().map_or(Ok(()), MtpInputWorkspace::close);
|
||||
drop(workspace);
|
||||
for buffer in owned {
|
||||
cleanup = combine(cleanup, buffer.release());
|
||||
}
|
||||
combine(operation, cleanup)
|
||||
combine(operation.map(|()| report), cleanup)
|
||||
}
|
||||
/// Every case of the proof over one workspace; the caller closes whatever was created, whatever the outcome.
|
||||
fn run_cases<'a>(
|
||||
context: &'a Context<'a>,
|
||||
foreign: &'a Context<'a>,
|
||||
(workspace, owned): (&mut Option<MtpInputWorkspace<'a>>, &mut Vec<DeviceBuffer<'a>>),
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
upload_corpus(context, foreign, owned)?;
|
||||
*workspace = Some(context.mtp_input_workspace()?);
|
||||
let ws = workspace.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
report.witness_errors += usize::from(ws.allocated_bytes() != TOTAL);
|
||||
let good = [&owned[0], &owned[1], &owned[2], &owned[3], &owned[3], &owned[3], &owned[3]];
|
||||
for case in [0usize, 1, 2, 0] {
|
||||
finite_case(ws, context, good, case, report)?;
|
||||
}
|
||||
numeric_refusals(ws, context, good, owned, report)?;
|
||||
let (embedding, streams) = inputs(0);
|
||||
let io = (&embedding[..], &streams[..]);
|
||||
shape_refusals(ws, io, owned, report)?;
|
||||
refuse_foreign_after_nonfinite(ws, context, io, owned, report)?;
|
||||
refuse_late_extent(ws, io, owned, report)?;
|
||||
finite_case(ws, context, good, 0, report)
|
||||
}
|
||||
fn upload_corpus<'a>(
|
||||
context: &'a Context<'a>,
|
||||
foreign: &'a Context<'a>,
|
||||
owned: &mut Vec<DeviceBuffer<'a>>,
|
||||
) -> Result<()> {
|
||||
let gamma_e = vec![1.0; 2560];
|
||||
let gamma_h = vec![1.0; 10240];
|
||||
let e = raw(11);
|
||||
let h = raw(79);
|
||||
for data in [bytes(&gamma_e), e.clone(), bytes(&gamma_h), h.clone()] {
|
||||
owned.push(upload(context, &data)?);
|
||||
}
|
||||
let mut en_bad = gamma_e.clone();
|
||||
en_bad[2559] = f32::INFINITY;
|
||||
owned.push(upload(context, &bytes(&en_bad))?);
|
||||
let en_quant = vec![1.0e30; 2560];
|
||||
owned.push(upload(context, &bytes(&en_quant))?);
|
||||
let mut hn_bad = gamma_h.clone();
|
||||
hn_bad[10239] = f32::NAN;
|
||||
owned.push(upload(context, &bytes(&hn_bad))?);
|
||||
let mut e_bad = e.clone();
|
||||
e_bad[6_963_166..6_963_168].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
owned.push(upload(context, &e_bad)?);
|
||||
let mut h_bad = h.clone();
|
||||
h_bad[..2].copy_from_slice(&0x7e00u16.to_le_bytes());
|
||||
owned.push(upload(context, &h_bad)?);
|
||||
owned.push(upload(foreign, &bytes(&gamma_e))?);
|
||||
owned.push(context.allocate(10236)?);
|
||||
Ok(())
|
||||
}
|
||||
fn numeric_refusals(
|
||||
ws: &mut MtpInputWorkspace<'_>,
|
||||
context: &Context<'_>,
|
||||
good: [&DeviceBuffer<'_>; 7],
|
||||
owned: &[DeviceBuffer<'_>],
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
for (weight, index, error, stage) in [
|
||||
(4usize, 0usize, MtpInputRefusal::NonFinite, STAGES[0]),
|
||||
(5, 0, MtpInputRefusal::InvalidQ8Activation, STAGES[1]),
|
||||
(6, 2, MtpInputRefusal::NonFinite, STAGES[3]),
|
||||
(7, 1, MtpInputRefusal::NonFinite, STAGES[2]),
|
||||
(8, 6, MtpInputRefusal::NonFinite, STAGES[11]),
|
||||
] {
|
||||
let mut bad = good;
|
||||
bad[index] = &owned[weight];
|
||||
numeric_case(ws, context, bad, Numeric { error, stage }, report)?;
|
||||
finite_case(ws, context, good, 1, report)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Malformed sources and first-stage weights are refused and leave the prefix drainable.
|
||||
fn shape_refusals(
|
||||
ws: &mut MtpInputWorkspace<'_>,
|
||||
(embedding, streams): (&[f32], &[f32]),
|
||||
owned: &[DeviceBuffer<'_>],
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
refuse(ws.begin(&embedding[..2559], streams), Error::InvalidQwenShape, report)?;
|
||||
let mut bad_input = embedding.to_vec();
|
||||
bad_input[2559] = f32::INFINITY;
|
||||
refuse(ws.begin(&bad_input, streams), Error::InvalidDriverValue("MTP input finite source"), report)?;
|
||||
let mut empty = ws.begin(embedding, streams)?;
|
||||
refuse(empty.hidden_norm(&owned[2]), Error::InvalidQwenShape, report)?;
|
||||
refuse(empty.drain_prefix(), Error::InvalidQwenShape, report)?;
|
||||
refuse_first_weight(ws, (embedding, streams), (&owned[9], Error::ContextMismatch), report)?;
|
||||
refuse_first_weight(ws, (embedding, streams), (&owned[10], Error::InvalidQwenShape), report)
|
||||
}
|
||||
fn refuse_first_weight(
|
||||
ws: &mut MtpInputWorkspace<'_>,
|
||||
(embedding, streams): (&[f32], &[f32]),
|
||||
(weight, expected): (&DeviceBuffer<'_>, Error),
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
let mut prefix = ws.begin(embedding, streams)?;
|
||||
refuse(prefix.embedding_norm(weight), expected.clone(), report)?;
|
||||
refuse(prefix.drain_prefix(), expected, report)
|
||||
}
|
||||
fn refuse_foreign_after_nonfinite(
|
||||
ws: &mut MtpInputWorkspace<'_>,
|
||||
context: &Context<'_>,
|
||||
(embedding, streams): (&[f32], &[f32]),
|
||||
owned: &[DeviceBuffer<'_>],
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
// Earlier genuine full EN finite refusal beats a later real foreign E.
|
||||
let weights = [&owned[4], &owned[1], &owned[2], &owned[3], &owned[3], &owned[3], &owned[3]];
|
||||
let old = original(context, embedding, streams, weights)?;
|
||||
report.witness_errors += usize::from(old != Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[0] }));
|
||||
let mut prefix = ws.begin(embedding, streams)?;
|
||||
prefix.embedding_norm(&owned[4])?;
|
||||
refuse(prefix.embedding_projection(&owned[9]), Error::ContextMismatch, report)?;
|
||||
report.witness_errors += usize::from(prefix.drain_prefix()? != Some(MtpInputRefusal::NonFinite));
|
||||
report.numeric += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn refuse_late_extent(
|
||||
ws: &mut MtpInputWorkspace<'_>,
|
||||
(embedding, streams): (&[f32], &[f32]),
|
||||
owned: &[DeviceBuffer<'_>],
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
// Finite earlier work preserves the later actual extent error after drain.
|
||||
let mut prefix = ws.begin(embedding, streams)?;
|
||||
prefix.embedding_norm(&owned[0])?;
|
||||
prefix.embedding_projection(&owned[1])?;
|
||||
prefix.hidden_norm(&owned[2])?;
|
||||
for _ in 0..3 {
|
||||
prefix.hidden_projection(&owned[3])?;
|
||||
}
|
||||
refuse(prefix.hidden_projection(&owned[10]), Error::InvalidQwenShape, report)?;
|
||||
refuse(prefix.drain_prefix(), Error::InvalidQwenShape, report)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ struct Library(*mut c_void);
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here.
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly
|
||||
// once, here.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
@@ -42,16 +43,70 @@ fn check(op: &'static str, code: i32) -> Result<()> {
|
||||
}
|
||||
macro_rules! sym {
|
||||
($l:ident,$n:literal,$t:ty) => {{
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below.
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is
|
||||
// rejected right below.
|
||||
let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) };
|
||||
if p.is_null() {
|
||||
return Err(Error::MissingSymbol($n.to_str().expect("static ABI")));
|
||||
}
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature
|
||||
// (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for).
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C
|
||||
// signature (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled
|
||||
// for).
|
||||
unsafe { std::mem::transmute::<*mut c_void, $t>(p) }
|
||||
}};
|
||||
}
|
||||
type Dims = ([u32; 3], [u32; 3]);
|
||||
fn open_libcuda() -> Library {
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and
|
||||
// null-checked next.
|
||||
Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) })
|
||||
}
|
||||
fn probe_device(l: &Library) -> Result<()> {
|
||||
let dev = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
let mut device = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuCtxGetDevice", unsafe { dev(&mut device) })?;
|
||||
let major = device_attribute(attr, device, 75, "cuDeviceGetAttribute")?;
|
||||
let shared = device_attribute(attr, device, 8, "cuDeviceGetAttribute")?;
|
||||
if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn device_attribute(attr: Attr, device: i32, key: i32, name: &'static str) -> Result<i32> {
|
||||
let mut value = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check(name, unsafe { attr(&mut value, key, device) })?;
|
||||
Ok(value)
|
||||
}
|
||||
fn check_launch_geometry(grid: [u32; 3], block: [u32; 3], shared: u32, stream: usize) -> Result<()> {
|
||||
if grid.contains(&0)
|
||||
|| !(matches!(block, [32, 4, 1] | [32, 8, 1])
|
||||
|| block[1..] == [1, 1] && (block[0] == 1 || block[0] <= 1024 && block[0] % 32 == 0))
|
||||
|| shared > 131072
|
||||
|| stream == 0
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rebuild_pointers(args: &mut Arguments) {
|
||||
args.pointers.clear();
|
||||
for v in &mut args.values {
|
||||
args.pointers.push(match v {
|
||||
Arg::U64(x) => (x as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::I64(x) => (x as *mut i64).cast(),
|
||||
Arg::F32(x) => (x as *mut f32).cast(),
|
||||
Arg::Words3(x) => x.as_mut_ptr().cast(),
|
||||
Arg::GrMulti(x) => x.as_mut_ptr().cast(),
|
||||
Arg::Params(x) => (x as *mut crate::SamplerParams).cast(),
|
||||
});
|
||||
}
|
||||
}
|
||||
pub(crate) struct Module {
|
||||
library: Option<Library>,
|
||||
module: Option<usize>,
|
||||
@@ -76,31 +131,22 @@ impl Module {
|
||||
if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next.
|
||||
let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) });
|
||||
let l = open_libcuda();
|
||||
if l.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
let load = sym!(l, c"cuModuleLoadData", Load);
|
||||
let get = sym!(l, c"cuModuleGetFunction", Function);
|
||||
let dev = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
let mut device = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuCtxGetDevice", unsafe { dev(&mut device) })?;
|
||||
let mut major = 0;
|
||||
let mut shared = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?;
|
||||
if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
probe_device(&l)?;
|
||||
let mut owner = Self::bind(l)?;
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
if let Err(e) = owner.load_entries(ptx, entries, (load, get)) {
|
||||
return combine(Err(e), owner.close());
|
||||
}
|
||||
let mut owner = Self {
|
||||
Ok(owner)
|
||||
}
|
||||
fn bind(l: Library) -> Result<Self> {
|
||||
Ok(Self {
|
||||
launch: sym!(l, c"cuLaunchKernel", Launch),
|
||||
unload: sym!(l, c"cuModuleUnload", Unload),
|
||||
copy: sym!(l, c"cuMemcpyAsync", Copy),
|
||||
@@ -113,67 +159,72 @@ impl Module {
|
||||
library: Some(l),
|
||||
module: None,
|
||||
functions: Vec::new(),
|
||||
};
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let result = (|| {
|
||||
let mut m = std::ptr::null_mut();
|
||||
// SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from
|
||||
// sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
owner.module = Some(m as usize);
|
||||
for n in entries {
|
||||
let mut f = std::ptr::null_mut();
|
||||
// SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static
|
||||
// NUL-terminated literal; the function out-pointer is valid.
|
||||
check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
owner.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
return combine(Err(e), owner.close());
|
||||
})
|
||||
}
|
||||
fn load_entries(
|
||||
&mut self,
|
||||
ptx: &'static [u8],
|
||||
entries: &'static [&'static CStr],
|
||||
(load, get): (Load, Function),
|
||||
) -> Result<()> {
|
||||
let mut m = std::ptr::null_mut();
|
||||
// SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86
|
||||
// companions come from sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the
|
||||
// driver is done with the image on return.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
Ok(owner)
|
||||
self.module = Some(m as usize);
|
||||
for n in entries {
|
||||
let mut f = std::ptr::null_mut();
|
||||
// SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name
|
||||
// is a 'static NUL-terminated literal; the function out-pointer is valid.
|
||||
check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
self.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// Literal down_chunk geometry: sm75 uses1280, others2560; preVolta
|
||||
// uses actual per-block shared capacity rather than opt-in promise.
|
||||
pub(crate) fn configure_gr(&self) -> Result<(usize, usize)> {
|
||||
let l = self.library.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let device = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
let mut d = 0;
|
||||
check("cuCtxGetDevice", unsafe { device(&mut d) })?;
|
||||
let mut optin = 0;
|
||||
let mut major = 0;
|
||||
let mut minor = 0;
|
||||
let mut per_block = 0;
|
||||
for (value, key) in [(&mut optin, 97), (&mut major, 75), (&mut minor, 76), (&mut per_block, 8)] {
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuDeviceGetAttribute(GR)", unsafe { attr(value, key, d) })?;
|
||||
}
|
||||
let [optin, major, minor, per_block] = self.probe_gr()?;
|
||||
let tile = if major * 10 + minor == 75 { 1280 } else { 2560 };
|
||||
let usable = if major >= 7 && optin > 0 { optin } else { per_block };
|
||||
if usable <= 0 {
|
||||
return Err(Error::InvalidDriverValue("Original GR shared geometry"));
|
||||
}
|
||||
// Original sets both down-kernel attributes once, before launches.
|
||||
self.set_gr_attributes(tile, optin)?;
|
||||
Ok((usable as usize, tile))
|
||||
}
|
||||
/// Original sets both down-kernel attributes once, before launches.
|
||||
fn set_gr_attributes(&self, tile: usize, optin: i32) -> Result<()> {
|
||||
for (index, want) in [(if tile == 1280 { 4 } else { 5 }, 8 * tile * 4), (2, 2 * 8 * 1280 * 4)] {
|
||||
let want = if optin > 0 { want.min(optin as usize) } else { want };
|
||||
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
// SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`);
|
||||
// attribute id and value are plain integers.
|
||||
// SAFETY: the function handle belongs to this live module and the context is current (caller holds
|
||||
// `Context::enter`); attribute id and value are plain integers.
|
||||
check("cuFuncSetAttribute", unsafe { (self.attr)(function as *mut c_void, 8, want as i32) })?;
|
||||
}
|
||||
Ok((usable as usize, tile))
|
||||
Ok(())
|
||||
}
|
||||
/// `[opt-in shared, cc major, cc minor, per-block shared]` of the current device.
|
||||
fn probe_gr(&self) -> Result<[i32; 4]> {
|
||||
let l = self.library.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let device = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
let mut d = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuCtxGetDevice", unsafe { device(&mut d) })?;
|
||||
let optin = device_attribute(attr, d, 97, "cuDeviceGetAttribute(GR)")?;
|
||||
let major = device_attribute(attr, d, 75, "cuDeviceGetAttribute(GR)")?;
|
||||
let minor = device_attribute(attr, d, 76, "cuDeviceGetAttribute(GR)")?;
|
||||
let per_block = device_attribute(attr, d, 8, "cuDeviceGetAttribute(GR)")?;
|
||||
Ok([optin, major, minor, per_block])
|
||||
}
|
||||
pub(crate) fn launch(
|
||||
&self,
|
||||
@@ -184,32 +235,19 @@ impl Module {
|
||||
stream: usize,
|
||||
args: &mut Arguments,
|
||||
) -> Result<()> {
|
||||
if grid.contains(&0)
|
||||
|| !(matches!(block, [32, 4, 1] | [32, 8, 1])
|
||||
|| block[1..] == [1, 1] && (block[0] == 1 || block[0] <= 1024 && block[0] % 32 == 0))
|
||||
|| shared > 131072
|
||||
|| stream == 0
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
check_launch_geometry(grid, block, shared, stream)?;
|
||||
let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
args.pointers.clear();
|
||||
for v in &mut args.values {
|
||||
args.pointers.push(match v {
|
||||
Arg::U64(x) => (x as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::I64(x) => (x as *mut i64).cast(),
|
||||
Arg::F32(x) => (x as *mut f32).cast(),
|
||||
Arg::Words3(x) => x.as_mut_ptr().cast(),
|
||||
Arg::GrMulti(x) => x.as_mut_ptr().cast(),
|
||||
Arg::Params(x) => (x as *mut crate::SamplerParams).cast(),
|
||||
});
|
||||
}
|
||||
// SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a
|
||||
// handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt
|
||||
// just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares;
|
||||
// the driver copies the parameter bytes during this call (also under stream capture), so the storage need not
|
||||
// outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here.
|
||||
rebuild_pointers(args);
|
||||
self.launch_raw(f, (grid, block), shared, stream, args)
|
||||
}
|
||||
fn launch_raw(&self, f: usize, dims: Dims, shared: u32, stream: usize, args: &mut Arguments) -> Result<()> {
|
||||
let (grid, block) = dims;
|
||||
// SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop);
|
||||
// `stream` is a handle of a live stream owner that is synchronized before it is destroyed; every pointer
|
||||
// in `pointers` was rebuilt just above to point into the boxed, never-resized argument storage with the
|
||||
// size/type the kernel's .param declares; the driver copies the parameter bytes during this call (also
|
||||
// under stream capture), so the storage need not outlive it. Argument/PTX parameter agreement is a
|
||||
// producer contract checked by the GPU parity tests, not here.
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch)(
|
||||
f as *mut c_void,
|
||||
@@ -231,35 +269,40 @@ impl Module {
|
||||
if n == 0 || stream == 0 || dst == 0 || src == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents
|
||||
// (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners
|
||||
// must outlive the stream drain (graph resources / Context::synchronize on every close path).
|
||||
// SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with
|
||||
// checked extents (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is
|
||||
// asynchronous: both owners must outlive the stream drain (graph resources / Context::synchronize on
|
||||
// every close path).
|
||||
check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) })
|
||||
}
|
||||
// SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host destinations;
|
||||
// a device->device copy is merely ordered on the legacy default stream (callers: mtp_original_full_round.rs).
|
||||
// SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host
|
||||
// destinations; a device->device copy is merely ordered on the legacy default stream (callers:
|
||||
// mtp_original_full_round.rs).
|
||||
pub(crate) fn copy_sync(&self, dst: u64, src: u64, n: usize) -> Result<()> {
|
||||
if dst == 0 || src == 0 || n == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
check("cuMemcpy", unsafe { (self.copy_sync)(dst, src, n) })
|
||||
}
|
||||
// SAFETY: stream handle 0 is the legacy default stream, which `copy_sync` (cuMemcpy) uses; synchronizing it returns once every earlier
|
||||
// legacy-stream operation (the D2D copies) has completed, and it does NOT wait for work queued on non-blocking streams (a pending
|
||||
// verifier commit), unlike cuCtxSynchronize. After it returns, a launch on a non-blocking stream is ordered after the copies by the host.
|
||||
// SAFETY: stream handle 0 is the legacy default stream, which `copy_sync` (cuMemcpy) uses; synchronizing it
|
||||
// returns once every earlier legacy-stream operation (the D2D copies) has completed, and it does NOT wait for
|
||||
// work queued on non-blocking streams (a pending verifier commit), unlike cuCtxSynchronize. After it returns,
|
||||
// a launch on a non-blocking stream is ordered after the copies by the host.
|
||||
pub(crate) fn fence_legacy_stream(&self) -> Result<()> {
|
||||
check("cuStreamSynchronize", unsafe { (self.stream_sync)(std::ptr::null_mut()) })
|
||||
}
|
||||
// SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered on the legacy
|
||||
// default stream but asynchronous with respect to the host; its only caller (FullOwned::new_internal) fences it.
|
||||
// SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered
|
||||
// on the legacy default stream but asynchronous with respect to the host; its only caller
|
||||
// (FullOwned::new_internal) fences it.
|
||||
pub(crate) fn zero(&self, dst: u64, n: usize) -> Result<()> {
|
||||
if dst == 0 || n == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
check("cuMemsetD8_v2", unsafe { (self.memset)(dst, 0, n) })
|
||||
}
|
||||
// SAFETY: `descriptor` is a #[repr(C)] CUDA_MEMCPY2D (layout asserted at compile time above) read by the driver during
|
||||
// this call only; its src/dst are device addresses of live whole owners sized for pitch*height (see the q_split test).
|
||||
// SAFETY: `descriptor` is a #[repr(C)] CUDA_MEMCPY2D (layout asserted at compile time above) read by the
|
||||
// driver during this call only; its src/dst are device addresses of live whole owners sized for pitch*height
|
||||
// (see the q_split test).
|
||||
pub(crate) fn copy2d(&self, descriptor: &Copy2D, stream: usize) -> Result<()> {
|
||||
if stream == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -270,9 +313,10 @@ impl Module {
|
||||
if dst == 0 || source.is_empty() || stream == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the
|
||||
// driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is
|
||||
// drained, so even a pinned-source (fully asynchronous) copy would read valid memory.
|
||||
// SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable
|
||||
// source is staged by the driver before return; callers additionally retain the bytes
|
||||
// (OriginalMtpScalarPrefill::pending_host) until the stream is drained, so even a pinned-source (fully
|
||||
// asynchronous) copy would read valid memory.
|
||||
check("cuMemcpyHtoDAsync_v2", unsafe {
|
||||
(self.h2d)(dst, source.as_ptr().cast(), source.len(), stream as *mut c_void)
|
||||
})
|
||||
@@ -282,8 +326,9 @@ impl Module {
|
||||
}
|
||||
fn close_inner(&mut self) -> Result<()> {
|
||||
if let Some(m) = self.module.take() {
|
||||
// SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the
|
||||
// library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence.
|
||||
// SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most
|
||||
// once; on failure the library is forgotten so the stored fn pointers stay valid. Callers drain the
|
||||
// stream first; unload is not a fence.
|
||||
let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) });
|
||||
if r.is_err()
|
||||
&& let Some(l) = self.library.take()
|
||||
|
||||
@@ -11,7 +11,8 @@ mod mapped_enabled {
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here.
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly
|
||||
// once, here.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
@@ -23,16 +24,29 @@ mod mapped_enabled {
|
||||
}
|
||||
macro_rules! sym {
|
||||
($l:ident,$s:literal,$t:ty) => {{
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below.
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is
|
||||
// rejected right below.
|
||||
let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) };
|
||||
if p.is_null() {
|
||||
return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI")));
|
||||
}
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature
|
||||
// (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for).
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's
|
||||
// C signature (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is
|
||||
// compiled for).
|
||||
unsafe { std::mem::transmute::<*mut c_void, $t>(p) }
|
||||
}};
|
||||
}
|
||||
fn host_alloc(alloc: Alloc, bytes: usize) -> Result<*mut c_void> {
|
||||
let mut ptr = std::ptr::null_mut();
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked
|
||||
// below. The block is owned by this type and released only by an explicit close() (Drop deliberately
|
||||
// leaks instead of freeing).
|
||||
check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?;
|
||||
if ptr.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
Ok(ptr)
|
||||
}
|
||||
pub(crate) struct MappedOwner {
|
||||
library: Option<Library>,
|
||||
host: Option<usize>,
|
||||
@@ -48,7 +62,8 @@ mod mapped_enabled {
|
||||
}
|
||||
let records = max_t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 };
|
||||
let bytes = ((records + 255) & !255) + max_t * 40960;
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next.
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop)
|
||||
// and null-checked next.
|
||||
let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) });
|
||||
if library.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
@@ -56,31 +71,31 @@ mod mapped_enabled {
|
||||
let alloc = sym!(library, c"cuMemHostAlloc", Alloc);
|
||||
let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address);
|
||||
let free = sym!(library, c"cuMemFreeHost", Free);
|
||||
let mut ptr = std::ptr::null_mut();
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is
|
||||
// owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing).
|
||||
check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?;
|
||||
if ptr.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
let ptr = host_alloc(alloc, bytes)?;
|
||||
let mut owner =
|
||||
Self { library: Some(library), host: Some(ptr as usize), alias: 0, free, bytes, shared: None };
|
||||
// SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0.
|
||||
let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) });
|
||||
owner.publish(address, ptr)?;
|
||||
Ok(owner)
|
||||
}
|
||||
/// Map the fresh block to its device alias, check its alignment and zero it; a failure closes the owner.
|
||||
fn publish(&mut self, address: Address, ptr: *mut c_void) -> Result<()> {
|
||||
// SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and
|
||||
// flags are 0.
|
||||
let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut self.alias, ptr, 0) });
|
||||
if let Err(primary) = op {
|
||||
let _ = owner.close();
|
||||
let _ = self.close();
|
||||
return Err(primary);
|
||||
}
|
||||
if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) {
|
||||
let _ = owner.close();
|
||||
if self.alias == 0 || self.alias % 256 != 0 || self.host.is_none_or(|p| p % 256 != 0) {
|
||||
let _ = self.close();
|
||||
return Err(Error::InvalidDriverValue("mapped-host-alignment"));
|
||||
}
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes
|
||||
// the block fully initialized before the first CPU read.
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it
|
||||
// yet; zeroing makes the block fully initialized before the first CPU read.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(ptr.cast::<u8>(), 0, bytes);
|
||||
std::ptr::write_bytes(ptr.cast::<u8>(), 0, self.bytes);
|
||||
} // initialized final whole owner; never resized.
|
||||
Ok(owner)
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn original(max_t: usize, coupled: bool) -> Result<Self> {
|
||||
let mut owner = Self::new(max_t, coupled)?;
|
||||
@@ -104,9 +119,10 @@ mod mapped_enabled {
|
||||
}
|
||||
pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> {
|
||||
let p = self.range(o, b.len())?;
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and
|
||||
// `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference
|
||||
// ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range.
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <=
|
||||
// bytes, checked_add) and `b` is a distinct Rust slice, so the ranges cannot overlap. The address is
|
||||
// kept as usize on purpose: no Rust reference ever aliases memory the GPU may write. Caller
|
||||
// obligation: no enqueued GPU work reads or writes this range.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len());
|
||||
}
|
||||
@@ -115,8 +131,8 @@ mod mapped_enabled {
|
||||
pub(crate) fn read(&self, o: usize, b: &mut [u8]) -> Result<()> {
|
||||
let p = self.range(o, b.len())?;
|
||||
for (i, dst) in b.iter_mut().enumerate() {
|
||||
// SAFETY: (p + i) < p + b.len() is inside the range proved by range(); volatile because the GPU may have written the
|
||||
// byte, and callers read only after the producing stream was drained.
|
||||
// SAFETY: (p + i) < p + b.len() is inside the range proved by range(); volatile because the GPU
|
||||
// may have written the byte, and callers read only after the producing stream was drained.
|
||||
*dst = unsafe { std::ptr::read_volatile((p + i) as *const u8) };
|
||||
}
|
||||
Ok(())
|
||||
@@ -126,8 +142,9 @@ mod mapped_enabled {
|
||||
if self.shared.as_ref().is_some_and(|shared| Rc::strong_count(shared) > 1) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
// SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every
|
||||
// stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing.
|
||||
// SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed
|
||||
// once; callers drained every stream that references it before close(). On failure host stays
|
||||
// Some so Drop leaks the block rather than re-freeing.
|
||||
check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?;
|
||||
self.host = None;
|
||||
self.alias = 0;
|
||||
|
||||
@@ -24,7 +24,8 @@ struct Library(*mut c_void);
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here.
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly
|
||||
// once, here.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
@@ -36,16 +37,66 @@ fn check(op: &'static str, code: i32) -> Result<()> {
|
||||
}
|
||||
macro_rules! sym {
|
||||
($l:ident,$n:literal,$t:ty) => {{
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below.
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is
|
||||
// rejected right below.
|
||||
let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) };
|
||||
if p.is_null() {
|
||||
return Err(Error::MissingSymbol($n.to_str().expect("static ABI")));
|
||||
}
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature
|
||||
// (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for).
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C
|
||||
// signature (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled
|
||||
// for).
|
||||
unsafe { std::mem::transmute::<*mut c_void, $t>(p) }
|
||||
}};
|
||||
}
|
||||
type Dims = ([u32; 3], [u32; 3]);
|
||||
fn open_libcuda() -> Library {
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and
|
||||
// null-checked next.
|
||||
Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) })
|
||||
}
|
||||
fn probe_device(l: &Library) -> Result<()> {
|
||||
let dev = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
let mut device = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuCtxGetDevice", unsafe { dev(&mut device) })?;
|
||||
let major = device_attribute(attr, device, 75, "cuDeviceGetAttribute")?;
|
||||
let shared = device_attribute(attr, device, 8, "cuDeviceGetAttribute")?;
|
||||
if major < 8 || shared < 45584 {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn device_attribute(attr: Attr, device: i32, key: i32, name: &'static str) -> Result<i32> {
|
||||
let mut value = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check(name, unsafe { attr(&mut value, key, device) })?;
|
||||
Ok(value)
|
||||
}
|
||||
fn check_launch_geometry(grid: [u32; 3], block: [u32; 3], shared: u32, stream: usize) -> Result<()> {
|
||||
if grid.contains(&0)
|
||||
|| !matches!(block, [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1])
|
||||
|| !matches!(shared, 0 | 45584)
|
||||
|| stream == 0
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rebuild_pointers(args: &mut Arguments) {
|
||||
args.pointers.clear();
|
||||
for v in &mut args.values {
|
||||
args.pointers.push(match v {
|
||||
Arg::U64(x) => (x as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::I64(x) => (x as *mut i64).cast(),
|
||||
Arg::F32(x) => (x as *mut f32).cast(),
|
||||
});
|
||||
}
|
||||
}
|
||||
pub(crate) struct Module {
|
||||
library: Option<Library>,
|
||||
module: Option<usize>,
|
||||
@@ -59,64 +110,56 @@ impl Module {
|
||||
if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next.
|
||||
let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) });
|
||||
let l = open_libcuda();
|
||||
if l.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
let load = sym!(l, c"cuModuleLoadData", Load);
|
||||
let get = sym!(l, c"cuModuleGetFunction", Function);
|
||||
let dev = sym!(l, c"cuCtxGetDevice", Device);
|
||||
let attr = sym!(l, c"cuDeviceGetAttribute", Attr);
|
||||
let mut device = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuCtxGetDevice", unsafe { dev(&mut device) })?;
|
||||
let mut major = 0;
|
||||
let mut shared = 0;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?;
|
||||
// SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside
|
||||
// `Context::enter` (module load / geometry probes are never called without it).
|
||||
check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?;
|
||||
if major < 8 || shared < 45584 {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
probe_device(&l)?;
|
||||
let mut owner = Self::bind(l)?;
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
if let Err(e) = owner.load_entries(ptx, entries, (load, get)) {
|
||||
return combine(Err(e), owner.close());
|
||||
}
|
||||
let mut owner = Self {
|
||||
Ok(owner)
|
||||
}
|
||||
fn bind(l: Library) -> Result<Self> {
|
||||
Ok(Self {
|
||||
launch: sym!(l, c"cuLaunchKernel", Launch),
|
||||
unload: sym!(l, c"cuModuleUnload", Unload),
|
||||
copy: sym!(l, c"cuMemcpyAsync", Copy),
|
||||
library: Some(l),
|
||||
module: None,
|
||||
functions: Vec::new(),
|
||||
};
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let result = (|| {
|
||||
let mut m = std::ptr::null_mut();
|
||||
// SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from
|
||||
// sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
owner.module = Some(m as usize);
|
||||
for n in entries {
|
||||
let mut f = std::ptr::null_mut();
|
||||
// SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static
|
||||
// NUL-terminated literal; the function out-pointer is valid.
|
||||
check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
owner.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
return combine(Err(e), owner.close());
|
||||
})
|
||||
}
|
||||
fn load_entries(
|
||||
&mut self,
|
||||
ptx: &'static [u8],
|
||||
entries: &'static [&'static CStr],
|
||||
(load, get): (Load, Function),
|
||||
) -> Result<()> {
|
||||
let mut m = std::ptr::null_mut();
|
||||
// SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86
|
||||
// companions come from sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the
|
||||
// driver is done with the image on return.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
Ok(owner)
|
||||
self.module = Some(m as usize);
|
||||
for n in entries {
|
||||
let mut f = std::ptr::null_mut();
|
||||
// SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name
|
||||
// is a 'static NUL-terminated literal; the function out-pointer is valid.
|
||||
check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
self.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn launch(
|
||||
&self,
|
||||
@@ -127,28 +170,19 @@ impl Module {
|
||||
stream: usize,
|
||||
args: &mut Arguments,
|
||||
) -> Result<()> {
|
||||
if grid.contains(&0)
|
||||
|| !matches!(block, [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1])
|
||||
|| !matches!(shared, 0 | 45584)
|
||||
|| stream == 0
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
check_launch_geometry(grid, block, shared, stream)?;
|
||||
let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
args.pointers.clear();
|
||||
for v in &mut args.values {
|
||||
args.pointers.push(match v {
|
||||
Arg::U64(x) => (x as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::I64(x) => (x as *mut i64).cast(),
|
||||
Arg::F32(x) => (x as *mut f32).cast(),
|
||||
});
|
||||
}
|
||||
// SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a
|
||||
// handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt
|
||||
// just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares;
|
||||
// the driver copies the parameter bytes during this call (also under stream capture), so the storage need not
|
||||
// outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here.
|
||||
rebuild_pointers(args);
|
||||
self.launch_raw(f, (grid, block), shared, stream, args)
|
||||
}
|
||||
fn launch_raw(&self, f: usize, dims: Dims, shared: u32, stream: usize, args: &mut Arguments) -> Result<()> {
|
||||
let (grid, block) = dims;
|
||||
// SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop);
|
||||
// `stream` is a handle of a live stream owner that is synchronized before it is destroyed; every pointer
|
||||
// in `pointers` was rebuilt just above to point into the boxed, never-resized argument storage with the
|
||||
// size/type the kernel's .param declares; the driver copies the parameter bytes during this call (also
|
||||
// under stream capture), so the storage need not outlive it. Argument/PTX parameter agreement is a
|
||||
// producer contract checked by the GPU parity tests, not here.
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch)(
|
||||
f as *mut c_void,
|
||||
@@ -170,9 +204,10 @@ impl Module {
|
||||
if n == 0 || stream == 0 || dst == 0 || src == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents
|
||||
// (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners
|
||||
// must outlive the stream drain (graph resources / Context::synchronize on every close path).
|
||||
// SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with
|
||||
// checked extents (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is
|
||||
// asynchronous: both owners must outlive the stream drain (graph resources / Context::synchronize on
|
||||
// every close path).
|
||||
check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) })
|
||||
}
|
||||
pub(crate) fn close(mut self) -> Result<()> {
|
||||
@@ -180,8 +215,9 @@ impl Module {
|
||||
}
|
||||
fn close_inner(&mut self) -> Result<()> {
|
||||
if let Some(m) = self.module.take() {
|
||||
// SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the
|
||||
// library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence.
|
||||
// SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most
|
||||
// once; on failure the library is forgotten so the stored fn pointers stay valid. Callers drain the
|
||||
// stream first; unload is not a fence.
|
||||
let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) });
|
||||
if r.is_err()
|
||||
&& let Some(l) = self.library.take()
|
||||
|
||||
@@ -9,7 +9,8 @@ struct Library(*mut c_void);
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here.
|
||||
// SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly
|
||||
// once, here.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
@@ -21,16 +22,29 @@ fn check(op: &'static str, n: i32) -> Result<()> {
|
||||
}
|
||||
macro_rules! sym {
|
||||
($l:ident,$s:literal,$t:ty) => {{
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below.
|
||||
// SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is
|
||||
// rejected right below.
|
||||
let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) };
|
||||
if p.is_null() {
|
||||
return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI")));
|
||||
}
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature
|
||||
// (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for).
|
||||
// SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C
|
||||
// signature (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled
|
||||
// for).
|
||||
unsafe { std::mem::transmute::<*mut c_void, $t>(p) }
|
||||
}};
|
||||
}
|
||||
fn host_alloc(alloc: Alloc, bytes: usize) -> Result<*mut c_void> {
|
||||
let mut ptr = std::ptr::null_mut();
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked
|
||||
// below. The block is owned by this type and released only by an explicit close() (Drop deliberately
|
||||
// leaks instead of freeing).
|
||||
check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?;
|
||||
if ptr.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
Ok(ptr)
|
||||
}
|
||||
pub(crate) struct MappedOwner {
|
||||
library: Option<Library>,
|
||||
host: Option<usize>,
|
||||
@@ -52,7 +66,8 @@ impl MappedOwner {
|
||||
if !matches!(bytes, 20 | 96 | HOST_BYTES) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next.
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and
|
||||
// null-checked next.
|
||||
let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) });
|
||||
if library.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
@@ -60,40 +75,38 @@ impl MappedOwner {
|
||||
let alloc = sym!(library, c"cuMemHostAlloc", Alloc);
|
||||
let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address);
|
||||
let free = sym!(library, c"cuMemFreeHost", Free);
|
||||
let mut ptr = std::ptr::null_mut();
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is
|
||||
// owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing).
|
||||
check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?;
|
||||
if ptr.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
let ptr = host_alloc(alloc, bytes)?;
|
||||
let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, free, bytes };
|
||||
// SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0.
|
||||
let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) });
|
||||
owner.publish(address, ptr, context)?;
|
||||
Ok(owner)
|
||||
}
|
||||
/// Map the fresh block to its device alias, check its alignment and zero it; a failure closes the owner.
|
||||
fn publish(&mut self, address: Address, ptr: *mut c_void, context: Option<&crate::Context<'_>>) -> Result<()> {
|
||||
// SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags
|
||||
// are 0.
|
||||
let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut self.alias, ptr, 0) });
|
||||
if let Err(primary) = op {
|
||||
if owner.close().is_err() {
|
||||
if let Some(c) = context {
|
||||
c.poison();
|
||||
c.retain_driver();
|
||||
}
|
||||
}
|
||||
self.close_or_poison(context);
|
||||
return Err(primary);
|
||||
}
|
||||
if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) {
|
||||
if owner.close().is_err() {
|
||||
if let Some(c) = context {
|
||||
c.poison();
|
||||
c.retain_driver();
|
||||
}
|
||||
}
|
||||
if self.alias == 0 || self.alias % 256 != 0 || self.host.is_none_or(|p| p % 256 != 0) {
|
||||
self.close_or_poison(context);
|
||||
return Err(Error::InvalidDriverValue("mapped-host-alignment"));
|
||||
}
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes
|
||||
// the block fully initialized before the first CPU read.
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet;
|
||||
// zeroing makes the block fully initialized before the first CPU read.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(ptr.cast::<u8>(), 0, bytes);
|
||||
std::ptr::write_bytes(ptr.cast::<u8>(), 0, self.bytes);
|
||||
} // initialized final whole owner; never resized.
|
||||
Ok(owner)
|
||||
Ok(())
|
||||
}
|
||||
fn close_or_poison(&mut self, context: Option<&crate::Context<'_>>) {
|
||||
if self.close().is_err()
|
||||
&& let Some(c) = context
|
||||
{
|
||||
c.poison();
|
||||
c.retain_driver();
|
||||
}
|
||||
}
|
||||
/// Literal qsa_state_zero on the caller's checked whole state spans.
|
||||
/// Context is entered by the owning state; legacy default stream exactly.
|
||||
@@ -104,8 +117,8 @@ impl MappedOwner {
|
||||
type Zero = unsafe extern "C" fn(u64, u8, usize, *mut c_void) -> i32;
|
||||
let library = self.library.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let zero = sym!(library, c"cuMemsetD8Async", Zero);
|
||||
// SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the legacy default
|
||||
// stream and the caller drains (Context::synchronize) before the span is read or freed.
|
||||
// SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the
|
||||
// legacy default stream and the caller drains (Context::synchronize) before the span is read or freed.
|
||||
check("cuMemsetD8Async", unsafe { zero(destination, 0, bytes, std::ptr::null_mut()) })
|
||||
}
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
@@ -124,9 +137,10 @@ impl MappedOwner {
|
||||
}
|
||||
pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> {
|
||||
let p = self.range(o, b.len())?;
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and
|
||||
// `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference
|
||||
// ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range.
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes,
|
||||
// checked_add) and `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as
|
||||
// usize on purpose: no Rust reference ever aliases memory the GPU may write. Caller obligation: no
|
||||
// enqueued GPU work reads or writes this range.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len());
|
||||
}
|
||||
@@ -135,8 +149,9 @@ impl MappedOwner {
|
||||
/// CPU access only after the real producer stream drained.
|
||||
pub(crate) fn read_into(&self, o: usize, b: &mut [u8]) -> Result<()> {
|
||||
let p = self.range(o, b.len())?;
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation and `b` is a distinct Rust slice. CPU reads happen only
|
||||
// after the producing stream was drained (documented at each call site); GPU-written bytes are plain integers.
|
||||
// SAFETY: range() proved [p, p+len) lies inside the live allocation and `b` is a distinct Rust slice. CPU
|
||||
// reads happen only after the producing stream was drained (documented at each call site); GPU-written
|
||||
// bytes are plain integers.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(p as *const u8, b.as_mut_ptr(), b.len());
|
||||
}
|
||||
@@ -144,8 +159,9 @@ impl MappedOwner {
|
||||
}
|
||||
pub(crate) fn close(&mut self) -> Result<()> {
|
||||
if let Some(p) = self.host {
|
||||
// SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every
|
||||
// stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing.
|
||||
// SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once;
|
||||
// callers drained every stream that references it before close(). On failure host stays Some so Drop
|
||||
// leaks the block rather than re-freeing.
|
||||
check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?;
|
||||
self.host = None;
|
||||
self.alias = 0;
|
||||
|
||||
@@ -14,6 +14,24 @@ pub struct OriginalMtpSkippedPrefix {
|
||||
lease: OriginalPromptLeaseIdentity,
|
||||
}
|
||||
impl OriginalMtpSkippedPrefix {
|
||||
/// `span` is the skipped `(start, logical_end)` cells and `prompt` the `(full_prompt_length, first_needed)` cutoff.
|
||||
fn new(
|
||||
physical: &MtpInt8Snapshot,
|
||||
generation: u64,
|
||||
span: (usize, usize),
|
||||
prompt: (usize, usize),
|
||||
lease: OriginalPromptLeaseIdentity,
|
||||
) -> Self {
|
||||
Self {
|
||||
physical: physical.clone(),
|
||||
generation,
|
||||
start: span.0,
|
||||
logical_end: span.1,
|
||||
full_prompt_length: prompt.0,
|
||||
first_needed: prompt.1,
|
||||
lease,
|
||||
}
|
||||
}
|
||||
pub fn logical_end(&self) -> usize {
|
||||
self.logical_end
|
||||
}
|
||||
@@ -68,6 +86,35 @@ impl MtpOriginalInt8<'_> {
|
||||
full_prompt_length: usize,
|
||||
) -> Result<Option<OriginalMtpSkippedPrefix>> {
|
||||
self.validate_snapshot(physical_prior)?;
|
||||
let end = self.check_skip_range(residual, cell0, full_prompt_length)?;
|
||||
let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64);
|
||||
let logical_start = self.logical_start(logical_prior, physical_prior, full_prompt_length, first_needed)?;
|
||||
if logical_start != cell0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
// All complete groups are skipped iff the last group's end<=cutoff. This
|
||||
// includes Original short remainder group; no individual-cell rounding.
|
||||
if end > first_needed {
|
||||
return Ok(None);
|
||||
}
|
||||
let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
|
||||
let lease = residual.lease_identity();
|
||||
let prompt = (full_prompt_length, first_needed);
|
||||
let result = OriginalMtpSkippedPrefix::new(physical_prior, generation, (cell0, end), prompt, lease);
|
||||
self.current = Some(physical_prior.clone());
|
||||
self.generation = generation;
|
||||
Ok(Some(result))
|
||||
}
|
||||
}
|
||||
|
||||
impl MtpOriginalInt8<'_> {
|
||||
/// The end cell of the chunk, after the context, row and prompt-length admission of a skip.
|
||||
fn check_skip_range(
|
||||
&self,
|
||||
residual: &OriginalDeviceResidual<'_, '_, '_>,
|
||||
cell0: usize,
|
||||
full_prompt_length: usize,
|
||||
) -> Result<usize> {
|
||||
if !residual.context_matches(self.context)
|
||||
|| residual.rows() == 0
|
||||
|| full_prompt_length > MTP_ORIGINAL_MAX_CELLS
|
||||
@@ -78,50 +125,34 @@ impl MtpOriginalInt8<'_> {
|
||||
if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64);
|
||||
let logical_start = if let Some(old) = logical_prior {
|
||||
old.validate_current(self)?;
|
||||
if old.full_prompt_length != full_prompt_length
|
||||
|| old.first_needed != first_needed
|
||||
|| !Rc::ptr_eq(&old.physical.0, &physical_prior.0)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
old.logical_end
|
||||
} else {
|
||||
Ok(end)
|
||||
}
|
||||
/// Where the logical cursor stands: the end of the logical prior, or of the physical prior without one.
|
||||
fn logical_start(
|
||||
&self,
|
||||
logical_prior: Option<&OriginalMtpSkippedPrefix>,
|
||||
physical_prior: &MtpInt8Snapshot,
|
||||
full_prompt_length: usize,
|
||||
first_needed: usize,
|
||||
) -> Result<usize> {
|
||||
let Some(old) = logical_prior else {
|
||||
if self.current.as_ref().is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if self.current.is_none() && physical_prior.0.end != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
physical_prior.0.end
|
||||
return Ok(physical_prior.0.end);
|
||||
};
|
||||
if logical_start != cell0 {
|
||||
old.validate_current(self)?;
|
||||
if old.full_prompt_length != full_prompt_length
|
||||
|| old.first_needed != first_needed
|
||||
|| !Rc::ptr_eq(&old.physical.0, &physical_prior.0)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
// All complete groups are skipped iff the last group's end<=cutoff. This
|
||||
// includes Original short remainder group; no individual-cell rounding.
|
||||
if end > first_needed {
|
||||
return Ok(None);
|
||||
}
|
||||
let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
|
||||
let result = OriginalMtpSkippedPrefix {
|
||||
physical: physical_prior.clone(),
|
||||
generation,
|
||||
start: cell0,
|
||||
logical_end: end,
|
||||
full_prompt_length,
|
||||
first_needed,
|
||||
lease: residual.lease_identity(),
|
||||
};
|
||||
self.current = Some(physical_prior.clone());
|
||||
self.generation = generation;
|
||||
Ok(Some(result))
|
||||
Ok(old.logical_end)
|
||||
}
|
||||
}
|
||||
|
||||
impl MtpOriginalInt8<'_> {
|
||||
/// Private affine transition used only by the literal captured drafter. Actual
|
||||
/// graph/window guards and successful drain, not these integers, authorize it.
|
||||
pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result<u64> {
|
||||
@@ -157,7 +188,29 @@ impl MtpOriginalInt8<'_> {
|
||||
if page0 > prior.0.pages.len() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
// The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back.
|
||||
let tail = self.read_tail_pages(page0, page1)?;
|
||||
let snapshot = self.seal_snapshot(prior, (page0, end), tail);
|
||||
self.current = Some(snapshot.clone());
|
||||
Ok(snapshot)
|
||||
}
|
||||
fn seal_snapshot(
|
||||
&self,
|
||||
prior: &MtpInt8Snapshot,
|
||||
(page0, end): (usize, usize),
|
||||
tail: Vec<Rc<Page>>,
|
||||
) -> MtpInt8Snapshot {
|
||||
MtpInt8Snapshot(Rc::new(Snapshot {
|
||||
origin: self.origin.clone(),
|
||||
pages: prior.0.pages.with_tail(page0, tail),
|
||||
end,
|
||||
// the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized
|
||||
// by `zero_bytes`
|
||||
checked: std::cell::Cell::new(true),
|
||||
}))
|
||||
}
|
||||
/// The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from
|
||||
/// `page0` on are read back.
|
||||
fn read_tail_pages(&mut self, page0: usize, page1: usize) -> Result<Vec<Rc<Page>>> {
|
||||
let mut tail = Vec::new();
|
||||
tail.try_reserve_exact(page1.saturating_sub(page0)).map_err(|_| Error::HostAllocation)?;
|
||||
for p in page0..page1 {
|
||||
@@ -168,14 +221,6 @@ impl MtpOriginalInt8<'_> {
|
||||
self.read_encoded_page(p, &mut runs)?;
|
||||
tail.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) }));
|
||||
}
|
||||
let snapshot = MtpInt8Snapshot(Rc::new(Snapshot {
|
||||
origin: self.origin.clone(),
|
||||
pages: prior.0.pages.with_tail(page0, tail),
|
||||
end,
|
||||
// the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes`
|
||||
checked: std::cell::Cell::new(true),
|
||||
}));
|
||||
self.current = Some(snapshot.clone());
|
||||
Ok(snapshot)
|
||||
Ok(tail)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user