import: Original-literal source-port snapshot (frozen 2026-10-12 06:36, uncompiled together, no GPU run)

Snapshot of target/stra169-direct-port-integration/source-port (without target/), now the tracked base for the full Strata Rust port.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:38:46 +02:00
co-authored by Claude Sonnet 5.5
parent 5a06a29b9a
commit 7f896a8bb8
875 changed files with 957768 additions and 472 deletions
Generated
+10
View File
@@ -1011,6 +1011,7 @@ version = "0.1.0"
name = "leleka-cuda-driver"
version = "0.1.0"
dependencies = [
"leleka-model-format",
"libc",
]
@@ -1021,6 +1022,13 @@ dependencies = [
"sha2",
]
[[package]]
name = "leleka-native-cpu-expert"
version = "0.1.0"
dependencies = [
"leleka-cuda-driver",
]
[[package]]
name = "leleka-quant-core"
version = "0.1.0"
@@ -1036,9 +1044,11 @@ dependencies = [
"leleka-backend-api",
"leleka-cuda-driver",
"leleka-model-format",
"leleka-native-cpu-expert",
"leleka-quant-core",
"leleka-tokenizer",
"rustix",
"serde_json",
"sha2",
]
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
[workspace.package]
+61
View File
@@ -0,0 +1,61 @@
# Mode17 MTP / NativeHead / Verifier source gaps
Read-only snapshot, 2026-10-12. Audit artifact only; no builds, tests, GPU,
Strata, model or daemon execution. Paths below are relative to this source-port
tree or to the imported `engine/strata/`. Root integration remains mutable.
This is a bounded core-path ledger, not a whole-project completion certificate.
## Actionable remaining boundaries
| Original source / function | Current Rust boundary | Required completion |
| --- | --- | --- |
| `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | `cuda-driver/src/original_mtp_loader.rs:278` always returns `MissingOperations`. `original_mtp_actor.rs:140` always returns operation-specific `Unselected`. Existing `mtp_original_full_*` implements genuine forward/graph owners, not an RT-directory loader. | Actual dense.txt/dense.bin/experts.bin loading, required-name check at original stage, real geometry/session/device capture, optional draft_vocab head gather, coupled setup and retained ring resume/idle linkage. Do not substitute configuration metadata for those owners. No actor reset exists upstream. |
| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. No concrete implementation of that combined verifier resource trait was found in `crates/`. | Implement retained whole 48-layer native window resources, actual projection/GR/GDN/QSA/MoE/head command recording, cache-slot/source lifetime and CPU pool/PCIe plan callbacks. Record all T graphs and real commit graph before `run`; existing scheduler alone is not the window producer. |
| `mtp.cpp` `draft/draft_first` and `verify.cpp` `run/commit/wait_commit`, used together by mode17 generation | `qwen_forward/original_spec_draft.rs` defines `OriginalDraftEngine` / `OriginalFirstDraftEngine`; `original_spec_controller.rs:20` defines `OriginalSpecEngine`. No concrete impl or production `OriginalSpecController::new` call was found. The real driver `OriginalMtpDrafter` and verifier receipt bridge already exist. | Bind the genuine verifier receipts, all-T residual catch-up, actual MTP ring/full seed, accepted-prefix replay/publication, adaptive work and BOTH checkpoint restoration to these traits; then select that controller in the actual serving owner. Preserve sampled history/counter and async commit event dependencies. |
| `include/strata/core/verify.hpp` `set_stage/set_next`; `src/core/verify.cpp:191,1054,1382,1412`; `core/on_device.hpp` | `OriginalVerifier` loops all 48 layers, has no next-stage owner or stage handoff fields. Context identity exists, but the unselected MTP actor cannot infer an actual current CUDA device ordinal. | Port stage bounds, mapped portable R+pending-bo+inject handoff, next-user CPU dispatch and last-stage head/sampling/final_R/commit forwarding. This is an absent multi-GPU mode17 leaf, not a single-device quality defect. |
| `verify.cpp:137,158,899,1323,1422` public release/diag/profile/logprob/logit APIs | Internal Rust bounded wait release, commit event and completed-row bridge are present. No equivalent public diagnostic/watchdog registry, profile report, window_logprobs or copy_logits API was found in the inspected Original Rust modules. | Expose the actual live verifier release/diagnostic owner; port literal GPU-stage stamps and completed logit/logprob readout (including LOGPOS_TOPK). Keep capture-only graphs inadmissible for readout. Do not call the existing internal release absent. |
## Existing source that must not be reported missing
- `native_head.rs` / `output_native.rs` retain unchanged head weights and real
mapped/fallback embedding, T1..8 head rows, request sampling/history and MTP
head-weight loans. `model-format/src/gguf_native_head.rs` has shard/architecture
and `strata-embd` override parsing. Production binding of these owners remains
part of the controller gap above, rather than an absent arithmetic leaf.
- NativeHead's earlier penalties-off empty-history refusal is already corrected
in current `native_head.rs:140..158`; do not reopen that stale finding.
- Verifier GDN/QSA accepted-prefix journals, stream release and async commit event
are real implementations; the missing piece is their complete window resource
adapter and serving use, not fake reimplementation of those owners.
- `original_session_state.rs` implements physical carve/primary RoPE registration
and release. This audit does not certify every optional `session.cpp` graph,
replay sweep or loop frontend as ported.
## Sealing is separately pending, not a new arithmetic gap
`native_head.rs` NATIVE/IQ/SAMPLER_ASSET and `original_verify.rs` ASSET/QSA_ASSET
are explicitly `None`; constructors refuse. MTP scalar/full leaves also check
unsealed compiled assets. Source-first authorization prohibits building here;
Root must seal actual recipes only after source closure. A filename/PTX placeholder
is not an executable or numerical acceptance result.
## Observed source pins
Original imported upstream: `d9ab8435f654c368c586340d490915f6addf56a3`.
SHA256:
- `core/mtp.cpp`: `71d8a93f6edc18916a5df9954cba372833f3cfd4efd952e2aedaed089a8d3fb4`
- `core/native_head.cpp`: `e4c7865002ad5a22b797c055c0780956469b8128b47bc03529e469a7c93e82c6`
- `core/verify.cpp`: `b5af6d947a4c2afbfd66db7a7dab0282e8fbf9ab8b58227f5e0f2ea502f8a0dd`
- `core/session.cpp`: `1e3a979614dae1910924e592ae1e2190afd8c6eb14438d7fdba5886ea034de18`
Rust pins below are the read-time snapshot, not a seal of Root's entire tree.
No runtime trace or hardware parity is inferred from these source reads.
- `original_mtp_actor.rs`: `803343141b4540fc1a6294d5f72ccea27d8f39f10b356f56285306f6862b3e8a`
- `original_mtp_loader.rs`: `40d89efb3da51bdfd854999d00828518869a43c352cfb716c612d612bd7e6267`
- `original_verify.rs`: `4fdf15d8d1070bccd4ae7617e2caf35137a605e9cea2843b36fa9a9f4023e85f`
- `original_verify_schedule.rs`: `ad8c2e457f66bd9f60a75b4ba7257684e13b76813c1e5a6815213414fb3b32e8`
- `native_head.rs`: `3f39fd575336a232d609c8a3f968f222b819e75603b36ccd0fbaf533d5d43a4d`
- `original_spec_controller.rs`: `04c50717e0f0cd34af9116c2e2977acb7c8b7145e674dd5c8880617d517f5df3`
- `original_spec_draft.rs`: `fce64b72b628201f1d3f61b4ff21a92b1d32f5f3352642fa9b4bc0d2561c8572`
Vendored Executable → Regular
View File
+3
View File
@@ -6,6 +6,9 @@ edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
leleka-model-format = { path = "../model-format" }
[features]
default = []
cuda-driver = []
@@ -0,0 +1,13 @@
// Original Strata fetch_blobs_kernel; arithmetic-free uint4 copy.
// engine/strata/src/kernels/cuda/verify_kernels.cu, pinned upstream provenance.
#include <cuda_runtime.h>
#include <cstdint>
extern "C" __global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n,
uint4* __restrict__ dst, long long per) {
const long long total = (long long) *n * per;
for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total;
i += (long long) gridDim.x * blockDim.x) {
const long long k = i / per, off = i - k * per;
dst[i] = ((const uint4*) src[k])[off];
}
}
Binary file not shown.
+499
View File
@@ -0,0 +1,499 @@
//! Closed optional asynchronous owned-copy ABI. Loaded only by the new API.
//! CUDA Driver 12.8 memory/stream/event ABI: registered host ranges remain owned
//! until a successfully recorded event completes; NOT_READY is not success.
use crate::{Error, Result};
#[derive(Clone, Copy)]
pub(crate) struct Stream(pub(crate) usize);
#[derive(Clone, Copy)]
pub(crate) struct Event(pub(crate) usize);
#[derive(Clone, Copy, Default)]
pub(crate) struct MappedCopyArguments {
pub(crate) source: u64,
pub(crate) count: u64,
pub(crate) destination: u64,
pub(crate) words: i64,
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod enabled {
use super::*;
use libc::{c_int, c_uint, c_void};
type Create = unsafe extern "C" fn(*mut *mut c_void, c_uint) -> c_int;
type Destroy = unsafe extern "C" fn(*mut c_void) -> c_int;
type Record = unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int;
type Query = unsafe extern "C" fn(*mut c_void) -> c_int;
type Copy = unsafe extern "C" fn(u64, *const c_void, usize, *mut c_void) -> c_int;
type Register = unsafe extern "C" fn(*mut c_void, usize, c_uint) -> c_int;
type Unregister = unsafe extern "C" fn(*mut c_void) -> c_int;
type Zero = unsafe extern "C" fn(u64, u8, usize) -> c_int;
struct Library(*mut c_void);
impl Drop for Library {
fn drop(&mut self) {
// SAFETY: one owned dlopen reference; pending owners retain this API.
unsafe {
libc::dlclose(self.0);
}
}
}
pub(crate) struct AsyncApi {
_library: Library,
stream_create: Create,
stream_destroy: Destroy,
event_create: Create,
event_destroy: Destroy,
event_record: Record,
event_query: Query,
event_wait: Query,
copy: Copy,
register: Register,
unregister: Unregister,
stream_wait: Query,
zero: Zero,
}
fn check(operation: &'static str, code: c_int) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
}
macro_rules! symbol {
($library:ident, $name:literal, $ty:ty) => {{
// SAFETY: fixed C name and live dlopen owner, never caller-selected.
let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("ASCII ABI name"),
));
}
// SAFETY: exact Linux64 fixed function signature for this symbol.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
}};
}
impl AsyncApi {
pub(crate) fn load() -> Result<Self> {
// SAFETY: fixed library name/flags; a second owned reference leaves
// the original synchronous loader and its symbol set untouched.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
let library = Library(handle);
Ok(Self {
stream_create: symbol!(library, c"cuStreamCreate", Create),
stream_destroy: symbol!(library, c"cuStreamDestroy_v2", Destroy),
event_create: symbol!(library, c"cuEventCreate", Create),
event_destroy: symbol!(library, c"cuEventDestroy_v2", Destroy),
event_record: symbol!(library, c"cuEventRecord", Record),
event_query: symbol!(library, c"cuEventQuery", Query),
event_wait: symbol!(library, c"cuEventSynchronize", Query),
copy: symbol!(library, c"cuMemcpyHtoDAsync_v2", Copy),
register: symbol!(library, c"cuMemHostRegister_v2", Register),
unregister: symbol!(library, c"cuMemHostUnregister", Unregister),
stream_wait: symbol!(library, c"cuStreamSynchronize", Query),
zero: symbol!(library, c"cuMemsetD8_v2", Zero),
_library: library,
})
}
pub(crate) fn create_stream(&self) -> Result<Stream> {
let mut handle = std::ptr::null_mut();
// SAFETY: valid out pointer, NON_BLOCKING=1, current owning Context.
check("cuStreamCreate", unsafe {
(self.stream_create)(&mut handle, 1)
})?;
if handle.is_null() {
return Err(Error::InvalidDriverValue("cuStreamCreate"));
}
Ok(Stream(handle as usize))
}
pub(crate) fn create_event(&self) -> Result<Event> {
let mut handle = std::ptr::null_mut();
// SAFETY: valid out pointer, DISABLE_TIMING=2, current Context.
check("cuEventCreate", unsafe {
(self.event_create)(&mut handle, 2)
})?;
if handle.is_null() {
return Err(Error::InvalidDriverValue("cuEventCreate"));
}
Ok(Event(handle as usize))
}
pub(crate) fn register(&self, bytes: &mut [u8]) -> Result<()> {
// SAFETY: nonempty whole uniquely owned initialized allocation,
// no resize/mutation/free until unregister after completion.
check("cuMemHostRegister_v2", unsafe {
(self.register)(bytes.as_mut_ptr().cast(), bytes.len(), 0)
})
}
pub(crate) fn unregister(&self, bytes: &mut [u8]) -> Result<()> {
// SAFETY: identical registered base retained by private owner.
check("cuMemHostUnregister", unsafe {
(self.unregister)(bytes.as_mut_ptr().cast())
})
}
pub(crate) fn copy(&self, destination: u64, bytes: &[u8], stream: Stream) -> Result<()> {
// SAFETY: whole actual admitted allocation, registered source and
// stream retained until genuine recorded event completion.
check("cuMemcpyHtoDAsync_v2", unsafe {
(self.copy)(
destination,
bytes.as_ptr().cast(),
bytes.len(),
stream.0 as *mut c_void,
)
})
}
pub(crate) fn synchronize_stream(&self, stream: Stream) -> Result<()> {
// SAFETY: the cache owns every source/destination until this fence;
// Stream(0) is CUDA's actual legacy default stream, not a fake owner.
check("cuStreamSynchronize", unsafe {
(self.stream_wait)(stream.0 as *mut c_void)
})
}
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
// SAFETY: the caller validates the genuine whole cache allocation.
check("cuMemsetD8_v2", unsafe {
(self.zero)(destination, 0, bytes)
})
}
pub(crate) fn record(&self, event: Event, stream: Stream) -> Result<()> {
// SAFETY: live owned handles in their actual current Context.
check("cuEventRecord", unsafe {
(self.event_record)(event.0 as *mut c_void, stream.0 as *mut c_void)
})
}
pub(crate) fn query(&self, event: Event) -> Result<bool> {
// SAFETY: event was genuinely recorded after the complete batch.
match unsafe { (self.event_query)(event.0 as *mut c_void) } {
0 => Ok(true),
600 => Ok(false), // CUDA_ERROR_NOT_READY, never publication.
code => Err(Error::Driver {
operation: "cuEventQuery",
code,
}),
}
}
pub(crate) fn wait(&self, event: Event) -> Result<()> {
// SAFETY: event and registered sources remain live for this wait.
check("cuEventSynchronize", unsafe {
(self.event_wait)(event.0 as *mut c_void)
})
}
pub(crate) fn destroy_event(&self, event: Event) -> Result<()> {
// SAFETY: only called before enqueue or after proven completion.
check("cuEventDestroy_v2", unsafe {
(self.event_destroy)(event.0 as *mut c_void)
})
}
pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> {
// SAFETY: only called before enqueue or after proven completion.
check("cuStreamDestroy_v2", unsafe {
(self.stream_destroy)(stream.0 as *mut c_void)
})
}
}
type Alias = unsafe extern "C" fn(*mut u64, *mut c_void, c_uint) -> c_int;
type LoadModule = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int;
type GetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int;
type Launch = unsafe extern "C" fn(
*mut c_void,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
*mut c_void,
*mut *mut c_void,
*mut *mut c_void,
) -> c_int;
pub(crate) struct MappedApi {
inner: AsyncApi,
alias: Alias,
module: *mut c_void,
function: *mut c_void,
unload: Destroy,
launch: Launch,
}
impl MappedApi {
pub(crate) fn load() -> Result<Self> {
let image = include_bytes!("../kernels/mapped_expert_copy.ptx");
if image.starts_with(b"UNSEALED") || image.last() != Some(&0) {
return Err(Error::InvalidDriverValue(
"mapped expert copy asset unsealed",
));
}
let inner = AsyncApi::load()?;
let library = &inner._library;
let alias = symbol!(library, c"cuMemHostGetDevicePointer_v2", Alias);
let load = symbol!(library, c"cuModuleLoadData", LoadModule);
let get = symbol!(library, c"cuModuleGetFunction", GetFunction);
let unload = symbol!(library, c"cuModuleUnload", Destroy);
let launch = symbol!(library, c"cuLaunchKernel", Launch);
let mut module = std::ptr::null_mut();
// SAFETY: fixed sealed terminated image; current actual Context.
check("cuModuleLoadData", unsafe {
load(&mut module, image.as_ptr().cast())
})?;
if module.is_null() {
return Err(Error::InvalidDriverValue("mapped module"));
}
let mut function = std::ptr::null_mut();
// SAFETY: real owned module and fixed original byte-only symbol.
let result = check("cuModuleGetFunction", unsafe {
get(&mut function, module, c"fetch_blobs_kernel".as_ptr())
});
if result.is_err() || function.is_null() {
// SAFETY: no launch occurred; release actual partial module.
let cleanup = check("cuModuleUnload", unsafe { unload(module) });
return crate::combine(
result.and_then(|()| Err(Error::InvalidDriverValue("mapped function"))),
cleanup,
);
}
Ok(Self {
inner,
alias,
module,
function,
unload,
launch,
})
}
pub(crate) fn register_bank(&self, bytes: &[u8]) -> Result<()> {
// SAFETY: immutable retained actual initialized Box; DEVICEMAP=2.
check("cuMemHostRegister_v2", unsafe {
(self.inner.register)(bytes.as_ptr().cast_mut().cast(), bytes.len(), 2)
})
}
pub(crate) fn bank_alias(&self, bytes: &[u8]) -> Result<u64> {
let mut address = 0u64;
// SAFETY: identical registered base retained by actual bank owner.
check("cuMemHostGetDevicePointer_v2", unsafe {
(self.alias)(&mut address, bytes.as_ptr().cast_mut().cast(), 0)
})?;
if address == 0
|| !address.is_multiple_of(16)
|| address.checked_add(bytes.len() as u64).is_none()
{
return Err(Error::InvalidDriverValue("mapped alias"));
}
Ok(address)
}
pub(crate) fn unregister_bank(&self, bytes: &[u8]) -> Result<()> {
// SAFETY: identical live registered base; all consumers drained.
check("cuMemHostUnregister", unsafe {
(self.inner.unregister)(bytes.as_ptr().cast_mut().cast())
})
}
pub(crate) fn copy_kernel(
&self,
actual: &mut MappedCopyArguments,
stream: Stream,
) -> Result<()> {
let mut args = [
(&mut actual.source as *mut u64).cast(),
(&mut actual.count as *mut u64).cast(),
(&mut actual.destination as *mut u64).cast(),
(&mut actual.words as *mut i64).cast(),
];
// SAFETY: fixed original ABI; parameter storage, sources/module and
// all whole destinations stay owned until the recorded event drains.
check("cuLaunchKernel", unsafe {
(self.launch)(
self.function,
48 * 8,
1,
1,
256,
1,
1,
0,
stream.0 as *mut c_void,
args.as_mut_ptr(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn stream(&self) -> Result<Stream> {
self.inner.create_stream()
}
pub(crate) fn event(&self) -> Result<Event> {
self.inner.create_event()
}
pub(crate) fn record(&self, e: Event, s: Stream) -> Result<()> {
self.inner.record(e, s)
}
pub(crate) fn query(&self, e: Event) -> Result<bool> {
self.inner.query(e)
}
pub(crate) fn wait(&self, e: Event) -> Result<()> {
self.inner.wait(e)
}
pub(crate) fn destroy_event(&self, e: Event) -> Result<()> {
self.inner.destroy_event(e)
}
pub(crate) fn destroy_stream(&self, s: Stream) -> Result<()> {
self.inner.destroy_stream(s)
}
pub(crate) fn close(&mut self) -> Result<()> {
if self.module.is_null() {
return Ok(());
}
// SAFETY: only called after all actual consumers/registrations drain.
check("cuModuleUnload", unsafe { (self.unload)(self.module) })?;
self.module = std::ptr::null_mut();
Ok(())
}
}
pub(crate) fn page_size() -> Result<usize> {
// SAFETY: read-only process page-size query; no mutation.
let n = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
let n = usize::try_from(n).map_err(|_| Error::InvalidSize)?;
if !n.is_power_of_two() {
return Err(Error::InvalidSize);
}
Ok(n)
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) use enabled::AsyncApi;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) struct AsyncApi;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
impl AsyncApi {
pub(crate) fn load() -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn create_stream(&self) -> Result<Stream> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn create_event(&self) -> Result<Event> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn register(&self, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn unregister(&self, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy(&self, _: u64, _: &[u8], stream: Stream) -> Result<()> {
let _ = stream.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn synchronize_stream(&self, _: Stream) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn zero(&self, _: u64, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn record(&self, event: Event, stream: Stream) -> Result<()> {
let _ = (event.0, stream.0);
Err(Error::UnsupportedPlatform)
}
pub(crate) fn query(&self, event: Event) -> Result<bool> {
let _ = event.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn wait(&self, event: Event) -> Result<()> {
let _ = event.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy_event(&self, event: Event) -> Result<()> {
let _ = event.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> {
let _ = stream.0;
Err(Error::UnsupportedPlatform)
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) use enabled::{MappedApi, page_size};
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) struct MappedApi;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
impl MappedApi {
pub(crate) fn load() -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn register_bank(&self, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn bank_alias(&self, _: &[u8]) -> Result<u64> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn unregister_bank(&self, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_kernel(&self, _: &mut MappedCopyArguments, _: Stream) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn stream(&self) -> Result<Stream> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn event(&self) -> Result<Event> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn record(&self, _: Event, _: Stream) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn query(&self, _: Event) -> Result<bool> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn wait(&self, _: Event) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy_event(&self, _: Event) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy_stream(&self, _: Stream) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn close(&mut self) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) fn page_size() -> Result<usize> {
Err(Error::UnsupportedPlatform)
}
+358
View File
@@ -0,0 +1,358 @@
//! Owner-thread confined asynchronous byte transport, not a source/finite/slot
//! certificate. Runtime alone maps these physical owners to genuine G/U/D roles.
use crate::{Context, DeviceBuffer, Error, Result, api, combine};
use std::rc::Rc;
pub const MAX_ASYNC_COPY_PAIRS: usize = 6;
pub type OwnedCopyPairs<'ctx> = [Option<(DeviceBuffer<'ctx>, Vec<u8>)>; MAX_ASYNC_COPY_PAIRS];
/// Actual registered staging and destination owners. No buffer is exposed while
/// pending; moving the owner cannot move a Vec allocation or a CUDA allocation.
pub struct PendingOwnedCopy<'ctx> {
context: &'ctx Context<'ctx>,
pairs: OwnedCopyPairs<'ctx>,
count: usize,
api: Option<Rc<api::AsyncApi>>,
stream: Option<api::Stream>,
event: Option<api::Event>,
registered: [bool; MAX_ASYNC_COPY_PAIRS],
attempted: bool,
recorded: bool,
completed: bool,
}
/// Only a real successful query/wait followed by cleanup can create this owner.
/// Completion proves copied bytes only, never their source, role or finiteness.
pub struct CompletedOwnedCopy<'ctx> {
pairs: OwnedCopyPairs<'ctx>,
count: usize,
}
pub enum OwnedCopyPoll<'ctx> {
Pending(PendingOwnedCopy<'ctx>),
Complete(CompletedOwnedCopy<'ctx>),
}
impl<'ctx> CompletedOwnedCopy<'ctx> {
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
/// Consume the opaque receipt; all actual owners retain original order.
pub fn into_pairs(self) -> OwnedCopyPairs<'ctx> {
self.pairs
}
}
fn admit_count_and_capacities(capacities: &[(usize, usize)], budget: usize) -> Result<()> {
if !(1..=MAX_ASYNC_COPY_PAIRS).contains(&capacities.len()) {
return Err(Error::InvalidSize);
}
let mut total = 0usize;
for &(len, capacity) in capacities {
crate::valid_size(len)?;
if capacity < len {
return Err(Error::InvalidSize);
}
total = total.checked_add(capacity).ok_or(Error::BudgetExceeded)?;
}
if total > budget {
return Err(Error::BudgetExceeded);
}
Ok(())
}
fn close_input_pairs(pairs: Vec<(DeviceBuffer<'_>, Vec<u8>)>) -> Result<()> {
let mut result = Ok(());
for (destination, source) in pairs {
result = combine(result, destination.release());
drop(source);
}
result
}
impl Context<'_> {
/// Start a bounded whole-owner batch on its own NON_BLOCKING stream.
/// The complete owned host capacities must fit this Context's byte budget;
/// callers additionally charge their actual host and slot policy budgets.
/// Host registration failure is an error, never pageable-copy fallback.
pub fn copy_owned_batch_async<'ctx>(
&'ctx self,
pairs: Vec<(DeviceBuffer<'ctx>, Vec<u8>)>,
) -> Result<PendingOwnedCopy<'ctx>> {
let admitted = (|| -> Result<()> {
if !(1..=MAX_ASYNC_COPY_PAIRS).contains(&pairs.len()) {
return Err(Error::InvalidSize);
}
let mut capacities = [(0usize, 0usize); MAX_ASYNC_COPY_PAIRS];
for (i, (destination, source)) in pairs.iter().enumerate() {
if !std::ptr::eq(destination.context, self) {
return Err(Error::ContextMismatch);
}
if destination.bytes != source.len() {
return Err(Error::ShapeMismatch {
expected: destination.bytes,
actual: source.len(),
});
}
let handle = destination.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_extent(destination.bytes)?;
capacities[i] = (source.len(), source.capacity());
for (prior, _) in &pairs[..i] {
let prior_handle = prior.handle.ok_or(Error::ContextPoisoned)?;
if handle.overlaps(destination.bytes, prior_handle, prior.bytes) {
return Err(Error::OutputAliasesInput);
}
}
}
admit_count_and_capacities(&capacities[..pairs.len()], self.budget)?;
if self.is_poisoned() {
return Err(Error::ContextPoisoned);
}
Ok(())
})();
if let Err(primary) = admitted {
return combine(Err(primary), close_input_pairs(pairs));
}
// Resolve all optional ABI symbols before any stream/register/copy.
let api = match api::AsyncApi::load() {
Ok(api) => Rc::new(api),
Err(primary) => return combine(Err(primary), close_input_pairs(pairs)),
};
let count = pairs.len();
let mut pending = PendingOwnedCopy {
context: self,
pairs: std::array::from_fn(|_| None),
count,
api: Some(api),
stream: None,
event: None,
registered: [false; MAX_ASYNC_COPY_PAIRS],
attempted: false,
recorded: false,
completed: false,
};
for (i, pair) in pairs.into_iter().enumerate() {
pending.pairs[i] = Some(pair);
}
let guard = self.enter()?;
let launch = pending.enqueue();
let result = combine(launch, guard.finish());
if let Err(primary) = result {
// Any native failure may report older asynchronous work. No pending
// bytes or registrations are reclaimable under uncertain completion.
if pending.attempted || self.is_poisoned() {
self.poisoned.set(true);
pending.retain_uncertain();
return Err(primary);
}
// No copy has been attempted: release every successful partial
// registration/event/stream, preserving the initial native error.
let cleanup = pending.drain_and_close();
return combine(Err(primary), cleanup);
}
Ok(pending)
}
}
impl<'ctx> PendingOwnedCopy<'ctx> {
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
fn enqueue(&mut self) -> Result<()> {
let api = self.api.as_ref().expect("private live ABI");
self.stream = Some(api.create_stream()?);
self.event = Some(api.create_event()?);
for i in 0..self.count {
let (_, source) = self.pairs[i].as_mut().expect("admitted whole pair");
api.register(source)?;
self.registered[i] = true;
}
let stream = self.stream.expect("actual created stream");
for i in 0..self.count {
let (destination, source) = self.pairs[i].as_ref().expect("admitted whole pair");
self.attempted = true;
api.copy(
destination
.handle
.expect("admitted live allocation")
.qwen_address(),
source,
stream,
)?;
}
api.record(self.event.expect("actual created event"), stream)?;
self.recorded = true;
Ok(())
}
fn observe(&mut self, wait: bool) -> Result<bool> {
if self.completed {
return Ok(true);
}
if !self.recorded || self.context.is_poisoned() {
// A copy that was attempted and is not known complete may still be reading the
// registered host Vec and writing the destination. Under poison nothing can be
// waited for, so every owner, registration, stream/event handle and the ABI are
// retained (not dropped) before the primary error is returned; `drain_and_close`
// and `Drop` then see an emptied owner and return without freeing anything.
if self.attempted {
self.retain_uncertain();
}
return Err(Error::ContextPoisoned);
}
let guard = match self.context.enter() {
Ok(guard) => guard,
Err(primary) => {
self.context.poisoned.set(true);
self.retain_uncertain();
return Err(primary);
}
};
let api = self.api.as_ref().expect("private live ABI");
let event = self.event.expect("actual recorded event");
let observed = if wait {
api.wait(event).map(|()| true)
} else {
api.query(event)
};
let observed = combine(observed, guard.finish());
match observed {
Ok(true) => {
self.completed = true;
Ok(true)
}
Ok(false) => Ok(false),
Err(primary) => {
self.context.poisoned.set(true);
self.retain_uncertain();
Err(primary)
}
}
}
/// Poll actual CUDA event; the caller receives this same pending owner when
/// NOT_READY, and cannot publish/read its destinations in that branch.
pub fn poll(mut self) -> Result<OwnedCopyPoll<'ctx>> {
if self.observe(false)? {
self.complete().map(OwnedCopyPoll::Complete)
} else {
Ok(OwnedCopyPoll::Pending(self))
}
}
pub fn wait(mut self) -> Result<CompletedOwnedCopy<'ctx>> {
self.observe(true)?;
self.complete()
}
fn complete(mut self) -> Result<CompletedOwnedCopy<'ctx>> {
if !self.completed {
return Err(Error::ContextPoisoned);
}
self.cleanup_transport()?;
let pairs = std::mem::replace(&mut self.pairs, std::array::from_fn(|_| None));
Ok(CompletedOwnedCopy {
pairs,
count: self.count,
})
}
/// Cancellation/draining discards the unpublished destinations only after
/// genuine completion; first failure is preserved with all cleanup attempts.
pub fn close(mut self) -> Result<()> {
self.drain_and_close()
}
fn cleanup_transport(&mut self) -> Result<()> {
if self.api.is_none() {
return Ok(());
}
if self.context.is_poisoned() {
self.retain_uncertain();
return Err(Error::ContextPoisoned);
}
let guard = match self.context.enter() {
Ok(guard) => guard,
Err(error) => {
self.context.poisoned.set(true);
self.retain_uncertain();
return Err(error);
}
};
let api = self.api.as_ref().expect("private live ABI");
let mut result = Ok(());
// Completed work no longer references host storage. Still attempt every
// unregister/destroy on partial cleanup failure, retaining failed owners.
for i in 0..self.count {
if self.registered[i] {
let (_, source) = self.pairs[i].as_mut().expect("registered owner retained");
let release = api.unregister(source);
if release.is_ok() {
self.registered[i] = false;
}
result = combine(result, release);
}
}
if let Some(event) = self.event {
let release = api.destroy_event(event);
if release.is_ok() {
self.event = None;
}
result = combine(result, release);
}
if let Some(stream) = self.stream {
let release = api.destroy_stream(stream);
if release.is_ok() {
self.stream = None;
}
result = combine(result, release);
}
result = combine(result, guard.finish());
if result.is_err() {
self.context.poisoned.set(true);
self.retain_uncertain();
} else {
self.api.take();
}
result
}
fn retain_uncertain(&mut self) {
for pair in &mut self.pairs {
if let Some(pair) = pair.take() {
std::mem::forget(pair);
}
}
if let Some(api) = self.api.take() {
std::mem::forget(api);
}
// These opaque handles have no automatic destructors. On uncertain
// completion keep the original ABI loaded too, as existing driver does.
let stream = self.stream.take();
let event = self.event.take();
if stream.is_some() || event.is_some() || self.attempted {
std::mem::forget(Rc::clone(&self.context.driver.api));
}
self.registered.fill(false);
self.recorded = false;
}
fn drain_and_close(&mut self) -> Result<()> {
if self.api.is_none() {
return Ok(());
}
if self.attempted && !self.completed {
self.observe(true)?;
}
let transport = self.cleanup_transport();
let mut release = Ok(());
for pair in &mut self.pairs {
if let Some((destination, source)) = pair.take() {
release = combine(release, destination.release());
drop(source);
}
}
combine(transport, release)
}
}
impl Drop for PendingOwnedCopy<'_> {
fn drop(&mut self) {
let _ = self.drain_and_close();
}
}
#[cfg(test)]
#[path = "async_owned_copy_gpu.rs"]
mod gpu;
@@ -0,0 +1,216 @@
//! ONE changed asynchronous transport proof, not expert/model/CPU-overlap proof.
use super::*;
#[test]
fn bounded_host_capacity_admission_has_no_completion_shortcut() {
assert!(matches!(
admit_count_and_capacities(&[], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, 1); 7], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, 0)], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(0, 0)], 100),
Err(Error::InvalidSize)
));
assert!(matches!(
admit_count_and_capacities(&[(1, usize::MAX), (1, 1)], usize::MAX),
Err(Error::BudgetExceeded)
));
assert!(matches!(
admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 47),
Err(Error::BudgetExceeded)
));
assert!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 48).is_ok());
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[test]
#[ignore = "Root-only genuine registered triplet event transport proof"]
fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(),
Ok("yes")
);
let driver = crate::Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(16 * 1024 * 1024).unwrap();
let foreign = device.create_context(16 * 1024 * 1024).unwrap();
let mut compared = 0usize;
let mut receipts = 0usize;
let mut refusals = 0usize;
let result = (|| -> Result<()> {
let sizes = [262_144usize, 524_288, 786_432];
for round in 0..3u32 {
let mut pairs = Vec::new();
pairs
.try_reserve_exact(3)
.map_err(|_| Error::HostAllocation)?;
let mut expected = Vec::new();
expected
.try_reserve_exact(3)
.map_err(|_| Error::HostAllocation)?;
let mut pointers = [0usize; 3];
for (role, bytes) in sizes.into_iter().enumerate() {
let mut source = Vec::new();
source
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
for i in 0..bytes / 4 {
let word = if round == 2 {
[0, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0042][i % 6]
} else {
(i as u32)
.wrapping_mul(0x9e37_79b9)
.wrapping_add(round + role as u32)
};
source.extend_from_slice(&word.to_le_bytes());
}
// Original borrowed synchronous copy FIRST on the same complete
// bytes; no candidate-derived expected outputs or ready flags.
let mut original = context.allocate(bytes)?;
original.copy_from(&source)?;
let reference = original.copy_to_owned(bytes)?;
original.release()?;
if reference != source {
return Err(Error::InvalidDriverValue("original byte reference"));
}
expected.push(reference);
pointers[role] = source.as_ptr() as usize;
pairs.push((context.allocate(bytes)?, source));
}
let pending = context.copy_owned_batch_async(pairs)?;
let receipt = if round == 1 {
match pending.poll()? {
OwnedCopyPoll::Complete(receipt) => receipt,
OwnedCopyPoll::Pending(pending) => pending.wait()?,
}
} else {
pending.wait()?
};
if receipt.len() != 3 {
return Err(Error::InvalidDriverValue("receipt pair count"));
}
receipts += 1;
let mut completion_error = Ok(());
for (i, pair) in receipt.into_pairs().into_iter().enumerate() {
if let Some((destination, source)) = pair {
let observed = destination.copy_to_owned(sizes[i]);
if source.as_ptr() as usize != pointers[i] {
completion_error = combine(
completion_error,
Err(Error::InvalidDriverValue("staging ownership")),
);
}
match observed {
Ok(bytes) if bytes == expected[i] && source == expected[i] => {
compared += bytes.len()
}
Ok(_) => {
completion_error = combine(
completion_error,
Err(Error::InvalidDriverValue("async byte equality")),
)
}
Err(error) => completion_error = combine(completion_error, Err(error)),
}
completion_error = combine(completion_error, destination.release());
}
}
completion_error?;
}
// Genuine foreign allocation and exact whole-byte shape admission.
let invalid =
context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]);
if !matches!(invalid, Err(Error::ContextMismatch)) {
return Err(Error::InvalidDriverValue("foreign refusal"));
}
drop(invalid);
refusals += 1;
let invalid =
context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]);
if !matches!(
invalid,
Err(Error::ShapeMismatch {
expected: 4096,
actual: 4095
})
) {
return Err(Error::InvalidDriverValue("extent refusal"));
}
drop(invalid);
refusals += 1;
// Real abandoned pending owner explicitly drains without publication.
context
.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?
.close()?;
Ok(())
})();
let sync = context.synchronize();
let foreign_sync = foreign.synchronize();
let allocated = context.allocated_bytes();
let foreign_allocated = foreign.allocated_bytes();
let foreign_close = foreign.close();
let close = context.close();
// All owned cleanup is attempted before any numerical/assertion gate.
assert!(result.is_ok(), "transport {result:?}");
assert!(sync.is_ok() && foreign_sync.is_ok() && foreign_close.is_ok() && close.is_ok());
assert_eq!((allocated, foreign_allocated), (0, 0));
assert_eq!((compared, receipts, refusals), (4_718_592, 3, 2));
println!(
"owned_async_copy original_first=true complete_bytes={compared} receipts={receipts} refusals={refusals} abandoned_pending_drained=true allocated=0 overlap_not_measured=true injected_cuda_faults=false"
);
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[test]
#[ignore = "Root-only: poison while a registered copy is pending must retain, not free"]
fn poison_while_pending_retains_registered_owners_and_preserves_the_primary_error() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(),
Ok("yes")
);
let driver = crate::Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(16 * 1024 * 1024).unwrap();
let bytes = 262_144usize;
let mut source = Vec::new();
source.try_reserve_exact(bytes).unwrap();
source.resize(bytes, 0x5a);
let before = context.allocated_bytes();
let pairs = vec![(context.allocate(bytes).unwrap(), source)];
let charged = context.allocated_bytes();
assert_eq!(charged, before + bytes);
let mut pending = context.copy_owned_batch_async(pairs).unwrap();
assert!(pending.attempted && pending.recorded);
// Another failure poisons the Context while this registered copy is still outstanding.
context.poisoned.set(true);
// The primary error is preserved ...
assert!(matches!(pending.observe(true), Err(Error::ContextPoisoned)));
// ... and ownership has moved to retention BEFORE Drop runs: no destination, host Vec,
// registration, stream, event or ABI handle is left for drain_and_close()/Drop to free.
assert!(pending.pairs.iter().all(Option::is_none));
assert!(pending.api.is_none());
assert!(pending.stream.is_none());
assert!(pending.event.is_none());
assert!(pending.registered.iter().all(|registered| !registered));
assert!(!pending.recorded);
// The retained destination stays charged: forgotten buffers are never credited back.
assert_eq!(context.allocated_bytes(), charged);
drop(pending);
assert_eq!(context.allocated_bytes(), charged);
}
+267
View File
@@ -0,0 +1,267 @@
//! First real chunk primitive: one launch over independent GR token columns.
//! Numerical experiment only; no production asset admission or session commit.
use super::*;
fn batch_layout(operation: Operation, tokens: usize) -> Result<qwen_ffi::Layout> {
if !(1..=64).contains(&tokens)
|| !matches!(
operation,
Operation::Norm
| Operation::LayerGate
| Operation::FinalGate
| Operation::InjectResidual
)
{
return Err(Error::InvalidQwenShape);
}
let mut layout = operation.layout();
for i in 0..layout.count {
if operation == Operation::Norm && i == 1 {
continue;
}
layout.bytes[i] = layout.bytes[i]
.checked_mul(tokens)
.ok_or(Error::InvalidQwenShape)?;
}
if operation != Operation::Norm {
layout.columns = layout
.columns
.checked_mul(tokens as u32)
.ok_or(Error::InvalidQwenShape)?;
}
layout.grid_y = tokens as u32;
Ok(layout)
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
mod installed {
use super::*;
fn slot(operation: Operation) -> Result<usize> {
match operation {
Operation::LayerGate => Ok(0),
Operation::FinalGate => Ok(1),
Operation::InjectResidual => Ok(2),
Operation::Norm => Ok(3),
_ => Err(Error::InvalidQwenShape),
}
}
pub struct GrBatchPreview<'ctx> {
context: &'ctx Context<'ctx>,
module: Option<ffi::ModuleHandle>,
functions: [ffi::FunctionHandle; 4],
launch_attempts: std::cell::Cell<usize>,
}
impl<'ctx> GrBatchPreview<'ctx> {
pub fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.poisoned() {
return Err(Error::ContextPoisoned);
}
let guard = context.enter()?;
let module = match context.driver.api.load_gr_batch_preview_module() {
Ok(v) => v,
Err(e) => return combine(Err(e), guard.finish()),
};
let result = (|| {
Ok([
context
.driver
.api
.qwen_function(module, Operation::LayerGate)?,
context
.driver
.api
.qwen_function(module, Operation::FinalGate)?,
context
.driver
.api
.qwen_function(module, Operation::InjectResidual)?,
context.driver.api.qwen_function(module, Operation::Norm)?,
])
})();
let functions = match result {
Ok(v) => v,
Err(e) => {
let cleanup = context.driver.api.unload(module);
if cleanup.is_err() {
context.poison();
context.retain_driver();
}
return combine(combine(Err(e), cleanup), guard.finish());
}
};
if let Err(e) = guard.finish() {
context.poison();
context.retain_driver();
return Err(e);
}
Ok(Self {
context,
module: Some(module),
functions,
launch_attempts: std::cell::Cell::new(0),
})
}
pub fn inject(
&self,
tokens: usize,
residual: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
inject: &DeviceBuffer<'_>,
candidate: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.run(
Operation::InjectResidual,
tokens,
&[residual, output, inject, candidate],
)
}
pub(super) fn run(
&self,
operation: Operation,
tokens: usize,
buffers: &[&DeviceBuffer<'_>],
) -> Result<()> {
self.run_with_epsilon(operation, tokens, buffers, 0.)
}
pub(super) fn run_with_epsilon(
&self,
operation: Operation,
tokens: usize,
buffers: &[&DeviceBuffer<'_>],
epsilon: f32,
) -> Result<()> {
if !epsilon.is_finite() || epsilon < 0. {
return Err(Error::InvalidQwenShape);
}
let context = self.context;
if context.poisoned() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
let layout = batch_layout(operation, tokens)?;
if buffers.len() != layout.count {
return Err(Error::InvalidQwenShape);
}
let first = buffers[0].handle.ok_or(Error::ContextPoisoned)?;
let mut handles = [first; 9];
let mut bytes = [0; 9];
for (i, b) in buffers.iter().enumerate() {
if !std::ptr::eq(context, b.context) {
return Err(Error::ContextMismatch);
}
handles[i] = b.handle.ok_or(Error::ContextPoisoned)?;
bytes[i] = b.bytes;
}
ranges_layout(operation, layout, handles, bytes, false)?;
if context.allocated_bytes() > context.budget_bytes() {
return Err(Error::BudgetExceeded);
}
let kernel = self.functions[slot(operation)?];
let mut arguments = Arguments::with_layout(operation, layout, handles, epsilon);
let guard = context.enter()?;
let launch = context
.driver
.api
.launch_qwen(kernel, operation, &mut arguments);
self.launch_attempts.set(self.launch_attempts.get() + 1);
let sync = context.driver.api.synchronize();
if sync.is_err() {
context.poison();
context.retain_driver();
}
let pop = guard.finish();
if sync.is_err() || pop.is_err() {
std::mem::forget(arguments);
}
combine(combine(launch, sync), pop)
}
pub fn close(mut self) -> Result<()> {
self.unload()
}
fn unload(&mut self) -> Result<()> {
let Some(module) = self.module.take() else {
return Ok(());
};
if self.context.poisoned() {
self.context.retain_driver();
return Err(Error::ContextPoisoned);
}
let guard = match self.context.enter() {
Ok(v) => v,
Err(e) => {
self.context.poison();
self.context.retain_driver();
return Err(e);
}
};
let cleanup = self.context.driver.api.unload(module);
if cleanup.is_err() {
self.context.poison();
self.context.retain_driver();
}
combine(cleanup, guard.finish())
}
}
impl Drop for GrBatchPreview<'_> {
fn drop(&mut self) {
let _ = self.unload();
}
}
}
impl Context<'_> {
pub fn gr_batch_inject_residual_f32(
&self,
tokens: usize,
residual: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
inject: &DeviceBuffer<'_>,
candidate: &mut DeviceBuffer<'_>,
) -> Result<()> {
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
{
let dispatcher = installed::GrBatchPreview::new(self)?;
let result = dispatcher.run(
Operation::InjectResidual,
tokens,
&[residual, output, inject, candidate],
);
let cleanup = dispatcher.close();
combine(result, cleanup)
}
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver")))]
{
let _ = (tokens, residual, output, inject, candidate);
Err(Error::UnsupportedPlatform)
}
}
}
// Private ignored derivative proof entry; shared gamma, per-token R/output.
impl Context<'_> {
pub fn gr_batch_norm_f32(
&self,
tokens: usize,
residual: &DeviceBuffer<'_>,
gamma: &DeviceBuffer<'_>,
epsilon: f32,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
{
let dispatcher = installed::GrBatchPreview::new(self)?;
let result = dispatcher.run_with_epsilon(
Operation::Norm,
tokens,
&[residual, gamma, output],
epsilon,
);
combine(result, dispatcher.close())
}
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver")))]
{
let _ = (tokens, residual, gamma, epsilon, output);
Err(Error::UnsupportedPlatform)
}
}
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use installed::GrBatchPreview as GrBatchModule;
File diff suppressed because it is too large Load Diff
+125
View File
@@ -0,0 +1,125 @@
//! Stage-local Option-B GEMM loan of the ONE model-lifetime native workspace.
//! No vendor owner, allocation, synchronization or row authority is minted here.
use crate::{DeviceBuffer, Error, GdnGemm, GdnStream, GemmShape, NativeBatchWorkspace, Result};
const DEQUANT_BYTES: usize = 10240 * 2560 * 2;
/// The exclusive workspace loan remains borrowed until the producer's complete
/// same-stream prefix drains. It cannot be stored in a model-persistent Box.
pub struct NativeGdnGemm<'loan, 'ctx> {
workspace: &'loan mut NativeBatchWorkspace<'ctx>,
stream: GdnStream,
}
impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
pub(crate) fn new(workspace: &'loan mut NativeBatchWorkspace<'ctx>) -> Result<Self> {
let stream = workspace.blas()?.stream();
if stream == 0 {
return Err(Error::InvalidDriverValue("native GDN shared stream"));
}
Ok(Self {
workspace,
stream: GdnStream::from_raw(stream),
})
}
fn enqueue(
&self,
bf16: bool,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
let context = self.workspace.context_for_gdn();
self.workspace.validate_context(context)?;
if !(1..=64).contains(&shape.tokens) {
return Err(Error::InvalidQwenShape);
}
let ordinary = matches!(
(shape.rows, shape.depth),
(10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)
);
if bf16 {
let interleaved = (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96)
&& matches!(shape.y_offset, 0 | 48);
let moe = matches!((shape.rows, shape.depth), (512, 2560) | (1, 2560))
&& shape.ldy == shape.rows
&& shape.y_offset == 0;
if (!interleaved && !moe) || (shape.beta != 0.0 && shape.beta != 1.0) {
return Err(Error::InvalidQwenShape);
}
} else if !ordinary || shape.ldy != shape.rows || shape.y_offset != 0 || shape.beta != 0.0 {
return Err(Error::InvalidQwenShape);
}
let input_bytes = shape.tokens * shape.depth * 2;
let matrix_bytes = shape.rows * shape.depth * 2;
let output_bytes = shape.tokens * shape.ldy * 4;
if x.bytes != input_bytes
|| y.bytes != output_bytes
|| (bf16 && w.bytes != matrix_bytes)
|| (!bf16
&& w.bytes != matrix_bytes
&& w.bytes != DEQUANT_BYTES
&& !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640))
&& w.bytes == 3_276_800))
{
return Err(Error::InvalidQwenShape);
}
// Validate WHOLE actual owners, including the unused dequantized tail.
// Only the fixed matrix prefix is consumed by the original GEMM.
for buffer in [x, w, y] {
if !std::ptr::eq(buffer.context, context) {
return Err(Error::ContextMismatch);
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_projection_extent(buffer.bytes, 4)?;
self.workspace.reject_alias(handle, buffer.bytes)?;
}
let xh = x.handle.ok_or(Error::ContextPoisoned)?;
let wh = w.handle.ok_or(Error::ContextPoisoned)?;
let yh = y.handle.ok_or(Error::ContextPoisoned)?;
if xh.overlaps(x.bytes, wh, w.bytes)
|| xh.overlaps(x.bytes, yh, y.bytes)
|| wh.overlaps(w.bytes, yh, y.bytes)
{
return Err(Error::OutputAliasesInput);
}
self.workspace.blas()?.gemm_gdn(
bf16,
xh,
wh,
yh,
shape.tokens as i32,
shape.rows as i32,
shape.depth as i32,
shape.ldy as i32,
shape.y_offset,
&shape.beta,
)
}
}
impl GdnGemm for NativeGdnGemm<'_, '_> {
fn stream(&self) -> GdnStream {
self.stream
}
fn f16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.enqueue(false, x, w, y, shape)
}
fn bf16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.enqueue(true, x, w, y, shape)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,720 @@
//! Changed GDN row transport only. The original scalar calls finish FIRST for
//! every comparison. Synthetic data does not certify a binding, row, layer or
//! model publication; it proves queued bytes, ordered refusal and cleanup.
use super::*;
use crate::Driver;
const ENABLE: &str = "LELEKA_STRA169_RUN_GDN_ROW_QUEUE";
const CHANNELS: usize = 10_240;
const HISTORY: usize = 30_720;
const STATE: usize = 786_432;
const VALUES: usize = 6_144;
const EPSILON: f32 = 1e-6;
#[derive(Default, Debug)]
struct Report {
words: usize,
differences: usize,
refusals: usize,
guards: usize,
rows: usize,
}
fn bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn upload<'a>(context: &'a Context<'_>, values: &[f32]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(values.len() * 4)?;
match buffer.copy_from(&bytes(values)) {
Ok(()) => Ok(buffer),
Err(primary) => combine(Err(primary), buffer.release()).map(|()| unreachable!()),
}
}
fn blank<'a>(context: &'a Context<'_>, words: usize) -> Result<DeviceBuffer<'a>> {
upload(context, &vec![0.0; words])
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut out = vec![0; buffer.len()];
buffer.copy_to(&mut out)?;
Ok(out)
}
fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec<f32> {
(0..count)
.map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset)
.collect()
}
/// One complete row of inputs and outputs, all whole real owners.
struct Row<'a> {
history: DeviceBuffer<'a>,
qkv: DeviceBuffer<'a>,
weights: DeviceBuffer<'a>,
alpha: DeviceBuffer<'a>,
beta_raw: DeviceBuffer<'a>,
dt: DeviceBuffer<'a>,
a: DeviceBuffer<'a>,
gamma: DeviceBuffer<'a>,
z: DeviceBuffer<'a>,
state: DeviceBuffer<'a>,
next_history: DeviceBuffer<'a>,
raw: DeviceBuffer<'a>,
h: DeviceBuffer<'a>,
qk: DeviceBuffer<'a>,
sigmoid: DeviceBuffer<'a>,
gate: DeviceBuffer<'a>,
next_state: DeviceBuffer<'a>,
readout: DeviceBuffer<'a>,
normalized: DeviceBuffer<'a>,
}
#[derive(Clone, Copy, Default)]
struct Poison {
alpha: bool,
conv_weights: bool,
state: bool,
z: bool,
}
impl<'a> Row<'a> {
fn new(context: &'a Context<'_>, salt: usize, poison: Poison) -> Result<Self> {
let nan = f32::from_bits(0x7fc0_0001);
let mut alpha = pattern(48, salt, 17, 1.0 / 32.0, 0.25);
if poison.alpha {
alpha[47] = nan;
}
let mut weights = (0..4 * CHANNELS)
.map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4])
.collect::<Vec<f32>>();
if poison.conv_weights {
weights[4 * CHANNELS - 1] = nan;
}
let mut state = pattern(STATE, salt, 19, 1.0 / 512.0, 0.0175);
if poison.state {
state[STATE - 1] = nan;
}
let mut z = pattern(VALUES, salt + 2, 23, 1.0 / 64.0, 0.17);
if poison.z {
z[VALUES - 1] = nan;
}
Ok(Self {
history: upload(context, &pattern(HISTORY, salt, 13, 1.0 / 256.0, 0.0234))?,
qkv: upload(context, &pattern(CHANNELS, salt + 1, 29, 1.0 / 64.0, 0.21))?,
weights: upload(context, &weights)?,
alpha: upload(context, &alpha)?,
beta_raw: upload(context, &pattern(48, salt + 3, 11, 1.0 / 16.0, 0.3))?,
dt: upload(context, &[-2.0; 48])?,
a: upload(context, &[1.0; 48])?,
gamma: upload(context, &[1.0; 128])?,
z: upload(context, &z)?,
state: upload(context, &state)?,
next_history: blank(context, HISTORY)?,
raw: blank(context, CHANNELS)?,
h: blank(context, CHANNELS)?,
// The retained QK slot keeps a preset positive-zero tail.
qk: blank(context, CHANNELS)?,
sigmoid: blank(context, 48)?,
gate: blank(context, 48)?,
next_state: blank(context, STATE)?,
readout: blank(context, VALUES)?,
normalized: blank(context, VALUES)?,
})
}
fn release(self) -> Result<()> {
let mut result = Ok(());
for buffer in [
self.history,
self.qkv,
self.weights,
self.alpha,
self.beta_raw,
self.dt,
self.a,
self.gamma,
self.z,
self.state,
self.next_history,
self.raw,
self.h,
self.qk,
self.sigmoid,
self.gate,
self.next_state,
self.readout,
self.normalized,
] {
result = combine(result, buffer.release());
}
result
}
/// The whole result set that must be bit-identical between both paths.
fn products(&self) -> Result<Vec<Vec<u8>>> {
[
&self.next_history,
&self.raw,
&self.h,
&self.qk,
&self.sigmoid,
&self.gate,
&self.next_state,
&self.readout,
&self.normalized,
]
.into_iter()
.map(read)
.collect()
}
}
/// Independent original sequence: every launch separately completed.
fn scalar(context: &Context<'_>, row: &mut Row<'_>) -> Result<()> {
context.gdn_conv_silu_f32(
&row.history,
&row.qkv,
&row.weights,
&mut row.next_history,
&mut row.raw,
&mut row.h,
)?;
context.gdn_qk_l2_f32(&row.h, &mut row.qk, EPSILON)?;
context.gdn_beta_sigmoid_f32(&row.beta_raw, &mut row.sigmoid)?;
context.gdn_gate_softplus_f32(&row.alpha, &row.dt, &row.a, &mut row.gate)?;
context.gdn_step_from_products_f32(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&mut row.next_state,
&mut row.readout,
)?;
context.gdn_out_norm_f32(
&row.readout,
&row.z,
&row.gamma,
&mut row.normalized,
EPSILON,
)
}
fn queued<'q>(queue: &'q mut GdnRowQueue<'_>, row: &'q Row<'_>) -> Result<GdnRowCompletion> {
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.next_state,
&row.readout,
)?;
prefix.scan_z(&row.z)?;
prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?;
prefix.fetch_next_history(&row.next_history)?;
prefix.finish()
}
/// Same program as `queued`, but QKV is row `index` of a retained batched
/// projection output (`tokens x 10,240` words), scanned as the first stage.
fn queued_columns<'q>(
queue: &'q mut GdnRowQueue<'_>,
row: &'q Row<'_>,
columns: &'q DeviceBuffer<'_>,
index: usize,
) -> Result<GdnRowCompletion> {
let mut prefix = queue.begin()?;
prefix.scan_qkv_columns(columns, index)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu_columns(
&row.history,
columns,
index,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.next_state,
&row.readout,
)?;
prefix.scan_z(&row.z)?;
prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?;
prefix.fetch_next_history(&row.next_history)?;
prefix.finish()
}
/// Batched host image: row `used` is the row's own QKV, every other row differs.
fn column_image(salt: usize, tokens: usize, used: usize) -> Vec<f32> {
let mut image = Vec::with_capacity(tokens * CHANNELS);
for row in 0..tokens {
let source = if row == used {
salt + 1
} else {
salt + 40 + row
};
image.extend(pattern(CHANNELS, source, 29, 1.0 / 64.0, 0.21));
}
image
}
/// Retained-row QKV must match the original sequence over the same row bit for
/// bit; non-finite words in OTHER rows must not matter, in the used row they
/// must refuse at the first stage.
#[allow(clippy::too_many_arguments)] // Test case selectors, not caller geometry.
fn columns_pair(
context: &Context<'_>,
queue: &mut GdnRowQueue<'_>,
salt: usize,
tokens: usize,
used: usize,
poison_used: bool,
poison_other: bool,
report: &mut Report,
) -> Result<()> {
let nan = f32::from_bits(0x7fc0_0001);
let mut image = column_image(salt, tokens, used);
if poison_used {
image[used * CHANNELS + 17] = nan;
}
if poison_other {
let other = (used + 1) % tokens;
image[other * CHANNELS + 3] = nan;
}
let mut old = Row::new(context, salt, Poison::default())?;
let actual = Row::new(context, salt, Poison::default())?;
let columns = upload(context, &image)?;
let operation = (|| {
scalar(context, &mut old)?;
let expected = old.products()?;
let completion = queued_columns(queue, &actual, &columns, used)?;
report.guards += 1;
if poison_used {
if completion.numerical_refusal() == Some(GdnQueueStage::Qkv) {
report.refusals += 1;
} else {
report.differences += 1;
}
return Ok(());
}
let history = completion
.into_next_history()
.map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?;
let found = actual.products()?;
compare(&expected, &found, report);
if bytes(&history) != found[0] {
report.differences += 1;
}
report.rows += 1;
Ok(())
})();
combine(
combine(combine(operation, old.release()), actual.release()),
columns.release(),
)
}
fn compare(old: &[Vec<u8>], actual: &[Vec<u8>], report: &mut Report) {
assert_eq!(old.len(), actual.len());
for (a, b) in old.iter().zip(actual) {
assert_eq!(a.len(), b.len());
for (x, y) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) {
report.words += 1;
report.differences += usize::from(x != y);
}
}
}
/// A clean row on the SAME queue must match the original sequence bit for bit.
fn clean_pair(
context: &Context<'_>,
queue: &mut GdnRowQueue<'_>,
salt: usize,
report: &mut Report,
) -> Result<()> {
let mut old = Row::new(context, salt, Poison::default())?;
let actual = Row::new(context, salt, Poison::default())?;
let operation = (|| {
scalar(context, &mut old)?;
let expected = old.products()?;
let completion = queued(queue, &actual)?;
if completion.numerical_refusal().is_some() {
return Err(Error::InvalidDriverValue("unexpected GDN row refusal"));
}
let history = completion
.into_next_history()
.map_err(|_| Error::InvalidDriverValue("missing GDN next history"))?;
let found = actual.products()?;
compare(&expected, &found, report);
// The fetched canonical history is exactly the next-history owner.
if bytes(&history) != found[0] {
report.differences += 1;
}
report.rows += 1;
Ok(())
})();
combine(combine(operation, old.release()), actual.release())
}
fn refusal_case(
context: &Context<'_>,
queue: &mut GdnRowQueue<'_>,
poison: Poison,
expected: GdnQueueStage,
report: &mut Report,
) -> Result<()> {
let row = Row::new(context, 5, poison)?;
let operation = (|| {
let completion = queued(queue, &row)?;
report.guards += 1;
if completion.numerical_refusal() != Some(expected)
|| completion.into_next_history().err() != Some(expected)
{
report.differences += 1;
} else {
report.refusals += 1;
}
Ok(())
})();
combine(operation, row.release())
}
fn refuse<T>(result: Result<T>, expected: Error, report: &mut Report) -> Result<()> {
report.guards += 1;
match result {
Err(error) if error == expected => {
report.refusals += 1;
Ok(())
}
Ok(_) => {
report.differences += 1;
Ok(())
}
Err(error) => Err(error),
}
}
#[test]
#[ignore = "Root-only changed GDN row queue proof: exact scalar equivalence, ordered refusal, cleanup"]
fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() {
assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(256 * 1024 * 1024).unwrap();
let foreign = device.create_context(64 * 1024 * 1024).unwrap();
let mut report = Report::default();
let result = (|| -> Result<()> {
let mut queue = context.gdn_row_queue()?;
if queue.allocated_bytes() != STATUS_BYTES {
return Err(Error::InvalidDriverValue("unexpected queue charge"));
}
// Three clean rows on one queue: statuses are reset on every drain.
for salt in [0, 1, 2] {
clean_pair(&context, &mut queue, salt, &mut report)?;
}
// Earliest refusal in program order, then the queue stays usable.
let cases = [
(
Poison {
alpha: true,
..Poison::default()
},
GdnQueueStage::Alpha,
),
(
Poison {
conv_weights: true,
..Poison::default()
},
GdnQueueStage::ConvRaw,
),
(
Poison {
state: true,
..Poison::default()
},
GdnQueueStage::NextState,
),
(
Poison {
z: true,
..Poison::default()
},
GdnQueueStage::Z,
),
(
Poison {
alpha: true,
z: true,
..Poison::default()
},
GdnQueueStage::Alpha,
),
];
for (poison, stage) in cases {
refusal_case(&context, &mut queue, poison, stage, &mut report)?;
clean_pair(&context, &mut queue, 3, &mut report)?;
}
// Retained batched QKV rows: first, middle and last of a 3-row and a
// 64-row batch; a poisoned OTHER row is irrelevant, the USED row refuses.
for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] {
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
false,
false,
&mut report,
)?;
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
false,
true,
&mut report,
)?;
columns_pair(
&context,
&mut queue,
8,
tokens,
used,
true,
false,
&mut report,
)?;
clean_pair(&context, &mut queue, 3, &mut report)?;
}
// Program order, data flow, aliasing, context and shape admission.
let row = Row::new(&context, 7, Poison::default())?;
let other = Row::new(&foreign, 7, Poison::default())?;
let admission = (|| -> Result<()> {
// Convolution before the two input scans.
let mut prefix = queue.begin()?;
refuse(
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
// Q/K over a buffer that is not the convolution H output.
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
refuse(
prefix.qk_l2(&row.raw, &row.qk, EPSILON),
Error::InvalidQwenShape,
&mut report,
)?;
// A latched admission error still drains the admitted prefix first.
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
// Recurrence whose current state and next state are one owner.
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
prefix.qk_l2(&row.h, &row.qk, EPSILON)?;
prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?;
prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?;
refuse(
prefix.recurrence(
&row.state,
&row.qk,
&row.h,
&row.gate,
&row.sigmoid,
&row.state,
&row.readout,
),
Error::OutputAliasesInput,
&mut report,
)?;
refuse(prefix.finish(), Error::OutputAliasesInput, &mut report)?;
// A buffer from another Context.
let mut prefix = queue.begin()?;
refuse(
prefix.scan_alpha(&other.alpha),
Error::ContextMismatch,
&mut report,
)?;
refuse(prefix.finish(), Error::ContextMismatch, &mut report)?;
// A whole buffer of the wrong size.
let short = blank(&context, 47)?;
let mut prefix = queue.begin()?;
let result = prefix.scan_alpha(&short);
refuse(result, Error::InvalidQwenShape, &mut report)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
short.release()?;
// History fetch of a buffer that is not the convolution output,
// a second fetch, and a finish before the program is complete.
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
)?;
refuse(
prefix.fetch_next_history(&row.history),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
let incomplete = prefix.finish();
refuse(incomplete, Error::InvalidQwenShape, &mut report)?;
// Retained-row admission: not a whole number of rows, a row beyond
// the batch, the host convolution after a column scan, a different
// row index or owner at the convolution, and a late column scan.
let ragged = blank(&context, CHANNELS + 1)?;
let image = upload(&context, &column_image(1, 3, 1))?;
let admission = (|| -> Result<()> {
let mut prefix = queue.begin()?;
refuse(
prefix.scan_qkv_columns(&ragged, 0),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
refuse(
prefix.scan_qkv_columns(&image, 3),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_qkv_columns(&image, 1)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
refuse(
prefix.conv_silu(
&row.history,
&row.qkv,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_qkv_columns(&image, 1)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
refuse(
prefix.conv_silu_columns(
&row.history,
&image,
2,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
let mut prefix = queue.begin()?;
prefix.scan_alpha(&row.alpha)?;
refuse(
prefix.scan_qkv_columns(&image, 1),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?;
// The retained-row conv over another owner than the scanned one.
let mut prefix = queue.begin()?;
prefix.scan_qkv_columns(&image, 1)?;
prefix.scan_alpha(&row.alpha)?;
prefix.scan_beta_raw(&row.beta_raw)?;
refuse(
prefix.conv_silu_columns(
&row.history,
&ragged,
1,
&row.weights,
&row.next_history,
&row.raw,
&row.h,
),
Error::InvalidQwenShape,
&mut report,
)?;
refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)
})();
combine(combine(admission, ragged.release()), image.release())
})();
let cleanup = combine(row.release(), other.release());
combine(admission, cleanup)?;
// The queue survives every refusal above and still matches the scalar path.
clean_pair(&context, &mut queue, 4, &mut report)?;
queue.close()
})();
let allocated = (context.allocated_bytes(), foreign.allocated_bytes());
let closes = (context.close(), foreign.close());
result.expect("completed changed GDN row queue proof");
assert!(closes.0.is_ok() && closes.1.is_ok());
assert_eq!(allocated, (0, 0));
assert_eq!(report.differences, 0, "{report:?}");
// 3 + 5 clean rows after refusals + 1 final + per column group (12 clean_pair-or-columns).
assert_eq!(report.rows, 9 + 4 * (2 + 1));
println!(
"GDN_ROW_QUEUE PASS rows={} exact_words={} refusals={} guards={} allocated0=true",
report.rows, report.words, report.refusals, report.guards
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
// Driver entry points for the Strata T1 fused-GDN module. This file is `include!`d inside `ffi::enabled` (items
// only, hence no inner attributes) for access to the private symbol table. The PTX image is a privately pinned
// immutable candidate asset of `gdn_fused_t1`; no caller can supply code or an entry name. Launching reuses
// `launch_gdn_native` (generic fixed-ABI storage; this program runs on the context's default stream).
use crate::qwen_dispatch::gdn_fused_t1::{self as fused, FusedKernel};
impl Api {
pub(crate) fn load_gdn_fused_t1_module(&self) -> Result<ModuleHandle> {
let ptx = fused::fused_asset()?;
let mut module = std::ptr::null_mut();
// SAFETY: fixed NUL-terminated pinned PTX and the current owning context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, ptx.as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn gdn_fused_t1_function(
&self,
module: ModuleHandle,
kernel: FusedKernel,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: closed kernel-to-entry map, live retained module of the matching family, writable output pointer.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, kernel.entry().as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
}
+304
View File
@@ -0,0 +1,304 @@
//! Root-only ignored smoke of the Original fused T1 GDN program. It proves transport, order, geometry, prior
//! immutability, earliest-stage refusal and cleanup with synthetic data and a serial host reference of the three
//! Original kernels (tolerance-based: the device kernels use FMA contraction and warp-shuffle reduction trees, so
//! the host reference is a sanity bound, NOT a bit-exactness proof). It is NOT the Original17 numerical gate: tensors
//! of the real model compared against the captured Original T1 references are that separate gate.
use super::*;
use crate::Driver;
const ENABLE: &str = "LELEKA_STRA169_RUN_GDN_FUSED_T1";
const EPS: f32 = 1e-6;
fn bytes_of(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn bf_bits(f: f32) -> u16 {
let mut u = f.to_bits();
u = u.wrapping_add(0x7fff + ((u >> 16) & 1));
(u >> 16) as u16
}
fn bf_value(b: u16) -> f32 {
f32::from_bits((b as u32) << 16)
}
fn mismatch<T>(what: &'static str) -> Result<T> {
Err(Error::InvalidDriverValue(what))
}
/// Deterministic small values in about [-0.5, 0.5].
fn synth(count: usize, salt: u32) -> Vec<f32> {
(0..count)
.map(|i| {
let x = (i as u32)
.wrapping_mul(2_654_435_761)
.wrapping_add(salt.wrapping_mul(40_503));
((x >> 8) % 1000) as f32 / 1000.0 - 0.5
})
.collect()
}
struct Case {
qkv: Vec<f32>,
z: Vec<f32>,
history: Vec<f32>,
state: Vec<f32>,
conv: Vec<f32>,
mixed: Vec<f32>,
wa: Vec<u16>,
wb: Vec<u16>,
dt: Vec<f32>,
a: Vec<f32>,
gamma: Vec<f32>,
}
fn case() -> Case {
let wa: Vec<u16> = synth(HV * N_EMBD, 7)
.iter()
.map(|v| bf_bits(v * 0.05))
.collect();
let wb: Vec<u16> = synth(HV * N_EMBD, 8)
.iter()
.map(|v| bf_bits(v * 0.05))
.collect();
Case {
qkv: synth(C, 1),
z: synth(VALUES, 2),
history: synth(HISTORY_WORDS, 3),
state: synth(STATE_WORDS, 4).iter().map(|v| v * 0.1).collect(),
conv: synth(4 * C, 5),
mixed: synth(N_EMBD, 6),
wa,
wb,
dt: synth(HV, 9),
a: synth(HV, 10).iter().map(|v| -v.abs() - 0.1).collect(),
gamma: synth(S, 11).iter().map(|v| v + 1.0).collect(),
}
}
struct Reference {
history: Vec<f32>,
h: Vec<f32>,
gate: Vec<f32>,
beta: Vec<f32>,
y: Vec<f32>,
state: Vec<f32>,
}
fn reference(c: &Case) -> Reference {
let mut history = c.history.clone();
let mut h = vec![0f32; C];
for ch in 0..C {
let (v0, v1, v2, x) = (
history[ch * 3],
history[ch * 3 + 1],
history[ch * 3 + 2],
c.qkv[ch],
);
let sum = v0 * c.conv[ch * 4]
+ v1 * c.conv[ch * 4 + 1]
+ v2 * c.conv[ch * 4 + 2]
+ x * c.conv[ch * 4 + 3];
history[ch * 3] = v1;
history[ch * 3 + 1] = v2;
history[ch * 3 + 2] = x;
h[ch] = sum / (1.0 + (-sum).exp());
}
for head in 0..(2 * HK) {
let ss: f32 = h[head * S..(head + 1) * S].iter().map(|v| v * v).sum();
let scale = 1.0 / (ss + EPS).sqrt();
for v in &mut h[head * S..(head + 1) * S] {
*v *= scale;
}
}
let mut gate = vec![0f32; HV];
let mut beta = vec![0f32; HV];
for r in 0..HV {
let mut aa = 0f32;
let mut ab = 0f32;
for j in 0..N_EMBD {
aa += bf_value(c.wa[r * N_EMBD + j]) * c.mixed[j];
ab += bf_value(c.wb[r * N_EMBD + j]) * c.mixed[j];
}
let v = aa + c.dt[r];
let sp = if v > 20.0 { v } else { v.exp().ln_1p() };
gate[r] = sp * c.a[r];
beta[r] = 1.0 / (1.0 + (-ab).exp());
}
let mut state = c.state.clone();
let mut y = vec![0f32; VALUES];
for head in 0..HV {
let qh = head % HK;
let g = gate[head].exp();
let mut oc = [0f32; S];
for col in 0..S {
let mut kv = 0f32;
for row in 0..S {
kv += state[(row * HV + head) * S + col] * h[QK + qh * S + row];
}
let delta = (h[2 * QK + head * S + col] - g * kv) * beta[head];
let mut o = 0f32;
for row in 0..S {
let s = &mut state[(row * HV + head) * S + col];
*s = g * *s + h[QK + qh * S + row] * delta;
o += *s * h[qh * S + row];
}
oc[col] = o / (S as f32).sqrt();
}
let ss: f32 = oc.iter().map(|v| v * v).sum();
let scale = 1.0 / (ss / S as f32 + EPS).sqrt();
for col in 0..S {
let zz = c.z[head * S + col];
y[head * S + col] = oc[col] * scale * c.gamma[col] / (1.0 + (-zz).exp());
}
}
Reference {
history,
h,
gate,
beta,
y,
state,
}
}
const QK: usize = 2048;
const HK: usize = 16;
fn close(name: &'static str, got: &[f32], want: &[f32]) -> Result<()> {
if got.len() != want.len() {
return mismatch(name);
}
for (g, w) in got.iter().zip(want) {
if !g.is_finite() || (g - w).abs() > 2e-3 * w.abs().max(1.0) {
return mismatch(name);
}
}
Ok(())
}
fn upload<'c>(context: &'c Context<'c>, values: &[f32]) -> Result<DeviceBuffer<'c>> {
let mut buffer = context.allocate(values.len() * 4)?;
buffer.copy_from(&bytes_of(values))?;
Ok(buffer)
}
fn upload_bf<'c>(context: &'c Context<'c>, bits: &[u16]) -> Result<DeviceBuffer<'c>> {
let mut buffer = context.allocate(bits.len() * 2)?;
buffer.copy_from(
&bits
.iter()
.flat_map(|v| v.to_le_bytes())
.collect::<Vec<_>>(),
)?;
Ok(buffer)
}
fn download<'c>(buffer: &DeviceBuffer<'c>, count: usize) -> Result<Vec<f32>> {
let bytes = buffer.copy_to_owned(count * 4)?;
Ok(bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect())
}
/// One program run. `from_resident`: seed the candidate state by the device copy of a resident mirror instead of a
/// host upload. `poison_qkv`: put a NaN into the QKV input. Returns the refusal stage, if any.
fn run(
context: &Context<'_>,
owner: &mut GdnFusedT1<'_>,
c: &Case,
from_resident: bool,
poison_qkv: bool,
) -> Result<Option<GdnFusedStage>> {
let mut qkv = c.qkv.clone();
if poison_qkv {
qkv[17] = f32::NAN;
}
let qkv_b = upload(context, &qkv)?;
let z_b = upload(context, &c.z)?;
let hist_b = upload(context, &c.history)?;
let conv_b = upload(context, &c.conv)?;
let h_b = context.allocate(C * 4)?;
let mixed_b = upload(context, &c.mixed)?;
let wa_b = upload_bf(context, &c.wa)?;
let wb_b = upload_bf(context, &c.wb)?;
let dt_b = upload(context, &c.dt)?;
let a_b = upload(context, &c.a)?;
let gate_b = context.allocate(HV * 4)?;
let beta_b = context.allocate(HV * 4)?;
let gamma_b = upload(context, &c.gamma)?;
let y_b = context.allocate(VALUES * 4)?;
let resident = upload(context, &c.state)?;
let next_state = if from_resident {
context.allocate(STATE_WORDS * 4)?
} else {
upload(context, &c.state)?
};
let refusal = (|| -> Result<Option<GdnFusedStage>> {
let mut prefix = owner.begin()?;
prefix.scan_inputs(&qkv_b, &z_b)?;
prefix.seed_state(
if from_resident { Some(&resident) } else { None },
&next_state,
)?;
prefix.conv_l2(&hist_b, &conv_b, &h_b, EPS)?;
prefix.ab(&mixed_b, &wa_b, &wb_b, &dt_b, &a_b, &gate_b, &beta_b)?;
prefix.step_norm(&gamma_b, &y_b, EPS)?;
prefix.fetch_candidate()?;
let completion = prefix.finish()?;
if let Some(stage) = completion.numerical_refusal() {
return Ok(Some(stage));
}
let (state, history) = completion
.into_fetched()
.map_err(|_| Error::InvalidQwenShape)?;
let want = reference(c);
close("history", &history, &want.history)?;
close("state", &state, &want.state)?;
close("h", &download(&h_b, C)?, &want.h)?;
close("gate", &download(&gate_b, HV)?, &want.gate)?;
close("beta", &download(&beta_b, HV)?, &want.beta)?;
close("y", &download(&y_b, VALUES)?, &want.y)?;
// The immutable prior (bound only on the key-hit run) is never written.
if from_resident && download(&resident, STATE_WORDS)? != c.state {
return mismatch("resident prior state was modified");
}
Ok(None)
})();
let mut cleanup = Ok(());
for buffer in [
qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b,
y_b, resident, next_state,
] {
cleanup = combine(cleanup, buffer.release());
}
let refusal = refusal?;
cleanup?;
Ok(refusal)
}
#[test]
#[ignore = "Root-only GPU qualification; never run by the source owner"]
fn original_fused_t1_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() {
assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(256 * 1024 * 1024).unwrap();
let result = (|| -> Result<()> {
let mut owner = context.gdn_fused_t1()?;
if owner.allocated_bytes() != GDN_FUSED_T1_PERSISTENT_BYTES {
return mismatch("unexpected owner charge");
}
let c = case();
// Candidate seeded by a host upload (key miss), then by the device copy of the resident mirror (key hit).
if run(&context, &mut owner, &c, false, false)?.is_some() {
return mismatch("unexpected refusal (miss)");
}
if run(&context, &mut owner, &c, true, false)?.is_some() {
return mismatch("unexpected refusal (hit)");
}
// A non-finite projected QKV is the earliest refusal and the owner stays usable.
if run(&context, &mut owner, &c, false, true)? != Some(GdnFusedStage::Qkv) {
return mismatch("non-finite qkv not refused at the first stage");
}
if run(&context, &mut owner, &c, true, false)?.is_some() {
return mismatch("owner unusable after a refusal");
}
owner.close()
})();
let leaked = context.allocated_bytes();
assert!(result.is_ok(), "{result:?}");
assert_eq!(leaked, 0, "bytes still allocated after close");
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,104 @@
//! Closed kernel-parameter storage for the Strata-prefill GDN module and the
//! native FP16 dequantization module. Every launch owns its own stable Box so
//! the pointees never move between enqueue and the single final synchronize.
//! Declared as a child of `ffi` (like `mmq_ffi.rs`) for access to `BufferHandle`.
use super::*;
use std::ffi::c_void;
/// Most parameters any kernel of the two modules takes.
pub(crate) const MAX_ARGS: usize = 8;
/// One kernel parameter, in declaration order. Pointers are device addresses of
/// admitted allocations; `NullPointer` is the original's optional output.
#[derive(Clone, Copy)]
pub(crate) enum KernelArg {
Pointer(BufferHandle),
NullPointer,
I64(i64),
U32(u32),
F32(f32),
}
#[repr(C)]
struct Storage {
// Each argument occupies its own 8-byte little-endian slot; the 4-byte
// scalars live in the low half, which is where the kernel reads them.
slots: [u64; MAX_ARGS],
parameters: [*mut c_void; MAX_ARGS],
}
pub(crate) struct GdnPrefillArguments(std::ptr::NonNull<Storage>);
impl GdnPrefillArguments {
pub(crate) fn new(args: &[KernelArg]) -> Result<Self> {
if args.is_empty() || args.len() > MAX_ARGS {
return Err(Error::InvalidQwenShape);
}
let owner = Box::into_raw(Box::new(Storage {
slots: [0; MAX_ARGS],
parameters: [std::ptr::null_mut(); MAX_ARGS],
}));
let owner = std::ptr::NonNull::new(owner).expect("Box is non-null");
// SAFETY: freshly allocated, uniquely owned, stable storage; the
// parameter pointers target this same Box and live until `Drop`.
unsafe {
let s = &mut *owner.as_ptr();
for (i, arg) in args.iter().enumerate() {
s.slots[i] = match *arg {
KernelArg::Pointer(handle) => handle.0,
KernelArg::NullPointer => 0,
KernelArg::I64(v) => v as u64,
KernelArg::U32(v) => u64::from(v),
KernelArg::F32(v) => u64::from(v.to_bits()),
};
s.parameters[i] = (&raw mut s.slots[i]).cast();
}
}
Ok(Self(owner))
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
// SAFETY: stable uniquely owned storage retained by the caller through
// completion of the launch (final synchronize and context pop).
unsafe { (&raw mut (*self.0.as_ptr()).parameters).cast() }
}
}
impl Drop for GdnPrefillArguments {
fn drop(&mut self) {
// SAFETY: reconstructed exactly once after completion; on completion
// uncertainty the owner is `mem::forget`-ed by the drain instead.
unsafe { drop(Box::from_raw(self.0.as_ptr())) }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scalar_slots_hold_little_endian_low_halves_and_parameters_point_at_slots() {
let mut a = GdnPrefillArguments::new(&[
KernelArg::Pointer(BufferHandle(0x10_0000)),
KernelArg::NullPointer,
KernelArg::I64(-3),
KernelArg::U32(7),
KernelArg::F32(1.5),
])
.unwrap();
let p = a.parameters();
// SAFETY: five initialised parameters in the owned Box.
unsafe {
assert_eq!(*(*p.add(0)).cast::<u64>(), 0x10_0000);
assert_eq!(*(*p.add(1)).cast::<u64>(), 0);
assert_eq!(*(*p.add(2)).cast::<i64>(), -3);
assert_eq!(*(*p.add(3)).cast::<u32>(), 7);
assert_eq!(*(*p.add(4)).cast::<f32>(), 1.5);
}
}
#[test]
fn empty_and_oversized_argument_lists_are_refused() {
assert!(GdnPrefillArguments::new(&[]).is_err());
assert!(GdnPrefillArguments::new(&[KernelArg::U32(0); MAX_ARGS + 1]).is_err());
}
}
@@ -0,0 +1,66 @@
// Driver entry points for the Strata-prefill GDN module and the native FP16
// dequantization module. This file is `include!`d inside `ffi::enabled` (items
// only, hence no inner attributes) for access to the private symbol table.
// Both PTX images are privately pinned immutable candidate assets of
// `gdn_native_batch`; no caller can supply code or an entry name.
use crate::qwen_dispatch::gdn_native_batch::{self as batch, Kernel};
impl Api {
pub(crate) fn load_gdn_native_module(&self, dequant: bool) -> Result<ModuleHandle> {
let ptx = if dequant {
batch::dequant_asset()?
} else {
batch::prefill_asset()?
};
let mut module = std::ptr::null_mut();
// SAFETY: fixed NUL-terminated pinned PTX and the current owning context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, ptx.as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn gdn_native_function(
&self,
module: ModuleHandle,
kernel: Kernel,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: closed kernel-to-entry map, live retained module of the matching
// family, writable output pointer.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, kernel.entry().as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
pub(crate) fn launch_gdn_native(
&self,
function: FunctionHandle,
stream: batch::GdnStream,
grid: [u32; 3],
block: [u32; 3],
args: &mut GdnPrefillArguments,
) -> Result<()> {
if grid.contains(&0) || block.contains(&0) {
return Err(Error::InvalidQwenShape);
}
// SAFETY: geometry and parameter list are derived from the closed kernel
// table and admitted extents; the owned argument storage survives the
// final synchronize. `stream` is the adapter-owned stream (or the default
// stream) of this context, minted only inside the driver crate.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid[0],
grid[1],
grid[2],
block[0],
block[1],
block[2],
0,
stream.address() as *mut c_void,
args.parameters(),
std::ptr::null_mut(),
)
})
}
}
@@ -0,0 +1,754 @@
//! Root-only ignored smoke of the Strata-prefill GDN program (option B). It
//! proves transport, order, geometry, immutability, refusal and cleanup of the
//! new program with synthetic data and a host-side stand-in for the closed
//! cuBLAS adapter. It is NOT the Original17 prefill numerical gate: tensors
//! produced by the real adapter and the captured prompt-path references are
//! compared by that separate gate, never by this test.
use super::*;
use crate::Driver;
use std::cell::{Cell, RefCell};
const ENABLE: &str = "LELEKA_STRA169_RUN_GDN_BATCH";
const EPS: f32 = GDN_BATCH_EPSILON;
const Q8_0_BLOCK: usize = 34;
// ---------------------------------------------------------------- host numerics helpers
fn bytes_of(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn words_of(bytes: &[u8]) -> Vec<f32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect()
}
fn halves_of(bytes: &[u8]) -> Vec<u16> {
bytes
.as_chunks::<2>()
.0
.iter()
.map(|w| u16::from_le_bytes(*w))
.collect()
}
fn f16_bits(f: f32) -> u16 {
let x = f.to_bits();
let sign = ((x >> 16) & 0x8000) as u16;
let exp = ((x >> 23) & 0xff) as i32;
let man = x & 0x7f_ffff;
if exp == 0xff {
return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 };
}
let e = exp - 127 + 15;
if e >= 0x1f {
return sign | 0x7c00;
}
if e <= 0 {
if e < -10 {
return sign;
}
let m = man | 0x80_0000;
let shift = (14 - e) as u32;
let mut h = (m >> shift) as u16;
let rem = m & ((1 << shift) - 1);
let mid = 1 << (shift - 1);
if rem > mid || (rem == mid && h & 1 == 1) {
h += 1;
}
return sign | h;
}
let mut h = ((e as u32) << 10) | (man >> 13);
let rem = man & 0x1fff;
if rem > 0x1000 || (rem == 0x1000 && h & 1 == 1) {
h += 1;
}
sign | h as u16
}
fn f16_value(h: u16) -> f32 {
let sign = ((h & 0x8000) as u32) << 16;
let exp = ((h >> 10) & 0x1f) as i32;
let man = (h & 0x3ff) as u32;
if exp == 0 {
let v = man as f32 * 2f32.powi(-24);
return if sign != 0 { -v } else { v };
}
if exp == 0x1f {
return f32::from_bits(sign | 0x7f80_0000 | (man << 13));
}
f32::from_bits(sign | (((exp - 15 + 127) as u32) << 23) | (man << 13))
}
fn bf_bits(f: f32) -> u16 {
let mut u = f.to_bits();
u = u.wrapping_add(0x7fff + ((u >> 16) & 1));
(u >> 16) as u16
}
fn bf_value(b: u16) -> f32 {
f32::from_bits((b as u32) << 16)
}
fn sigm(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec<f32> {
(0..count)
.map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset)
.collect()
}
fn close(a: f32, b: f32, tolerance: f32) -> bool {
(a - b).abs() <= tolerance * (1.0 + b.abs())
}
/// Q8_0 blocks of a `rows x cols` matrix and its exact FP16 dequantization.
fn q8_0(rows: usize, cols: usize, salt: usize) -> (Vec<u8>, Vec<u16>) {
let mut blocks = Vec::with_capacity(rows * cols / 32 * Q8_0_BLOCK);
let mut half = Vec::with_capacity(rows * cols);
for r in 0..rows {
for b in 0..cols / 32 {
let scale = f16_bits(0.0078125 * (1 + (r + b + salt) % 3) as f32);
blocks.extend_from_slice(&scale.to_le_bytes());
for j in 0..32 {
let q = ((r * 31 + b * 17 + j * 5 + salt) % 41) as i32 - 20;
blocks.push(q as i8 as u8);
half.push(f16_bits(q as f32 * f16_value(scale)));
}
}
}
(blocks, half)
}
// ---------------------------------------------------------------- host reference of the original kernels
struct Reference {
h: Vec<f32>,
next_history: Vec<f32>,
next_state: Vec<f32>,
y: Vec<f32>,
y16: Vec<u16>,
}
#[allow(clippy::too_many_arguments)] // The fixed operands of the original program.
fn reference(
tokens: usize,
qkv: &[f32],
z: &[f32],
ab: &[f32],
history: &[f32],
conv_w: &[f32],
dt: &[f32],
a: &[f32],
gamma: &[f32],
state: &[f32],
) -> Reference {
let mut gate = vec![0f32; tokens * HV];
let mut beta = vec![0f32; tokens * HV];
for t in 0..tokens {
for h in 0..HV {
let v = ab[t * 2 * HV + h] + dt[h];
gate[t * HV + h] = (if v > 20.0 { v } else { v.exp().ln_1p() }) * a[h];
beta[t * HV + h] = sigm(ab[t * 2 * HV + HV + h]);
}
}
let mut h = vec![0f32; tokens * C];
for c in 0..C {
let (mut v0, mut v1, mut v2) = (history[c * 3], history[c * 3 + 1], history[c * 3 + 2]);
let w = &conv_w[c * 4..c * 4 + 4];
for t in 0..tokens {
let x = qkv[t * C + c];
let s = v0 * w[0] + v1 * w[1] + v2 * w[2] + x * w[3];
h[t * C + c] = s / (1.0 + (-s).exp());
(v0, v1, v2) = (v1, v2, x);
}
}
let mut next_history = vec![0f32; HISTORY_WORDS];
for c in 0..C {
for k in 0..3 {
let t = tokens as isize - 3 + k as isize;
next_history[c * 3 + k] = if t >= 0 {
qkv[t as usize * C + c]
} else {
history[c * 3 + (t + 3) as usize]
};
}
}
for t in 0..tokens {
for head in 0..2 * 16 {
let x = &mut h[t * C + head * S..t * C + head * S + S];
let ss: f32 = x.iter().map(|v| v * v).sum();
let scale = 1.0 / (ss + EPS).sqrt();
x.iter_mut().for_each(|v| *v *= scale);
}
}
let mut next_state = state.to_vec();
let mut y = vec![0f32; tokens * ZV];
for head in 0..HV {
let qh = head % 16;
for t in 0..tokens {
let q = &h[t * C + qh * S..t * C + qh * S + S];
let k = &h[t * C + 16 * S + qh * S..t * C + 16 * S + qh * S + S];
let g = gate[t * HV + head].exp();
for col in 0..S {
let mut kv = 0f32;
for row in 0..S {
kv += next_state[(row * HV + head) * S + col] * k[row];
}
let delta = (h[t * C + 2 * 16 * S + head * S + col] - g * kv) * beta[t * HV + head];
let mut o = 0f32;
for row in 0..S {
let at = (row * HV + head) * S + col;
next_state[at] = g * next_state[at] + k[row] * delta;
o += next_state[at] * q[row];
}
y[t * ZV + head * S + col] = o / (S as f32).sqrt();
}
}
}
let mut y16 = vec![0u16; tokens * ZV];
for t in 0..tokens {
for head in 0..HV {
let at = t * ZV + head * S;
let ss: f32 = y[at..at + S].iter().map(|v| v * v).sum();
for col in 0..S {
let v = y[at + col] / (ss / S as f32 + EPS).sqrt() * gamma[col] * sigm(z[at + col]);
y[at + col] = v;
y16[at + col] = f16_bits(v);
}
}
}
Reference {
h,
next_history,
next_state,
y,
y16,
}
}
// ---------------------------------------------------------------- host stand-in for the cuBLAS adapter
#[derive(Default, Clone, Copy)]
struct Poison {
z: bool,
ab: bool,
dt: bool,
state: bool,
}
#[derive(Default)]
struct Captured {
scratch: Vec<(usize, Vec<u16>)>, // (rows, FP16 matrix prefix)
x: Vec<(usize, Vec<u8>)>, // (depth, activation bytes)
y: Vec<(usize, Vec<f32>)>, // (rows, result words written by call)
}
struct HostGemm {
poison: Poison,
captured: RefCell<Captured>,
calls: Cell<usize>,
}
impl HostGemm {
fn run(
&self,
bf16: bool,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.calls.set(self.calls.get() + 1);
let mut xb = vec![0u8; x.len()];
x.copy_to(&mut xb)?;
let mut wb = vec![0u8; w.len()];
w.copy_to(&mut wb)?;
let mut yb = vec![0u8; y.len()];
y.copy_to(&mut yb)?;
let value = |bits: u16| {
if bf16 {
bf_value(bits)
} else {
f16_value(bits)
}
};
let xh = halves_of(&xb);
let wh = halves_of(&wb);
let mut out = words_of(&yb);
let GemmShape {
tokens,
rows,
depth,
ldy,
y_offset,
beta,
} = shape;
if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy {
return Err(Error::InvalidQwenShape);
}
for t in 0..tokens {
for n in 0..rows {
let mut acc = 0f32;
for k in 0..4 {
acc += value(xh[t * depth + (7 * n + k) % depth])
* value(wh[n * depth + (3 * k + n) % depth]);
}
let at = t * ldy + y_offset + n;
out[at] = acc + beta * out[at];
}
}
if self.poison.z && rows == ZV {
out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001);
}
if self.poison.ab && rows == HV {
out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001);
}
y.context
.driver
.api
.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?;
let mut captured = self.captured.borrow_mut();
if !bf16 {
captured.scratch.push((rows, wh[..rows * depth].to_vec()));
}
captured.x.push((depth, xb));
captured.y.push((rows, out));
Ok(())
}
}
impl GdnGemm for HostGemm {
fn stream(&self) -> GdnStream {
// The host stand-in copies synchronously on the default stream.
GdnStream::default_stream()
}
fn f16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.run(false, x, w, y, shape)
}
fn bf16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.run(true, x, w, y, shape)
}
}
// ---------------------------------------------------------------- buffers
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
match buffer.copy_from(bytes) {
Ok(()) => Ok(buffer),
Err(primary) => combine(Err(primary), buffer.release()).map(|()| unreachable!()),
}
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut out = vec![0; buffer.len()];
buffer.copy_to(&mut out)?;
Ok(out)
}
struct Fixture<'a> {
mixed: DeviceBuffer<'a>,
mixed_h: DeviceBuffer<'a>,
mixed_bf: DeviceBuffer<'a>,
mixed_bf_lo: DeviceBuffer<'a>,
qkv_w: DeviceBuffer<'a>,
z_w: DeviceBuffer<'a>,
out_w: DeviceBuffer<'a>,
alpha_w: DeviceBuffer<'a>,
beta_w: DeviceBuffer<'a>,
scratch: DeviceBuffer<'a>,
qkv: DeviceBuffer<'a>,
z: DeviceBuffer<'a>,
ab: DeviceBuffer<'a>,
dt: DeviceBuffer<'a>,
a: DeviceBuffer<'a>,
gate: DeviceBuffer<'a>,
beta: DeviceBuffer<'a>,
history: DeviceBuffer<'a>,
conv_w: DeviceBuffer<'a>,
next_history: DeviceBuffer<'a>,
h: DeviceBuffer<'a>,
state: DeviceBuffer<'a>,
next_state: DeviceBuffer<'a>,
y: DeviceBuffer<'a>,
gamma: DeviceBuffer<'a>,
y16: DeviceBuffer<'a>,
bo: DeviceBuffer<'a>,
// host copies of the immutable inputs
host_mixed: Vec<f32>,
host_history: Vec<f32>,
host_conv_w: Vec<f32>,
host_dt: Vec<f32>,
host_a: Vec<f32>,
host_gamma: Vec<f32>,
host_state: Vec<f32>,
}
impl<'a> Fixture<'a> {
fn new(context: &'a Context<'_>, tokens: usize, poison: Poison) -> Result<Self> {
let blank = |bytes: usize| upload(context, &vec![0; bytes]);
let mut dt = vec![-2.0f32; HV];
if poison.dt {
dt[0] = f32::INFINITY;
}
let host_mixed = pattern(tokens * N, 1, 37, 1.0 / 32.0, 0.5);
let host_history = pattern(HISTORY_WORDS, 2, 13, 1.0 / 128.0, 0.04);
let host_conv_w: Vec<f32> = (0..4 * C)
.map(|i| [0.25, 0.5, -0.25, 0.125][i % 4])
.collect();
let host_a = vec![-1.0f32; HV];
let host_gamma = pattern(S, 3, 7, 1.0 / 16.0, 0.0)
.iter()
.map(|v| v + 0.5)
.collect::<Vec<_>>();
let mut host_state = pattern(STATE_WORDS, 4, 19, 1.0 / 2048.0, 0.004);
if poison.state {
host_state[STATE_WORDS - 1] = f32::from_bits(0x7fc0_0001);
}
let bf16_weights = |salt: usize| -> Vec<u8> {
pattern(HV * N, salt, 11, 1.0 / 64.0, 0.08)
.into_iter()
.flat_map(|v| bf_bits(v).to_le_bytes())
.collect()
};
Ok(Self {
mixed: upload(context, &bytes_of(&host_mixed))?,
mixed_h: blank(tokens * N * 2)?,
mixed_bf: blank(tokens * N * 2)?,
mixed_bf_lo: blank(tokens * N * 2)?,
qkv_w: upload(context, &q8_0(C, N, 1).0)?,
z_w: upload(context, &q8_0(ZV, N, 2).0)?,
out_w: upload(context, &q8_0(N, ZV, 3).0)?,
alpha_w: upload(context, &bf16_weights(5))?,
beta_w: upload(context, &bf16_weights(6))?,
scratch: blank(C * N * 2)?,
qkv: blank(tokens * C * 4)?,
z: blank(tokens * ZV * 4)?,
ab: blank(tokens * 2 * HV * 4)?,
dt: upload(context, &bytes_of(&dt))?,
a: upload(context, &bytes_of(&host_a))?,
gate: blank(tokens * HV * 4)?,
beta: blank(tokens * HV * 4)?,
history: upload(context, &bytes_of(&host_history))?,
conv_w: upload(context, &bytes_of(&host_conv_w))?,
next_history: blank(HISTORY_WORDS * 4)?,
h: blank(tokens * C * 4)?,
state: upload(context, &bytes_of(&host_state))?,
next_state: blank(STATE_WORDS * 4)?,
y: blank(tokens * ZV * 4)?,
gamma: upload(context, &bytes_of(&host_gamma))?,
y16: blank(tokens * ZV * 2)?,
bo: blank(tokens * N * 4)?,
host_mixed,
host_history,
host_conv_w,
host_dt: dt,
host_a,
host_gamma,
host_state,
})
}
fn release(self) -> Result<()> {
let mut result = Ok(());
for buffer in [
self.mixed,
self.mixed_h,
self.mixed_bf,
self.mixed_bf_lo,
self.qkv_w,
self.z_w,
self.out_w,
self.alpha_w,
self.beta_w,
self.scratch,
self.qkv,
self.z,
self.ab,
self.dt,
self.a,
self.gate,
self.beta,
self.history,
self.conv_w,
self.next_history,
self.h,
self.state,
self.next_state,
self.y,
self.gamma,
self.y16,
self.bo,
] {
result = combine(result, buffer.release());
}
result
}
}
fn mismatch<T>(what: &'static str) -> Result<T> {
Err(Error::InvalidDriverValue(what))
}
/// One complete program for `tokens` rows; returns the completion and, when the
/// program finished clean, the checks against the host reference.
fn run_case(
context: &Context<'_>,
batch: &mut GdnPrefillBatch<'_>,
tokens: usize,
poison: Poison,
expect: Option<GdnBatchStage>,
) -> Result<()> {
let fixture = Fixture::new(context, tokens, poison)?;
let gemm = HostGemm {
poison,
captured: RefCell::new(Captured::default()),
calls: Cell::new(0),
};
let result = (|| -> Result<()> {
let mut prefix = batch.begin(tokens, &gemm)?;
let program = (|| -> Result<()> {
prefix.pack_mixed(
&fixture.mixed,
&fixture.mixed_h,
&fixture.mixed_bf,
Some(&fixture.mixed_bf_lo),
)?;
prefix.project_qkv(
GdnNativeFormat::Q8_0,
&fixture.qkv_w,
&fixture.scratch,
&fixture.qkv,
)?;
prefix.project_z(
GdnNativeFormat::Q8_0,
&fixture.z_w,
&fixture.scratch,
&fixture.z,
)?;
prefix.project_alpha_beta(&fixture.alpha_w, &fixture.beta_w, &fixture.ab)?;
prefix.gates(&fixture.dt, &fixture.a, &fixture.gate, &fixture.beta)?;
prefix.conv(
&fixture.history,
&fixture.conv_w,
&fixture.next_history,
&fixture.h,
)?;
prefix.l2()?;
prefix.recurrence(&fixture.state, &fixture.next_state, &fixture.y)?;
prefix.out_norm(&fixture.gamma, &fixture.y16)?;
prefix.project_out(
GdnNativeFormat::Q8_0,
&fixture.out_w,
&fixture.scratch,
&fixture.bo,
)
})();
let completion = prefix.finish();
program?;
let completion = completion?;
if completion.numerical_refusal() != expect {
return mismatch("refusal stage differs from the expected earliest stage");
}
// The immutable inputs are untouched in every case.
if read(&fixture.state)? != bytes_of(&fixture.host_state)
|| read(&fixture.history)? != bytes_of(&fixture.host_history)
{
return mismatch("prior state or history was modified");
}
let history = completion.into_next_history();
if expect.is_some() {
return match history {
Err(stage) if Some(stage) == expect => Ok(()),
_ => mismatch("refused batch must withhold its history"),
};
}
let history =
history.map_err(|_| Error::InvalidDriverValue("clean batch lost its history"))?;
check_clean(&fixture, &gemm, tokens, &history)
})();
combine(result, fixture.release())
}
fn check_clean(
f: &Fixture<'_>,
gemm: &HostGemm,
tokens: usize,
next_history: &[f32],
) -> Result<()> {
// Five projections' FP16 matrices, the images and four GEMM calls with the lo pass.
let captured = gemm.captured.borrow();
if gemm.calls.get() != 3 + 4 || captured.x.len() != 7 {
return mismatch("unexpected GEMM call sequence");
}
// Dequantization is exact against the host transcription of group32<8>.
for ((rows, half), (r, c, salt)) in
captured
.scratch
.iter()
.zip([(C, N, 1usize), (ZV, N, 2), (N, ZV, 3)])
{
if *rows != r || half != &q8_0(r, c, salt).1 {
return mismatch("dequantized FP16 weights differ from the original group32<Q8_0>");
}
}
// The images of `mixed`.
let (h_img, bf_img, lo_img) = (
halves_of(&read(&f.mixed_h)?),
halves_of(&read(&f.mixed_bf)?),
halves_of(&read(&f.mixed_bf_lo)?),
);
for (i, &s) in f.host_mixed.iter().enumerate() {
let hi = bf_bits(s);
if h_img[i] != f16_bits(s) || bf_img[i] != hi || lo_img[i] != bf_bits(s - bf_value(hi)) {
return mismatch("mixed images differ from bf()/bf_lo()/hf()");
}
}
// Downstream kernels against the host reference built from the adapter's own outputs.
let by_rows = |rows: usize, nth: usize| -> Option<&Vec<f32>> {
captured
.y
.iter()
.filter(|(r, _)| *r == rows)
.nth(nth)
.map(|(_, y)| y)
};
let qkv = by_rows(C, 0).ok_or(Error::InvalidDriverValue("qkv call missing"))?;
let z = by_rows(ZV, 0).ok_or(Error::InvalidDriverValue("z call missing"))?;
// alpha, alpha(lo), beta, beta(lo): the last call holds the complete interleaved ab.
let ab = captured
.y
.iter()
.rev()
.find(|(r, _)| *r == HV)
.map(|(_, y)| y)
.ok_or(Error::InvalidDriverValue("ab calls missing"))?;
let want = reference(
tokens,
qkv,
z,
ab,
&f.host_history,
&f.host_conv_w,
&f.host_dt,
&f.host_a,
&f.host_gamma,
&f.host_state,
);
if next_history != want.next_history.as_slice() {
return mismatch("next history is not the exact last three inputs");
}
let h = words_of(&read(&f.h)?);
let state = words_of(&read(&f.next_state)?);
let y = words_of(&read(&f.y)?);
let y16 = halves_of(&read(&f.y16)?);
for (name, got, expected) in [
("conv+l2", &h, &want.h),
("next state", &state, &want.next_state),
("normalized output", &y, &want.y),
] {
if got.len() != expected.len()
|| got
.iter()
.zip(expected)
.any(|(g, e)| !g.is_finite() || !close(*g, *e, 2e-4))
{
return Err(Error::InvalidDriverValue(match name {
"conv+l2" => "conv+l2 differs from the host reference",
"next state" => "next state differs from the host reference",
_ => "normalized output differs from the host reference",
}));
}
}
if y16
.iter()
.zip(&want.y16)
.any(|(g, e)| !close(f16_value(*g), f16_value(*e), 4e-3))
{
return mismatch("y16 differs from the host reference");
}
// The Out GEMM consumed exactly the device y16.
let last = captured
.x
.last()
.ok_or(Error::InvalidDriverValue("out call missing"))?;
if last.0 != ZV || halves_of(&last.1) != y16 {
return mismatch("Out GEMM did not read the y16 image");
}
Ok(())
}
#[test]
#[ignore = "Root-only GPU qualification; never run by the source owner"]
fn strata_prefill_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() {
assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(768 * 1024 * 1024).unwrap();
let result = (|| -> Result<()> {
let mut batch = context.gdn_prefill_batch()?;
if batch.allocated_bytes() != STATUS_BYTES {
return mismatch("unexpected owner charge");
}
// Serial-conv chunk, tiled-conv chunk, then the same owner again.
for tokens in [2, 70, 5] {
run_case(&context, &mut batch, tokens, Poison::default(), None)?;
}
// Earliest stage in program order wins and the owner stays usable.
run_case(
&context,
&mut batch,
4,
Poison {
z: true,
ab: true,
..Poison::default()
},
Some(GdnBatchStage::Z),
)?;
run_case(
&context,
&mut batch,
4,
Poison {
ab: true,
..Poison::default()
},
Some(GdnBatchStage::Ab),
)?;
run_case(
&context,
&mut batch,
4,
Poison {
dt: true,
..Poison::default()
},
Some(GdnBatchStage::Gate),
)?;
// A non-finite prior state is caught by the recurrence kernel's own witness
// before the final-state scan could see it.
run_case(
&context,
&mut batch,
4,
Poison {
state: true,
..Poison::default()
},
Some(GdnBatchStage::StateSteps),
)?;
run_case(&context, &mut batch, 3, Poison::default(), None)?;
// Admission refusals leave nothing behind.
let idle = HostGemm {
poison: Poison::default(),
captured: RefCell::new(Captured::default()),
calls: Cell::new(0),
};
if batch.begin(0, &idle).is_ok() || batch.begin(GDN_BATCH_MAX_TOKENS + 1, &idle).is_ok() {
return mismatch("token bounds not enforced");
}
batch.close()
})();
let leaked = context.allocated_bytes();
assert!(result.is_ok(), "{result:?}");
assert_eq!(leaked, 0, "bytes still allocated after close");
}
+634
View File
@@ -0,0 +1,634 @@
//! Literal Original prompt GDN over the physical R/GR arena. No mixed or Block
//! payload roundtrip and no fabricated DeviceBuffer for a carved span.
use super::*;
use crate::original_prefill_arena::OriginalPromptSpan;
use crate::original_prefill_layout::PrefillPhase;
use crate::{NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead};
const SCRATCH: usize = 52_428_800;
const HISTORY: usize = 122_880;
const RESERVE: usize = 128 << 20;
pub struct OriginalGdnPromptDevice<'ctx> {
context: &'ctx Context<'ctx>,
capacity: usize,
profile: crate::GrNativeProfile,
batch: Option<GdnPrefillBatch<'ctx>>,
scratch: Option<DeviceBuffer<'ctx>>,
history: [Option<DeviceBuffer<'ctx>>; 2],
failed: bool,
}
/// Actual complete role owners; source/row/current prior are authenticated by runtime.
pub struct OriginalGdnPromptWeights<'w, 'ctx> {
pub matrices: [&'w DeviceBuffer<'ctx>; 5], // QKV,Z,Out,Alpha,Beta
pub formats: [GdnNativeFormat; 3],
pub aux: [&'w DeviceBuffer<'ctx>; 4],
}
enum DeviceCommand {
Kernel {
function: ffi::FunctionHandle,
grid: [u32; 3],
block: [u32; 3],
args: ffi::GdnPrefillArguments,
},
Gemm {
bf16: bool,
x: ffi::BufferHandle,
w: ffi::BufferHandle,
y: ffi::BufferHandle,
n: i32,
k: i32,
ldy: i32,
offset: usize,
beta: f32,
},
}
impl<'ctx> Context<'ctx> {
pub fn original_gdn_prompt_device(
&'ctx self,
capacity: usize,
profile: crate::GrNativeProfile,
) -> Result<OriginalGdnPromptDevice<'ctx>> {
OriginalGdnPromptDevice::new(self, capacity, profile)
}
}
impl<'ctx> OriginalGdnPromptDevice<'ctx> {
pub fn device_bytes(capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
Ok(SCRATCH + 2 * HISTORY + STATUS_BYTES)
}
fn new(
context: &'ctx Context<'ctx>,
capacity: usize,
profile: crate::GrNativeProfile,
) -> Result<Self> {
let required = Self::device_bytes(capacity)?
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|x| x > context.budget_bytes())
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
capacity,
profile,
batch: None,
scratch: None,
history: [None, None],
failed: false,
};
let operation = (|| -> Result<()> {
owner.batch = Some(context.gdn_prefill_batch_for_prompt(capacity)?);
owner.scratch = Some(context.allocate(SCRATCH)?);
for slot in &mut owner.history {
*slot = Some(context.allocate(HISTORY)?)
}
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(e) = operation {
let _ = owner.close();
return Err(e);
}
Ok(owner)
}
pub fn is_failed(&self) -> bool {
self.failed
|| self.context.is_poisoned()
|| self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed)
}
pub fn allocated_bytes(&self) -> usize {
self.batch
.as_ref()
.map_or(0, GdnPrefillBatch::allocated_bytes)
+ self.scratch.as_ref().map_or(0, DeviceBuffer::len)
+ self
.history
.iter()
.flatten()
.map(DeviceBuffer::len)
.sum::<usize>()
}
/// Consumes the actual affine GR read. `state` is untouched prior; only
/// `next_state` is written. Runtime alone may adopt it after this clean drain.
#[allow(clippy::too_many_arguments)]
pub fn produce<'arena, 'loan>(
&mut self,
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
weights: OriginalGdnPromptWeights<'_, 'ctx>,
state: &DeviceBuffer<'ctx>,
next_state: &DeviceBuffer<'ctx>,
history: &[f32],
) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> {
let lease = read.lease();
let t = read.rows();
if self.is_failed() || lease.is_failed() {
return Err(Error::ContextPoisoned);
}
if !read.context_matches(self.context) {
return Err(Error::ContextMismatch);
}
if !(1..=self.capacity).contains(&t) || history.len() != HISTORY_WORDS {
return Err(Error::InvalidQwenShape);
}
if history.iter().any(|x| !x.is_finite()) {
return Err(Error::NonFiniteMmqOutput("GDN prior history"));
}
workspace.validate_context(self.context)?;
let batch = self.batch.as_ref().ok_or(Error::ContextPoisoned)?;
let status = batch.status_handle()?;
let mut bindings = Bindings::new();
let mut buffer =
|role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result<ffi::BufferHandle> {
if !std::ptr::eq(b.context, self.context) {
return Err(Error::ContextMismatch);
}
if b.len() != bytes {
return Err(Error::InvalidQwenShape);
}
let h = b.handle.ok_or(Error::ContextPoisoned)?;
h.validate_projection_extent(bytes, 4)?;
workspace.reject_alias(h, bytes)?;
if h.overlaps(bytes, status, STATUS_BYTES) {
return Err(Error::OutputAliasesInput);
}
bindings.bind(role, h, bytes)?;
Ok(h)
};
let scratch = buffer(
Role::Scratch,
self.scratch.as_ref().ok_or(Error::ContextPoisoned)?,
SCRATCH,
)?;
let hin = buffer(
Role::History,
self.history[0].as_ref().ok_or(Error::ContextPoisoned)?,
HISTORY,
)?;
let hout = buffer(
Role::NextHistory,
self.history[1].as_ref().ok_or(Error::ContextPoisoned)?,
HISTORY,
)?;
let sin = buffer(Role::StateIn, state, STATE_WORDS * 4)?;
let sout = buffer(Role::StateOut, next_state, STATE_WORDS * 4)?;
let mut w = [sin; 5];
for (i, role, n, k) in [
(0, Role::QkvW, C, N),
(1, Role::ZW, ZV, N),
(2, Role::OutW, N, ZV),
(3, Role::AlphaW, HV, N),
(4, Role::BetaW, HV, N),
] {
let bytes = if i < 3 {
weights.formats[i].matrix_bytes(n, k)?
} else {
n * k * 2
};
w[i] = buffer(role, weights.matrices[i], bytes)?;
}
let mut a = [sin; 4];
for (i, role, n) in [
(0, Role::ConvW, C * 4 * 4),
(1, Role::Dt, HV * 4),
(2, Role::SsmA, HV * 4),
(3, Role::Gamma, S * 4),
] {
a[i] = buffer(role, weights.aux[i], n)?;
}
drop(buffer);
let mut carved = |role: Role,
phase: Option<(&str, usize)>,
common: Option<(OriginalPromptSpan, usize)>|
-> Result<ffi::BufferHandle> {
let (h, capacity, bytes) = if let Some((name, width)) = phase {
let (h, n) = lease.span(PrefillPhase::Gdn, name)?;
(h, n, t * width)
} else {
let (r, width) = common.ok_or(Error::InvalidQwenShape)?;
let (h, n) = lease.common_span(r)?;
(h, n, t * width)
};
let h = h.checked_subspan(capacity, 0, bytes)?;
h.validate_projection_extent(bytes, 2)?;
workspace.reject_alias(h, bytes)?;
if h.overlaps(bytes, status, STATUS_BYTES) {
return Err(Error::OutputAliasesInput);
}
bindings.bind(role, h, bytes)?;
Ok(h)
};
let mixed = carved(
Role::MixedH,
None,
Some((OriginalPromptSpan::MixedHalf, 5120)),
)?;
let high = carved(
Role::MixedBf,
None,
Some((OriginalPromptSpan::MixedHigh, 5120)),
)?;
let lower = if self.profile == crate::GrNativeProfile::HighAndLow {
Some(carved(
Role::MixedBfLo,
None,
Some((OriginalPromptSpan::MixedLow, 5120)),
)?)
} else {
None
};
let qkv = carved(Role::Qkv, Some(("qkv", C * 4)), None)?;
let z = carved(Role::Z, Some(("z", ZV * 4)), None)?;
let ab = carved(Role::Ab, Some(("ab", HV * 8)), None)?;
let gate = carved(Role::Gate, Some(("gate", HV * 4)), None)?;
let beta = carved(Role::Beta, Some(("beta", HV * 4)), None)?;
let h = carved(Role::H, Some(("hbuf", C * 4)), None)?;
let y = carved(Role::Y, Some(("y", ZV * 4)), None)?;
let yh = carved(Role::Y16, Some(("y_h", ZV * 2)), None)?;
let bo = carved(Role::Bo, None, Some((OriginalPromptSpan::Block, N * 4)))?;
drop(carved);
// Every owner/alias/shape admission above precedes the first write.
let mut commands = Vec::new();
commands
.try_reserve_exact(48)
.map_err(|_| Error::HostAllocation)?;
let funcs = batch.functions.as_ref().ok_or(Error::ContextPoisoned)?;
let mut push = |kernel: Kernel,
geometry: ([u32; 3], [u32; 3]),
args: &[ffi::KernelArg]|
-> Result<()> {
commands.push(DeviceCommand::Kernel {
function: funcs.get(kernel),
grid: geometry.0,
block: geometry.1,
args: ffi::GdnPrefillArguments::new(args)?,
});
Ok(())
};
push(
Kernel::Zero,
linear(SLOTS)?,
&[
ffi::KernelArg::Pointer(status),
ffi::KernelArg::U32(SLOTS as u32),
],
)?;
drop(push);
let add_kernel = |commands: &mut Vec<DeviceCommand>,
kernel: Kernel,
geometry: ([u32; 3], [u32; 3]),
args: &[ffi::KernelArg]|
-> Result<()> {
commands.push(DeviceCommand::Kernel {
function: funcs.get(kernel),
grid: geometry.0,
block: geometry.1,
args: ffi::GdnPrefillArguments::new(args)?,
});
Ok(())
};
let scan = |commands: &mut Vec<DeviceCommand>,
stage: GdnBatchStage,
data: ffi::BufferHandle|
-> Result<()> {
let word = status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?;
add_kernel(
commands,
if stage.is_half() {
Kernel::FiniteF16
} else {
Kernel::FiniteF32
},
linear(stage.elements(t))?,
&[
ffi::KernelArg::Pointer(data),
ffi::KernelArg::Pointer(word),
ffi::KernelArg::U32(stage.elements(t) as u32),
],
)
};
let native = |commands: &mut Vec<DeviceCommand>,
format: GdnNativeFormat,
input,
weight,
output,
n,
k|
-> Result<()> {
add_kernel(
commands,
format.kernel(),
linear(n * (k / 32))?,
&[
ffi::KernelArg::Pointer(weight),
ffi::KernelArg::I64((k / format.block().0 * format.block().1) as i64),
ffi::KernelArg::I64(0),
ffi::KernelArg::I64(n as i64),
ffi::KernelArg::I64((k / 32) as i64),
ffi::KernelArg::Pointer(scratch),
],
)?;
commands.push(DeviceCommand::Gemm {
bf16: false,
x: input,
w: scratch,
y: output,
n: n as i32,
k: k as i32,
ldy: n as i32,
offset: 0,
beta: 0.,
});
Ok(())
};
scan(&mut commands, GdnBatchStage::MixedH, mixed)?;
native(&mut commands, weights.formats[0], mixed, w[0], qkv, C, N)?;
scan(&mut commands, GdnBatchStage::Qkv, qkv)?;
native(&mut commands, weights.formats[1], mixed, w[1], z, ZV, N)?;
scan(&mut commands, GdnBatchStage::Z, z)?;
for (i, offset) in [(3, 0), (4, HV)] {
commands.push(DeviceCommand::Gemm {
bf16: true,
x: high,
w: w[i],
y: ab,
n: HV as i32,
k: N as i32,
ldy: 96,
offset,
beta: 0.,
});
if let Some(lo) = lower {
commands.push(DeviceCommand::Gemm {
bf16: true,
x: lo,
w: w[i],
y: ab,
n: HV as i32,
k: N as i32,
ldy: 96,
offset,
beta: 1.,
})
}
}
scan(&mut commands, GdnBatchStage::Ab, ab)?;
add_kernel(
&mut commands,
Kernel::Gates,
linear(t * HV)?,
&[
ffi::KernelArg::Pointer(ab),
ffi::KernelArg::Pointer(a[1]),
ffi::KernelArg::Pointer(a[2]),
ffi::KernelArg::Pointer(gate),
ffi::KernelArg::Pointer(beta),
ffi::KernelArg::I64(t as i64),
],
)?;
scan(&mut commands, GdnBatchStage::Gate, gate)?;
scan(&mut commands, GdnBatchStage::Beta, beta)?;
if t <= 64 {
add_kernel(
&mut commands,
Kernel::Conv,
([80, 1, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(hin),
ffi::KernelArg::Pointer(hout),
ffi::KernelArg::Pointer(qkv),
ffi::KernelArg::Pointer(a[0]),
ffi::KernelArg::Pointer(h),
ffi::KernelArg::I64(t as i64),
],
)?
} else {
add_kernel(
&mut commands,
Kernel::ConvTiled,
([80, t.div_ceil(64) as u32, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(hin),
ffi::KernelArg::Pointer(qkv),
ffi::KernelArg::Pointer(a[0]),
ffi::KernelArg::Pointer(h),
ffi::KernelArg::I64(t as i64),
],
)?;
add_kernel(
&mut commands,
Kernel::ConvHist,
([80, 1, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(hout),
ffi::KernelArg::Pointer(hin),
ffi::KernelArg::Pointer(qkv),
ffi::KernelArg::I64(t as i64),
],
)?;
}
scan(&mut commands, GdnBatchStage::ConvH, h)?;
scan(&mut commands, GdnBatchStage::NextHistory, hout)?;
add_kernel(
&mut commands,
Kernel::L2,
([32, t as u32, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(h),
ffi::KernelArg::F32(GDN_BATCH_EPSILON),
],
)?;
scan(&mut commands, GdnBatchStage::Qk, h)?;
let witness =
status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?;
add_kernel(
&mut commands,
Kernel::RecColsPipe,
([192, 1, 1], [32, 4, 1]),
&[
ffi::KernelArg::Pointer(sin),
ffi::KernelArg::Pointer(sout),
ffi::KernelArg::Pointer(h),
ffi::KernelArg::Pointer(gate),
ffi::KernelArg::Pointer(beta),
ffi::KernelArg::Pointer(y),
ffi::KernelArg::I64(t as i64),
ffi::KernelArg::Pointer(witness),
],
)?;
scan(&mut commands, GdnBatchStage::NextState, sout)?;
scan(&mut commands, GdnBatchStage::Readout, y)?;
add_kernel(
&mut commands,
Kernel::OutNorm,
([t as u32, 48, 1], [128, 1, 1]),
&[
ffi::KernelArg::Pointer(z),
ffi::KernelArg::Pointer(a[3]),
ffi::KernelArg::F32(GDN_BATCH_EPSILON),
ffi::KernelArg::Pointer(y),
ffi::KernelArg::Pointer(yh),
],
)?;
scan(&mut commands, GdnBatchStage::Y, y)?;
scan(&mut commands, GdnBatchStage::Y16, yh)?;
native(&mut commands, weights.formats[2], yh, w[2], bo, N, ZV)?;
scan(&mut commands, GdnBatchStage::Bo, bo)?;
let mut history_bytes = staging(HISTORY)?;
for (x, b) in history.iter().zip(history_bytes.as_chunks_mut::<4>().0) {
b.copy_from_slice(&x.to_le_bytes())
}
let mut flags = staging(STATUS_BYTES)?;
let mut final_history = staging(HISTORY)?;
let mut values = Vec::new();
values
.try_reserve_exact(HISTORY_WORDS)
.map_err(|_| Error::HostAllocation)?;
let context = self.context;
let blas = workspace.blas()?;
let guard = match context.enter() {
Ok(g) => g,
Err(e) => {
self.failed = true;
context.poison();
context.retain_driver();
return Err(e);
}
};
let mut operation = context
.driver
.api
.copy_from(hin, &history_bytes)
.and_then(|()| context.driver.api.synchronize());
for cmd in &mut commands {
if operation.is_err() {
break;
}
operation = match cmd {
DeviceCommand::Kernel {
function,
grid,
block,
args,
} => context.driver.api.launch_gdn_native(
*function,
GdnStream::from_raw(blas.stream()),
*grid,
*block,
args,
),
DeviceCommand::Gemm {
bf16,
x,
w,
y,
n,
k,
ldy,
offset,
beta,
} => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta),
}
}
let sync = blas.synchronize();
if operation.is_ok() && sync.is_ok() {
operation = context
.driver
.api
.copy_to(status, &mut flags)
.and_then(|()| context.driver.api.copy_to(hout, &mut final_history))
}
let all = context.driver.api.synchronize();
let pop = guard.finish();
let result = combine(combine(combine(operation, sync), all), pop);
if result.is_err() {
// A failed drain has no trustworthy completion boundary. Retain the
// command and host buffers before returning, so none can be freed
// while driver work may still reference them.
self.failed = true;
context.poison();
context.retain_driver();
std::mem::forget((commands, history_bytes, flags, final_history));
workspace.mark_failed();
return result.map(|()| unreachable!("failed GDN drain"));
}
let refusal = match decode_statuses(&flags, SLOTS) {
Ok(r) => r,
Err(e) => {
self.failed = true;
context.poison();
context.retain_driver();
return Err(e);
}
};
if let Some(stage) = refusal {
return Err(Error::NonFiniteMmqOutput(match stage {
GdnBatchStage::Bo => "GDN block",
_ => "GDN prompt stage",
}));
}
values.extend(
final_history
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x)),
);
if values.iter().any(|x| !x.is_finite()) {
return Err(Error::NonFiniteMmqOutput("GDN final history"));
}
Ok((read.from_completed_block(), values.into_boxed_slice()))
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut result = Ok(());
for b in self
.history
.iter_mut()
.filter_map(Option::take)
.chain(self.scratch.take())
{
let r = if self.context.is_poisoned() {
std::mem::forget(b);
Err(Error::ContextPoisoned)
} else {
b.release()
};
result = combine(result, r);
}
if let Some(b) = self.batch.take() {
let r = if self.context.is_poisoned() {
std::mem::forget(b);
Err(Error::ContextPoisoned)
} else {
b.close()
};
result = combine(result, r);
}
if result.is_err() {
self.context.poison();
self.context.retain_driver()
}
result
}
}
impl Drop for OriginalGdnPromptDevice<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
@@ -0,0 +1,188 @@
//! Closed complete finite witness for the canonical GDN next-state allocation.
//! Reuses the pinned integer exponent scan; performs no floating-point arithmetic.
use super::*;
const STATE_BYTES: usize = 3_145_728;
const STATE_WORDS: u32 = 786_432;
const STATUS_BYTES: usize = 4;
/// Thread-confined guard owning one persistent helper module and four status bytes.
/// Create and charge it before lazy expert-cache growth. Module memory is implicit
/// CUDA memory, separate from the four bytes exposed by `allocated_bytes`.
pub struct GdnStateFiniteGuard<'ctx> {
context: &'ctx Context<'ctx>,
status: Option<DeviceBuffer<'ctx>>,
module: Option<ffi::ModuleHandle>,
functions: Option<[ffi::FunctionHandle; 2]>,
failed: bool,
}
impl Context<'_> {
/// Construct a closed guard for the exact canonical 786,432-F32 GDN state.
pub fn gdn_state_finite_guard(&self) -> Result<GdnStateFiniteGuard<'_>> {
GdnStateFiniteGuard::new(self)
}
}
impl<'ctx> GdnStateFiniteGuard<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if context
.allocated_bytes()
.checked_add(STATUS_BYTES)
.is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
status: None,
module: None,
functions: None,
failed: false,
};
let result = (|| {
owner.status = Some(context.allocate(STATUS_BYTES)?);
let guard = context.enter()?;
let load = (|| {
// This existing loader validates the immutable asset digest/NUL.
let module = context.driver.api.load_mmq_resident()?;
owner.module = Some(module);
owner.functions = Some([
context.driver.api.mmq_resident_function(module, 0)?,
context.driver.api.mmq_resident_function(module, 1)?,
]);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poisoned.set(true);
}
combine(load, pop)
})();
if let Err(error) = result {
return combine(Err(error), owner.close());
}
Ok(owner)
}
/// Actual private status allocation; no state buffer is allocated here.
pub fn allocated_bytes(&self) -> usize {
self.status.as_ref().map_or(0, |status| status.bytes)
}
/// Scan every next-state word. `false` is a completed numerical refusal;
/// `Err` retains driver/admission errors, with CUDA uncertainty fenced.
/// No capability asserting causal origin or committed state is minted here.
pub fn check_next_state(&mut self, next: &DeviceBuffer<'_>) -> Result<bool> {
if self.failed || self.context.is_poisoned() || self.context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let functions = self.functions.ok_or(Error::ContextPoisoned)?;
if self.module.is_none() {
return Err(Error::ContextPoisoned);
}
let status_buffer = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(self.context, next.context)
|| !std::ptr::eq(self.context, status_buffer.context)
{
return Err(Error::ContextMismatch);
}
if next.bytes != STATE_BYTES || status_buffer.bytes != STATUS_BYTES {
return Err(Error::InvalidQwenShape);
}
let source = next.handle.ok_or(Error::ContextPoisoned)?;
let status = status_buffer.handle.ok_or(Error::ContextPoisoned)?;
source.validate_projection_extent(STATE_BYTES, 4)?;
status.validate_projection_extent(STATUS_BYTES, 4)?;
if source.overlaps(STATE_BYTES, status, STATUS_BYTES) {
return Err(Error::OutputAliasesInput);
}
// Stable boxed ABI arguments and owned staging precede all CUDA work.
let mut reset = ffi::MmqResidentArguments::zero(status, 1);
let mut scan = ffi::MmqResidentArguments::finite(source, status, 0, STATE_WORDS, 0);
let mut staging = Vec::new();
staging
.try_reserve_exact(STATUS_BYTES)
.map_err(|_| Error::HostAllocation)?;
staging.resize(STATUS_BYTES, 0);
let guard = self.context.enter()?;
let mut operation =
self.context
.driver
.api
.launch_mmq_resident(functions[0], 1, &mut reset);
if operation.is_ok() {
operation =
self.context
.driver
.api
.launch_mmq_resident(functions[1], STATE_WORDS, &mut scan);
}
if operation.is_ok() {
operation = self.context.driver.api.copy_to(status, &mut staging);
}
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if operation.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
self.context.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
// Completion is uncertain: retain all actual argument/staging owners.
// Context poison prevents state/status release or subsequent reuse.
std::mem::forget((reset, scan, staging));
return combine(combine(operation, sync), pop).map(|()| false);
}
combine(combine(operation, sync), pop)?;
match u32::from_le_bytes(staging.as_chunks::<4>().0[0]) {
0 => Ok(true),
1 => Ok(false),
_ => {
self.failed = true;
Err(Error::InvalidDriverValue("GDN finite witness"))
}
}
}
/// Attempt both owned releases and preserve their fixed error order.
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
self.functions = None;
let status_result = self.status.take().map_or(Ok(()), |status| {
if self.context.is_poisoned() {
std::mem::forget(status);
Err(Error::ContextPoisoned)
} else {
status.release()
}
});
if status_result.is_err() {
self.context.poisoned.set(true);
}
let module_result =
self.module
.take()
.map_or(Ok(()), |module| match self.context.enter() {
Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()),
Err(error) => Err(error),
});
if module_result.is_err() {
self.context.poisoned.set(true);
// Keep the driver ABI loaded while an uncertain module can exist.
std::mem::forget(Rc::clone(&self.context.driver.api));
}
combine(status_result, module_result)
}
}
impl Drop for GdnStateFiniteGuard<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
@@ -0,0 +1,332 @@
//! Closed upload scheduling for the original BatchGrInject kernel.
//! Raw completed output is not a model, finite, row or publication certificate.
use super::*;
const ROW_BYTES: [usize; 4] = [40960, 10240, 16, 40960];
const RESERVE: usize = 128 * 1024 * 1024;
pub const GR_BATCH_INJECT_WORKSPACE_BYTES: usize = 553_056;
/// Only the three independently stored whole-buffer layouts are selectable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GrBatchInjectShape {
T1,
T2,
T3,
}
impl GrBatchInjectShape {
pub fn tokens(self) -> usize {
match self {
Self::T1 => 1,
Self::T2 => 2,
Self::T3 => 3,
}
}
fn bank(self) -> usize {
self.tokens() - 1
}
}
/// Twelve eager whole owners; exclusive `&mut self` is the operation lease.
pub struct GrBatchInjectWorkspace<'ctx> {
context: &'ctx Context<'ctx>,
buffers: [[Option<DeviceBuffer<'ctx>>; 4]; 3],
module: Option<ffi::ModuleHandle>,
kernel: Option<ffi::FunctionHandle>,
failed: bool,
}
impl Context<'_> {
pub fn gr_batch_inject_workspace(&self) -> Result<GrBatchInjectWorkspace<'_>> {
GrBatchInjectWorkspace::new(self)
}
}
// Identical layout derivation to batch_gr_preview::batch_layout for the one
// fixed InjectResidual operation. No caller-selected operation or raw ranges.
fn layout(shape: GrBatchInjectShape) -> Result<qwen_ffi::Layout> {
let tokens = shape.tokens();
let mut result = Operation::InjectResidual.layout();
for bytes in result.bytes.iter_mut().take(result.count) {
*bytes = bytes.checked_mul(tokens).ok_or(Error::InvalidQwenShape)?;
}
result.columns = result
.columns
.checked_mul(tokens as u32)
.ok_or(Error::InvalidQwenShape)?;
result.grid_y = tokens as u32;
Ok(result)
}
impl<'ctx> GrBatchInjectWorkspace<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
// Validate the SAME original module receipt before any allocation.
qwen_ffi::gr_batch_preview_ptx()?;
let required = GR_BATCH_INJECT_WORKSPACE_BYTES
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget_bytes())
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
buffers: std::array::from_fn(|_| std::array::from_fn(|_| None)),
module: None,
kernel: None,
failed: false,
};
let operation = (|| {
for (bank, buffers) in owner.buffers.iter_mut().enumerate() {
for (slot, size) in ROW_BYTES.into_iter().enumerate() {
buffers[slot] = Some(context.allocate(size * (bank + 1))?);
}
}
let guard = context.enter()?;
let load = (|| {
let module = context.driver.api.load_gr_batch_preview_module()?;
owner.module = Some(module);
owner.kernel = Some(
context
.driver
.api
.qwen_function(module, Operation::InjectResidual)?,
);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver();
}
combine(load, pop)?;
// Module overhead consumes real free memory; retain the full reserve.
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
owner.handles(GrBatchInjectShape::T1)?;
Ok(())
})();
if let Err(primary) = operation {
return combine(Err(primary), owner.close());
}
Ok(owner)
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned() || self.context.handle.is_none()
}
pub fn allocated_bytes(&self) -> usize {
self.buffers
.iter()
.flatten()
.flatten()
.map(|buffer| buffer.bytes)
.sum()
}
fn handles(&self, shape: GrBatchInjectShape) -> Result<[ffi::BufferHandle; 9]> {
if self.is_failed() || self.module.is_none() || self.kernel.is_none() {
return Err(Error::ContextPoisoned);
}
// Fixed stack ledger; no heap allocation in whole-owner validation.
let first = self.buffers[0][0]
.as_ref()
.and_then(|b| b.handle)
.ok_or(Error::ContextPoisoned)?;
let mut owned = [(first, 0usize); 12];
let mut count = 0;
for (bank, buffers) in self.buffers.iter().enumerate() {
for (slot, buffer) in buffers.iter().enumerate() {
let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?;
let bytes = ROW_BYTES[slot] * (bank + 1);
if !std::ptr::eq(self.context, buffer.context) {
return Err(Error::ContextMismatch);
}
if buffer.bytes != bytes {
return Err(Error::InvalidQwenShape);
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_projection_extent(bytes, 4)?;
if owned
.iter()
.take(count)
.any(|(prior, prior_bytes)| handle.overlaps(bytes, *prior, *prior_bytes))
{
return Err(Error::OutputAliasesInput);
}
owned[count] = (handle, bytes);
count += 1;
}
}
let start = shape.bank() * 4;
let mut handles = [first; 9];
let mut bytes = [0usize; 9];
for i in 0..4 {
(handles[i], bytes[i]) = owned[start + i];
}
ranges_layout(
Operation::InjectResidual,
layout(shape)?,
handles,
bytes,
false,
)?;
if self.context.allocated_bytes() > self.context.budget_bytes() {
return Err(Error::BudgetExceeded);
}
Ok(handles)
}
/// Three initialized uploads and the original kernel share one completion.
/// The full output is copied by the unchanged synchronized copy helper.
/// Numeric overflow remains raw output; the runtime validates each real row.
pub fn inject(
&mut self,
context: &Context<'_>,
shape: GrBatchInjectShape,
streams: &[f32],
blocks: &[f32],
injects: &[f32],
) -> Result<Box<[f32]>> {
if !std::ptr::eq(self.context, context) {
return Err(Error::ContextMismatch);
}
let handles = self.handles(shape)?;
let tokens = shape.tokens();
if streams.len() != 10240 * tokens
|| blocks.len() != 2560 * tokens
|| injects.len() != 4 * tokens
{
return Err(Error::InvalidQwenShape);
}
if streams
.iter()
.chain(blocks)
.chain(injects)
.any(|value| !value.is_finite())
{
return Err(Error::InvalidDriverValue("GR batch injection finite input"));
}
// Fallible initialized staging is retained through every attempted command.
let staging = [encode(streams)?, encode(blocks)?, encode(injects)?];
let mut arguments = Box::new(Arguments::with_layout(
Operation::InjectResidual,
layout(shape)?,
handles,
0.,
));
let kernel = self.kernel.ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let mut commands = Ok(());
for (handle, bytes) in handles.iter().zip(staging.iter()).take(3) {
commands = self.context.driver.api.copy_from(*handle, bytes);
if commands.is_err() {
break;
}
}
if commands.is_ok() {
commands = self.context.driver.api.launch_qwen(
kernel,
Operation::InjectResidual,
&mut arguments,
);
}
// Fence all attempted uploads/launches, including the first failed call.
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if commands.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
}
if sync.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
// close/Drop retains the real module and all charged device owners.
std::mem::forget((staging, arguments));
}
combine(combine(commands, sync), pop)?;
let output = self.buffers[shape.bank()][3]
.as_ref()
.ok_or(Error::ContextPoisoned)?;
let readback = match output.copy_to_owned(40960 * tokens) {
Ok(bytes) => bytes,
Err(error) => {
if !matches!(error, Error::HostAllocation) {
self.failed = true;
}
return Err(error);
}
};
let mut values = Vec::new();
values
.try_reserve_exact(10240 * tokens)
.map_err(|_| Error::HostAllocation)?;
values.extend(
readback
.as_chunks::<4>()
.0
.iter()
.map(|bytes| f32::from_le_bytes(*bytes)),
);
Ok(values.into_boxed_slice())
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
self.kernel = None;
let mut result = Ok(());
for buffer in self.buffers.iter_mut().flatten() {
if let Some(buffer) = buffer.take() {
let release = if self.context.is_poisoned() {
std::mem::forget(buffer);
self.context.retain_driver();
Err(Error::ContextPoisoned)
} else {
buffer.release()
};
if release.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, release);
}
}
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) => combine(self.context.driver.api.unload(module), guard.finish()),
Err(error) => Err(error),
}
};
if release.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, release);
}
result
}
}
impl Drop for GrBatchInjectWorkspace<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
fn encode(values: &[f32]) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(values.len() * 4)
.map_err(|_| Error::HostAllocation)?;
bytes.extend(values.iter().flat_map(|value| value.to_le_bytes()));
Ok(bytes)
}
#[cfg(test)]
#[path = "gr_batch_inject_workspace_gpu.rs"]
mod gpu;
@@ -0,0 +1,295 @@
//! Original methods FIRST; synthetic finite inputs are not a model certificate.
use super::*;
use crate::Driver;
type Products = [Vec<u8>; 4];
fn check(ok: bool) -> Result<()> {
if ok {
Ok(())
} else {
Err(Error::InvalidDriverValue("GR batch workspace proof"))
}
}
fn bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn inputs(tokens: usize, pattern: usize) -> [Vec<f32>; 3] {
let streams = (0..10240 * tokens)
.map(|i| match pattern {
0 => (i as i32 % 83 - 41) as f32 * 0.03125,
1 => (i as i32 % 107 - 53) as f32 * -0.0625,
_ => {
if i % 2 == 0 {
-0.0
} else {
0.0
}
}
})
.collect();
let blocks = (0..2560 * tokens)
.map(|i| match pattern {
0 => (i as i32 % 31 - 15) as f32 * 0.015625,
1 => (i as i32 % 53 - 26) as f32 * -0.125,
_ => {
if i % 2 == 0 {
0.0
} else {
-0.0
}
}
})
.collect();
let injects = (0..4 * tokens)
.map(|i| match pattern {
0 => (i % 7) as f32 * 0.25,
1 => (i as i32 % 13 - 6) as f32 * -0.0625,
_ => {
if i % 2 == 0 {
-0.0
} else {
0.0
}
}
})
.collect();
[streams, blocks, injects]
}
// All actual old owners are explicitly closed even on a comparison refusal.
fn original(
context: &Context<'_>,
shape: GrBatchInjectShape,
source: &[Vec<f32>; 3],
) -> Result<Products> {
let mut buffers: [Option<DeviceBuffer<'_>>; 4] = std::array::from_fn(|_| None);
let result = (|| {
for (i, size) in ROW_BYTES.into_iter().enumerate() {
buffers[i] = Some(context.allocate(size * shape.tokens())?);
}
for (buffer, source) in buffers.iter_mut().zip(source).take(3) {
buffer
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from(&bytes(source))?;
}
let (sources, output) = buffers.split_at_mut(3);
context.gr_batch_inject_residual_f32(
shape.tokens(),
sources[0].as_ref().ok_or(Error::ContextPoisoned)?,
sources[1].as_ref().ok_or(Error::ContextPoisoned)?,
sources[2].as_ref().ok_or(Error::ContextPoisoned)?,
output[0].as_mut().ok_or(Error::ContextPoisoned)?,
)?;
let mut products: Products = std::array::from_fn(|_| Vec::new());
for (i, buffer) in buffers.iter().enumerate() {
products[i] = buffer
.as_ref()
.ok_or(Error::ContextPoisoned)?
.copy_to_owned(ROW_BYTES[i] * shape.tokens())?;
}
Ok(products)
})();
let mut cleanup = Ok(());
for buffer in buffers.into_iter().flatten() {
cleanup = combine(cleanup, buffer.release());
}
combine(result, cleanup)
}
fn products(workspace: &GrBatchInjectWorkspace<'_>, shape: GrBatchInjectShape) -> Result<Products> {
let mut result = std::array::from_fn(|_| Vec::new());
for (i, buffer) in workspace.buffers[shape.bank()].iter().enumerate() {
result[i] = buffer
.as_ref()
.ok_or(Error::ContextPoisoned)?
.copy_to_owned(ROW_BYTES[i] * shape.tokens())?;
}
Ok(result)
}
fn original_first(
context: &Context<'_>,
workspace: &mut GrBatchInjectWorkspace<'_>,
shape: GrBatchInjectShape,
source: &[Vec<f32>; 3],
) -> Result<usize> {
let expected = original(context, shape, source)?;
let charged = context.allocated_bytes();
let actual = workspace.inject(context, shape, &source[0], &source[1], &source[2])?;
check(context.allocated_bytes() == charged && !workspace.is_failed())?;
let observed = products(workspace, shape)?;
for i in 0..4 {
check(observed[i] == expected[i])?;
}
for i in 0..3 {
check(observed[i] == bytes(&source[i]))?;
}
check(bytes(&actual) == expected[3])?;
Ok(expected.iter().map(|p| p.len() / 4).sum())
}
fn refuses_without_change(
context: &Context<'_>,
workspace: &mut GrBatchInjectWorkspace<'_>,
shape: GrBatchInjectShape,
source: &[Vec<f32>; 3],
expected: Error,
) -> Result<()> {
let previous = products(workspace, shape)?;
let charged = context.allocated_bytes();
let refusal = workspace.inject(context, shape, &source[0], &source[1], &source[2]);
check(refusal.err() == Some(expected))?;
check(
products(workspace, shape)? == previous
&& context.allocated_bytes() == charged
&& !workspace.is_failed(),
)
}
#[test]
#[ignore]
fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() {
assert_eq!(
std::env::var("LELEKA_STRA172_RUN_GR_BATCH_INJECT_WORKSPACE").as_deref(),
Ok("yes")
);
let driver = Driver::load().expect("real CUDA driver required");
let device = driver.device(0).expect("real GPU required");
let context = device
.create_context(512 * 1024 * 1024)
.expect("owned Context");
let foreign = device
.create_context(512 * 1024 * 1024)
.expect("foreign Context");
let budget = device
.create_context(GR_BATCH_INJECT_WORKSPACE_BYTES + RESERVE - 1)
.expect("budget Context");
let result = (|| -> Result<(usize, usize)> {
// Scope the borrowed Result/owner before the budget Context is moved.
let refused = match budget.gr_batch_inject_workspace() {
Ok(owner) => combine(
Err(Error::InvalidDriverValue("missing eager budget refusal")),
owner.close(),
),
Err(error) => check(error == Error::BudgetExceeded),
};
refused?;
check(budget.allocated_bytes() == 0)?;
let mut workspace = context.gr_batch_inject_workspace()?;
let operation = (|| -> Result<(usize, usize)> {
check(workspace.allocated_bytes() == GR_BATCH_INJECT_WORKSPACE_BYTES)?;
let mut words = 0;
let mut guards = 1;
for shape in [
GrBatchInjectShape::T1,
GrBatchInjectShape::T2,
GrBatchInjectShape::T3,
] {
for pattern in [0, 1, 2, 0] {
words += original_first(
&context,
&mut workspace,
shape,
&inputs(shape.tokens(), pattern),
)?;
}
// All three roles and both short/long lengths refuse before writes.
for role in 0..3 {
let mut wrong = inputs(shape.tokens(), 1);
wrong[role].pop();
refuses_without_change(
&context,
&mut workspace,
shape,
&wrong,
Error::InvalidQwenShape,
)?;
guards += 1;
wrong[role].push(0.);
wrong[role].push(0.);
refuses_without_change(
&context,
&mut workspace,
shape,
&wrong,
Error::InvalidQwenShape,
)?;
guards += 1;
for invalid in [f32::NAN, f32::INFINITY] {
let mut late = inputs(shape.tokens(), 1);
*late[role].last_mut().ok_or(Error::InvalidQwenShape)? = invalid;
refuses_without_change(
&context,
&mut workspace,
shape,
&late,
Error::InvalidDriverValue("GR batch injection finite input"),
)?;
guards += 1;
words += original_first(
&context,
&mut workspace,
shape,
&inputs(shape.tokens(), 0),
)?;
}
}
let previous = products(&workspace, shape)?;
let source = inputs(shape.tokens(), 0);
check(
workspace
.inject(&foreign, shape, &source[0], &source[1], &source[2])
.err()
== Some(Error::ContextMismatch),
)?;
check(products(&workspace, shape)? == previous && !workspace.is_failed())?;
guards += 1;
// Completed numeric overflow is raw output, not transport poison.
let overflow = [
vec![f32::MAX; shape.tokens() * 10240],
vec![f32::MAX; shape.tokens() * 2560],
vec![f32::MAX; shape.tokens() * 4],
];
words += original_first(&context, &mut workspace, shape, &overflow)?;
check(
products(&workspace, shape)?[3]
.as_chunks::<4>()
.0
.iter()
.any(|b| !f32::from_le_bytes(*b).is_finite()),
)?;
words +=
original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 1))?;
}
// Switching one bank cannot overwrite a completed other whole bank.
let t1 = products(&workspace, GrBatchInjectShape::T1)?;
let t2 = products(&workspace, GrBatchInjectShape::T2)?;
words += original_first(
&context,
&mut workspace,
GrBatchInjectShape::T3,
&inputs(3, 2),
)?;
check(
products(&workspace, GrBatchInjectShape::T1)? == t1
&& products(&workspace, GrBatchInjectShape::T2)? == t2,
)?;
guards += 1;
Ok((words, guards))
})();
combine(operation, workspace.close())
})();
let allocated = [
context.allocated_bytes(),
foreign.allocated_bytes(),
budget.allocated_bytes(),
];
// Every actual Context is closed before result/numerical assertions.
let result = combine(
combine(combine(result, context.close()), foreign.close()),
budget.close(),
);
let (words, guards) = result.expect("original-first workspace proof and exhaustive teardown");
assert_eq!(allocated, [0; 3]);
println!(
"GR_BATCH_INJECT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true raw_overflow=true"
);
}
+726
View File
@@ -0,0 +1,726 @@
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{norm.cu,common.cuh}. Scope: contiguous weighted F32 RMSNorm.
//
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Fixed GR assets derived from these pinned imported sources:
// native_gr_norm.cu SHA256 494cb16ddcaf345972c1c05c406e2f4377733975ae35bfe0587bfe91bb75b228
// native_gr_postops.cu SHA256 8c10274e8693bf8c3ddc85073731841d62a8467308f5a29ed3b07e441f63ca28
// This is candidate regeneration source, never the independent native oracle.
// Offline only: nvcc --ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math
// --ftz=true --fmad=true offline_gr_kernel.cu -o PRIVATE_OUTPUT
// Cargo neither compiles nor links this file; no Toolkit serving dependency.
// Fixed topology N2560/HC4/H320. Norm grid4/block1024; other entries block256.
// All pointers are aligned4, exact owned extents; no output/input overlap except
// exact residual/output alias for inject. Runtime stage must validate finite
// inputs/intermediates/candidates before publishing. Kernels have no status ABI.
// No asset is admitted solely by this source or its generated PTX.
// Failure-only qNaN0x7fc00000 guards preserve every valid arithmetic instruction.
// Invalid partials propagate through the same warp/shared tree; staged finite
// validation must discard the entire candidate before publishing any stream.
// Authored trusted PTX candidate, not claimed byte-identical to nvcc output.
// Primitive instruction semantics: NVIDIA PTX ISA, CUDA13.0.1 archive.
// Fast exp candidate uses log2(e) scaling and ex2.approx.ftz; fast divide/rsqrt
// use approximate FTZ primitives. Exact installed-profile interval qualification
// remains required; prior original native outputs do not qualify these bytes.
.version 9.0
.target sm_120
.address_size 64
// Private fixed storage; no host symbol/write API.
.global .align 4 .u32 leleka_gr_norm_columns = 2560;
.visible .entry leleka_gr_norm_f32(
.param .u64 residual,
.param .u64 gamma,
.param .u64 output,
.param .f32 epsilon
)
.reqntid 1024, 1, 1
{
.reg .pred %p<4>;
.reg .b32 %r<16>;
.reg .b64 %rd<12>;
.reg .f32 %f<14>;
.shared .align 4 .b8 norm_sums[128];
ld.param.u64 %rd0, [residual];
ld.param.u64 %rd1, [gamma];
ld.param.u64 %rd2, [output];
ld.param.f32 %f11, [epsilon];
mov.u32 %r15, %ctaid.y;
mul.wide.u32 %rd10, %r15, 40960;
add.u64 %rd0, %rd0, %rd10;
add.u64 %rd2, %rd2, %rd10;
testp.finite.f32 %p3, %f11;
@!%p3 mov.f32 %f11, 0f7FC00000;
setp.lt.f32 %p3, %f11, 0f00000000;
@%p3 mov.f32 %f11, 0f7FC00000;
mov.u32 %r0, %ctaid.x;
mov.u32 %r1, %tid.x;
setp.ge.u32 %p0, %r0, 4;
@%p0 bra NORM_DONE;
mul.wide.u32 %rd3, %r0, 10240;
add.u64 %rd0, %rd0, %rd3;
add.u64 %rd1, %rd1, %rd3;
add.u64 %rd2, %rd2, %rd3;
mov.f32 %f0, 0f00000000;
mov.u32 %r2, %r1;
NORM_SQUARE:
setp.ge.u32 %p1, %r2, 2560;
@%p1 bra NORM_WARP;
mul.wide.u32 %rd4, %r2, 4;
add.u64 %rd5, %rd0, %rd4;
ld.global.f32 %f1, [%rd5];
testp.finite.f32 %p3, %f1;
@!%p3 mov.f32 %f1, 0f7FC00000;
// Native partial+=value*value contracts under the pinned fmad=true profile.
fma.rn.ftz.f32 %f0, %f1, %f1, %f0;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
add.u32 %r2, %r2, 1024;
bra NORM_SQUARE;
NORM_WARP:
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 16, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 8, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 4, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 2, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 1, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
and.b32 %r3, %r1, 31;
shr.u32 %r4, %r1, 5;
mov.u64 %rd6, norm_sums;
cvta.to.shared.u64 %rd6, %rd6;
setp.ne.u32 %p2, %r3, 0;
@%p2 bra NORM_STORED;
mul.wide.u32 %rd7, %r4, 4;
add.u64 %rd7, %rd6, %rd7;
st.shared.f32 [%rd7], %f0;
NORM_STORED:
bar.sync 0;
// Every warp reads all 32 initialized warp sums and repeats the XOR tree.
mul.wide.u32 %rd7, %r3, 4;
add.u64 %rd7, %rd6, %rd7;
ld.shared.f32 %f0, [%rd7];
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 16, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 8, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 4, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 2, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
mov.b32 %r12, %f0;
shfl.sync.bfly.b32 %r13, %r12, 1, 31, -1;
mov.b32 %f10, %r13;
add.rn.ftz.f32 %f0, %f0, %f10;
testp.finite.f32 %p3, %f0;
@!%p3 mov.f32 %f0, 0f7FC00000;
div.approx.ftz.f32 %f2, %f0, 0f45200000;
testp.finite.f32 %p3, %f2;
@!%p3 mov.f32 %f2, 0f7FC00000;
// Mean remains a refusal guard; denominator has one fused rounding.
@!%p3 mov.f32 %f0, 0f7FC00000;
ld.volatile.global.u32 %r14, [leleka_gr_norm_columns];
cvt.rn.f32.s32 %f12, %r14;
rcp.approx.ftz.f32 %f13, %f12;
fma.rn.ftz.f32 %f2, %f0, %f13, %f11;
testp.finite.f32 %p3, %f2;
@!%p3 mov.f32 %f2, 0f7FC00000;
setp.le.f32 %p3, %f2, 0f00000000;
@%p3 mov.f32 %f2, 0f7FC00000;
rsqrt.approx.ftz.f32 %f3, %f2;
testp.finite.f32 %p3, %f3;
@!%p3 mov.f32 %f3, 0f7FC00000;
mov.u32 %r2, %r1;
NORM_OUTPUT:
setp.ge.u32 %p3, %r2, 2560;
@%p3 bra NORM_DONE;
mul.wide.u32 %rd4, %r2, 4;
add.u64 %rd5, %rd0, %rd4;
ld.global.f32 %f4, [%rd5];
testp.finite.f32 %p3, %f4;
@!%p3 mov.f32 %f4, 0f7FC00000;
add.u64 %rd5, %rd1, %rd4;
ld.global.f32 %f5, [%rd5];
testp.finite.f32 %p3, %f5;
@!%p3 mov.f32 %f5, 0f7FC00000;
mul.rn.ftz.f32 %f6, %f3, %f4;
testp.finite.f32 %p3, %f6;
@!%p3 mov.f32 %f6, 0f7FC00000;
mul.rn.ftz.f32 %f6, %f6, %f5;
testp.finite.f32 %p3, %f6;
@!%p3 mov.f32 %f6, 0f7FC00000;
add.u64 %rd5, %rd2, %rd4;
st.global.f32 [%rd5], %f6;
add.u32 %r2, %r2, 1024;
bra NORM_OUTPUT;
NORM_DONE:
ret;
}
// Regenerated NVCC12.8.93 postops; retained exact closed ABI/block256.
.visible .entry leleka_gr_down_silu_hc_f32(
.param .u64 down,
.param .u64 output
)
.reqntid 256, 1, 1
{
.reg .pred %p<7>;
.reg .b32 %r<5>;
.reg .f32 %f<18>;
.reg .b64 %rd<8>;
ld.param.u64 %rd1, [down];
ld.param.u64 %rd2, [output];
mov.u32 %r2, %ctaid.x;
shl.b32 %r3, %r2, 8;
mov.u32 %r4, %tid.x;
or.b32 %r1, %r3, %r4;
setp.gt.u32 %p1, %r1, 319;
@%p1 bra $L__BB1_2;
cvta.to.global.u64 %rd3, %rd2;
cvta.to.global.u64 %rd4, %rd1;
mul.wide.u32 %rd5, %r1, 4;
add.s64 %rd6, %rd4, %rd5;
ld.global.nc.f32 %f1, [%rd6];
abs.ftz.f32 %f2, %f1;
setp.equ.ftz.f32 %p2, %f2, 0f7F800000;
selp.f32 %f3, 0f7FC00000, %f1, %p2;
fma.rn.ftz.f32 %f4, %f3, 0f3E800000, 0f00000000;
abs.ftz.f32 %f5, %f4;
setp.equ.ftz.f32 %p3, %f5, 0f7F800000;
selp.f32 %f6, 0f7FC00000, %f4, %p3;
neg.ftz.f32 %f7, %f6;
selp.f32 %f8, 0f7FC00000, %f7, %p3;
mul.ftz.f32 %f9, %f8, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f10, %f9;
setp.ltu.ftz.f32 %p4, %f10, 0f00000000;
selp.f32 %f11, 0f7FC00000, %f10, %p4;
mov.f32 %f12, 0f3F800000;
add.rn.ftz.f32 %f13, %f12, %f11;
setp.gt.ftz.f32 %p5, %f13, 0f00000000;
selp.f32 %f14, %f13, 0f7FC00000, %p5;
div.approx.ftz.f32 %f15, %f6, %f14;
abs.ftz.f32 %f16, %f15;
setp.equ.ftz.f32 %p6, %f16, 0f7F800000;
selp.f32 %f17, 0f7FC00000, %f15, %p6;
add.s64 %rd7, %rd3, %rd5;
st.global.f32 [%rd7], %f17;
$L__BB1_2:
ret;
}
// Regenerated NVCC12.8.93 postops; retained exact closed ABI/block256.
.visible .entry leleka_gr_gate_mean_layer_fused_f32(
.param .u64 xn,
.param .u64 gates,
.param .u64 products,
.param .u64 mixed
)
.reqntid 256, 1, 1
{
.reg .pred %p<31>;
.reg .b32 %r<5>;
.reg .f32 %f<90>;
.reg .b64 %rd<14>;
// BEGIN batch-column declarations
.reg .b32 %leleka_batch_y;
.reg .b64 %leleka_batch_off<4>;
// END batch-column declarations
ld.param.u64 %rd1, [xn];
ld.param.u64 %rd2, [gates];
ld.param.u64 %rd3, [products];
ld.param.u64 %rd4, [mixed];
// BEGIN batch-column offsets
mov.u32 %leleka_batch_y, %ctaid.y;
mul.wide.u32 %leleka_batch_off0, %leleka_batch_y, 40960;
add.u64 %rd1, %rd1, %leleka_batch_off0;
mul.wide.u32 %leleka_batch_off1, %leleka_batch_y, 40960;
add.u64 %rd2, %rd2, %leleka_batch_off1;
mul.wide.u32 %leleka_batch_off2, %leleka_batch_y, 40960;
add.u64 %rd3, %rd3, %leleka_batch_off2;
mul.wide.u32 %leleka_batch_off3, %leleka_batch_y, 10240;
add.u64 %rd4, %rd4, %leleka_batch_off3;
// END batch-column offsets
mov.u32 %r2, %ctaid.x;
shl.b32 %r3, %r2, 8;
mov.u32 %r4, %tid.x;
add.s32 %r1, %r3, %r4;
setp.gt.u32 %p1, %r1, 2559;
@%p1 bra $L__BB2_2;
cvta.to.global.u64 %rd5, %rd4;
cvta.to.global.u64 %rd6, %rd1;
cvta.to.global.u64 %rd7, %rd2;
cvta.to.global.u64 %rd8, %rd3;
mul.wide.u32 %rd9, %r1, 4;
add.s64 %rd10, %rd6, %rd9;
ld.global.nc.f32 %f1, [%rd10];
abs.ftz.f32 %f2, %f1;
setp.equ.ftz.f32 %p2, %f2, 0f7F800000;
selp.f32 %f3, 0f7FC00000, %f1, %p2;
add.s64 %rd11, %rd7, %rd9;
ld.global.nc.f32 %f4, [%rd11];
neg.ftz.f32 %f5, %f4;
abs.ftz.f32 %f6, %f4;
setp.equ.ftz.f32 %p3, %f6, 0f7F800000;
selp.f32 %f7, 0f7FC00000, %f5, %p3;
mul.ftz.f32 %f8, %f7, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f9, %f8;
setp.ltu.ftz.f32 %p4, %f9, 0f00000000;
selp.f32 %f10, 0f7FC00000, %f9, %p4;
mov.f32 %f11, 0f3F800000;
add.rn.ftz.f32 %f12, %f11, %f10;
setp.gt.ftz.f32 %p5, %f12, 0f00000000;
selp.f32 %f13, %f12, 0f7FC00000, %p5;
div.approx.ftz.f32 %f14, %f11, %f13;
abs.ftz.f32 %f15, %f14;
setp.equ.ftz.f32 %p6, %f15, 0f7F800000;
selp.f32 %f16, 0f7FC00000, %f14, %p6;
mul.rn.ftz.f32 %f17, %f3, %f16;
abs.ftz.f32 %f18, %f17;
setp.equ.ftz.f32 %p7, %f18, 0f7F800000;
selp.f32 %f19, 0f7FC00000, %f17, %p7;
add.s64 %rd12, %rd8, %rd9;
st.global.f32 [%rd12], %f19;
fma.rn.ftz.f32 %f20, %f3, %f16, 0f00000000;
abs.ftz.f32 %f21, %f20;
setp.equ.ftz.f32 %p8, %f21, 0f7F800000;
selp.f32 %f22, 0f7FC00000, %f20, %p8;
ld.global.nc.f32 %f23, [%rd10+10240];
abs.ftz.f32 %f24, %f23;
setp.equ.ftz.f32 %p9, %f24, 0f7F800000;
selp.f32 %f25, 0f7FC00000, %f23, %p9;
ld.global.nc.f32 %f26, [%rd11+10240];
neg.ftz.f32 %f27, %f26;
abs.ftz.f32 %f28, %f26;
setp.equ.ftz.f32 %p10, %f28, 0f7F800000;
selp.f32 %f29, 0f7FC00000, %f27, %p10;
mul.ftz.f32 %f30, %f29, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f31, %f30;
setp.ltu.ftz.f32 %p11, %f31, 0f00000000;
selp.f32 %f32, 0f7FC00000, %f31, %p11;
add.rn.ftz.f32 %f33, %f11, %f32;
setp.gt.ftz.f32 %p12, %f33, 0f00000000;
selp.f32 %f34, %f33, 0f7FC00000, %p12;
div.approx.ftz.f32 %f35, %f11, %f34;
abs.ftz.f32 %f36, %f35;
setp.equ.ftz.f32 %p13, %f36, 0f7F800000;
selp.f32 %f37, 0f7FC00000, %f35, %p13;
mul.rn.ftz.f32 %f38, %f25, %f37;
abs.ftz.f32 %f39, %f38;
setp.equ.ftz.f32 %p14, %f39, 0f7F800000;
selp.f32 %f40, 0f7FC00000, %f38, %p14;
st.global.f32 [%rd12+10240], %f40;
fma.rn.ftz.f32 %f41, %f25, %f37, %f22;
abs.ftz.f32 %f42, %f41;
setp.equ.ftz.f32 %p15, %f42, 0f7F800000;
selp.f32 %f43, 0f7FC00000, %f41, %p15;
ld.global.nc.f32 %f44, [%rd10+20480];
abs.ftz.f32 %f45, %f44;
setp.equ.ftz.f32 %p16, %f45, 0f7F800000;
selp.f32 %f46, 0f7FC00000, %f44, %p16;
ld.global.nc.f32 %f47, [%rd11+20480];
neg.ftz.f32 %f48, %f47;
abs.ftz.f32 %f49, %f47;
setp.equ.ftz.f32 %p17, %f49, 0f7F800000;
selp.f32 %f50, 0f7FC00000, %f48, %p17;
mul.ftz.f32 %f51, %f50, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f52, %f51;
setp.ltu.ftz.f32 %p18, %f52, 0f00000000;
selp.f32 %f53, 0f7FC00000, %f52, %p18;
add.rn.ftz.f32 %f54, %f11, %f53;
setp.gt.ftz.f32 %p19, %f54, 0f00000000;
selp.f32 %f55, %f54, 0f7FC00000, %p19;
div.approx.ftz.f32 %f56, %f11, %f55;
abs.ftz.f32 %f57, %f56;
setp.equ.ftz.f32 %p20, %f57, 0f7F800000;
selp.f32 %f58, 0f7FC00000, %f56, %p20;
mul.rn.ftz.f32 %f59, %f46, %f58;
abs.ftz.f32 %f60, %f59;
setp.equ.ftz.f32 %p21, %f60, 0f7F800000;
selp.f32 %f61, 0f7FC00000, %f59, %p21;
st.global.f32 [%rd12+20480], %f61;
fma.rn.ftz.f32 %f62, %f46, %f58, %f43;
abs.ftz.f32 %f63, %f62;
setp.equ.ftz.f32 %p22, %f63, 0f7F800000;
selp.f32 %f64, 0f7FC00000, %f62, %p22;
ld.global.nc.f32 %f65, [%rd10+30720];
abs.ftz.f32 %f66, %f65;
setp.equ.ftz.f32 %p23, %f66, 0f7F800000;
selp.f32 %f67, 0f7FC00000, %f65, %p23;
ld.global.nc.f32 %f68, [%rd11+30720];
neg.ftz.f32 %f69, %f68;
abs.ftz.f32 %f70, %f68;
setp.equ.ftz.f32 %p24, %f70, 0f7F800000;
selp.f32 %f71, 0f7FC00000, %f69, %p24;
mul.ftz.f32 %f72, %f71, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f73, %f72;
setp.ltu.ftz.f32 %p25, %f73, 0f00000000;
selp.f32 %f74, 0f7FC00000, %f73, %p25;
add.rn.ftz.f32 %f75, %f11, %f74;
setp.gt.ftz.f32 %p26, %f75, 0f00000000;
selp.f32 %f76, %f75, 0f7FC00000, %p26;
div.approx.ftz.f32 %f77, %f11, %f76;
abs.ftz.f32 %f78, %f77;
setp.equ.ftz.f32 %p27, %f78, 0f7F800000;
selp.f32 %f79, 0f7FC00000, %f77, %p27;
mul.rn.ftz.f32 %f80, %f67, %f79;
abs.ftz.f32 %f81, %f80;
setp.equ.ftz.f32 %p28, %f81, 0f7F800000;
selp.f32 %f82, 0f7FC00000, %f80, %p28;
st.global.f32 [%rd12+30720], %f82;
fma.rn.ftz.f32 %f83, %f67, %f79, %f64;
abs.ftz.f32 %f84, %f83;
setp.equ.ftz.f32 %p29, %f84, 0f7F800000;
selp.f32 %f85, 0f7FC00000, %f83, %p29;
mov.f32 %f86, 0f3E800000;
mul.rn.ftz.f32 %f87, %f86, %f85;
abs.ftz.f32 %f88, %f87;
setp.equ.ftz.f32 %p30, %f88, 0f7F800000;
selp.f32 %f89, 0f7FC00000, %f87, %p30;
add.s64 %rd13, %rd5, %rd9;
st.global.f32 [%rd13], %f89;
$L__BB2_2:
ret;
}
// Regenerated NVCC12.8.93 postops; retained exact closed ABI/block256.
.visible .entry leleka_gr_gate_mean_final_unfused_f32(
.param .u64 xn,
.param .u64 gates,
.param .u64 products,
.param .u64 mixed
)
.reqntid 256, 1, 1
{
.reg .pred %p<30>;
.reg .b32 %r<5>;
.reg .f32 %f<86>;
.reg .b64 %rd<14>;
// BEGIN batch-column declarations
.reg .b32 %leleka_batch_y;
.reg .b64 %leleka_batch_off<4>;
// END batch-column declarations
ld.param.u64 %rd1, [xn];
ld.param.u64 %rd2, [gates];
ld.param.u64 %rd3, [products];
ld.param.u64 %rd4, [mixed];
// BEGIN batch-column offsets
mov.u32 %leleka_batch_y, %ctaid.y;
mul.wide.u32 %leleka_batch_off0, %leleka_batch_y, 40960;
add.u64 %rd1, %rd1, %leleka_batch_off0;
mul.wide.u32 %leleka_batch_off1, %leleka_batch_y, 40960;
add.u64 %rd2, %rd2, %leleka_batch_off1;
mul.wide.u32 %leleka_batch_off2, %leleka_batch_y, 40960;
add.u64 %rd3, %rd3, %leleka_batch_off2;
mul.wide.u32 %leleka_batch_off3, %leleka_batch_y, 10240;
add.u64 %rd4, %rd4, %leleka_batch_off3;
// END batch-column offsets
mov.u32 %r2, %ctaid.x;
shl.b32 %r3, %r2, 8;
mov.u32 %r4, %tid.x;
add.s32 %r1, %r3, %r4;
setp.gt.u32 %p1, %r1, 2559;
@%p1 bra $L__BB3_2;
cvta.to.global.u64 %rd5, %rd4;
cvta.to.global.u64 %rd6, %rd1;
cvta.to.global.u64 %rd7, %rd2;
cvta.to.global.u64 %rd8, %rd3;
mul.wide.u32 %rd9, %r1, 4;
add.s64 %rd10, %rd6, %rd9;
ld.global.nc.f32 %f1, [%rd10];
abs.ftz.f32 %f2, %f1;
setp.equ.ftz.f32 %p2, %f2, 0f7F800000;
selp.f32 %f3, 0f7FC00000, %f1, %p2;
add.s64 %rd11, %rd7, %rd9;
ld.global.nc.f32 %f4, [%rd11];
neg.ftz.f32 %f5, %f4;
abs.ftz.f32 %f6, %f4;
setp.equ.ftz.f32 %p3, %f6, 0f7F800000;
selp.f32 %f7, 0f7FC00000, %f5, %p3;
mul.ftz.f32 %f8, %f7, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f9, %f8;
setp.ltu.ftz.f32 %p4, %f9, 0f00000000;
selp.f32 %f10, 0f7FC00000, %f9, %p4;
mov.f32 %f11, 0f3F800000;
add.rn.ftz.f32 %f12, %f11, %f10;
setp.gt.ftz.f32 %p5, %f12, 0f00000000;
selp.f32 %f13, %f12, 0f7FC00000, %p5;
div.approx.ftz.f32 %f14, %f11, %f13;
abs.ftz.f32 %f15, %f14;
setp.equ.ftz.f32 %p6, %f15, 0f7F800000;
selp.f32 %f16, 0f7FC00000, %f14, %p6;
mul.rn.ftz.f32 %f17, %f3, %f16;
abs.ftz.f32 %f18, %f17;
setp.equ.ftz.f32 %p7, %f18, 0f7F800000;
selp.f32 %f19, 0f7FC00000, %f17, %p7;
add.s64 %rd12, %rd8, %rd9;
st.global.f32 [%rd12], %f19;
ld.global.nc.f32 %f20, [%rd10+10240];
abs.ftz.f32 %f21, %f20;
setp.equ.ftz.f32 %p8, %f21, 0f7F800000;
selp.f32 %f22, 0f7FC00000, %f20, %p8;
ld.global.nc.f32 %f23, [%rd11+10240];
neg.ftz.f32 %f24, %f23;
abs.ftz.f32 %f25, %f23;
setp.equ.ftz.f32 %p9, %f25, 0f7F800000;
selp.f32 %f26, 0f7FC00000, %f24, %p9;
mul.ftz.f32 %f27, %f26, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f28, %f27;
setp.ltu.ftz.f32 %p10, %f28, 0f00000000;
selp.f32 %f29, 0f7FC00000, %f28, %p10;
add.rn.ftz.f32 %f30, %f11, %f29;
setp.gt.ftz.f32 %p11, %f30, 0f00000000;
selp.f32 %f31, %f30, 0f7FC00000, %p11;
div.approx.ftz.f32 %f32, %f11, %f31;
abs.ftz.f32 %f33, %f32;
setp.equ.ftz.f32 %p12, %f33, 0f7F800000;
selp.f32 %f34, 0f7FC00000, %f32, %p12;
mul.rn.ftz.f32 %f35, %f22, %f34;
abs.ftz.f32 %f36, %f35;
setp.equ.ftz.f32 %p13, %f36, 0f7F800000;
selp.f32 %f37, 0f7FC00000, %f35, %p13;
st.global.f32 [%rd12+10240], %f37;
add.rn.ftz.f32 %f38, %f19, %f37;
abs.ftz.f32 %f39, %f38;
setp.equ.ftz.f32 %p14, %f39, 0f7F800000;
selp.f32 %f40, 0f7FC00000, %f38, %p14;
ld.global.nc.f32 %f41, [%rd10+20480];
abs.ftz.f32 %f42, %f41;
setp.equ.ftz.f32 %p15, %f42, 0f7F800000;
selp.f32 %f43, 0f7FC00000, %f41, %p15;
ld.global.nc.f32 %f44, [%rd11+20480];
neg.ftz.f32 %f45, %f44;
abs.ftz.f32 %f46, %f44;
setp.equ.ftz.f32 %p16, %f46, 0f7F800000;
selp.f32 %f47, 0f7FC00000, %f45, %p16;
mul.ftz.f32 %f48, %f47, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f49, %f48;
setp.ltu.ftz.f32 %p17, %f49, 0f00000000;
selp.f32 %f50, 0f7FC00000, %f49, %p17;
add.rn.ftz.f32 %f51, %f11, %f50;
setp.gt.ftz.f32 %p18, %f51, 0f00000000;
selp.f32 %f52, %f51, 0f7FC00000, %p18;
div.approx.ftz.f32 %f53, %f11, %f52;
abs.ftz.f32 %f54, %f53;
setp.equ.ftz.f32 %p19, %f54, 0f7F800000;
selp.f32 %f55, 0f7FC00000, %f53, %p19;
mul.rn.ftz.f32 %f56, %f43, %f55;
abs.ftz.f32 %f57, %f56;
setp.equ.ftz.f32 %p20, %f57, 0f7F800000;
selp.f32 %f58, 0f7FC00000, %f56, %p20;
st.global.f32 [%rd12+20480], %f58;
add.rn.ftz.f32 %f59, %f40, %f58;
abs.ftz.f32 %f60, %f59;
setp.equ.ftz.f32 %p21, %f60, 0f7F800000;
selp.f32 %f61, 0f7FC00000, %f59, %p21;
ld.global.nc.f32 %f62, [%rd10+30720];
abs.ftz.f32 %f63, %f62;
setp.equ.ftz.f32 %p22, %f63, 0f7F800000;
selp.f32 %f64, 0f7FC00000, %f62, %p22;
ld.global.nc.f32 %f65, [%rd11+30720];
neg.ftz.f32 %f66, %f65;
abs.ftz.f32 %f67, %f65;
setp.equ.ftz.f32 %p23, %f67, 0f7F800000;
selp.f32 %f68, 0f7FC00000, %f66, %p23;
mul.ftz.f32 %f69, %f68, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f70, %f69;
setp.ltu.ftz.f32 %p24, %f70, 0f00000000;
selp.f32 %f71, 0f7FC00000, %f70, %p24;
add.rn.ftz.f32 %f72, %f11, %f71;
setp.gt.ftz.f32 %p25, %f72, 0f00000000;
selp.f32 %f73, %f72, 0f7FC00000, %p25;
div.approx.ftz.f32 %f74, %f11, %f73;
abs.ftz.f32 %f75, %f74;
setp.equ.ftz.f32 %p26, %f75, 0f7F800000;
selp.f32 %f76, 0f7FC00000, %f74, %p26;
mul.rn.ftz.f32 %f77, %f64, %f76;
abs.ftz.f32 %f78, %f77;
setp.equ.ftz.f32 %p27, %f78, 0f7F800000;
selp.f32 %f79, 0f7FC00000, %f77, %p27;
st.global.f32 [%rd12+30720], %f79;
add.rn.ftz.f32 %f80, %f61, %f79;
abs.ftz.f32 %f81, %f80;
setp.equ.ftz.f32 %p28, %f81, 0f7F800000;
selp.f32 %f82, 0f7FC00000, %f80, %p28;
fma.rn.ftz.f32 %f83, %f82, 0f3E800000, 0f00000000;
abs.ftz.f32 %f84, %f83;
setp.equ.ftz.f32 %p29, %f84, 0f7F800000;
selp.f32 %f85, 0f7FC00000, %f83, %p29;
add.s64 %rd13, %rd5, %rd9;
st.global.f32 [%rd13], %f85;
$L__BB3_2:
ret;
}
// Regenerated NVCC12.8.93 postops; retained exact closed ABI/block256.
.visible .entry leleka_gr_inject_residual_f32(
.param .u64 residual,
.param .u64 block_output,
.param .u64 inject,
.param .u64 output
)
.reqntid 256, 1, 1
{
.reg .pred %p<11>;
.reg .b16 %rs<6>;
.reg .b32 %r<7>;
.reg .f32 %f<29>;
.reg .b64 %rd<16>;
// BEGIN batch-column declarations
.reg .b32 %leleka_batch_y;
.reg .b64 %leleka_batch_off<4>;
// END batch-column declarations
ld.param.u64 %rd1, [residual];
ld.param.u64 %rd2, [block_output];
ld.param.u64 %rd3, [inject];
ld.param.u64 %rd4, [output];
// BEGIN batch-column offsets
mov.u32 %leleka_batch_y, %ctaid.y;
mul.wide.u32 %leleka_batch_off0, %leleka_batch_y, 40960;
add.u64 %rd1, %rd1, %leleka_batch_off0;
mul.wide.u32 %leleka_batch_off1, %leleka_batch_y, 10240;
add.u64 %rd2, %rd2, %leleka_batch_off1;
mul.wide.u32 %leleka_batch_off2, %leleka_batch_y, 16;
add.u64 %rd3, %rd3, %leleka_batch_off2;
mul.wide.u32 %leleka_batch_off3, %leleka_batch_y, 40960;
add.u64 %rd4, %rd4, %leleka_batch_off3;
// END batch-column offsets
mov.u32 %r2, %ctaid.x;
shl.b32 %r3, %r2, 8;
mov.u32 %r4, %tid.x;
or.b32 %r1, %r3, %r4;
setp.gt.u32 %p1, %r1, 10239;
@%p1 bra $L__BB4_2;
cvta.to.global.u64 %rd5, %rd2;
cvta.to.global.u64 %rd6, %rd1;
cvta.to.global.u64 %rd7, %rd4;
cvta.to.global.u64 %rd8, %rd3;
cvt.u16.u32 %rs1, %r1;
mul.hi.u16 %rs2, %rs1, -13107;
shr.u16 %rs3, %rs2, 11;
mul.lo.s16 %rs4, %rs3, 2560;
sub.s16 %rs5, %rs1, %rs4;
cvt.u32.u16 %r5, %rs3;
mul.wide.u32 %rd9, %r5, 4;
add.s64 %rd10, %rd8, %rd9;
ld.global.nc.f32 %f1, [%rd10];
abs.ftz.f32 %f2, %f1;
setp.equ.ftz.f32 %p2, %f2, 0f7F800000;
selp.f32 %f3, 0f7FC00000, %f1, %p2;
fma.rn.ftz.f32 %f4, %f3, 0f3E800000, 0f00000000;
neg.ftz.f32 %f5, %f4;
abs.ftz.f32 %f6, %f4;
setp.equ.ftz.f32 %p3, %f6, 0f7F800000;
selp.f32 %f7, 0f7FC00000, %f5, %p3;
mul.ftz.f32 %f8, %f7, 0f3FB8AA3B;
ex2.approx.ftz.f32 %f9, %f8;
setp.ltu.ftz.f32 %p4, %f9, 0f00000000;
selp.f32 %f10, 0f7FC00000, %f9, %p4;
mov.f32 %f11, 0f3F800000;
add.rn.ftz.f32 %f12, %f11, %f10;
setp.gt.ftz.f32 %p5, %f12, 0f00000000;
selp.f32 %f13, %f12, 0f7FC00000, %p5;
div.approx.ftz.f32 %f14, %f11, %f13;
abs.ftz.f32 %f15, %f14;
setp.equ.ftz.f32 %p6, %f15, 0f7F800000;
selp.f32 %f16, 0f7FC00000, %f14, %p6;
fma.rn.ftz.f32 %f17, %f16, 0f40000000, 0f00000000;
abs.ftz.f32 %f18, %f17;
setp.equ.ftz.f32 %p7, %f18, 0f7F800000;
selp.f32 %f19, 0f7FC00000, %f17, %p7;
cvt.u32.u16 %r6, %rs5;
mul.wide.u32 %rd11, %r6, 4;
add.s64 %rd12, %rd5, %rd11;
ld.global.nc.f32 %f20, [%rd12];
abs.ftz.f32 %f21, %f20;
setp.equ.ftz.f32 %p8, %f21, 0f7F800000;
selp.f32 %f22, 0f7FC00000, %f20, %p8;
mul.wide.u32 %rd13, %r1, 4;
add.s64 %rd14, %rd6, %rd13;
ld.global.f32 %f23, [%rd14];
abs.ftz.f32 %f24, %f23;
setp.equ.ftz.f32 %p9, %f24, 0f7F800000;
selp.f32 %f25, 0f7FC00000, %f23, %p9;
fma.rn.ftz.f32 %f26, %f22, %f19, %f25;
abs.ftz.f32 %f27, %f26;
setp.equ.ftz.f32 %p10, %f27, 0f7F800000;
selp.f32 %f28, 0f7FC00000, %f26, %p10;
add.s64 %rd15, %rd7, %rd13;
st.global.f32 [%rd15], %f28;
$L__BB4_2:
ret;
}
+870
View File
@@ -0,0 +1,870 @@
//! Closed T-bank adapter for the original GR arithmetic. No host scalar read
//! loop: all actual row offsets are admitted before one queued completion.
//! This preserves MMVF F32 operands/reduction; it does not claim Strata GEMM
//! rounding equivalence or expose a model/row/finite capability.
use super::*;
const SIZES: [usize; 11] = [
40960, 40960, 1280, 1280, 40960, 40960, 10240, 16, 10240, 40960, 32,
];
const OPS: [Operation; 6] = [
Operation::Norm,
Operation::Down,
Operation::DownSilu,
Operation::Up,
Operation::LayerGate,
Operation::InjectProjection,
];
const RESERVE: usize = 128 * 1024 * 1024;
/// Complete host outputs from the actual corresponding whole T banks.
pub struct GrMicroValues {
pub mixed: Box<[f32]>,
pub inject: Box<[f32]>,
}
/// One actual current microbatch, exclusively owned through attention write
/// and the immediate FFN read. Whole candidate/residual owners are swapped
/// only after completed full finite readback; no arbitrary subview is public.
pub struct GrMicrobatchRead<'ctx> {
context: &'ctx Context<'ctx>,
tokens: usize,
buffers: [Option<DeviceBuffer<'ctx>>; 11],
finite_module: Option<ffi::ModuleHandle>,
finite: Option<ffi::FunctionHandle>,
phase: u8,
failed: bool,
}
impl Context<'_> {
pub fn gr_microbatch_read(
&self,
tokens: usize,
streams: &[f32],
) -> Result<GrMicrobatchRead<'_>> {
GrMicrobatchRead::new(self, tokens, streams)
}
}
fn checked_row(tokens: usize, index: usize, bytes: usize) -> Result<(usize, usize)> {
if !(1..=64).contains(&tokens) || index >= tokens || bytes == 0 || !bytes.is_multiple_of(4) {
return Err(Error::InvalidQwenShape);
}
Ok((
tokens.checked_mul(bytes).ok_or(Error::InvalidQwenShape)?,
index.checked_mul(bytes).ok_or(Error::InvalidQwenShape)?,
))
}
fn encode(values: &[f32]) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::HostAllocation)?)
.map_err(|_| Error::HostAllocation)?;
bytes.extend(values.iter().flat_map(|value| value.to_le_bytes()));
Ok(bytes)
}
impl<'ctx> GrMicrobatchRead<'ctx> {
fn new(context: &'ctx Context<'ctx>, tokens: usize, streams: &[f32]) -> Result<Self> {
checked_row(tokens, 0, 40960)?;
if streams.len() != tokens * 10240 {
return Err(Error::InvalidQwenShape);
}
if streams.iter().any(|x| !x.is_finite()) {
return Err(Error::InvalidDriverValue("GR micro input finite"));
}
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let required = SIZES.iter().try_fold(RESERVE, |sum, n| {
sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded)
})?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget_bytes())
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let staging = encode(streams)?;
let mut owner = Self {
context,
tokens,
buffers: std::array::from_fn(|_| None),
finite_module: None,
finite: None,
phase: 0,
failed: false,
};
let result = (|| {
for (slot, size) in SIZES.into_iter().enumerate() {
owner.buffers[slot] = Some(context.allocate(size * tokens)?);
}
let guard = context.enter()?;
let load = (|| {
let module = context.driver.api.load_mmq_resident()?;
owner.finite_module = Some(module);
owner.finite = Some(context.driver.api.mmq_resident_function(module, 1)?);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver();
}
combine(load, pop)?;
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
owner.buffers[0]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from_owned(staging)?;
Ok(())
})();
if let Err(primary) = result {
return combine(Err(primary), owner.close());
}
Ok(owner)
}
pub fn tokens(&self) -> usize {
self.tokens
}
pub fn allocated_bytes(&self) -> usize {
self.buffers.iter().flatten().map(DeviceBuffer::len).sum()
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned()
}
fn buffer(&self, slot: usize) -> Result<&DeviceBuffer<'ctx>> {
if self.is_failed() {
return Err(Error::ContextPoisoned);
}
self.buffers
.get(slot)
.and_then(Option::as_ref)
.ok_or(Error::ContextPoisoned)
}
fn handle(&self, slot: usize, row: usize) -> Result<ffi::BufferHandle> {
let buffer = self.buffer(slot)?;
let (whole, offset) = checked_row(self.tokens, row, SIZES[slot])?;
if !std::ptr::eq(self.context, buffer.context) {
return Err(Error::ContextMismatch);
}
if buffer.len() != whole {
return Err(Error::InvalidQwenShape);
}
buffer
.handle
.ok_or(Error::ContextPoisoned)?
.checked_subspan(whole, offset, SIZES[slot])
}
fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> {
if self.is_failed() || self.finite_module.is_none() || self.finite.is_none() {
return Err(Error::ContextPoisoned);
}
for (i, buffer) in self.buffers.iter().enumerate() {
let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?;
self.handle(i, self.tokens - 1)?;
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
for prior in self.buffers[..i].iter().flatten() {
if handle.overlaps(
buffer.bytes,
prior.handle.ok_or(Error::ContextPoisoned)?,
prior.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
for weight in weights {
if !std::ptr::eq(self.context, weight.context) {
return Err(Error::ContextMismatch);
}
if handle.overlaps(
buffer.bytes,
weight.handle.ok_or(Error::ContextPoisoned)?,
weight.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
fn row_arguments(
&self,
row: usize,
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
) -> Result<[Arguments; 6]> {
if !epsilon.is_finite() || epsilon < 0.0 {
return Err(Error::InvalidQwenShape);
}
let sizes = [40960, 6553600, 6553600, 81920];
let mut w = [self.handle(0, row)?; 4];
for (i, weight) in weights.iter().enumerate() {
if weight.len() != sizes[i] {
return Err(Error::InvalidQwenShape);
}
w[i] = weight.handle.ok_or(Error::ContextPoisoned)?;
}
let mut h = [self.handle(0, row)?; 8];
for (i, handle) in h.iter_mut().enumerate() {
*handle = self.handle(i, row)?;
}
let sets: [&[ffi::BufferHandle]; 6] = [
&[h[0], w[0], h[1]],
&[w[1], h[1], h[2]],
&[h[2], h[3]],
&[w[2], h[3], h[4]],
&[h[1], h[4], h[5], h[6]],
&[w[3], h[1], h[7]],
];
let mut prepared = Vec::new();
prepared
.try_reserve_exact(6)
.map_err(|_| Error::HostAllocation)?;
for (operation, set) in OPS.into_iter().zip(sets) {
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
asset.validate(operation)?;
let layout = operation.layout();
let mut handles = [set[0]; 9];
handles[..set.len()].copy_from_slice(set);
ranges_layout(operation, layout, handles, layout.bytes, false)?;
prepared.push(Arguments::with_layout(operation, layout, handles, epsilon));
}
prepared.try_into().map_err(|_| Error::InvalidQwenShape)
}
// Seven separate actual status words per row preserve complete ordered
// Norm/Down/Silu/Up/products/mixed/inject refusal arbitration. The reused
// integer finite kernel sets bit0 only and scans every actual F32 word.
pub fn read(&mut self, weights: [&DeviceBuffer<'_>; 4], epsilon: f32) -> Result<GrMicroValues> {
if self.phase != 0 {
return Err(Error::InvalidQwenShape);
}
self.validate(&weights)?;
let mut arguments = Vec::new();
arguments
.try_reserve_exact(self.tokens)
.map_err(|_| Error::HostAllocation)?;
let mut scans = Vec::new();
scans
.try_reserve_exact(self.tokens * 7)
.map_err(|_| Error::HostAllocation)?;
for row in 0..self.tokens {
arguments.push(self.row_arguments(row, weights, epsilon)?);
for (stage, slot) in [1, 2, 3, 4, 5, 6, 7].into_iter().enumerate() {
let status = self.handle(10, row)?.checked_subspan(32, stage * 4, 4)?;
scans.push(ffi::MmqResidentArguments::finite(
self.handle(slot, row)?,
status,
0,
(SIZES[slot] / 4) as u32,
0,
));
}
}
let zero = vec![0u8; 32 * self.tokens];
let mut readback = vec![0u8; 32 * self.tokens];
let guard = self.context.enter()?;
let kernels = (|| {
let mut result = Vec::new();
result
.try_reserve_exact(6)
.map_err(|_| Error::HostAllocation)?;
for operation in OPS {
result.push(registered(
self.context,
&self.context.qwen_kernels,
qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?,
)?);
}
Ok(result)
})();
let kernels = match kernels {
Ok(kernels) => kernels,
Err(error) => {
let pop = guard.finish();
if pop.is_err() {
self.failed = true;
self.context.poison();
self.context.retain_driver();
}
return combine(Err(error), pop);
}
};
let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?;
let finite = self.finite.ok_or(Error::ContextPoisoned)?;
let mut commands = self.context.driver.api.copy_from(status, &zero);
let initialized = commands.is_ok();
let mut completed_scans = 0usize;
for (row, row_args) in arguments.iter_mut().enumerate() {
for stage in 0..6 {
if commands.is_err() {
break;
}
commands = self.context.driver.api.launch_qwen(
kernels[stage].function,
OPS[stage],
&mut row_args[stage],
);
if commands.is_ok() {
let scan_stage = if stage == 5 { 6 } else { stage };
let words = SIZES[[1, 2, 3, 4, 5, 7][stage]] / 4;
commands = self.context.driver.api.launch_mmq_resident(
finite,
words as u32,
&mut scans[row * 7 + scan_stage],
);
if commands.is_ok() {
completed_scans += 1;
}
}
if stage == 4 && commands.is_ok() {
commands = self.context.driver.api.launch_mmq_resident(
finite,
2560,
&mut scans[row * 7 + 5],
);
if commands.is_ok() {
completed_scans += 1;
}
}
}
if commands.is_err() {
break;
}
}
let read_status = if initialized {
self.context.driver.api.copy_to(status, &mut readback)
} else {
Ok(())
};
let status_read = initialized && read_status.is_ok();
let commands = combine(commands, read_status);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if commands.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
}
if sync.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
std::mem::forget((arguments, scans, zero, readback));
} else {
// A later enqueue failure cannot replace an earlier completed
// numeric refusal. Only actually enqueued scans, successful
// status readback and confirmed sync/pop authorize this ordering.
if status_read {
let mut scan_index = 0usize;
for row in readback.chunks_exact(32) {
for (stage, bytes) in row.chunks_exact(4).take(7).enumerate() {
if scan_index >= completed_scans {
break;
}
scan_index += 1;
let flag = u32::from_le_bytes(
bytes.try_into().map_err(|_| Error::InvalidQwenShape)?,
);
if flag & !1 != 0 {
self.failed = true;
return Err(Error::InvalidDriverValue("GR micro finite status"));
}
if flag != 0 {
return Err(Error::NonFiniteMmqOutput(STAGES[stage]));
}
}
}
}
combine(combine(commands, sync), pop)?;
let mixed = decode(self.buffer(6)?)?;
let inject = decode(self.buffer(7)?)?;
self.phase = 1;
return Ok(GrMicroValues { mixed, inject });
}
combine(combine(commands, sync), pop)
.map(|()| unreachable!("uncertain completion is an error"))
}
/// Original residual write consumes retained real input and injection banks.
/// Blocks are the only new upload. Completed candidate is retained as the
/// next input bank, while canonical host values remain truthful.
pub fn inject(&mut self, blocks: &[f32]) -> Result<Box<[f32]>> {
if self.phase != 1 {
return Err(Error::InvalidQwenShape);
}
self.validate(&[])?;
if blocks.len() != self.tokens * 2560 {
return Err(Error::InvalidQwenShape);
}
if blocks.iter().any(|x| !x.is_finite()) {
return Err(Error::InvalidDriverValue("GR micro block finite"));
}
let staging = encode(blocks)?;
let mut arguments = Vec::new();
let mut scans = Vec::new();
arguments
.try_reserve_exact(self.tokens)
.map_err(|_| Error::HostAllocation)?;
scans
.try_reserve_exact(self.tokens)
.map_err(|_| Error::HostAllocation)?;
let operation = Operation::InjectResidual;
let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?;
asset.validate(operation)?;
for row in 0..self.tokens {
let layout = operation.layout();
let mut handles = [self.handle(0, row)?; 9];
for (i, slot) in [0, 8, 7, 9].into_iter().enumerate() {
handles[i] = self.handle(slot, row)?;
}
ranges_layout(operation, layout, handles, layout.bytes, false)?;
arguments.push(Arguments::with_layout(operation, layout, handles, 0.));
scans.push(ffi::MmqResidentArguments::finite(
handles[3],
self.handle(10, row)?.checked_subspan(32, 28, 4)?,
0,
10240,
0,
));
}
let zero = vec![0u8; 32 * self.tokens];
let mut readback = vec![0u8; 32 * self.tokens];
let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?;
let block = self.buffer(8)?.handle.ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let kernel = match registered(self.context, &self.context.qwen_kernels, asset) {
Ok(kernel) => kernel,
Err(error) => {
let pop = guard.finish();
if pop.is_err() {
self.failed = true;
self.context.poison();
self.context.retain_driver();
}
return combine(Err(error), pop);
}
};
let mut commands = self.context.driver.api.copy_from(block, &staging);
if commands.is_ok() {
commands = self.context.driver.api.copy_from(status, &zero);
}
let initialized = commands.is_ok();
let mut completed_scans = 0usize;
for (args, scan) in arguments.iter_mut().zip(scans.iter_mut()) {
if commands.is_err() {
break;
}
commands = self
.context
.driver
.api
.launch_qwen(kernel.function, operation, args);
if commands.is_ok() {
commands = self.context.driver.api.launch_mmq_resident(
self.finite.ok_or(Error::ContextPoisoned)?,
10240,
scan,
);
}
if commands.is_ok() {
completed_scans += 1;
}
}
let read_status = if initialized {
self.context.driver.api.copy_to(status, &mut readback)
} else {
Ok(())
};
let status_read = initialized && read_status.is_ok();
let commands = combine(commands, read_status);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if commands.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
}
if sync.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
std::mem::forget((arguments, scans, staging, zero, readback));
return combine(combine(commands, sync), pop)
.map(|()| unreachable!("uncertain completion"));
}
if status_read {
for row in readback.chunks_exact(32).take(completed_scans) {
let flag = u32::from_le_bytes(
row[28..32]
.try_into()
.map_err(|_| Error::InvalidQwenShape)?,
);
if flag & !1 != 0 {
self.failed = true;
return Err(Error::InvalidDriverValue("GR micro candidate status"));
}
if flag != 0 {
return Err(Error::NonFiniteMmqOutput("GR inject candidate"));
}
}
}
combine(combine(commands, sync), pop)?;
let values = decode(self.buffer(9)?)?;
self.buffers.swap(0, 9);
self.phase = 0;
Ok(values)
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut result = Ok(());
for slot in self.buffers.iter_mut().rev() {
if let Some(buffer) = slot.take() {
let release = if self.context.is_poisoned() {
std::mem::forget(buffer);
self.context.retain_driver();
Err(Error::ContextPoisoned)
} else {
buffer.release()
};
if release.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, release);
}
}
self.finite = None;
if let Some(module) = self.finite_module.take() {
let release = if self.context.is_poisoned() {
self.context.retain_driver();
Err(Error::ContextPoisoned)
} else {
match self.context.enter() {
Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()),
Err(error) => Err(error),
}
};
if release.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, release);
}
result
}
}
const STAGES: [&str; 7] = [
"GR norm",
"GR down",
"GR silu",
"GR up",
"GR products",
"GR mixed",
"GR inject",
];
impl Drop for GrMicrobatchRead<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
fn decode(buffer: &DeviceBuffer<'_>) -> Result<Box<[f32]>> {
let bytes = buffer.copy_to_owned(buffer.len())?;
let mut values = Vec::new();
values
.try_reserve_exact(bytes.len() / 4)
.map_err(|_| Error::HostAllocation)?;
values.extend(
bytes
.as_chunks::<4>()
.0
.iter()
.map(|word| f32::from_le_bytes(*word)),
);
if values.iter().any(|x| !x.is_finite()) {
return Err(Error::NonFiniteMmqOutput("GR canonical readback"));
}
Ok(values.into_boxed_slice())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn closed_micro_offsets_cover_disjoint_whole_banks_without_tail_views() {
for tokens in [1, 2, 3, 63, 64] {
for bytes in SIZES {
let mut end = 0;
for row in 0..tokens {
let (whole, offset) = checked_row(tokens, row, bytes).unwrap();
assert_eq!(offset, end);
end = offset + bytes;
assert!(end <= whole);
}
assert_eq!(end, tokens * bytes);
assert_eq!(
checked_row(tokens, tokens, bytes),
Err(Error::InvalidQwenShape)
);
}
}
for invalid in [0, 65, usize::MAX] {
assert_eq!(checked_row(invalid, 0, 40960), Err(Error::InvalidQwenShape));
}
}
}
#[cfg(all(
test,
target_os = "linux",
target_arch = "x86_64",
feature = "cuda-driver"
))]
mod installed {
use super::*;
use crate::Driver;
fn upload<'a>(context: &'a Context<'a>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
buffer.copy_from(bytes)?;
Ok(buffer)
}
type OriginalValues = (Box<[f32]>, Box<[f32]>, Box<[f32]>);
fn original(
context: &Context<'_>,
weights: [&DeviceBuffer<'_>; 4],
streams: &[f32],
block: &[f32],
) -> Result<OriginalValues> {
let mut buffers = Vec::new();
buffers
.try_reserve_exact(10)
.map_err(|_| Error::HostAllocation)?;
for bytes in SIZES.iter().take(10) {
buffers.push(context.allocate(*bytes)?);
}
let result = (|| {
buffers[0].copy_from_owned(encode(streams)?)?;
let [
residual,
xn,
down,
activated,
gates,
products,
mixed,
inject,
output,
candidate,
] = buffers.as_mut_slice()
else {
return Err(Error::InvalidQwenShape);
};
// Original independently completed calls and complete readback
// are evaluated FIRST, including every intermediate finite check.
context.gr_norm_f32(residual, weights[0], 1e-6, xn)?;
decode(xn)?;
context.gr_down_projection_bf16_f32(weights[1], xn, down)?;
decode(down)?;
context.gr_down_silu_hc_f32(down, activated)?;
decode(activated)?;
context.gr_up_projection_bf16_f32(weights[2], activated, gates)?;
decode(gates)?;
context.gr_gate_mean_layer_fused_f32(xn, gates, products, mixed)?;
decode(products)?;
let mixed_values = decode(mixed)?;
context.gr_inject_projection_bf16_f32(weights[3], xn, inject)?;
let injection_values = decode(inject)?;
output.copy_from_owned(encode(block)?)?;
context.gr_inject_residual_f32(residual, output, inject, candidate)?;
Ok((mixed_values, injection_values, decode(candidate)?))
})();
let cleanup = buffers
.into_iter()
.rev()
.fold(Ok(()), |old, buffer| combine(old, buffer.release()));
combine(result, cleanup)
}
#[test]
#[ignore = "Root-only changed genuine T-bank transport arithmetic gate"]
fn original_first_microbank_read_inject_ffn_all_rows_bits_and_cleanup() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_GR_MICROBATCH").as_deref(),
Ok("yes")
);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(192 * 1024 * 1024).unwrap();
let mut weights = Vec::new();
for (count, bf16) in [
(10240, false),
(320 * 10240, true),
(10240 * 320, true),
(4 * 10240, true),
] {
let mut bytes = Vec::new();
for i in 0..count {
let value = if bf16 {
if i % 13 == 0 { 0.015625f32 } else { 0.0 }
} else {
1.0f32
};
if bf16 {
bytes.extend_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes());
} else {
bytes.extend_from_slice(&value.to_le_bytes());
}
}
weights.push(upload(&context, &bytes).unwrap());
}
let result = (|| -> Result<usize> {
let refs: [&DeviceBuffer<'_>; 4] = weights
.iter()
.collect::<Vec<_>>()
.try_into()
.map_err(|_| Error::InvalidQwenShape)?;
let mut words = 0usize;
for tokens in [1usize, 3, 64] {
let streams: Vec<f32> = (0..tokens * 10240)
.map(|i| {
if i % 29 == 0 {
-0.0
} else {
((i % 97) as f32 - 48.) * 0.00390625
}
})
.collect();
let blocks: Vec<f32> = (0..tokens * 2560)
.map(|i| ((i % 19) as f32 - 9.) * 0.015625)
.collect();
let mut expected_mixed = Vec::new();
let mut expected_inject = Vec::new();
let mut expected_streams = Vec::new();
for row in 0..tokens {
let (mixed, inject, next) = original(
&context,
refs,
&streams[row * 10240..(row + 1) * 10240],
&blocks[row * 2560..(row + 1) * 2560],
)?;
expected_mixed.extend_from_slice(&mixed);
expected_inject.extend_from_slice(&inject);
expected_streams.extend_from_slice(&next);
}
let mut expected_ffn_mixed = Vec::new();
let mut expected_ffn_inject = Vec::new();
for row in 0..tokens {
let (mixed, inject, _) = original(
&context,
refs,
&expected_streams[row * 10240..(row + 1) * 10240],
&blocks[row * 2560..(row + 1) * 2560],
)?;
expected_ffn_mixed.extend_from_slice(&mixed);
expected_ffn_inject.extend_from_slice(&inject);
}
let mut bank = context.gr_microbatch_read(tokens, &streams)?;
let attempted = (|| {
let first = bank.read(refs, 1e-6)?;
let injected = bank.inject(&blocks)?;
let ffn = bank.read(refs, 1e-6)?;
let actual = first
.mixed
.iter()
.chain(first.inject.iter())
.chain(injected.iter())
.chain(ffn.mixed.iter())
.chain(ffn.inject.iter());
let expected = expected_mixed
.iter()
.chain(expected_inject.iter())
.chain(expected_streams.iter())
.chain(expected_ffn_mixed.iter())
.chain(expected_ffn_inject.iter());
let mut same = true;
for (a, b) in actual.zip(expected) {
same &= a.to_bits() == b.to_bits();
words += 1;
}
Ok(same)
})();
// Release all real T banks before turning a numerical mismatch
// into a gate failure. No fake model/current-row authority.
let same = combine(attempted, bank.close())?;
if !same {
return Err(Error::InvalidDriverValue("GR micro old-first bit mismatch"));
}
}
// Same ONE changed-bank entry: a late gamma NaN/Inf is
// observed by the old full read FIRST, then ordered bank status;
// valid weights reuse the completed numerical-refusal owner.
let streams: Vec<f32> = (0..3 * 10240)
.map(|i| ((i % 31) as f32 + 1.) / 32.)
.collect();
let blocks = vec![0.125f32; 3 * 2560];
let expected = original(&context, refs, &streams[..10240], &blocks[..2560])?.0;
let mut bank = context.gr_microbatch_read(3, &streams)?;
let faults = (|| {
let mut observations = 0;
for invalid in [f32::NAN, f32::INFINITY] {
let mut gamma = vec![1f32; 10240];
gamma[10239] = invalid;
let bad = upload(&context, &encode(&gamma)?)?;
let bad_refs = [&bad, refs[1], refs[2], refs[3]];
let old = original(&context, bad_refs, &streams[..10240], &blocks[..2560]);
let changed = bank.read(bad_refs, 1e-6);
let refused = matches!(old, Err(Error::NonFiniteMmqOutput(_)))
&& matches!(changed, Err(Error::NonFiniteMmqOutput("GR norm")))
&& !bank.is_failed();
bad.release()?;
if !refused {
return Err(Error::InvalidDriverValue(
"GR micro full finite arbitration",
));
}
let valid = bank.read(refs, 1e-6)?;
if !valid.mixed[..2560]
.iter()
.zip(expected.iter())
.all(|(a, b)| a.to_bits() == b.to_bits())
{
return Err(Error::InvalidDriverValue("GR micro status reset"));
}
let mut invalid_block = blocks.clone();
let last = invalid_block.len() - 1;
invalid_block[last] = invalid;
let before = bank.phase;
if !matches!(
bank.inject(&invalid_block),
Err(Error::InvalidDriverValue("GR micro block finite"))
) || bank.phase != before
|| bank.is_failed()
{
return Err(Error::InvalidDriverValue("GR micro prewrite refusal"));
}
bank.inject(&blocks)?;
observations += 3;
// Healthy bank reuse is already bit-tested above. Restore
// the same FIRST-reference input for the next fault pair.
let replacement = context.gr_microbatch_read(3, &streams)?;
let old_bank = std::mem::replace(&mut bank, replacement);
old_bank.close()?;
}
Ok(observations)
})();
let observations = combine(faults, bank.close())?;
if observations != 6 {
return Err(Error::InvalidDriverValue("GR micro guard count"));
}
Ok(words)
})();
let cleanup = weights
.into_iter()
.rev()
.fold(Ok(()), |old, buffer| combine(old, buffer.release()));
let allocated = context.allocated_bytes();
let closed = context.close();
let words = combine(combine(result, cleanup), closed).unwrap();
assert_eq!(allocated, 0);
eprintln!(
"GR microbank original-FIRST words={words} bit_exact=true allocated0=true context_closed=true"
);
}
}
+10 -2
View File
@@ -48,6 +48,9 @@
.target sm_120
.address_size 64
// Private read-only-by-contract storage; no host symbol/write API.
.global .align 4 .u32 leleka_gr_norm_columns = 2560;
.visible .entry leleka_gr_norm_f32(
.param .u64 residual,
.param .u64 gamma,
@@ -59,7 +62,7 @@
.reg .pred %p<4>;
.reg .b32 %r<16>;
.reg .b64 %rd<12>;
.reg .f32 %f<12>;
.reg .f32 %f<14>;
.shared .align 4 .b8 norm_sums[128];
ld.param.u64 %rd0, [residual];
ld.param.u64 %rd1, [gamma];
@@ -174,7 +177,12 @@ NORM_STORED:
div.approx.ftz.f32 %f2, %f0, 0f45200000;
testp.finite.f32 %p3, %f2;
@!%p3 mov.f32 %f2, 0f7FC00000;
add.rn.ftz.f32 %f2, %f2, %f11;
// Keep rounded mean only for independent finite refusal, not denominator.
@!%p3 mov.f32 %f0, 0f7FC00000;
ld.volatile.global.u32 %r14, [leleka_gr_norm_columns];
cvt.rn.f32.s32 %f12, %r14;
rcp.approx.ftz.f32 %f13, %f12;
fma.rn.ftz.f32 %f2, %f0, %f13, %f11;
testp.finite.f32 %p3, %f2;
@!%p3 mov.f32 %f2, 0f7FC00000;
setp.le.f32 %p3, %f2, 0f00000000;
+134
View File
@@ -0,0 +1,134 @@
// Literal imported Strata prefill GR helpers/kernels. Export-only adaptation.
// Root compiles this asset after integrated source port; placeholder PTX refuses.
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cstdint>
#include <cmath>
constexpr int N=2560, HC=4, D=N*HC, LR=320;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ float block_sum(float v, float* sh) {
const int lane = threadIdx.x & 31, w = threadIdx.x >> 5;
v = warp_sum(v);
__syncthreads();
if (lane == 0) sh[w] = v;
__syncthreads();
const int nw = (blockDim.x + 31) >> 5;
float t = (threadIdx.x < nw) ? sh[threadIdx.x] : 0.0f;
if (w == 0) t = warp_sum(t);
if (threadIdx.x == 0) sh[0] = t;
__syncthreads();
return sh[0];
}
__device__ __forceinline__ uint16_t bf(float f) {
uint32_t u = __float_as_uint(f);
u += 0x7fffu + ((u >> 16) & 1u);
return (uint16_t) (u >> 16);
}
__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); }
__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
extern "C" __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
uint16_t* __restrict__ xn16_lo) {
__shared__ float sh[32];
const int64_t row = blockIdx.x; // t * 4 + c
const int c = (int) (row % HC);
const float* r = R + row * N;
float ss = 0.0f;
for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d];
const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
if (threadIdx.x == 0) rs_out[row] = rs;
for (int d = threadIdx.x; d < N; d += blockDim.x) {
const float v = r[d] * rs * w[c * N + d];
const uint16_t h = bf(v);
xn16[row * N + d] = h;
if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
}
}
extern "C" __global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo,
int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
const float x = lo[i] / (float) HC;
const float v = x / (1.0f + __expf(-x));
const uint16_t h = bf(v);
lo16[i] = h;
if (lo16_lo) lo16_lo[i] = bf_lo(v, h);
}
extern "C" __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w,
const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16,
int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * N) return;
const int64_t t = i / N, d = i % N;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HC; ++c) {
const int64_t j = t * D + c * N + d;
const float x = R[j] * rs[t * HC + c] * w[c * N + d]; // gr_norm_kernel's value, bit for bit
s = fmaf(x, sigm(g[j]), s);
}
s /= (float) HC;
mixed[i] = s;
if (mixed16) {
const uint16_t h = bf(s);
mixed16[i] = h;
if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
}
if (mixed_h) mixed_h[i] = hf(s);
}
extern "C" __global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj,
int64_t inj_ld, int64_t T) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * D) return;
const int64_t t = i / D, c = (i % D) / N, d = i % N;
R[i] = fmaf(bo[t * N + d], 2.0f * sigm(inj[t * inj_ld + c] / (float) HC), R[i]);
}
// Full ordered numerical guards. Original normalized/product arithmetic is
// recomputed in original order, without fabricating a host normalized bank.
// Integer exponent checking covers every actual F32 word; flags per real row.
extern "C" __global__ void gr_scan(const float* x, uint32_t* flags,
int64_t width, int64_t T, uint32_t stage) {
const int64_t i = (int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if (i >= width*T) return;
if ((__float_as_uint(x[i]) & 0x7f800000u)==0x7f800000u)
atomicOr(flags+(i/width)*8+stage,1u);
}
extern "C" __global__ void gr_norm_scan(const float* R,const float* rs,const float* w,
uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if (i>=T*D) return;
const int64_t t=i/D,c=(i%D)/N,d=i%N;
const float x=R[i]*rs[t*HC+c]*w[c*N+d];
if ((__float_as_uint(x)&0x7f800000u)==0x7f800000u) atomicOr(flags+t*8,1u);
}
extern "C" __global__ void gr_silu_scan(const float* lo,uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if(i>=T*LR) return;
const float x=lo[i]/(float)HC;
const float v=x/(1.0f+__expf(-x));
if((__float_as_uint(v)&0x7f800000u)==0x7f800000u) atomicOr(flags+(i/LR)*8+2,1u);
}
extern "C" __global__ void gr_product_scan(const float* R,const float* rs,const float* w,
const float* g,uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if(i>=T*D) return;
const int64_t t=i/D,c=(i%D)/N,d=i%N;
const float x=R[i]*rs[t*HC+c]*w[c*N+d];
const float product=x*sigm(g[i]);
if((__float_as_uint(product)&0x7f800000u)==0x7f800000u) atomicOr(flags+t*8+4,1u);
}
File diff suppressed because it is too large Load Diff
+617
View File
@@ -0,0 +1,617 @@
//! Explicit Original Strata whole-T GR norm/BF16 GEMM/mix/write owner.
//! No MMVF substitution and no env inference. Root-sealed asset required.
use super::*;
use crate::ple_batch_ffi::{BatchArg as A, Blas, KernelArguments, KernelModule};
use crate::{CurrentGuard, NativeBatchWorkspace};
use std::ffi::CStr;
const PTX: &[u8] = concat!(include_str!("gr_native_batch.ptx"), "\0").as_bytes();
const ENTRIES: &[&CStr] = &[
c"gr_norm_rs_kernel",
c"gr_silu_kernel",
c"gr_mix_r_kernel",
c"gr_write_kernel",
c"gr_scan",
c"gr_norm_scan",
c"gr_silu_scan",
c"gr_product_scan",
];
// Every active span is a whole owner; optional low operands have genuine
// storage but are passed as NULL in HighOnly to preserve Original arithmetic.
const BYTES: [usize; 15] = [
40960, 16, 20480, 20480, 1280, 640, 640, 40960, 10240, 5120, 5120, 5120, 16, 10240, 32,
];
const RESERVE: usize = 128 * 1024 * 1024;
const STAGES: [&str; 7] = [
"GR native norm",
"GR native down",
"GR native silu",
"GR native up",
"GR native products",
"GR native mixed",
"GR native inject",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrNativeProfile {
HighOnly,
HighAndLow,
}
pub struct GrNativeBatch<'ctx> {
context: &'ctx Context<'ctx>,
tokens: usize,
profile: GrNativeProfile,
buffers: [Option<DeviceBuffer<'ctx>>; 15],
module: Option<KernelModule>,
scalars: Option<Box<[f32; 3]>>,
phase: u8,
failed: bool,
}
impl Context<'_> {
pub fn gr_native_batch(
&self,
tokens: usize,
streams: &[f32],
profile: GrNativeProfile,
) -> Result<GrNativeBatch<'_>> {
GrNativeBatch::new(self, tokens, streams, profile)
}
pub fn gr_native_prompt_batch(
&self,
tokens: usize,
streams: &[f32],
profile: GrNativeProfile,
) -> Result<GrNativeBatch<'_>> {
GrNativeBatch::new_bounded(self, tokens, streams, profile, 8192)
}
}
fn encode(values: &[f32]) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes
.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::HostAllocation)?)
.map_err(|_| Error::HostAllocation)?;
bytes.extend(values.iter().flat_map(|x| x.to_le_bytes()));
Ok(bytes)
}
fn decode(buffer: &DeviceBuffer<'_>) -> Result<Box<[f32]>> {
let bytes = buffer.copy_to_owned(buffer.len())?;
let mut values = Vec::new();
values
.try_reserve_exact(bytes.len() / 4)
.map_err(|_| Error::HostAllocation)?;
values.extend(
bytes
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x)),
);
if values.iter().any(|x| !x.is_finite()) {
return Err(Error::NonFiniteMmqOutput("GR native canonical"));
}
Ok(values.into_boxed_slice())
}
impl<'ctx> GrNativeBatch<'ctx> {
pub fn prompt_device_bytes(tokens: usize) -> Result<usize> {
if !(1..=8192).contains(&tokens) {
return Err(Error::InvalidQwenShape);
}
BYTES.iter().try_fold(0usize, |sum, n| {
sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded)
})
}
fn new(
context: &'ctx Context<'ctx>,
tokens: usize,
streams: &[f32],
profile: GrNativeProfile,
) -> Result<Self> {
Self::new_bounded(context, tokens, streams, profile, 64)
}
fn new_bounded(
context: &'ctx Context<'ctx>,
tokens: usize,
streams: &[f32],
profile: GrNativeProfile,
limit: usize,
) -> Result<Self> {
if !(1..=limit).contains(&tokens) || streams.len() != tokens * 10240 {
return Err(Error::InvalidQwenShape);
}
if streams.iter().any(|x| !x.is_finite()) {
return Err(Error::InvalidDriverValue("GR micro input finite"));
}
// Explicit unsealed source-only placeholder is never a CUDA producer.
if PTX.starts_with(b"// UNSEALED") {
return Err(Error::InvalidDriverValue("GR native asset unsealed"));
}
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let bank = BYTES.iter().try_fold(0usize, |n, x| {
n.checked_add(x * tokens).ok_or(Error::BudgetExceeded)
})?;
let required = bank.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget_bytes())
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
tokens,
profile,
buffers: std::array::from_fn(|_| None),
module: None,
scalars: Some(Box::new([1., 0., 1.])),
phase: 0,
failed: false,
};
let attempted = (|| {
for (i, n) in BYTES.into_iter().enumerate() {
owner.buffers[i] = Some(context.allocate(n * tokens)?);
}
let guard = context.enter()?;
let loaded = (|| {
owner.module = Some(KernelModule::load(PTX, ENTRIES)?);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver();
}
combine(loaded, pop)?;
if context.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
owner.buffers[0]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from_owned(encode(streams)?)?;
Ok(())
})();
if let Err(primary) = attempted {
let _ = owner.close();
return Err(primary);
}
Ok(owner)
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned()
}
pub fn allocated_bytes(&self) -> usize {
self.buffers.iter().flatten().map(DeviceBuffer::len).sum()
}
fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> {
if self.is_failed() {
return Err(Error::ContextPoisoned);
}
self.buffers
.get(i)
.and_then(Option::as_ref)
.ok_or(Error::ContextPoisoned)
}
fn handle(&self, i: usize) -> Result<ffi::BufferHandle> {
let b = self.buffer(i)?;
let bytes = BYTES.get(i).ok_or(Error::InvalidQwenShape)? * self.tokens;
if !std::ptr::eq(self.context, b.context) {
return Err(Error::ContextMismatch);
}
if b.len() != bytes {
return Err(Error::InvalidQwenShape);
}
let handle = b.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_projection_extent(bytes, 256)?;
Ok(handle)
}
fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> {
if self.is_failed() {
return Err(Error::ContextPoisoned);
}
for (i, b) in self.buffers.iter().enumerate() {
let b = b.as_ref().ok_or(Error::ContextPoisoned)?;
let h = self.handle(i)?;
for prior in self.buffers[..i].iter().flatten() {
if h.overlaps(
b.bytes,
prior.handle.ok_or(Error::ContextPoisoned)?,
prior.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
for w in weights {
if !std::ptr::eq(self.context, w.context) {
return Err(Error::ContextMismatch);
}
if h.overlaps(b.bytes, w.handle.ok_or(Error::ContextPoisoned)?, w.bytes) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
fn low(&self, slot: usize) -> Result<A> {
if self.profile == GrNativeProfile::HighOnly {
Ok(A::NullAddress)
} else {
Ok(A::Address(self.handle(slot)?))
}
}
fn args(values: Vec<A>) -> KernelArguments {
KernelArguments::new(values)
}
fn scan(&self, slot: usize, width: usize, stage: u32) -> Result<KernelArguments> {
Ok(Self::args(vec![
A::Address(self.handle(slot)?),
A::Address(self.handle(14)?),
A::I64(width as i64),
A::I64(self.tokens as i64),
A::U32(stage),
]))
}
fn launch(
&self,
blas: &Blas,
index: usize,
count: usize,
args: &mut KernelArguments,
) -> Result<()> {
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
let stream = blas.stream();
module.launch(index, count.div_ceil(256) as u32, 256, stream, args)
}
#[allow(clippy::too_many_arguments)] // Fixed Original GEMM roles and owned alpha/beta ABI.
fn gemm(
&self,
blas: &Blas,
input: usize,
low: usize,
weight: ffi::BufferHandle,
output: usize,
n: i32,
k: i32,
alpha: &f32,
beta0: &f32,
beta1: &f32,
) -> Result<()> {
blas.gemm_bf16(
self.handle(input)?,
weight,
self.handle(output)?,
self.tokens as i32,
n,
k,
alpha,
beta0,
)?;
if self.profile == GrNativeProfile::HighAndLow {
blas.gemm_bf16(
self.handle(low)?,
weight,
self.handle(output)?,
self.tokens as i32,
n,
k,
alpha,
beta1,
)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)] // One complete retained command/drain ownership set.
fn finish(
&mut self,
blas: &Blas,
commands: Result<()>,
eligible: [bool; 8],
mut zero: Vec<u8>,
mut arguments: Vec<KernelArguments>,
mut readback: Vec<u8>,
guard: CurrentGuard<'_, 'ctx>,
) -> Result<()> {
let sync = blas.synchronize();
let status = if sync.is_ok() {
self.buffers[14]
.as_ref()
.and_then(|buffer| buffer.handle)
.ok_or(Error::ContextPoisoned)
.and_then(|handle| self.context.driver.api.copy_to(handle, &mut readback))
} else {
Ok(())
};
let pop = guard.finish();
if commands.is_err() || sync.is_err() || status.is_err() || pop.is_err() {
self.failed = true;
self.context.poison();
self.context.retain_driver();
}
if sync.is_err() || status.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
std::mem::forget((arguments, zero, readback));
return combine(combine(combine(commands, sync), status), pop);
}
if commands.is_err() {
// A failed upload/fence may still own host staging; conservatively
// retain every command operand even when vendor drain succeeded.
std::mem::forget(std::mem::take(&mut arguments));
std::mem::forget(std::mem::take(&mut zero));
}
if status.is_ok() {
for stage in [0usize, 1, 2, 3, 6, 4, 5, 7] {
if !eligible[stage] {
continue;
}
for row in readback.chunks_exact(32) {
let flag = u32::from_le_bytes(
row[stage * 4..stage * 4 + 4]
.try_into()
.map_err(|_| Error::InvalidQwenShape)?,
);
if flag & !1 != 0 {
self.failed = true;
return Err(Error::InvalidDriverValue("GR native unknown finite status"));
}
if flag != 0 {
return Err(Error::NonFiniteMmqOutput(if stage == 7 {
"GR native candidate"
} else {
STAGES[stage]
}));
}
}
}
}
// Owned host ABI/staging cannot die before actual stream drain+pop.
arguments.clear();
zero.clear();
combine(combine(combine(commands, sync), status), pop)
}
pub fn read(
&mut self,
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<super::gr_batch_read::GrMicroValues> {
if self.phase != 0 || !epsilon.is_finite() || epsilon < 0.0 {
return Err(Error::InvalidQwenShape);
}
workspace.validate_context(self.context)?;
self.validate(&weights)?;
for (i, buffer) in self.buffers.iter().flatten().enumerate() {
workspace.reject_alias(self.handle(i)?, buffer.bytes)?;
}
let blas = workspace.blas()?;
let mut w = [self.handle(0)?; 4];
for (i, size) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() {
if weights[i].len() != size {
return Err(Error::InvalidQwenShape);
}
w[i] = weights[i].handle.ok_or(Error::ContextPoisoned)?;
w[i].validate_projection_extent(size, if i == 0 { 4 } else { 2 })?;
workspace.reject_alias(w[i], size)?;
}
let t = self.tokens as i64;
let flags = self.handle(14)?;
let mut args = vec![
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(w[0]),
A::F32(epsilon),
A::Address(self.handle(1)?),
A::Address(self.handle(2)?),
self.low(3)?,
]),
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(flags),
A::I64(t),
]),
self.scan(4, 320, 1)?,
Self::args(vec![
A::Address(self.handle(4)?),
A::Address(self.handle(5)?),
self.low(6)?,
A::I64(t * 320),
]),
Self::args(vec![
A::Address(self.handle(4)?),
A::Address(flags),
A::I64(t),
]),
self.scan(7, 10240, 3)?,
self.scan(12, 4, 6)?,
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(self.handle(7)?),
A::Address(self.handle(8)?),
A::Address(self.handle(9)?),
A::I64(t),
A::Address(self.handle(11)?),
self.low(10)?,
]),
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(1)?),
A::Address(w[0]),
A::Address(self.handle(7)?),
A::Address(flags),
A::I64(t),
]),
self.scan(8, 2560, 5)?,
];
let scalars = self.scalars.as_ref().ok_or(Error::ContextPoisoned)?;
let alpha = &scalars[0];
let beta0 = &scalars[1];
let beta1 = &scalars[2];
let zero = vec![0u8; 32 * self.tokens];
let readback = vec![0u8; 32 * self.tokens];
let context = self.context;
let guard = context.enter()?;
let mut eligible = [false; 8];
let commands = (|| {
self.context.driver.api.copy_from(flags, &zero)?;
// The private vendor stream is NON_BLOCKING: drain all actual
// legacy uploads/reset before any stream consumer is enqueued.
self.context.driver.api.synchronize()?;
// Original gr_norm_rs block topology T*HC blocks, 256 threads.
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
(self.tokens * 4) as u32,
256,
blas.stream(),
&mut args[0],
)?;
self.launch(blas, 5, self.tokens * 10240, &mut args[1])?;
eligible[0] = true;
self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 320, &mut args[2])?;
eligible[1] = true;
self.launch(blas, 1, self.tokens * 320, &mut args[3])?;
self.launch(blas, 6, self.tokens * 320, &mut args[4])?;
eligible[2] = true;
self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 10240, &mut args[5])?;
eligible[3] = true;
// Literal Original executes inject GEMM BEFORE gr_mix_r.
self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?;
self.launch(blas, 4, self.tokens * 4, &mut args[6])?;
eligible[6] = true;
self.launch(blas, 2, self.tokens * 2560, &mut args[7])?;
self.launch(blas, 7, self.tokens * 10240, &mut args[8])?;
eligible[4] = true;
self.launch(blas, 4, self.tokens * 2560, &mut args[9])?;
eligible[5] = true;
Ok(())
})();
self.finish(blas, commands, eligible, zero, args, readback, guard)?;
let mixed = decode(self.buffer(8)?)?;
let inject = decode(self.buffer(12)?)?;
self.phase = 1;
Ok(super::gr_batch_read::GrMicroValues { mixed, inject })
}
pub fn inject(
&mut self,
blocks: &[f32],
workspace: &mut NativeBatchWorkspace<'ctx>,
) -> Result<Box<[f32]>> {
if self.phase != 1 {
return Err(Error::InvalidQwenShape);
}
workspace.validate_context(self.context)?;
self.validate(&[])?;
for (i, buffer) in self.buffers.iter().flatten().enumerate() {
workspace.reject_alias(self.handle(i)?, buffer.bytes)?;
}
let blas = workspace.blas()?;
if blocks.len() != self.tokens * 2560 {
return Err(Error::InvalidQwenShape);
}
if blocks.iter().any(|x| !x.is_finite()) {
return Err(Error::InvalidDriverValue("GR micro block finite"));
}
self.buffers[13]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from_owned(encode(blocks)?)?;
let flags = self.handle(14)?;
let mut args = vec![
Self::args(vec![
A::Address(self.handle(0)?),
A::Address(self.handle(13)?),
A::Address(self.handle(12)?),
A::I64(4),
A::I64(self.tokens as i64),
]),
self.scan(0, 10240, 7)?,
];
let zero = vec![0u8; 32 * self.tokens];
let readback = vec![0u8; 32 * self.tokens];
let context = self.context;
let guard = context.enter()?;
let mut eligible = [false; 8];
let commands = (|| {
self.context.driver.api.copy_from(flags, &zero)?;
// The private vendor stream is NON_BLOCKING: drain all actual
// legacy uploads/reset before any stream consumer is enqueued.
self.context.driver.api.synchronize()?;
self.launch(blas, 3, self.tokens * 10240, &mut args[0])?;
self.launch(blas, 4, self.tokens * 10240, &mut args[1])?;
eligible[7] = true;
Ok(())
})();
// Original writes the real R bank in place. Any attempted failure
// retires this bank phase; no retry can add the same block twice.
// Mere completed numerical refusal does not poison the Context.
self.phase = 2;
self.finish(blas, commands, eligible, zero, args, readback, guard)?;
let values = decode(self.buffer(0)?)?;
self.phase = 0;
Ok(values)
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
let mut result = Ok(());
// Every returned operation drained this model's borrowed stream.
// Unknown completion already poisoned Context and retains ALL operands.
if let Some(module) = self.module.take() {
let closed = if self.context.is_poisoned() {
std::mem::forget(module);
self.context.retain_driver();
Err(Error::ContextPoisoned)
} else {
match self.context.enter() {
Ok(guard) => combine(module.close(), guard.finish()),
Err(error) => {
std::mem::forget(module);
Err(error)
}
}
};
if closed.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, closed);
}
if let Some(scalars) = self.scalars.take() {
if self.context.is_poisoned() {
std::mem::forget(scalars);
}
}
for slot in self.buffers.iter_mut().rev() {
if let Some(buffer) = slot.take() {
let closed = if self.context.is_poisoned() {
std::mem::forget(buffer);
self.context.retain_driver();
Err(Error::ContextPoisoned)
} else {
buffer.release()
};
if closed.is_err() {
self.context.poison();
self.context.retain_driver();
}
result = combine(result, closed);
}
}
result
}
}
impl Drop for GrNativeBatch<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
+169
View File
@@ -0,0 +1,169 @@
// Literal imported Strata prefill GR helpers/kernels. Export-only adaptation.
// Root compiles this asset after integrated source port; placeholder PTX refuses.
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cstdint>
#include <cmath>
constexpr int N=2560, HC=4, D=N*HC, LR=320;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ float block_sum(float v, float* sh) {
const int lane = threadIdx.x & 31, w = threadIdx.x >> 5;
v = warp_sum(v);
__syncthreads();
if (lane == 0) sh[w] = v;
__syncthreads();
const int nw = (blockDim.x + 31) >> 5;
float t = (threadIdx.x < nw) ? sh[threadIdx.x] : 0.0f;
if (w == 0) t = warp_sum(t);
if (threadIdx.x == 0) sh[0] = t;
__syncthreads();
return sh[0];
}
__device__ __forceinline__ uint16_t bf(float f) {
uint32_t u = __float_as_uint(f);
u += 0x7fffu + ((u >> 16) & 1u);
return (uint16_t) (u >> 16);
}
__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); }
__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
extern "C" __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
uint16_t* __restrict__ xn16_lo) {
__shared__ float sh[32];
const int64_t row = blockIdx.x; // t * 4 + c
const int c = (int) (row % HC);
const float* r = R + row * N;
float ss = 0.0f;
for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d];
const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
if (threadIdx.x == 0) rs_out[row] = rs;
for (int d = threadIdx.x; d < N; d += blockDim.x) {
const float v = r[d] * rs * w[c * N + d];
const uint16_t h = bf(v);
xn16[row * N + d] = h;
if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
}
}
extern "C" __global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo,
int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
const float x = lo[i] / (float) HC;
const float v = x / (1.0f + __expf(-x));
const uint16_t h = bf(v);
lo16[i] = h;
if (lo16_lo) lo16_lo[i] = bf_lo(v, h);
}
extern "C" __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w,
const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16,
int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * N) return;
const int64_t t = i / N, d = i % N;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HC; ++c) {
const int64_t j = t * D + c * N + d;
const float x = R[j] * rs[t * HC + c] * w[c * N + d]; // gr_norm_kernel's value, bit for bit
s = fmaf(x, sigm(g[j]), s);
}
s /= (float) HC;
mixed[i] = s;
if (mixed16) {
const uint16_t h = bf(s);
mixed16[i] = h;
if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
}
if (mixed_h) mixed_h[i] = hf(s);
}
extern "C" __global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj,
int64_t inj_ld, int64_t T) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * D) return;
const int64_t t = i / D, c = (i % D) / N, d = i % N;
R[i] = fmaf(bo[t * N + d], 2.0f * sigm(inj[t * inj_ld + c] / (float) HC), R[i]);
}
// Full ordered numerical guards. Original normalized/product arithmetic is
// recomputed in original order, without fabricating a host normalized bank.
// Integer exponent checking covers every actual F32 word; flags per real row.
extern "C" __global__ void gr_scan(const float* x, uint32_t* flags,
int64_t width, int64_t T, uint32_t stage) {
const int64_t i = (int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if (i >= width*T) return;
if ((__float_as_uint(x[i]) & 0x7f800000u)==0x7f800000u)
atomicOr(flags+(i/width)*8+stage,1u);
}
extern "C" __global__ void gr_norm_scan(const float* R,const float* rs,const float* w,
uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if (i>=T*D) return;
const int64_t t=i/D,c=(i%D)/N,d=i%N;
const float x=R[i]*rs[t*HC+c]*w[c*N+d];
if ((__float_as_uint(x)&0x7f800000u)==0x7f800000u) atomicOr(flags+t*8,1u);
}
extern "C" __global__ void gr_silu_scan(const float* lo,uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if(i>=T*LR) return;
const float x=lo[i]/(float)HC;
const float v=x/(1.0f+__expf(-x));
if((__float_as_uint(v)&0x7f800000u)==0x7f800000u) atomicOr(flags+(i/LR)*8+2,1u);
}
extern "C" __global__ void gr_product_scan(const float* R,const float* rs,const float* w,
const float* g,uint32_t* flags,int64_t T) {
const int64_t i=(int64_t)blockIdx.x*blockDim.x+threadIdx.x;
if(i>=T*D) return;
const int64_t t=i/D,c=(i%D)/N,d=i%N;
const float x=R[i]*rs[t*HC+c]*w[c*N+d];
const float product=x*sigm(g[i]);
if((__float_as_uint(product)&0x7f800000u)==0x7f800000u) atomicOr(flags+t*8+4,1u);
}
// Literal Original fused next-half norm carry.
constexpr int GRW_PER = (N + 255) / 256;
extern "C" __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo,
const float* __restrict__ inj, int64_t inj_ld,
const float* __restrict__ w, float eps,
float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
uint16_t* __restrict__ xn16_lo) {
__shared__ float sh[32];
const int64_t row = blockIdx.x; // t * 4 + c
const int64_t t = row / HC;
const int c = (int) (row % HC);
float* r = R + row * N;
const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);
float v[GRW_PER];
float ss = 0.0f;
int k = 0;
#pragma unroll
for (int d = threadIdx.x; d < N; d += 256, ++k) {
const float x = fmaf(bo[t * N + d], sc, r[d]);
r[d] = x;
v[k] = x;
ss += x * x;
}
const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps);
if (threadIdx.x == 0) rs_out[row] = rs;
k = 0;
#pragma unroll
for (int d = threadIdx.x; d < N; d += 256, ++k) {
const float x = v[k] * rs * w[c * N + d];
const uint16_t h = bf(x);
xn16[row * N + d] = h;
if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h);
}
}
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
.version 8.0
.target sm_80
.address_size 64
.visible .entry leleka_gr_read_finite(.param .u64 p0,.param .u64 p1,.param .u64 p2,.param .u64 p3,.param .u64 p4,.param .u64 p5) {
.reg .pred p;
.reg .b32 r<8>;
.reg .b64 a<9>;
mov.u32 r0,%ctaid.x; mov.u32 r1,%ntid.x; mov.u32 r2,%tid.x; mad.lo.u32 r3,r0,r1,r2;
mul.wide.u32 a6,r3,4;
ld.param.u64 a5,[p5];
setp.ge.u32 p,r3,10240; @p bra L0;
ld.param.u64 a0,[p0];
add.u64 a7,a0,a6; ld.global.u32 r4,[a7]; and.b32 r5,r4,0x7f800000; setp.ne.u32 p,r5,0x7f800000; @p bra L0;
atom.global.or.b32 r6,[a5],1;
L0:
setp.ge.u32 p,r3,320; @p bra L1;
ld.param.u64 a1,[p1];
add.u64 a7,a1,a6; ld.global.u32 r4,[a7]; and.b32 r5,r4,0x7f800000; setp.ne.u32 p,r5,0x7f800000; @p bra L1;
atom.global.or.b32 r6,[a5],2;
L1:
setp.ge.u32 p,r3,320; @p bra L2;
ld.param.u64 a2,[p2];
add.u64 a7,a2,a6; ld.global.u32 r4,[a7]; and.b32 r5,r4,0x7f800000; setp.ne.u32 p,r5,0x7f800000; @p bra L2;
atom.global.or.b32 r6,[a5],4;
L2:
setp.ge.u32 p,r3,10240; @p bra L3;
ld.param.u64 a3,[p3];
add.u64 a7,a3,a6; ld.global.u32 r4,[a7]; and.b32 r5,r4,0x7f800000; setp.ne.u32 p,r5,0x7f800000; @p bra L3;
atom.global.or.b32 r6,[a5],8;
L3:
setp.ge.u32 p,r3,10240; @p bra L4;
ld.param.u64 a4,[p4];
add.u64 a7,a4,a6; ld.global.u32 r4,[a7]; and.b32 r5,r4,0x7f800000; setp.ne.u32 p,r5,0x7f800000; @p bra L4;
atom.global.or.b32 r6,[a5],16;
L4:
ret;
}
+176
View File
@@ -0,0 +1,176 @@
//! Closed finite witness for five immutable real GR intermediate buffers.
use super::*;
const BYTES: [usize; 5] = [40960, 1280, 1280, 40960, 40960];
fn shape(bytes: [usize; 5]) -> Result<()> {
if bytes != BYTES {
return Err(Error::InvalidQwenShape);
}
Ok(())
}
impl Context<'_> {
/// Bit i means at least one nonfinite value in original stage i. All
/// buffers are immutable through completed launch; no float math changes.
pub fn gr_read_finite_mask(&self, buffers: [&DeviceBuffer<'_>; 5]) -> Result<u32> {
shape(buffers.map(|b| b.bytes))?;
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let mut handles = [buffers[0].handle.ok_or(Error::ContextPoisoned)?; 6];
for (i, b) in buffers.iter().enumerate() {
if !std::ptr::eq(self, b.context) {
return Err(Error::ContextMismatch);
}
handles[i] = b.handle.ok_or(Error::ContextPoisoned)?;
handles[i].validate_projection_extent(b.bytes, 4)?;
}
for i in 0..5 {
for j in 0..i {
if handles[i].overlaps(BYTES[i], handles[j], BYTES[j]) {
return Err(Error::OutputAliasesInput);
}
}
}
let mut status = self.allocate(4)?;
let result = (|| {
status.copy_from(&[0; 4])?;
handles[5] = status.handle.ok_or(Error::ContextPoisoned)?;
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
{
let guard = self.enter()?;
let kernel = match self.fixed_kernel(FixedOperation::GrReadFinite) {
Ok(kernel) => kernel,
Err(error) => return combine(Err(error), guard.finish()),
};
let mut arguments = ffi::GrReadGuardArguments::new(handles);
let launch = self
.driver
.api
.launch_gr_read_guard(kernel.function, &mut arguments);
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
std::mem::forget(Rc::clone(&self.driver.api));
}
let pop = guard.finish();
if sync.is_err() || pop.is_err() {
std::mem::forget(arguments);
}
combine(combine(launch, sync), pop)?;
}
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver")))]
{
return Err(Error::UnsupportedPlatform);
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
{
let mut bytes = [0; 4];
status.copy_to(&mut bytes)?;
let mask = u32::from_le_bytes(bytes);
if mask & !31 != 0 {
return Err(Error::InvalidDriverValue("GR finite witness"));
}
Ok(mask)
}
})();
let cleanup = status.release();
combine(result, cleanup)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gr_read_guard_closed_stage_extents_reject_truncated_and_reordered() {
assert!(shape(BYTES).is_ok());
for i in 0..5 {
let mut b = BYTES;
b[i] -= 4;
assert_eq!(shape(b), Err(Error::InvalidQwenShape));
}
let mut b = BYTES;
b.swap(0, 1);
assert_eq!(shape(b), Err(Error::InvalidQwenShape));
}
}
#[cfg(all(
test,
target_os = "linux",
target_arch = "x86_64",
feature = "cuda-driver"
))]
mod installed_tests {
use super::*;
#[test]
#[ignore = "root-only new installed-driver finite witness gate"]
fn installed_gr_read_guard_matches_all_stage_bits_and_first_nonfinite() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_GR_DEVICE_GUARD").as_deref(),
Ok("yes")
);
let driver = Driver::load().expect("installed driver");
let device = driver.device(0).unwrap();
let context = device.create_context(2 * 1024 * 1024).unwrap();
let mut buffers: Vec<_> = BYTES
.into_iter()
.map(|b| context.allocate(b).unwrap())
.collect();
let mut cases = 0;
for expected in 0u32..32 {
for (stage, buffer) in buffers.iter_mut().enumerate() {
let mut values = vec![0u8; BYTES[stage]];
for (index, word) in values.chunks_exact_mut(4).enumerate() {
word.copy_from_slice(
&(if index % 2 == 0 { 0.0f32 } else { -0.0f32 }).to_le_bytes(),
);
}
if expected & (1 << stage) != 0 {
let offset = values.len() - 4;
values[offset..].copy_from_slice(&f32::NAN.to_le_bytes());
}
buffer.copy_from(&values).unwrap();
}
let refs: Vec<_> = buffers.iter().collect();
let actual = context
.gr_read_finite_mask(
refs.try_into()
.ok()
.expect("exactly five actual stage buffers"),
)
.unwrap();
assert_eq!(actual, expected);
if actual != 0 {
assert_eq!(actual.trailing_zeros(), expected.trailing_zeros());
}
cases += 1;
}
for invalid in [f32::INFINITY, f32::NEG_INFINITY] {
for (stage, buffer) in buffers.iter_mut().enumerate() {
let mut bytes = vec![0; BYTES[stage]];
let offset = bytes.len() - 4;
bytes[offset..].copy_from_slice(&invalid.to_le_bytes());
buffer.copy_from(&bytes).unwrap();
}
let refs: Vec<_> = buffers.iter().collect();
assert_eq!(
context
.gr_read_finite_mask(
refs.try_into()
.ok()
.expect("exactly five actual stage buffers")
)
.unwrap(),
31
);
cases += 1;
}
for buffer in buffers {
buffer.release().unwrap();
}
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
eprintln!(
"GR finite witness PASS new_cases={cases} all5_stage_bits=true first_nonfinite=true signed_zero=true allocated0=true"
);
}
}
@@ -0,0 +1,349 @@
//! New geometry only: qualified scalar operations FIRST, then grouped transport.
use super::*;
fn bytes(values: &[f32]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
}
fn weights(format: RoutedFormat) -> Vec<u8> {
// Independent original packed layouts: IQ4_NL32/18B, Q2_0 64/18B.
let blocks = match format {
RoutedFormat::IQ4_NL => 20,
RoutedFormat::Q2_0 => 10,
_ => unreachable!(),
};
let mut result = Vec::with_capacity(2560 * blocks * 18);
for row in 0..2560 {
for block in 0..blocks {
result.extend_from_slice(&0x1c00_u16.to_le_bytes()); // d=2^-8.
for index in 0..16 {
result.push(((row * 17 + block * 29 + index * 31) & 255) as u8);
}
}
}
assert_eq!(result.len(), if blocks == 20 { 921600 } else { 460800 });
result
}
fn corpus(total: usize, zero: bool) -> (Vec<u8>, Vec<u8>) {
let mut gate = Vec::with_capacity(total * 640);
let mut up = Vec::with_capacity(total * 640);
for column in 0..total {
for row in 0..640 {
let (g, u) = if zero {
(
f32::from_bits(if (column + row).is_multiple_of(2) {
0
} else {
0x80000000
}),
f32::from_bits(if (column + 2 * row).is_multiple_of(2) {
0x80000000
} else {
0
}),
)
} else if row == 0 {
(-100.0, 1.0) // Valid finite sigmoid saturation, not malformed input.
} else {
(
((row * 7 + column * 11) % 31) as f32 / 8.0 - 2.0,
((row * 13 + column * 3) % 29) as f32 / 16.0 - 0.75,
)
};
gate.push(g);
up.push(u);
}
}
(bytes(&gate), bytes(&up))
}
#[test]
#[ignore = "root schedules one new grouped SwiGLU/Down20/42 geometry comparison, no model"]
fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() {
assert!(std::env::var("LELEKA_STRA169_RUN_GROUPED_DOWN").is_ok_and(|value| value == "yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(16 * 1024 * 1024).unwrap();
let mut hidden_pairs = Vec::new();
let mut down_pairs = Vec::new();
for total in [4_usize, 16, 64] {
for zero in [false, true] {
let (gate_bytes, up_bytes) = corpus(total, zero);
let mut scalar_gate = context.allocate(2560).unwrap();
let mut scalar_up = context.allocate(2560).unwrap();
let mut scalar_hidden = context.allocate(2560).unwrap();
let mut expected_hidden = Vec::with_capacity(total * 2560);
// No grouped launch precedes any scalar reference for this corpus.
for (g, u) in gate_bytes.chunks(2560).zip(up_bytes.chunks(2560)) {
scalar_gate.copy_from(g).unwrap();
scalar_up.copy_from(u).unwrap();
context
.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden)
.unwrap();
let mut observed = vec![0; 2560];
scalar_hidden.copy_to(&mut observed).unwrap();
expected_hidden.extend_from_slice(&observed);
}
scalar_gate.release().unwrap();
scalar_up.release().unwrap();
let mut scalar_output = context.allocate(10240).unwrap();
let mut references = Vec::new();
for format in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] {
let literal = weights(format);
let spec = ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 2560,
columns: 640,
};
let shape = projection_shape(spec).unwrap();
assert_eq!(shape.weight_bytes, literal.len());
assert_eq!(shape.scratch_bytes, 720);
let mut matrix = context.allocate(literal.len()).unwrap();
matrix.copy_from(&literal).unwrap();
let mut expected = Vec::with_capacity(total * 10240);
for h in expected_hidden.chunks(2560) {
scalar_hidden.copy_from(h).unwrap();
context
.project_q8_1(&matrix, &scalar_hidden, &mut scalar_output, spec)
.unwrap();
let mut observed = vec![0; 10240];
scalar_output.copy_to(&mut observed).unwrap();
expected.extend_from_slice(&observed);
}
matrix.release().unwrap();
references.push((format, literal, expected));
}
scalar_output.release().unwrap();
scalar_hidden.release().unwrap();
let mut gate = context.allocate(gate_bytes.len()).unwrap();
let mut up = context.allocate(up_bytes.len()).unwrap();
let mut hidden = context.allocate(gate_bytes.len()).unwrap();
gate.copy_from(&gate_bytes).unwrap();
up.copy_from(&up_bytes).unwrap();
context
.moe_swiglu_columns(&gate, &up, &mut hidden, total)
.unwrap();
let mut observed_hidden = vec![0; gate_bytes.len()];
hidden.copy_to(&mut observed_hidden).unwrap();
let mut gate_after = vec![0; gate_bytes.len()];
let mut up_after = vec![0; up_bytes.len()];
gate.copy_to(&mut gate_after).unwrap();
up.copy_to(&mut up_after).unwrap();
assert_eq!(gate_bytes, gate_after);
assert_eq!(up_bytes, up_after);
gate.release().unwrap();
up.release().unwrap();
for (format, literal, expected) in references {
let mut matrix = context.allocate(literal.len()).unwrap();
let mut output = context.allocate(total * 10240).unwrap();
let mut column = context.allocate(10240).unwrap();
matrix.copy_from(&literal).unwrap();
let charge = context.allocated_bytes();
context
.project_routed_down_columns(&matrix, &hidden, &mut output, total, format)
.unwrap();
assert_eq!(context.allocated_bytes(), charge);
let mut observed = vec![0; total * 10240];
output.copy_to(&mut observed).unwrap();
for index in [0, total / 2, total - 1] {
context
.copy_routed_down_column(&output, total, index, &mut column)
.unwrap();
let mut copied = vec![0; 10240];
column.copy_to(&mut copied).unwrap();
assert_eq!(copied, observed[index * 10240..(index + 1) * 10240]);
}
let mut matrix_after = vec![0; literal.len()];
matrix.copy_to(&mut matrix_after).unwrap();
assert_eq!(literal, matrix_after);
column.release().unwrap();
output.release().unwrap();
matrix.release().unwrap();
down_pairs.push((total, zero, format, expected, observed));
}
let mut hidden_after = vec![0; gate_bytes.len()];
hidden.copy_to(&mut hidden_after).unwrap();
assert_eq!(observed_hidden, hidden_after);
hidden.release().unwrap();
hidden_pairs.push((total, zero, expected_hidden, observed_hidden));
assert_eq!(context.allocated_bytes(), 0);
}
}
// Real source/status cleanup, not injected device faults or forged owners.
let literal = weights(RoutedFormat::IQ4_NL);
let mut matrix = context.allocate(literal.len()).unwrap();
let mut input = context.allocate(2560).unwrap();
let mut output = context.allocate(10240).unwrap();
let mut column = context.allocate(10240).unwrap();
let mut hidden = context.allocate(2560).unwrap();
let mut up = context.allocate(2560).unwrap();
matrix.copy_from(&literal).unwrap();
let valid = vec![0; 2560];
input.copy_from(&valid).unwrap();
up.copy_from(&valid).unwrap();
let sentinel = vec![0xa5; 10240];
output.copy_from(&sentinel).unwrap();
let charge = context.allocated_bytes();
for total in [0, 65] {
assert_eq!(
context.moe_swiglu_columns(&input, &up, &mut hidden, total),
Err(Error::InvalidProjectionShape)
);
assert_eq!(
context.project_routed_down_columns(
&matrix,
&input,
&mut output,
total,
RoutedFormat::IQ4_NL
),
Err(Error::InvalidProjectionShape)
);
}
assert_eq!(
context.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ3_S),
Err(Error::UnsupportedProjection)
);
assert_eq!(
context.copy_routed_down_column(&output, 1, 1, &mut column),
Err(Error::InvalidProjectionShape)
);
let short = context.allocate(2556).unwrap();
assert_eq!(
context.project_routed_down_columns(&matrix, &short, &mut output, 1, RoutedFormat::IQ4_NL),
Err(Error::InvalidProjectionShape)
);
short.release().unwrap();
let foreign = device.create_context(4096).unwrap();
let foreign_input = foreign.allocate(2560).unwrap();
assert_eq!(
context.project_routed_down_columns(
&matrix,
&foreign_input,
&mut output,
1,
RoutedFormat::IQ4_NL
),
Err(Error::ContextMismatch)
);
foreign_input.release().unwrap();
assert_eq!(foreign.allocated_bytes(), 0);
foreign.close().unwrap();
for bad in [0x7fc00001_u32, 0x7f800000, 0xff800000] {
let mut malformed = valid.clone();
malformed[2556..].copy_from_slice(&bad.to_le_bytes());
input.copy_from(&malformed).unwrap();
assert_eq!(
context.project_routed_down_columns(
&matrix,
&input,
&mut output,
1,
RoutedFormat::IQ4_NL
),
Err(Error::InvalidQ8Activation)
);
assert_eq!(context.allocated_bytes(), charge);
let mut after = vec![0; 2560];
input.copy_to(&mut after).unwrap();
assert_eq!(after, malformed);
}
let mut after = vec![0; 10240];
output.copy_to(&mut after).unwrap();
assert_eq!(after, sentinel);
input.copy_from(&valid).unwrap();
context
.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL)
.unwrap();
let mut malformed_gate = valid.clone();
malformed_gate[2556..].copy_from_slice(&0x7fc00001_u32.to_le_bytes());
input.copy_from(&malformed_gate).unwrap();
context
.moe_swiglu_columns(&input, &up, &mut hidden, 1)
.unwrap();
let mut malformed_hidden = vec![0; 2560];
hidden.copy_to(&mut malformed_hidden).unwrap();
assert!(!f32::from_le_bytes(malformed_hidden[2556..].try_into().unwrap()).is_finite());
// Driver math may return Ok+NaN; the finite consumer must refuse that result.
let mut malformed_weights = literal.clone();
malformed_weights[2559 * 360..2559 * 360 + 2].copy_from_slice(&0x7e00_u16.to_le_bytes());
matrix.copy_from(&malformed_weights).unwrap();
input.copy_from(&valid).unwrap();
context
.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL)
.unwrap();
let mut malformed_down = vec![0; 10240];
output.copy_to(&mut malformed_down).unwrap();
assert!(!f32::from_le_bytes(malformed_down[10236..].try_into().unwrap()).is_finite());
up.release().unwrap();
hidden.release().unwrap();
column.release().unwrap();
output.release().unwrap();
input.release().unwrap();
matrix.release().unwrap();
// Scratch/status budget failure occurs before quantizer or output mutation.
let budget = literal.len() + 2560 + 10240 + 723;
let small = device.create_context(budget).unwrap();
let mut w = small.allocate(literal.len()).unwrap();
let mut h = small.allocate(2560).unwrap();
let mut o = small.allocate(10240).unwrap();
w.copy_from(&literal).unwrap();
h.copy_from(&valid).unwrap();
o.copy_from(&sentinel).unwrap();
let charge = small.allocated_bytes();
assert_eq!(
small.project_routed_down_columns(&w, &h, &mut o, 1, RoutedFormat::IQ4_NL),
Err(Error::BudgetExceeded)
);
assert_eq!(small.allocated_bytes(), charge);
o.copy_to(&mut after).unwrap();
assert_eq!(after, sentinel);
o.release().unwrap();
h.release().unwrap();
w.release().unwrap();
assert_eq!(small.allocated_bytes(), 0);
small.close().unwrap();
context.synchronize().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
let mut hidden_words = 0;
for (total, zero, wanted, got) in hidden_pairs {
for (index, (a, b)) in wanted
.as_chunks::<4>()
.0
.iter()
.zip(got.as_chunks::<4>().0)
.enumerate()
{
assert_eq!(a, b, "hidden T={total} zero={zero} word={index}");
assert!(f32::from_le_bytes(*b).is_finite());
hidden_words += 1;
}
}
let mut down_words = 0;
for (total, zero, format, wanted, got) in down_pairs {
for (index, (a, b)) in wanted
.as_chunks::<4>()
.0
.iter()
.zip(got.as_chunks::<4>().0)
.enumerate()
{
assert_eq!(a, b, "Down {format:?} T={total} zero={zero} word={index}");
assert!(f32::from_le_bytes(*b).is_finite());
down_words += 1;
}
}
assert_eq!(hidden_words, 107520);
assert_eq!(down_words, 860160);
println!(
"STRA169_GROUPED_DOWN_PROOF hidden_words={hidden_words} down_words={down_words} exact=true allocated=0"
);
}
@@ -0,0 +1,399 @@
//! Source-only component proof: every original scalar product precedes adapters.
//! Genuine CUDA owners only; this is not a ModelBinding/row publication proof.
use super::*;
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
buffer.copy_from(bytes)?;
Ok(buffer)
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut bytes = vec![0; buffer.bytes];
buffer.copy_to(&mut bytes)?;
Ok(bytes)
}
fn gu_weights(format: RoutedFormat, salt: usize) -> Vec<u8> {
let width = match format {
RoutedFormat::IQ3_S => 110,
RoutedFormat::IQ4_XS => 136,
_ => unreachable!(),
};
let mut raw = vec![0; 640 * 10 * width];
for (row, bytes) in raw.chunks_exact_mut(10 * width).enumerate() {
for (block, bytes) in bytes.chunks_exact_mut(width).enumerate() {
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = ((row * 17 + block * 29 + index * 37 + salt) & 255) as u8;
}
bytes[..2].copy_from_slice(&0x1400u16.to_le_bytes()); // 2^-10
}
}
raw
}
fn down_weights(format: RoutedFormat) -> Vec<u8> {
let blocks = if format == RoutedFormat::IQ4_NL {
20
} else {
10
};
let mut bytes = Vec::with_capacity(2560 * blocks * 18);
for row in 0..2560 {
for block in 0..blocks {
bytes.extend_from_slice(&0x1400u16.to_le_bytes());
for index in 0..16 {
bytes.push(((row * 17 + block * 23 + index * 41) & 255) as u8);
}
}
}
bytes
}
fn input(column: usize, zero: bool) -> Vec<u8> {
(0usize..2560)
.flat_map(|index| {
let value = if zero {
f32::from_bits(if (index + column).is_multiple_of(2) {
0x80000000
} else {
0
})
} else {
((index * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 + column as f32 / 256.0
};
value.to_le_bytes()
})
.collect()
}
struct Comparison {
name: String,
expected: Vec<u8>,
actual: Vec<u8>,
}
fn numeric(context: &Context<'_>, checks: &mut Vec<Comparison>) -> Result<()> {
for format in [RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] {
let gate_bytes = gu_weights(format, 11);
let up_bytes = gu_weights(format, 79);
let gate_weights = upload(context, &gate_bytes)?;
let up_weights = upload(context, &up_bytes)?;
let down_raw = [
down_weights(RoutedFormat::IQ4_NL),
down_weights(RoutedFormat::Q2_0),
];
let down_weights = [
upload(context, &down_raw[0])?,
upload(context, &down_raw[1])?,
];
for total in [1usize, 2, 3, 4, 63, 64] {
for zero in [false, true] {
let inputs: Vec<_> = (0..total)
.map(|column| upload(context, &input(column, zero)))
.collect::<Result<_>>()?;
let prepared: Vec<_> = inputs
.iter()
.map(|input| context.prepare_routed_gate_up_q8(input))
.collect::<Result<_>>()?;
let refs: Vec<_> = prepared.iter().collect();
let mut scalar_gate = context.allocate(2560)?;
let mut scalar_up = context.allocate(2560)?;
let mut scalar_hidden = context.allocate(2560)?;
let mut scalar_down = context.allocate(10240)?;
let mut expected: [Vec<u8>; 5] = std::array::from_fn(|_| Vec::new());
// ALL original scalar operations for this complete corpus FIRST.
for owner in &prepared {
context.project_routed_gate_up_prepared(
&gate_weights,
owner,
&mut scalar_gate,
format,
)?;
context.project_routed_gate_up_prepared(
&up_weights,
owner,
&mut scalar_up,
format,
)?;
expected[0].extend_from_slice(&read(&scalar_gate)?);
expected[1].extend_from_slice(&read(&scalar_up)?);
context.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden)?;
expected[2].extend_from_slice(&read(&scalar_hidden)?);
for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0]
.into_iter()
.enumerate()
{
context.project_q8_1(
&down_weights[index],
&scalar_hidden,
&mut scalar_down,
ProjectionSpec {
kind: ProjectionKind::Routed(down_format),
rows: 2560,
columns: 640,
},
)?;
expected[index + 3].extend_from_slice(&read(&scalar_down)?);
}
}
scalar_down.release()?;
scalar_hidden.release()?;
scalar_up.release()?;
scalar_gate.release()?;
let mut gate = upload(context, &vec![0xa5; total * 2560])?;
let mut up = upload(context, &vec![0xa5; total * 2560])?;
let mut hidden = upload(context, &vec![0xa5; total * 2560])?;
let mut down = upload(context, &vec![0xa5; total * 10240])?;
let charge = context.allocated_bytes();
let mut actual: [Vec<u8>; 5] = std::array::from_fn(|_| Vec::new());
context.project_routed_gate_up_columns(&gate_weights, &refs, &mut gate, format)?;
context.project_routed_gate_up_columns(&up_weights, &refs, &mut up, format)?;
actual[0] = read(&gate)?;
actual[1] = read(&up)?;
context.moe_swiglu_columns(&gate, &up, &mut hidden, total)?;
actual[2] = read(&hidden)?;
for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0]
.into_iter()
.enumerate()
{
context.project_routed_down_columns(
&down_weights[index],
&hidden,
&mut down,
total,
down_format,
)?;
actual[index + 3] = read(&down)?;
}
// Repeat with fully overwritten sentinel outputs and same owners.
gate.copy_from(&vec![0x5a; total * 2560])?;
context.project_routed_gate_up_columns(&gate_weights, &refs, &mut gate, format)?;
checks.push(Comparison {
name: format!("repeat {format:?} T{total} zero={zero}"),
expected: actual[0].clone(),
actual: read(&gate)?,
});
checks.push(Comparison {
name: "transient charge".into(),
expected: charge.to_le_bytes().to_vec(),
actual: context.allocated_bytes().to_le_bytes().to_vec(),
});
// Device input/weight owners are immutable across all launches.
for (column, source) in inputs.iter().enumerate() {
checks.push(Comparison {
name: "input unchanged".into(),
expected: input(column, zero),
actual: read(source)?,
});
}
down.release()?;
hidden.release()?;
up.release()?;
gate.release()?;
drop(refs);
for owner in prepared {
owner.close()?;
}
for source in inputs {
source.release()?;
}
for (index, (expected, actual)) in expected.into_iter().zip(actual).enumerate() {
checks.push(Comparison {
name: format!("product{index} {format:?} T{total} zero={zero}"),
expected,
actual,
});
}
}
}
checks.push(Comparison {
name: "Gate weights unchanged".into(),
expected: gate_bytes,
actual: read(&gate_weights)?,
});
checks.push(Comparison {
name: "Up weights unchanged".into(),
expected: up_bytes,
actual: read(&up_weights)?,
});
for (matrix, raw) in down_weights.into_iter().zip(down_raw) {
checks.push(Comparison {
name: "Down weights unchanged".into(),
expected: raw,
actual: read(&matrix)?,
});
matrix.release()?;
}
up_weights.release()?;
gate_weights.release()?;
}
Ok(())
}
fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec<bool>) -> Result<()> {
for format in [RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] {
let raw = gu_weights(format, 11);
let mut weights = upload(context, &raw)?;
let valid = input(1, false);
let mut activation = upload(context, &valid)?;
let mut output = upload(context, &[0xa5; 2560])?;
let mut scalar = context.allocate(2560)?;
{
let owner = context.prepare_routed_gate_up_q8(&activation)?;
let charge = context.allocated_bytes();
checks.push(
context.project_routed_gate_up_columns(&weights, &[], &mut output, format)
== Err(Error::InvalidProjectionShape),
);
let too_many = vec![&owner; 65];
checks.push(
context.project_routed_gate_up_columns(&weights, &too_many, &mut output, format)
== Err(Error::InvalidProjectionShape),
);
checks.push(
context.project_routed_gate_up_columns(
&weights,
&[&owner],
&mut output,
RoutedFormat::IQ4_NL,
) == Err(Error::UnsupportedProjection),
);
let mut short = context.allocate(2556)?;
checks.push(
context.project_routed_gate_up_columns(&weights, &[&owner], &mut short, format)
== Err(Error::InvalidProjectionShape),
);
short.release()?;
let short_weight = context.allocate(raw.len() - 2)?;
checks.push(
context.project_routed_gate_up_columns(
&short_weight,
&[&owner],
&mut output,
format,
) == Err(Error::InvalidProjectionShape),
);
short_weight.release()?;
let foreign = device.create_context(raw.len() + 4096)?;
let foreign_weight = upload(&foreign, &raw)?;
checks.push(
context.project_routed_gate_up_columns(
&foreign_weight,
&[&owner],
&mut output,
format,
) == Err(Error::ContextMismatch),
);
foreign_weight.release()?;
checks.push(foreign.allocated_bytes() == 0);
foreign.close()?;
checks.push(read(&output)? == vec![0xa5; 2560]);
checks.push(context.allocated_bytes() == charge);
// A real whole weight allocation with a late NaN/Inf header: the
// unchanged arithmetic returns data; the original finite consumer
// refuses it. No typed finite product is manufactured here.
let block_bytes = if format == RoutedFormat::IQ3_S {
110
} else {
136
};
for bits in [0x7e01u16, 0x7c00, 0xfc00] {
let mut malformed = raw.clone();
let last = (640 * 10 - 1) * block_bytes;
malformed[last..last + 2].copy_from_slice(&bits.to_le_bytes());
weights.copy_from(&malformed)?;
context.project_routed_gate_up_prepared(&weights, &owner, &mut scalar, format)?;
let expected = read(&scalar)?;
context.project_routed_gate_up_columns(&weights, &[&owner], &mut output, format)?;
let actual = read(&output)?;
checks.push(
expected
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x).is_finite())
.eq(actual
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x).is_finite())),
);
checks.push(!f32::from_le_bytes(actual[2556..].try_into().unwrap()).is_finite());
}
weights.copy_from(&raw)?;
context.project_routed_gate_up_prepared(&weights, &owner, &mut scalar, format)?;
context.project_routed_gate_up_columns(&weights, &[&owner], &mut output, format)?;
checks.push(read(&scalar)? == read(&output)?);
owner.close()?;
}
for bits in [0x7fc00001u32, 0x7f800000, 0xff800000] {
let mut bad = valid.clone();
bad[10236..].copy_from_slice(&bits.to_le_bytes());
activation.copy_from(&bad)?;
checks.push(matches!(
context.prepare_routed_gate_up_q8(&activation),
Err(Error::InvalidQ8Activation)
));
activation.copy_from(&valid)?;
context.prepare_routed_gate_up_q8(&activation)?.close()?;
}
scalar.release()?;
output.release()?;
activation.release()?;
weights.release()?;
// Table budget (8B) refuses before any output write. All actual owners
// exist; this is not an invented raw device address/offset test.
let small = device.create_context(raw.len() + 10240 + 2880 + 2560 + 7)?;
let w = upload(&small, &raw)?;
let input = upload(&small, &valid)?;
let mut out = upload(&small, &[0xa5; 2560])?;
let owner = small.prepare_routed_gate_up_q8(&input)?;
let charge = small.allocated_bytes();
checks.push(
small.project_routed_gate_up_columns(&w, &[&owner], &mut out, format)
== Err(Error::BudgetExceeded),
);
checks.push(read(&out)? == vec![0xa5; 2560] && small.allocated_bytes() == charge);
owner.close()?;
out.release()?;
input.release()?;
w.release()?;
checks.push(small.allocated_bytes() == 0);
small.close()?;
}
Ok(())
}
#[test]
#[ignore = "root-only new native GU21/23 column adapters, no model or speed proof"]
fn original_first_gu21_gu23_full_products_refusals_reset_and_cleanup() {
assert!(
std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23").is_ok_and(|value| value == "yes")
);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(32 * 1024 * 1024).unwrap();
let mut products = Vec::new();
let mut refusals = Vec::new();
let work =
numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals));
let allocated = context.allocated_bytes();
let closed = context.close();
assert_eq!(work, Ok(()));
assert_eq!(allocated, 0);
assert_eq!(closed, Ok(()));
for check in &refusals {
assert!(*check, "prewrite/numeric/reset guard failed");
}
let mut words = 0;
for product in products {
assert_eq!(product.actual, product.expected, "{}", product.name);
if product.name.starts_with("product") || product.name.starts_with("repeat") {
for word in product.actual.as_chunks::<4>().0 {
assert!(f32::from_le_bytes(*word).is_finite(), "{}", product.name);
words += 1;
}
}
}
assert_eq!(words, 4_208_640);
assert_eq!(refusals.len(), 44);
println!(
"STRA172_GROUPED_GU21_GU23 exact_words={words} guards={} formats=21,23 down=20,42 T=1,2,3,4,63,64 allocated=0 no_model=true",
refusals.len()
);
}
@@ -0,0 +1,450 @@
//! NC4 successor component proof: every original scalar product precedes NC4.
//! Grid-y base4 and T5/63 tails retain actual whole owners; old fixture untouched.
//! Genuine CUDA owners only; this is not a ModelBinding/row publication proof.
use super::*;
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
buffer.copy_from(bytes)?;
Ok(buffer)
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut bytes = vec![0; buffer.bytes];
buffer.copy_to(&mut bytes)?;
Ok(bytes)
}
fn gu_weights(format: RoutedFormat, salt: usize) -> Vec<u8> {
let width = match format {
RoutedFormat::IQ3_S => 110,
RoutedFormat::IQ4_XS => 136,
_ => unreachable!(),
};
let mut raw = vec![0; 640 * 10 * width];
for (row, bytes) in raw.chunks_exact_mut(10 * width).enumerate() {
for (block, bytes) in bytes.chunks_exact_mut(width).enumerate() {
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = ((row * 17 + block * 29 + index * 37 + salt) & 255) as u8;
}
bytes[..2].copy_from_slice(&0x1400u16.to_le_bytes()); // 2^-10
}
}
raw
}
fn down_weights(format: RoutedFormat) -> Vec<u8> {
let blocks = if format == RoutedFormat::IQ4_NL {
20
} else {
10
};
let mut bytes = Vec::with_capacity(2560 * blocks * 18);
for row in 0..2560 {
for block in 0..blocks {
bytes.extend_from_slice(&0x1400u16.to_le_bytes());
for index in 0..16 {
bytes.push(((row * 17 + block * 23 + index * 41) & 255) as u8);
}
}
}
bytes
}
fn input(column: usize, zero: bool) -> Vec<u8> {
(0usize..2560)
.flat_map(|index| {
let value = if zero {
f32::from_bits(if (index + column).is_multiple_of(2) {
0x80000000
} else {
0
})
} else {
((index * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 + column as f32 / 256.0
};
value.to_le_bytes()
})
.collect()
}
struct Comparison {
name: String,
expected: Vec<u8>,
actual: Vec<u8>,
}
fn numeric(context: &Context<'_>, checks: &mut Vec<Comparison>) -> Result<()> {
for format in [RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] {
let gate_bytes = gu_weights(format, 11);
let up_bytes = gu_weights(format, 79);
let gate_weights = upload(context, &gate_bytes)?;
let up_weights = upload(context, &up_bytes)?;
let down_raw = [
down_weights(RoutedFormat::IQ4_NL),
down_weights(RoutedFormat::Q2_0),
];
let down_weights = [
upload(context, &down_raw[0])?,
upload(context, &down_raw[1])?,
];
for total in [1usize, 2, 3, 4, 5, 63, 64] {
for zero in [false, true] {
let inputs: Vec<_> = (0..total)
.map(|column| upload(context, &input(column, zero)))
.collect::<Result<_>>()?;
let prepared: Vec<_> = inputs
.iter()
.map(|input| context.prepare_routed_gate_up_q8(input))
.collect::<Result<_>>()?;
let refs: Vec<_> = prepared.iter().collect();
let mut scalar_gate = context.allocate(2560)?;
let mut scalar_up = context.allocate(2560)?;
let mut scalar_hidden = context.allocate(2560)?;
let mut scalar_down = context.allocate(10240)?;
let mut expected: [Vec<u8>; 5] = std::array::from_fn(|_| Vec::new());
// ALL original scalar operations for this complete corpus FIRST.
for owner in &prepared {
context.project_routed_gate_up_prepared(
&gate_weights,
owner,
&mut scalar_gate,
format,
)?;
context.project_routed_gate_up_prepared(
&up_weights,
owner,
&mut scalar_up,
format,
)?;
expected[0].extend_from_slice(&read(&scalar_gate)?);
expected[1].extend_from_slice(&read(&scalar_up)?);
context.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden)?;
expected[2].extend_from_slice(&read(&scalar_hidden)?);
for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0]
.into_iter()
.enumerate()
{
context.project_q8_1(
&down_weights[index],
&scalar_hidden,
&mut scalar_down,
ProjectionSpec {
kind: ProjectionKind::Routed(down_format),
rows: 2560,
columns: 640,
},
)?;
expected[index + 3].extend_from_slice(&read(&scalar_down)?);
}
}
scalar_down.release()?;
scalar_hidden.release()?;
scalar_up.release()?;
scalar_gate.release()?;
let mut gate = upload(context, &vec![0xa5; total * 2560])?;
let mut up = upload(context, &vec![0xa5; total * 2560])?;
let mut hidden = upload(context, &vec![0xa5; total * 2560])?;
let mut down = upload(context, &vec![0xa5; total * 10240])?;
let charge = context.allocated_bytes();
let mut actual: [Vec<u8>; 5] = std::array::from_fn(|_| Vec::new());
context.project_routed_gate_up_columns(&gate_weights, &refs, &mut gate, format)?;
context.project_routed_gate_up_columns(&up_weights, &refs, &mut up, format)?;
actual[0] = read(&gate)?;
actual[1] = read(&up)?;
context.moe_swiglu_columns(&gate, &up, &mut hidden, total)?;
actual[2] = read(&hidden)?;
for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0]
.into_iter()
.enumerate()
{
context.project_routed_down_columns(
&down_weights[index],
&hidden,
&mut down,
total,
down_format,
)?;
actual[index + 3] = read(&down)?;
}
// Repeat with fully overwritten sentinel outputs and same owners.
gate.copy_from(&vec![0x5a; total * 2560])?;
context.project_routed_gate_up_columns(&gate_weights, &refs, &mut gate, format)?;
checks.push(Comparison {
name: format!("repeat {format:?} T{total} zero={zero}"),
expected: actual[0].clone(),
actual: read(&gate)?,
});
checks.push(Comparison {
name: "transient charge".into(),
expected: charge.to_le_bytes().to_vec(),
actual: context.allocated_bytes().to_le_bytes().to_vec(),
});
// Device input/weight owners are immutable across all launches.
for (column, source) in inputs.iter().enumerate() {
checks.push(Comparison {
name: "input unchanged".into(),
expected: input(column, zero),
actual: read(source)?,
});
}
down.release()?;
hidden.release()?;
up.release()?;
gate.release()?;
drop(refs);
for owner in prepared {
owner.close()?;
}
for source in inputs {
source.release()?;
}
for (index, (expected, actual)) in expected.into_iter().zip(actual).enumerate() {
checks.push(Comparison {
name: format!("product{index} {format:?} T{total} zero={zero}"),
expected,
actual,
});
}
}
}
checks.push(Comparison {
name: "Gate weights unchanged".into(),
expected: gate_bytes,
actual: read(&gate_weights)?,
});
checks.push(Comparison {
name: "Up weights unchanged".into(),
expected: up_bytes,
actual: read(&up_weights)?,
});
for (matrix, raw) in down_weights.into_iter().zip(down_raw) {
checks.push(Comparison {
name: "Down weights unchanged".into(),
expected: raw,
actual: read(&matrix)?,
});
matrix.release()?;
}
up_weights.release()?;
gate_weights.release()?;
}
Ok(())
}
fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec<bool>) -> Result<()> {
for format in [RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] {
let raw = gu_weights(format, 11);
let mut weights = upload(context, &raw)?;
let valid = input(1, false);
let mut activation = upload(context, &valid)?;
let mut output = upload(context, &[0xa5; 2560])?;
let mut scalar = context.allocate(2560)?;
{
let owner = context.prepare_routed_gate_up_q8(&activation)?;
let charge = context.allocated_bytes();
checks.push(
context.project_routed_gate_up_columns(&weights, &[], &mut output, format)
== Err(Error::InvalidProjectionShape),
);
let too_many = vec![&owner; 65];
checks.push(
context.project_routed_gate_up_columns(&weights, &too_many, &mut output, format)
== Err(Error::InvalidProjectionShape),
);
checks.push(
context.project_routed_gate_up_columns(
&weights,
&[&owner],
&mut output,
RoutedFormat::IQ4_NL,
) == Err(Error::UnsupportedProjection),
);
let mut short = context.allocate(2556)?;
checks.push(
context.project_routed_gate_up_columns(&weights, &[&owner], &mut short, format)
== Err(Error::InvalidProjectionShape),
);
short.release()?;
let short_weight = context.allocate(raw.len() - 2)?;
checks.push(
context.project_routed_gate_up_columns(
&short_weight,
&[&owner],
&mut output,
format,
) == Err(Error::InvalidProjectionShape),
);
short_weight.release()?;
let foreign = device.create_context(raw.len() + 4096)?;
let foreign_weight = upload(&foreign, &raw)?;
checks.push(
context.project_routed_gate_up_columns(
&foreign_weight,
&[&owner],
&mut output,
format,
) == Err(Error::ContextMismatch),
);
foreign_weight.release()?;
checks.push(foreign.allocated_bytes() == 0);
foreign.close()?;
checks.push(read(&output)? == vec![0xa5; 2560]);
checks.push(context.allocated_bytes() == charge);
// Genuine T5 exercises the four-column tile plus its live tail.
// Every original scalar column completes FIRST for each fault/reset.
let extra_inputs: Vec<_> = (2..6)
.map(|column| upload(context, &input(column, false)))
.collect::<Result<_>>()?;
let extra_prepared: Vec<_> = extra_inputs
.iter()
.map(|input| context.prepare_routed_gate_up_q8(input))
.collect::<Result<_>>()?;
let mut refs = vec![&owner];
refs.extend(extra_prepared.iter());
let mut multi_output = upload(context, &[0xa5; 5 * 2560])?;
// Raw numerical outputs are inspected by the same full finite
// consumer; no usable finite product is manufactured after failure.
let block_bytes = if format == RoutedFormat::IQ3_S {
110
} else {
136
};
for bits in [0x7e01u16, 0x7c00, 0xfc00] {
let mut malformed = raw.clone();
let last = (640 * 10 - 1) * block_bytes;
malformed[last..last + 2].copy_from_slice(&bits.to_le_bytes());
weights.copy_from(&malformed)?;
let mut expected = Vec::new();
for column in &refs {
context.project_routed_gate_up_prepared(
&weights,
column,
&mut scalar,
format,
)?;
expected.extend_from_slice(&read(&scalar)?);
}
context.project_routed_gate_up_columns(
&weights,
&refs,
&mut multi_output,
format,
)?;
let actual = read(&multi_output)?;
checks.push(
expected
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x).is_finite())
.eq(actual
.as_chunks::<4>()
.0
.iter()
.map(|x| f32::from_le_bytes(*x).is_finite())),
);
checks.push(actual.chunks_exact(2560).all(|column| {
!f32::from_le_bytes(column[2556..].try_into().unwrap()).is_finite()
}));
}
weights.copy_from(&raw)?;
let mut expected = Vec::new();
for column in &refs {
context.project_routed_gate_up_prepared(&weights, column, &mut scalar, format)?;
expected.extend_from_slice(&read(&scalar)?);
}
multi_output.copy_from(&[0x5a; 5 * 2560])?;
context.project_routed_gate_up_columns(&weights, &refs, &mut multi_output, format)?;
checks.push(expected == read(&multi_output)?);
multi_output.release()?;
drop(refs);
for column in extra_prepared {
column.close()?;
}
for input in extra_inputs {
input.release()?;
}
owner.close()?;
}
for bits in [0x7fc00001u32, 0x7f800000, 0xff800000] {
let mut bad = valid.clone();
bad[10236..].copy_from_slice(&bits.to_le_bytes());
activation.copy_from(&bad)?;
checks.push(matches!(
context.prepare_routed_gate_up_q8(&activation),
Err(Error::InvalidQ8Activation)
));
activation.copy_from(&valid)?;
context.prepare_routed_gate_up_q8(&activation)?.close()?;
}
scalar.release()?;
output.release()?;
activation.release()?;
weights.release()?;
// T5 table budget (40B) refuses with only39B free before output write.
// Five genuine distinct Context/Q8 input owners, not repeated pointers.
let small = device.create_context(raw.len() + 5 * (10240 + 2880) + 5 * 2560 + 39)?;
let w = upload(&small, &raw)?;
let inputs: Vec<_> = (0..5)
.map(|column| upload(&small, &input(column, false)))
.collect::<Result<_>>()?;
let mut out = upload(&small, &[0xa5; 5 * 2560])?;
let owners: Vec<_> = inputs
.iter()
.map(|input| small.prepare_routed_gate_up_q8(input))
.collect::<Result<_>>()?;
let refs: Vec<_> = owners.iter().collect();
let charge = small.allocated_bytes();
checks.push(
small.project_routed_gate_up_columns(&w, &refs, &mut out, format)
== Err(Error::BudgetExceeded),
);
checks.push(read(&out)? == vec![0xa5; 5 * 2560] && small.allocated_bytes() == charge);
drop(refs);
for owner in owners {
owner.close()?;
}
out.release()?;
for input in inputs {
input.release()?;
}
w.release()?;
checks.push(small.allocated_bytes() == 0);
small.close()?;
}
Ok(())
}
#[test]
#[ignore = "root-only NC4 GU21/23 source successor, no model or speed proof"]
fn original_first_gu21_gu23_nc4_full_products_tails_refusals_reset_and_cleanup() {
assert!(
std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23_NC4").is_ok_and(|value| value == "yes")
);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(32 * 1024 * 1024).unwrap();
let mut products = Vec::new();
let mut refusals = Vec::new();
let work =
numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals));
let allocated = context.allocated_bytes();
let closed = context.close();
assert_eq!(work, Ok(()));
assert_eq!(allocated, 0);
assert_eq!(closed, Ok(()));
for check in &refusals {
assert!(*check, "prewrite/numeric/reset guard failed");
}
let mut words = 0;
for product in products {
assert_eq!(product.actual, product.expected, "{}", product.name);
if product.name.starts_with("product") || product.name.starts_with("repeat") {
for word in product.actual.as_chunks::<4>().0 {
assert!(f32::from_le_bytes(*word).is_finite(), "{}", product.name);
words += 1;
}
}
}
assert_eq!(words, 4_362_240);
assert_eq!(refusals.len(), 44);
println!(
"STRA172_GROUPED_GU21_GU23_NC4 exact_words={words} guards={} formats=21,23 down=20,42 T=1,2,3,4,5,63,64 allocated=0 no_model=true",
refusals.len()
);
}
+154
View File
@@ -0,0 +1,154 @@
// Root hand-authored integer-only PTX, not a compiler-generated asset.
// Exact topology: 248320 F32 bit patterns, 970 groups of 256, then one group.
// Every output is overwritten per invocation. No floating-point arithmetic.
.version 8.7
.target sm_120
.address_size 64
.visible .entry leleka_head_groups(.param .u64 source, .param .u64 groups) {
.reg .pred %p<8>;
.reg .b32 %r<20>;
.reg .b64 %d<20>;
.shared .align 8 .b8 keys[2048];
.shared .align 4 .b8 flags[1024];
ld.param.u64 %d1, [source];
ld.param.u64 %d2, [groups];
mov.u32 %r1, %tid.x;
mov.u32 %r2, %ctaid.x;
mad.lo.u32 %r3, %r2, 256, %r1;
mul.wide.u32 %d3, %r3, 4;
add.u64 %d3, %d1, %d3;
ld.global.u32 %r4, [%d3];
and.b32 %r5, %r4, 0x7f800000;
setp.eq.u32 %p1, %r5, 0x7f800000;
selp.u32 %r6, 1, 0, %p1;
and.b32 %r7, %r4, 0x7fffffff;
setp.eq.u32 %p2, %r7, 0;
selp.u32 %r4, 0, %r4, %p2;
and.b32 %r8, %r4, 0x80000000;
setp.ne.u32 %p3, %r8, 0;
not.b32 %r9, %r4;
xor.b32 %r10, %r4, 0x80000000;
selp.u32 %r11, %r9, %r10, %p3;
cvt.u64.u32 %d4, %r11;
shl.b64 %d4, %d4, 32;
not.b32 %r12, %r3;
cvt.u64.u32 %d5, %r12;
or.b64 %d4, %d4, %d5;
mov.u64 %d6, keys;
mov.u64 %d7, flags;
mul.wide.u32 %d8, %r1, 8;
mul.wide.u32 %d9, %r1, 4;
add.u64 %d8, %d6, %d8;
add.u64 %d9, %d7, %d9;
st.shared.u64 [%d8], %d4;
st.shared.u32 [%d9], %r6;
bar.sync 0;
mov.u32 %r13, 128;
HG_REDUCE:
setp.lt.u32 %p4, %r1, %r13;
@!%p4 bra HG_SKIP;
add.u32 %r14, %r1, %r13;
mul.wide.u32 %d10, %r14, 8;
mul.wide.u32 %d11, %r14, 4;
add.u64 %d10, %d6, %d10;
add.u64 %d11, %d7, %d11;
ld.shared.u64 %d12, [%d8];
ld.shared.u64 %d13, [%d10];
setp.gt.u64 %p5, %d13, %d12;
selp.b64 %d12, %d13, %d12, %p5;
ld.shared.u32 %r15, [%d9];
ld.shared.u32 %r16, [%d11];
or.b32 %r15, %r15, %r16;
st.shared.u64 [%d8], %d12;
st.shared.u32 [%d9], %r15;
HG_SKIP:
bar.sync 0;
shr.u32 %r13, %r13, 1;
setp.ne.u32 %p6, %r13, 0;
@%p6 bra HG_REDUCE;
setp.ne.u32 %p7, %r1, 0;
@%p7 bra HG_DONE;
ld.shared.u64 %d14, [keys];
ld.shared.u32 %r17, [flags];
mul.wide.u32 %d15, %r2, 8;
add.u64 %d15, %d2, %d15;
st.global.u64 [%d15], %d14;
mul.wide.u32 %d16, %r2, 4;
add.u64 %d16, %d2, %d16;
add.u64 %d16, %d16, 7760;
st.global.u32 [%d16], %r17;
HG_DONE:
ret;
}
.visible .entry leleka_head_final(.param .u64 groups, .param .u64 result) {
.reg .pred %p<8>;
.reg .b32 %r<20>;
.reg .b64 %d<20>;
.shared .align 8 .b8 keys[2048];
.shared .align 4 .b8 flags[1024];
ld.param.u64 %d1, [groups];
ld.param.u64 %d2, [result];
mov.u32 %r1, %tid.x;
mov.u32 %r2, %r1;
mov.u64 %d3, 0;
mov.u32 %r3, 0;
HF_LOAD:
setp.ge.u32 %p1, %r2, 970;
@%p1 bra HF_LOADED;
mul.wide.u32 %d4, %r2, 8;
add.u64 %d4, %d1, %d4;
ld.global.u64 %d5, [%d4];
setp.gt.u64 %p2, %d5, %d3;
selp.b64 %d3, %d5, %d3, %p2;
mul.wide.u32 %d6, %r2, 4;
add.u64 %d6, %d1, %d6;
add.u64 %d6, %d6, 7760;
ld.global.u32 %r4, [%d6];
or.b32 %r3, %r3, %r4;
add.u32 %r2, %r2, 256;
bra HF_LOAD;
HF_LOADED:
mov.u64 %d7, keys;
mov.u64 %d8, flags;
mul.wide.u32 %d9, %r1, 8;
mul.wide.u32 %d10, %r1, 4;
add.u64 %d9, %d7, %d9;
add.u64 %d10, %d8, %d10;
st.shared.u64 [%d9], %d3;
st.shared.u32 [%d10], %r3;
bar.sync 0;
mov.u32 %r5, 128;
HF_REDUCE:
setp.lt.u32 %p3, %r1, %r5;
@!%p3 bra HF_SKIP;
add.u32 %r6, %r1, %r5;
mul.wide.u32 %d11, %r6, 8;
mul.wide.u32 %d12, %r6, 4;
add.u64 %d11, %d7, %d11;
add.u64 %d12, %d8, %d12;
ld.shared.u64 %d13, [%d9];
ld.shared.u64 %d14, [%d11];
setp.gt.u64 %p4, %d14, %d13;
selp.b64 %d13, %d14, %d13, %p4;
ld.shared.u32 %r7, [%d10];
ld.shared.u32 %r8, [%d12];
or.b32 %r7, %r7, %r8;
st.shared.u64 [%d9], %d13;
st.shared.u32 [%d10], %r7;
HF_SKIP:
bar.sync 0;
shr.u32 %r5, %r5, 1;
setp.ne.u32 %p5, %r5, 0;
@%p5 bra HF_REDUCE;
setp.ne.u32 %p6, %r1, 0;
@%p6 bra HF_DONE;
ld.shared.u64 %d15, [keys];
ld.shared.u32 %r9, [flags];
st.global.u64 [%d2], %d15;
add.u64 %d16, %d2, 8;
st.global.u32 [%d16], %r9;
HF_DONE:
ret;
}
+249
View File
@@ -0,0 +1,249 @@
//! Fixed full-vocabulary integer comparison. This is not a model-state capability.
use super::*;
const WORDS: usize = 248_320;
const SOURCE_BYTES: usize = WORDS * 4;
const GROUP_BYTES: usize = 970 * 12;
const RESULT_BYTES: usize = 12;
pub const HEAD_GREEDY_WORKSPACE_BYTES: usize = GROUP_BYTES + RESULT_BYTES;
pub(crate) fn asset() -> Result<&'static [u8]> {
let bytes = concat!(include_str!("head_greedy.ptx"), "\0").as_bytes();
if !bytes[..bytes.len() - 1].is_ascii()
|| bytes[..bytes.len() - 1].contains(&0)
|| crate::qwen_ffi::sha256(&bytes[..bytes.len() - 1]) != ASSET_SHA
{
return Err(Error::InvalidDriverValue("fixed head greedy asset"));
}
Ok(bytes)
}
/// Minted only after both full-coverage kernels and completed result transfer.
/// Callers must separately authenticate their model, input and session identity.
pub struct HeadGreedySelection {
index: u32,
key: u32,
}
impl HeadGreedySelection {
pub fn vocabulary_index(&self) -> u32 {
self.index
}
/// Integer comparison key; +/-zero share one key. No logit values are changed.
pub fn ordered_key(&self) -> u32 {
self.key
}
}
/// Exclusive whole-buffer workspace, reserved before pinned/lazy expert fill.
/// Module/shared storage is implicit Driver memory covered by the caller reserve.
pub struct HeadGreedyWorkspace<'ctx> {
context: &'ctx Context<'ctx>,
buffers: [Option<DeviceBuffer<'ctx>>; 2],
module: Option<ffi::ModuleHandle>,
functions: Option<[ffi::FunctionHandle; 2]>,
failed: bool,
}
impl Context<'_> {
pub fn head_greedy_workspace(&self) -> Result<HeadGreedyWorkspace<'_>> {
HeadGreedyWorkspace::new(self)
}
}
impl<'ctx> HeadGreedyWorkspace<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if context
.allocated_bytes()
.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)
.is_none_or(|bytes| bytes > context.budget)
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
buffers: [None, None],
module: None,
functions: None,
failed: false,
};
let operation = (|| {
owner.buffers[0] = Some(context.allocate(GROUP_BYTES)?);
owner.buffers[1] = Some(context.allocate(RESULT_BYTES)?);
let guard = context.enter()?;
let load = (|| {
let module = context.driver.api.load_head_greedy()?;
owner.module = Some(module);
owner.functions = Some([
context.driver.api.head_greedy_function(module, false)?,
context.driver.api.head_greedy_function(module, true)?,
]);
Ok(())
})();
let pop = guard.finish();
if pop.is_err() {
context.poisoned.set(true);
}
combine(load, pop)
})();
if let Err(primary) = operation {
return combine(Err(primary), owner.close());
}
Ok(owner)
}
pub fn allocated_bytes(&self) -> usize {
self.buffers
.iter()
.flatten()
.map(|buffer| buffer.bytes)
.sum()
}
/// `None` means a completed whole-vocabulary NaN/Inf refusal. No partial
/// winner escapes. Every group and result is overwritten, including flags.
pub fn select(&mut self, source: &DeviceBuffer<'_>) -> Result<Option<HeadGreedySelection>> {
if self.failed || self.context.is_poisoned() || self.context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let functions = self.functions.ok_or(Error::ContextPoisoned)?;
if self.module.is_none() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self.context, source.context) {
return Err(Error::ContextMismatch);
}
if source.bytes != SOURCE_BYTES {
return Err(Error::InvalidQwenShape);
}
let source_handle = source.handle.ok_or(Error::ContextPoisoned)?;
source_handle.validate_projection_extent(SOURCE_BYTES, 4)?;
let groups = self.buffers[0].as_ref().ok_or(Error::ContextPoisoned)?;
let result = self.buffers[1].as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(self.context, groups.context)
|| !std::ptr::eq(self.context, result.context)
{
return Err(Error::ContextMismatch);
}
if groups.bytes != GROUP_BYTES || result.bytes != RESULT_BYTES {
return Err(Error::InvalidQwenShape);
}
let group_handle = groups.handle.ok_or(Error::ContextPoisoned)?;
let result_handle = result.handle.ok_or(Error::ContextPoisoned)?;
group_handle.validate_projection_extent(GROUP_BYTES, 8)?;
result_handle.validate_projection_extent(RESULT_BYTES, 8)?;
if source_handle.overlaps(SOURCE_BYTES, group_handle, GROUP_BYTES)
|| source_handle.overlaps(SOURCE_BYTES, result_handle, RESULT_BYTES)
|| group_handle.overlaps(GROUP_BYTES, result_handle, RESULT_BYTES)
{
return Err(Error::OutputAliasesInput);
}
// All stable argument owners and bounded host staging precede commands.
let mut first = ffi::HeadGreedyArguments::new(source_handle, group_handle);
let mut second = ffi::HeadGreedyArguments::new(group_handle, result_handle);
let mut staging = Vec::new();
staging
.try_reserve_exact(RESULT_BYTES)
.map_err(|_| Error::HostAllocation)?;
staging.resize(RESULT_BYTES, 0);
let guard = self.context.enter()?;
let mut operation =
self.context
.driver
.api
.launch_head_greedy(functions[0], false, &mut first);
if operation.is_ok() {
operation = self
.context
.driver
.api
.launch_head_greedy(functions[1], true, &mut second);
}
if operation.is_ok() {
operation = self.context.driver.api.copy_to(result_handle, &mut staging);
}
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if operation.is_err() || sync.is_err() || pop.is_err() {
self.failed = true;
self.context.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
// Retain actual host ABI/staging and poison all actual source/workspace
// owners. DeviceBuffer release refuses uncertain Context completion.
std::mem::forget((first, second, staging));
return combine(combine(operation, sync), pop).map(|()| None);
}
combine(combine(operation, sync), pop)?;
let status = u32::from_le_bytes(staging[8..12].try_into().expect("fixed status"));
match status {
1 => Ok(None),
0 => {
let packed = u64::from_le_bytes(staging[..8].try_into().expect("fixed result"));
let index = !(packed as u32);
let key = (packed >> 32) as u32;
let bits = if key & 0x8000_0000 != 0 {
key ^ 0x8000_0000
} else {
!key
};
if index >= WORDS as u32 || bits & 0x7f80_0000 == 0x7f80_0000 || bits == 0x8000_0000
{
self.failed = true;
return Err(Error::InvalidDriverValue("fixed head greedy witness"));
}
Ok(Some(HeadGreedySelection { index, key }))
}
_ => {
self.failed = true;
Err(Error::InvalidDriverValue("fixed head finite witness"))
}
}
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
self.functions = None;
let mut result = Ok(());
for buffer in &mut self.buffers {
let release = buffer.take().map_or(Ok(()), |buffer| {
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);
}
let module = self
.module
.take()
.map_or(Ok(()), |module| match self.context.enter() {
Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()),
Err(error) => Err(error),
});
if module.is_err() {
self.context.poisoned.set(true);
std::mem::forget(Rc::clone(&self.context.driver.api));
}
combine(result, module)
}
}
impl Drop for HeadGreedyWorkspace<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "head_greedy_gpu.rs"]
mod gpu;
const ASSET_SHA: [u8; 32] = [
0x78, 0x9f, 0xb7, 0xfc, 0xd5, 0x56, 0x4d, 0xea, 0xac, 0x9e, 0xbd, 0x24, 0x79, 0x7d, 0x3a, 0x15,
0xcd, 0xbb, 0x7c, 0x45, 0xf3, 0x97, 0xa7, 0x72, 0x05, 0x7a, 0x6c, 0x5e, 0xd3, 0xf5, 0x2e, 0xb1,
];
+158
View File
@@ -0,0 +1,158 @@
//! One changed-boundary proof: the old complete host scan always runs FIRST.
//! No inference/cancellation/model/speed certificate is manufactured here.
use super::*;
fn old_greedy(bytes: &[u8]) -> Option<(u32, f32)> {
assert_eq!(bytes.len(), SOURCE_BYTES);
let mut best = None;
for (index, word) in bytes.as_chunks::<4>().0.iter().enumerate() {
let value = f32::from_le_bytes(*word);
if !value.is_finite() {
return None;
}
if best.is_none_or(|(_, previous)| value > previous) {
best = Some((index as u32, value));
}
}
best
}
fn original_first(
source: &mut DeviceBuffer<'_>,
workspace: &mut HeadGreedyWorkspace<'_>,
values: &[u32],
) -> usize {
let bytes: Vec<u8> = values.iter().flat_map(|word| word.to_le_bytes()).collect();
source.copy_from(&bytes).unwrap();
let mut original = vec![0; SOURCE_BYTES];
source.copy_to(&mut original).unwrap();
assert_eq!(original, bytes);
let expected = old_greedy(&original);
let before = workspace.context.allocated_bytes();
let actual = workspace.select(source).unwrap();
match (expected, actual) {
(None, None) => {}
(Some((index, value)), Some(actual)) => {
assert_eq!(actual.vocabulary_index(), index);
let key = actual.ordered_key();
let bits = if key & 0x8000_0000 != 0 {
key ^ 0x8000_0000
} else {
!key
};
assert_eq!(f32::from_bits(bits), value);
if value == 0.0 {
assert_eq!(bits, 0);
}
}
_ => panic!("completed whole-vocabulary result differs from original"),
}
assert_eq!(workspace.context.allocated_bytes(), before);
let mut after = vec![0; SOURCE_BYTES];
source.copy_to(&mut after).unwrap();
assert_eq!(after, original);
WORDS
}
#[test]
#[ignore = "Root serially admits the one new whole-vocabulary integer selection proof"]
fn original_first_complete_greedy_ties_finite_reset_guards_and_cleanup() {
assert!(std::env::var("LELEKA_STRA172_RUN_HEAD_GREEDY").is_ok_and(|v| v == "yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(4 * 1024 * 1024).unwrap();
let foreign = device.create_context(2 * 1024 * 1024).unwrap();
let small = device
.create_context(HEAD_GREEDY_WORKSPACE_BYTES - 1)
.unwrap();
assert!(matches!(
small.head_greedy_workspace(),
Err(Error::BudgetExceeded)
));
assert_eq!(small.allocated_bytes(), 0);
let mut workspace = context.head_greedy_workspace().unwrap();
assert_eq!(workspace.allocated_bytes(), 11_652);
let mut source = context.allocate(SOURCE_BYTES).unwrap();
let other = foreign.allocate(SOURCE_BYTES).unwrap();
let short = context.allocate(SOURCE_BYTES - 4).unwrap();
assert!(matches!(
workspace.select(&other),
Err(Error::ContextMismatch)
));
assert!(matches!(
workspace.select(&short),
Err(Error::InvalidQwenShape)
));
let mut products = 0usize;
let mut words = 0usize;
for case in 0..6 {
let mut values: Vec<u32> = (0..WORDS)
.map(|i| match case {
0 => (-(1.0 + (i % 1703) as f32 / 128.0)).to_bits(),
1 => {
if i.is_multiple_of(2) {
0x8000_0000
} else {
0
}
}
2 => 0x8000_0001 + (i % 0x007f_ffff) as u32,
3 => 0xff7f_ffff,
4 => {
let n = (i as u32).wrapping_mul(2654435761).wrapping_add(17);
(n & 0x807f_ffff) | (((i % 255) as u32) << 23)
}
5 => (-1.0f32).to_bits(),
_ => unreachable!(),
})
.collect();
match case {
2 => {
values[257] = 0x007f_ffff;
values[WORDS - 1] = 0x007f_ffff;
}
3 => {
values[1] = 0x7f7f_ffff;
values[WORDS - 1] = 0x7f7f_ffff;
}
5 => values[WORDS - 1] = 1.0f32.to_bits(),
_ => {}
}
// Poison stale output bytes, not transport. Successful coverage must
// overwrite every physical group/status/result on each actual call.
for buffer in workspace.buffers.iter_mut().flatten() {
buffer.copy_from(&vec![0xff; buffer.len()]).unwrap();
}
words += original_first(&mut source, &mut workspace, &values);
products += 1;
words += original_first(&mut source, &mut workspace, &values);
products += 1;
}
let mut faults = 0;
for index in [0, 255, 256, WORDS / 2 + 17, WORDS - 1] {
for fault in [0x7fc0_0001, 0xffc0_0001, 0x7f80_0000, 0xff80_0000] {
let mut values = vec![0u32; WORDS];
values[index] = fault;
words += original_first(&mut source, &mut workspace, &values);
products += 1;
faults += 1;
values[index] = 0x8000_0000;
words += original_first(&mut source, &mut workspace, &values);
products += 1;
}
}
short.release().unwrap();
other.release().unwrap();
source.release().unwrap();
workspace.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(foreign.allocated_bytes(), 0);
small.synchronize().unwrap();
foreign.synchronize().unwrap();
context.synchronize().unwrap();
small.close().unwrap();
foreign.close().unwrap();
context.close().unwrap();
println!(
"head greedy changed-boundary PASS products={products} complete_host_words={words} finite_refusals={faults} guards=3 allocated=0 inference=false speed=false transport_fault_injection=false"
);
}
@@ -0,0 +1,109 @@
// Experimental source-only IQ3_XXS GU18, M640/K2560/T1..64. No StreamK/fixup.
// Native IQ3 codebook/sign decode: ggml 3cf03257f219afbe7334045ff7c6a06ac68c627d.
// Native arithmetic witness: grouped PTX SHA7882054865e555010d4d60fc21f1aebb97b10dc06af1afe3d09fce2196ac3767.
// MMA fragment layout follows ggml mma.cuh tile<16,8,int>/tile<16,8,half2>
// physical word mapping, equivalently PTX m16n8k32 signed int8 row.col layout.
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cuda_runtime.h>
#include <stdint.h>
__device__ __constant__ unsigned char iq3_native_grid[1024] = {4, 4, 4, 4, 20, 4, 4, 4, 36, 4, 4, 4, 12, 12, 4, 4, 28, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 4, 20, 20, 4, 4, 12, 28, 4, 4, 20, 36, 4, 4, 28, 62, 4, 4, 44, 62, 4, 4, 12, 4, 12, 4, 28, 4, 12, 4, 4, 12, 12, 4, 20, 12, 12, 4, 12, 20, 12, 4, 44, 20, 12, 4, 4, 28, 12, 4, 20, 28, 12, 4, 12, 36, 12, 4, 36, 44, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 20, 4, 20, 4, 36, 4, 20, 4, 12, 12, 20, 4, 4, 20, 20, 4, 20, 20, 20, 4, 12, 28, 20, 4, 28, 28, 20, 4, 62, 28, 20, 4, 12, 44, 20, 4, 62, 44, 20, 4, 44, 62, 20, 4, 12, 4, 28, 4, 62, 4, 28, 4, 4, 12, 28, 4, 20, 12, 28, 4, 44, 20, 28, 4, 4, 62, 28, 4, 28, 12, 36, 4, 62, 28, 36, 4, 36, 36, 36, 4, 62, 44, 36, 4, 28, 62, 36, 4, 44, 62, 36, 4, 12, 4, 44, 4, 62, 4, 44, 4, 20, 28, 44, 4, 20, 44, 44, 4, 44, 28, 52, 4, 36, 52, 52, 4, 4, 12, 62, 4, 36, 12, 62, 4, 52, 12, 62, 4, 28, 36, 62, 4, 12, 52, 62, 4, 12, 4, 4, 12, 28, 4, 4, 12, 4, 12, 4, 12, 20, 12, 4, 12, 12, 20, 4, 12, 28, 20, 4, 12, 4, 28, 4, 12, 20, 28, 4, 12, 36, 28, 4, 12, 62, 36, 4, 12, 4, 44, 4, 12, 4, 4, 12, 12, 20, 4, 12, 12, 12, 12, 12, 12, 4, 20, 12, 12, 20, 20, 12, 12, 12, 4, 20, 12, 28, 4, 20, 12, 4, 12, 20, 12, 20, 12, 20, 12, 12, 20, 20, 12, 4, 28, 20, 12, 20, 62, 20, 12, 4, 4, 28, 12, 20, 4, 28, 12, 4, 20, 28, 12, 12, 28, 28, 12, 52, 36, 28, 12, 52, 52, 28, 12, 12, 4, 36, 12, 44, 4, 36, 12, 4, 44, 36, 12, 4, 20, 44, 12, 36, 20, 44, 12, 52, 36, 44, 12, 12, 62, 44, 12, 44, 4, 52, 12, 20, 20, 62, 12, 4, 36, 62, 12, 4, 4, 4, 20, 20, 4, 4, 20, 12, 12, 4, 20, 28, 12, 4, 20, 4, 20, 4, 20, 20, 20, 4, 20, 52, 20, 4, 20, 12, 28, 4, 20, 20, 36, 4, 20, 12, 4, 12, 20, 28, 4, 12, 20, 44, 4, 12, 20, 4, 12, 12, 20, 20, 12, 12, 20, 12, 20, 12, 20, 4, 28, 12, 20, 28, 52, 12, 20, 62, 52, 12, 20, 4, 62, 12, 20, 4, 4, 20, 20, 20, 4, 20, 20, 12, 12, 20, 20, 62, 12, 20, 20, 4, 20, 20, 20, 20, 20, 20, 20, 62, 28, 20, 20, 4, 36, 20, 20, 44, 44, 20, 20, 12, 4, 28, 20, 4, 12, 28, 20, 36, 12, 28, 20, 4, 62, 28, 20, 36, 62, 28, 20, 44, 28, 36, 20, 28, 44, 36, 20, 28, 4, 44, 20, 62, 20, 44, 20, 12, 36, 44, 20, 36, 62, 44, 20, 12, 4, 62, 20, 28, 4, 62, 20, 52, 12, 62, 20, 44, 36, 62, 20, 12, 4, 4, 28, 4, 12, 4, 28, 20, 12, 4, 28, 12, 20, 4, 28, 28, 20, 4, 28, 4, 44, 4, 28, 44, 52, 4, 28, 20, 62, 4, 28, 4, 4, 12, 28, 20, 4, 12, 28, 4, 20, 12, 28, 12, 28, 12, 28, 36, 36, 12, 28, 52, 36, 12, 28, 12, 4, 20, 28, 28, 4, 20, 28, 4, 12, 20, 28, 44, 20, 20, 28, 20, 44, 20, 28, 20, 62, 20, 28, 12, 12, 28, 28, 28, 28, 28, 28, 4, 28, 36, 28, 62, 36, 36, 28, 20, 62, 36, 28, 4, 4, 44, 28, 52, 4, 44, 28, 20, 20, 44, 28, 44, 44, 44, 28, 36, 12, 52, 28, 52, 28, 52, 28, 28, 52, 52, 28, 28, 28, 62, 28, 4, 52, 62, 28, 36, 4, 4, 36, 62, 12, 4, 36, 44, 28, 4, 36, 62, 28, 4, 36, 28, 44, 4, 36, 62, 44, 4, 36, 36, 62, 12, 36, 4, 20, 20, 36, 62, 28, 20, 36, 4, 36, 20, 36, 4, 52, 20, 36, 52, 52, 20, 36, 62, 4, 28, 36, 44, 36, 28, 36, 36, 4, 36, 36, 12, 44, 36, 36, 36, 52, 36, 36, 44, 20, 44, 36, 28, 36, 44, 36, 4, 62, 44, 36, 44, 4, 62, 36, 4, 12, 62, 36, 20, 12, 62, 36, 4, 28, 62, 36, 20, 12, 4, 44, 12, 36, 4, 44, 4, 62, 4, 44, 4, 4, 12, 44, 52, 4, 12, 44, 52, 20, 12, 44, 44, 44, 12, 44, 36, 12, 20, 44, 20, 28, 20, 44, 20, 62, 20, 44, 20, 4, 28, 44, 28, 44, 28, 44, 4, 12, 36, 44, 28, 20, 36, 44, 62, 20, 36, 44, 20, 62, 36, 44, 20, 4, 44, 44, 12, 28, 44, 44, 4, 44, 52, 44, 36, 20, 62, 44, 20, 36, 62, 44, 36, 20, 4, 52, 36, 36, 4, 52, 52, 36, 4, 52, 36, 52, 4, 52, 12, 20, 12, 52, 12, 52, 12, 52, 62, 12, 20, 52, 36, 52, 20, 52, 4, 28, 28, 52, 52, 28, 28, 52, 36, 36, 36, 52, 44, 4, 44, 52, 20, 44, 44, 52, 28, 28, 52, 52, 28, 4, 62, 52, 12, 20, 62, 52, 28, 4, 4, 62, 44, 4, 4, 62, 62, 4, 4, 62, 4, 12, 4, 62, 20, 28, 4, 62, 20, 44, 4, 62, 52, 20, 12, 62, 4, 36, 12, 62, 20, 12, 20, 62, 44, 36, 20, 62, 20, 44, 20, 62, 4, 4, 28, 62, 44, 12, 28, 62, 28, 28, 28, 62, 4, 52, 28, 62, 12, 20, 36, 62, 12, 36, 36, 62, 4, 4, 44, 62, 20, 4, 44, 62, 36, 20, 44, 62, 4, 28, 52, 62};
__device__ __forceinline__ unsigned read_u32(const unsigned char* p) {
return unsigned(p[0]) | (unsigned(p[1])<<8) | (unsigned(p[2])<<16) | (unsigned(p[3])<<24);
}
__device__ __forceinline__ unsigned signed_grid4(const unsigned char* weights,
unsigned row, unsigned group, unsigned k) {
const unsigned char* block=weights+(row*10u+group/8u)*98u;
unsigned sub=group%8u;
unsigned aux=read_u32(block+66u+sub*4u);
unsigned s=(aux>>(7u*(k/8u)))&127u;
s |= (__popc(s)&1u)<<7;
unsigned code=block[2u+sub*8u+k/4u];
unsigned out=0u;
#pragma unroll
for(unsigned j=0;j<4u;++j) {
int v=int(iq3_native_grid[code*4u+j]);
if((s>>(k%8u+j))&1u) v=-v;
out |= unsigned(static_cast<unsigned char>(v))<<(j*8u);
}
return out;
}
// D4 is integer-only transport from the exact certified native Q8_1 producer:
// block128-major/token-minor, four promoted HALF scales then 128 original codes.
__device__ __forceinline__ unsigned codes4(const unsigned* d4,unsigned token,
unsigned tokens,unsigned group,unsigned k) {
if(token>=tokens) return 0u; // Complete 8-column tile, bounded tail has no reads/writes.
const unsigned* b=d4+(group/4u*tokens+token)*36u;
return b[4u+(group%4u)*8u+k/4u];
}
extern "C" __global__ void leleka_iq3_native_integer_dot(
const unsigned char* weights,const unsigned* d4,int* dots,unsigned tokens) {
// Fixed launch: (40,ceil(T/8),80), block(32,1,1). One actual k32 per warp.
if(tokens==0u||tokens>64u||blockDim.x!=32u||blockDim.y!=1u||blockDim.z!=1u
||blockIdx.x>=40u||blockIdx.y>=(tokens+7u)/8u||blockIdx.z>=80u) return;
unsigned lane=threadIdx.x,r=blockIdx.x*16u+lane/4u,k=(lane%4u)*4u;
unsigned token=blockIdx.y*8u+lane/4u,g=blockIdx.z;
unsigned a0=signed_grid4(weights,r,g,k);
unsigned a1=signed_grid4(weights,r+8u,g,k);
unsigned a2=signed_grid4(weights,r,g,k+16u);
unsigned a3=signed_grid4(weights,r+8u,g,k+16u);
unsigned b0=codes4(d4,token,tokens,g,k),b1=codes4(d4,token,tokens,g,k+16u);
int c0,c1,c2,c3;
asm volatile("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 "
"{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};"
: "=r"(c0),"=r"(c1),"=r"(c2),"=r"(c3)
: "r"(a0),"r"(a1),"r"(a2),"r"(a3),"r"(b0),"r"(b1),"r"(0));
unsigned t0=blockIdx.y*8u+(lane%4u)*2u;
if(t0<tokens) {dots[(t0*640u+r)*80u+g]=c0; dots[(t0*640u+r+8u)*80u+g]=c2;}
if(t0+1u<tokens) {dots[((t0+1u)*640u+r)*80u+g]=c1; dots[((t0+1u)*640u+r+8u)*80u+g]=c3;}
}
__device__ __forceinline__ float native_half(const unsigned char* p) {
unsigned short h=static_cast<unsigned short>(unsigned(p[0])|(unsigned(p[1])<<8));
float f; asm("cvt.f32.f16 %0,%1;" : "=f"(f) : "h"(h)); return f;
}
extern "C" __global__ void leleka_iq3_native_order_reduce(
const unsigned char* weights,const unsigned* d4,const int* dots,float* out,unsigned tokens) {
// Exactly original per-output warp lane g%32, ascending g+=32, XOR16/8/4/2/1.
if(tokens==0u||tokens>64u||blockDim.x!=32u||blockDim.y!=4u||blockDim.z!=1u
||blockIdx.x>=160u||blockIdx.y>=tokens||blockIdx.z!=0u) return;
unsigned row=blockIdx.x*4u+threadIdx.y,t=blockIdx.y,lane=threadIdx.x;
float sum=0.0f;
for(unsigned g=lane;g<80u;g+=32u) {
const unsigned char* b=weights+(row*10u+g/8u)*98u;
unsigned ls=read_u32(b+66u+(g%8u)*4u)>>28;
int c=dots[(t*640u+row)*80u+g];
// C/C++ signed division truncates toward zero, exactly both native PTX divisions.
// |C|<=32*62*128=253952, |ls*C+C/2|<=3936256, no s32 overflow.
int n=(int(ls)*c+c/2)/2;
float dw=native_half(b),da=__uint_as_float(d4[(g/4u*tokens+t)*36u+g%4u]);
float scale; asm("mul.ftz.f32 %0,%1,%2;" : "=f"(scale) : "f"(dw),"f"(da));
float nf; asm("cvt.rn.f32.s32 %0,%1;" : "=f"(nf) : "r"(n));
asm("fma.rn.ftz.f32 %0,%1,%2,%0;" : "+f"(sum) : "f"(scale),"f"(nf));
}
#pragma unroll
for(int shift=16;shift>0;shift/=2) {
float other=__shfl_xor_sync(0xffffffffu,sum,shift,32);
asm("add.ftz.f32 %0,%1,%2;" : "=f"(sum) : "f"(sum),"f"(other));
}
if(lane==0u) out[t*640u+row]=sum;
}
@@ -0,0 +1,492 @@
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-35583870
// Cuda compilation tools, release 12.8, V12.8.93
// Based on NVVM 20.0.0
//
.version 8.7
.target sm_120
.address_size 64
// .globl leleka_iq3_native_integer_dot
.const .align 1 .b8 iq3_native_grid[1024] = {4, 4, 4, 4, 20, 4, 4, 4, 36, 4, 4, 4, 12, 12, 4, 4, 28, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 4, 20, 20, 4, 4, 12, 28, 4, 4, 20, 36, 4, 4, 28, 62, 4, 4, 44, 62, 4, 4, 12, 4, 12, 4, 28, 4, 12, 4, 4, 12, 12, 4, 20, 12, 12, 4, 12, 20, 12, 4, 44, 20, 12, 4, 4, 28, 12, 4, 20, 28, 12, 4, 12, 36, 12, 4, 36, 44, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 20, 4, 20, 4, 36, 4, 20, 4, 12, 12, 20, 4, 4, 20, 20, 4, 20, 20, 20, 4, 12, 28, 20, 4, 28, 28, 20, 4, 62, 28, 20, 4, 12, 44, 20, 4, 62, 44, 20, 4, 44, 62, 20, 4, 12, 4, 28, 4, 62, 4, 28, 4, 4, 12, 28, 4, 20, 12, 28, 4, 44, 20, 28, 4, 4, 62, 28, 4, 28, 12, 36, 4, 62, 28, 36, 4, 36, 36, 36, 4, 62, 44, 36, 4, 28, 62, 36, 4, 44, 62, 36, 4, 12, 4, 44, 4, 62, 4, 44, 4, 20, 28, 44, 4, 20, 44, 44, 4, 44, 28, 52, 4, 36, 52, 52, 4, 4, 12, 62, 4, 36, 12, 62, 4, 52, 12, 62, 4, 28, 36, 62, 4, 12, 52, 62, 4, 12, 4, 4, 12, 28, 4, 4, 12, 4, 12, 4, 12, 20, 12, 4, 12, 12, 20, 4, 12, 28, 20, 4, 12, 4, 28, 4, 12, 20, 28, 4, 12, 36, 28, 4, 12, 62, 36, 4, 12, 4, 44, 4, 12, 4, 4, 12, 12, 20, 4, 12, 12, 12, 12, 12, 12, 4, 20, 12, 12, 20, 20, 12, 12, 12, 4, 20, 12, 28, 4, 20, 12, 4, 12, 20, 12, 20, 12, 20, 12, 12, 20, 20, 12, 4, 28, 20, 12, 20, 62, 20, 12, 4, 4, 28, 12, 20, 4, 28, 12, 4, 20, 28, 12, 12, 28, 28, 12, 52, 36, 28, 12, 52, 52, 28, 12, 12, 4, 36, 12, 44, 4, 36, 12, 4, 44, 36, 12, 4, 20, 44, 12, 36, 20, 44, 12, 52, 36, 44, 12, 12, 62, 44, 12, 44, 4, 52, 12, 20, 20, 62, 12, 4, 36, 62, 12, 4, 4, 4, 20, 20, 4, 4, 20, 12, 12, 4, 20, 28, 12, 4, 20, 4, 20, 4, 20, 20, 20, 4, 20, 52, 20, 4, 20, 12, 28, 4, 20, 20, 36, 4, 20, 12, 4, 12, 20, 28, 4, 12, 20, 44, 4, 12, 20, 4, 12, 12, 20, 20, 12, 12, 20, 12, 20, 12, 20, 4, 28, 12, 20, 28, 52, 12, 20, 62, 52, 12, 20, 4, 62, 12, 20, 4, 4, 20, 20, 20, 4, 20, 20, 12, 12, 20, 20, 62, 12, 20, 20, 4, 20, 20, 20, 20, 20, 20, 20, 62, 28, 20, 20, 4, 36, 20, 20, 44, 44, 20, 20, 12, 4, 28, 20, 4, 12, 28, 20, 36, 12, 28, 20, 4, 62, 28, 20, 36, 62, 28, 20, 44, 28, 36, 20, 28, 44, 36, 20, 28, 4, 44, 20, 62, 20, 44, 20, 12, 36, 44, 20, 36, 62, 44, 20, 12, 4, 62, 20, 28, 4, 62, 20, 52, 12, 62, 20, 44, 36, 62, 20, 12, 4, 4, 28, 4, 12, 4, 28, 20, 12, 4, 28, 12, 20, 4, 28, 28, 20, 4, 28, 4, 44, 4, 28, 44, 52, 4, 28, 20, 62, 4, 28, 4, 4, 12, 28, 20, 4, 12, 28, 4, 20, 12, 28, 12, 28, 12, 28, 36, 36, 12, 28, 52, 36, 12, 28, 12, 4, 20, 28, 28, 4, 20, 28, 4, 12, 20, 28, 44, 20, 20, 28, 20, 44, 20, 28, 20, 62, 20, 28, 12, 12, 28, 28, 28, 28, 28, 28, 4, 28, 36, 28, 62, 36, 36, 28, 20, 62, 36, 28, 4, 4, 44, 28, 52, 4, 44, 28, 20, 20, 44, 28, 44, 44, 44, 28, 36, 12, 52, 28, 52, 28, 52, 28, 28, 52, 52, 28, 28, 28, 62, 28, 4, 52, 62, 28, 36, 4, 4, 36, 62, 12, 4, 36, 44, 28, 4, 36, 62, 28, 4, 36, 28, 44, 4, 36, 62, 44, 4, 36, 36, 62, 12, 36, 4, 20, 20, 36, 62, 28, 20, 36, 4, 36, 20, 36, 4, 52, 20, 36, 52, 52, 20, 36, 62, 4, 28, 36, 44, 36, 28, 36, 36, 4, 36, 36, 12, 44, 36, 36, 36, 52, 36, 36, 44, 20, 44, 36, 28, 36, 44, 36, 4, 62, 44, 36, 44, 4, 62, 36, 4, 12, 62, 36, 20, 12, 62, 36, 4, 28, 62, 36, 20, 12, 4, 44, 12, 36, 4, 44, 4, 62, 4, 44, 4, 4, 12, 44, 52, 4, 12, 44, 52, 20, 12, 44, 44, 44, 12, 44, 36, 12, 20, 44, 20, 28, 20, 44, 20, 62, 20, 44, 20, 4, 28, 44, 28, 44, 28, 44, 4, 12, 36, 44, 28, 20, 36, 44, 62, 20, 36, 44, 20, 62, 36, 44, 20, 4, 44, 44, 12, 28, 44, 44, 4, 44, 52, 44, 36, 20, 62, 44, 20, 36, 62, 44, 36, 20, 4, 52, 36, 36, 4, 52, 52, 36, 4, 52, 36, 52, 4, 52, 12, 20, 12, 52, 12, 52, 12, 52, 62, 12, 20, 52, 36, 52, 20, 52, 4, 28, 28, 52, 52, 28, 28, 52, 36, 36, 36, 52, 44, 4, 44, 52, 20, 44, 44, 52, 28, 28, 52, 52, 28, 4, 62, 52, 12, 20, 62, 52, 28, 4, 4, 62, 44, 4, 4, 62, 62, 4, 4, 62, 4, 12, 4, 62, 20, 28, 4, 62, 20, 44, 4, 62, 52, 20, 12, 62, 4, 36, 12, 62, 20, 12, 20, 62, 44, 36, 20, 62, 20, 44, 20, 62, 4, 4, 28, 62, 44, 12, 28, 62, 28, 28, 28, 62, 4, 52, 28, 62, 12, 20, 36, 62, 12, 36, 36, 62, 4, 4, 44, 62, 20, 4, 44, 62, 36, 20, 44, 62, 4, 28, 52, 62};
.visible .entry leleka_iq3_native_integer_dot(
.param .u64 leleka_iq3_native_integer_dot_param_0,
.param .u64 leleka_iq3_native_integer_dot_param_1,
.param .u64 leleka_iq3_native_integer_dot_param_2,
.param .u32 leleka_iq3_native_integer_dot_param_3
)
{
.reg .pred %p<32>;
.reg .b16 %rs<3>;
.reg .b32 %r<234>;
.reg .b64 %rd<46>;
ld.param.u64 %rd3, [leleka_iq3_native_integer_dot_param_1];
ld.param.u64 %rd4, [leleka_iq3_native_integer_dot_param_2];
ld.param.u32 %r22, [leleka_iq3_native_integer_dot_param_3];
cvta.to.global.u64 %rd1, %rd4;
add.s32 %r23, %r22, -65;
setp.lt.u32 %p1, %r23, -64;
mov.u32 %r24, %ntid.x;
setp.ne.s32 %p2, %r24, 32;
mov.u32 %r25, %ntid.y;
setp.ne.s32 %p3, %r25, 1;
or.pred %p4, %p2, %p3;
or.pred %p5, %p4, %p1;
mov.u32 %r26, %ntid.z;
setp.ne.s32 %p6, %r26, 1;
or.pred %p7, %p6, %p5;
mov.u32 %r1, %ctaid.x;
setp.gt.u32 %p8, %r1, 39;
or.pred %p9, %p8, %p7;
@%p9 bra $L__BB0_8;
mov.u32 %r2, %ctaid.y;
add.s32 %r27, %r22, 7;
shr.u32 %r28, %r27, 3;
setp.ge.u32 %p10, %r2, %r28;
mov.u32 %r3, %ctaid.z;
setp.gt.u32 %p11, %r3, 79;
or.pred %p12, %p11, %p10;
@%p12 bra $L__BB0_8;
ld.param.u64 %rd45, [leleka_iq3_native_integer_dot_param_0];
cvta.to.global.u64 %rd5, %rd45;
mov.u32 %r4, %tid.x;
shl.b32 %r30, %r1, 4;
shr.u32 %r31, %r4, 2;
add.s32 %r5, %r30, %r31;
shl.b32 %r32, %r4, 2;
and.b32 %r33, %r32, 12;
shl.b32 %r6, %r2, 3;
add.s32 %r7, %r6, %r31;
shr.u32 %r34, %r3, 3;
mad.lo.s32 %r35, %r5, 10, %r34;
mul.lo.s32 %r36, %r35, 98;
shl.b32 %r37, %r3, 2;
and.b32 %r38, %r37, 28;
add.s32 %r39, %r38, %r36;
cvt.u64.u32 %rd6, %r39;
add.s64 %rd7, %rd5, %rd6;
ld.global.u8 %r40, [%rd7+66];
or.b32 %r41, %r39, 1;
cvt.u64.u32 %rd8, %r41;
add.s64 %rd9, %rd5, %rd8;
ld.global.u8 %rs1, [%rd9+66];
mul.wide.u16 %r42, %rs1, 256;
or.b32 %r43, %r42, %r40;
add.s32 %r44, %r39, 2;
cvt.u64.u32 %rd10, %r44;
add.s64 %rd11, %rd5, %rd10;
ld.global.u8 %r45, [%rd11+66];
shl.b32 %r46, %r45, 16;
or.b32 %r47, %r43, %r46;
add.s32 %r48, %r39, 3;
cvt.u64.u32 %rd12, %r48;
add.s64 %rd13, %rd5, %rd12;
ld.global.u8 %r49, [%rd13+66];
shl.b32 %r50, %r49, 24;
or.b32 %r51, %r47, %r50;
shr.u32 %r52, %r33, 3;
mul.lo.s32 %r53, %r52, 7;
shr.u32 %r54, %r51, %r53;
and.b32 %r55, %r54, 127;
popc.b32 %r56, %r55;
shl.b32 %r57, %r56, 7;
or.b32 %r58, %r57, %r55;
shl.b32 %r59, %r3, 3;
and.b32 %r60, %r59, 56;
shr.u32 %r8, %r33, 2;
or.b32 %r61, %r60, %r8;
add.s32 %r62, %r36, %r61;
cvt.u64.u32 %rd14, %r62;
add.s64 %rd15, %rd5, %rd14;
and.b32 %r63, %r32, 4;
ld.global.u8 %r64, [%rd15+2];
mul.wide.u32 %rd16, %r64, 4;
mov.u64 %rd17, iq3_native_grid;
add.s64 %rd18, %rd17, %rd16;
ld.const.u8 %r65, [%rd18];
mov.b32 %r66, 1;
shl.b32 %r67, %r66, %r63;
and.b32 %r68, %r67, %r58;
setp.eq.s32 %p13, %r68, 0;
neg.s32 %r69, %r65;
selp.b32 %r70, %r65, %r69, %p13;
and.b32 %r71, %r70, 255;
ld.const.u8 %r72, [%rd18+1];
mov.b32 %r73, 2;
shl.b32 %r74, %r73, %r63;
and.b32 %r75, %r74, %r58;
setp.eq.s32 %p14, %r75, 0;
neg.s32 %r76, %r72;
selp.b32 %r77, %r72, %r76, %p14;
shl.b32 %r78, %r77, 8;
and.b32 %r79, %r78, 65280;
or.b32 %r80, %r79, %r71;
ld.const.u8 %r81, [%rd18+2];
mov.b32 %r82, 4;
shl.b32 %r83, %r82, %r63;
and.b32 %r84, %r83, %r58;
setp.eq.s32 %p15, %r84, 0;
neg.s32 %r85, %r81;
selp.b32 %r86, %r81, %r85, %p15;
shl.b32 %r87, %r86, 16;
and.b32 %r88, %r87, 16711680;
or.b32 %r89, %r88, %r80;
ld.const.u8 %r90, [%rd18+3];
mov.b32 %r91, 8;
shl.b32 %r92, %r91, %r63;
and.b32 %r93, %r92, %r58;
setp.eq.s32 %p16, %r93, 0;
neg.s32 %r94, %r90;
selp.b32 %r95, %r90, %r94, %p16;
shl.b32 %r96, %r95, 24;
or.b32 %r9, %r96, %r89;
add.s32 %r97, %r36, 7840;
add.s32 %r98, %r38, %r97;
cvt.u64.u32 %rd19, %r98;
add.s64 %rd20, %rd5, %rd19;
ld.global.u8 %r99, [%rd20+66];
or.b32 %r100, %r98, 1;
cvt.u64.u32 %rd21, %r100;
add.s64 %rd22, %rd5, %rd21;
ld.global.u8 %rs2, [%rd22+66];
mul.wide.u16 %r101, %rs2, 256;
or.b32 %r102, %r101, %r99;
ld.global.u8 %r103, [%rd20+68];
shl.b32 %r104, %r103, 16;
or.b32 %r105, %r102, %r104;
ld.global.u8 %r106, [%rd20+69];
shl.b32 %r107, %r106, 24;
or.b32 %r108, %r105, %r107;
shr.u32 %r109, %r108, %r53;
and.b32 %r110, %r109, 127;
popc.b32 %r111, %r110;
shl.b32 %r112, %r111, 7;
or.b32 %r113, %r112, %r110;
add.s32 %r114, %r97, %r61;
cvt.u64.u32 %rd23, %r114;
add.s64 %rd24, %rd5, %rd23;
ld.global.u8 %r115, [%rd24+2];
mul.wide.u32 %rd25, %r115, 4;
add.s64 %rd26, %rd17, %rd25;
ld.const.u8 %r116, [%rd26];
and.b32 %r117, %r67, %r113;
setp.eq.s32 %p17, %r117, 0;
neg.s32 %r118, %r116;
selp.b32 %r119, %r116, %r118, %p17;
and.b32 %r120, %r119, 255;
ld.const.u8 %r121, [%rd26+1];
and.b32 %r122, %r74, %r113;
setp.eq.s32 %p18, %r122, 0;
neg.s32 %r123, %r121;
selp.b32 %r124, %r121, %r123, %p18;
shl.b32 %r125, %r124, 8;
and.b32 %r126, %r125, 65280;
or.b32 %r127, %r126, %r120;
ld.const.u8 %r128, [%rd26+2];
and.b32 %r129, %r83, %r113;
setp.eq.s32 %p19, %r129, 0;
neg.s32 %r130, %r128;
selp.b32 %r131, %r128, %r130, %p19;
shl.b32 %r132, %r131, 16;
and.b32 %r133, %r132, 16711680;
or.b32 %r134, %r133, %r127;
ld.const.u8 %r135, [%rd26+3];
and.b32 %r136, %r92, %r113;
setp.eq.s32 %p20, %r136, 0;
neg.s32 %r137, %r135;
selp.b32 %r138, %r135, %r137, %p20;
shl.b32 %r139, %r138, 24;
or.b32 %r10, %r139, %r134;
or.b32 %r140, %r33, 16;
shr.u32 %r141, %r140, 3;
mul.lo.s32 %r142, %r141, 7;
shr.u32 %r143, %r51, %r142;
and.b32 %r144, %r143, 127;
popc.b32 %r145, %r144;
shl.b32 %r146, %r145, 7;
or.b32 %r147, %r146, %r144;
shr.u32 %r148, %r140, 2;
or.b32 %r149, %r148, %r60;
add.s32 %r150, %r36, %r149;
cvt.u64.u32 %rd27, %r150;
add.s64 %rd28, %rd5, %rd27;
ld.global.u8 %r151, [%rd28+2];
mul.wide.u32 %rd29, %r151, 4;
add.s64 %rd30, %rd17, %rd29;
ld.const.u8 %r152, [%rd30];
and.b32 %r153, %r67, %r147;
setp.eq.s32 %p21, %r153, 0;
neg.s32 %r154, %r152;
selp.b32 %r155, %r152, %r154, %p21;
and.b32 %r156, %r155, 255;
ld.const.u8 %r157, [%rd30+1];
and.b32 %r158, %r74, %r147;
setp.eq.s32 %p22, %r158, 0;
neg.s32 %r159, %r157;
selp.b32 %r160, %r157, %r159, %p22;
shl.b32 %r161, %r160, 8;
and.b32 %r162, %r161, 65280;
or.b32 %r163, %r162, %r156;
ld.const.u8 %r164, [%rd30+2];
and.b32 %r165, %r83, %r147;
setp.eq.s32 %p23, %r165, 0;
neg.s32 %r166, %r164;
selp.b32 %r167, %r164, %r166, %p23;
shl.b32 %r168, %r167, 16;
and.b32 %r169, %r168, 16711680;
or.b32 %r170, %r169, %r163;
ld.const.u8 %r171, [%rd30+3];
and.b32 %r172, %r92, %r147;
setp.eq.s32 %p24, %r172, 0;
neg.s32 %r173, %r171;
selp.b32 %r174, %r171, %r173, %p24;
shl.b32 %r175, %r174, 24;
or.b32 %r11, %r175, %r170;
shr.u32 %r176, %r108, %r142;
and.b32 %r177, %r176, 127;
popc.b32 %r178, %r177;
shl.b32 %r179, %r178, 7;
or.b32 %r180, %r179, %r177;
add.s32 %r181, %r97, %r149;
cvt.u64.u32 %rd31, %r181;
add.s64 %rd32, %rd5, %rd31;
ld.global.u8 %r182, [%rd32+2];
mul.wide.u32 %rd33, %r182, 4;
add.s64 %rd34, %rd17, %rd33;
ld.const.u8 %r183, [%rd34];
and.b32 %r184, %r67, %r180;
setp.eq.s32 %p25, %r184, 0;
neg.s32 %r185, %r183;
selp.b32 %r186, %r183, %r185, %p25;
and.b32 %r187, %r186, 255;
ld.const.u8 %r188, [%rd34+1];
and.b32 %r189, %r74, %r180;
setp.eq.s32 %p26, %r189, 0;
neg.s32 %r190, %r188;
selp.b32 %r191, %r188, %r190, %p26;
shl.b32 %r192, %r191, 8;
and.b32 %r193, %r192, 65280;
or.b32 %r194, %r193, %r187;
ld.const.u8 %r195, [%rd34+2];
and.b32 %r196, %r83, %r180;
setp.eq.s32 %p27, %r196, 0;
neg.s32 %r197, %r195;
selp.b32 %r198, %r195, %r197, %p27;
shl.b32 %r199, %r198, 16;
and.b32 %r200, %r199, 16711680;
or.b32 %r201, %r200, %r194;
ld.const.u8 %r202, [%rd34+3];
and.b32 %r203, %r92, %r180;
setp.eq.s32 %p28, %r203, 0;
neg.s32 %r204, %r202;
selp.b32 %r205, %r202, %r204, %p28;
shl.b32 %r206, %r205, 24;
or.b32 %r12, %r206, %r201;
setp.ge.u32 %p29, %r7, %r22;
mov.b32 %r232, 0;
mov.u32 %r233, %r232;
@%p29 bra $L__BB0_4;
shr.u32 %r207, %r3, 2;
mad.lo.s32 %r208, %r22, %r207, %r7;
mul.lo.s32 %r209, %r208, 36;
cvt.u64.u32 %rd35, %r209;
and.b32 %r211, %r59, 24;
or.b32 %r212, %r211, %r8;
cvt.u64.u32 %rd36, %r212;
add.s64 %rd37, %rd35, %rd36;
cvta.to.global.u64 %rd38, %rd3;
shl.b64 %rd39, %rd37, 2;
add.s64 %rd40, %rd38, %rd39;
ld.global.u32 %r232, [%rd40+16];
ld.global.u32 %r233, [%rd40+32];
$L__BB0_4:
mov.b32 %r223, 0;
// begin inline asm
mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%r213,%r214,%r215,%r216}, {%r9,%r10,%r11,%r12}, {%r232,%r233}, {%r223,%r223,%r223,%r223};
// end inline asm
add.s32 %r224, %r4, %r4;
and.b32 %r225, %r224, 6;
add.s32 %r21, %r225, %r6;
setp.ge.u32 %p30, %r21, %r22;
@%p30 bra $L__BB0_6;
mad.lo.s32 %r226, %r21, 640, %r5;
mad.lo.s32 %r227, %r226, 80, %r3;
mul.wide.u32 %rd41, %r227, 4;
add.s64 %rd42, %rd1, %rd41;
st.global.u32 [%rd42], %r213;
st.global.u32 [%rd42+2560], %r215;
$L__BB0_6:
add.s32 %r228, %r21, 1;
setp.ge.u32 %p31, %r228, %r22;
@%p31 bra $L__BB0_8;
mad.lo.s32 %r229, %r21, 640, %r5;
add.s32 %r230, %r229, 640;
mad.lo.s32 %r231, %r230, 80, %r3;
mul.wide.u32 %rd43, %r231, 4;
add.s64 %rd44, %rd1, %rd43;
st.global.u32 [%rd44], %r214;
st.global.u32 [%rd44+2560], %r216;
$L__BB0_8:
ret;
}
// .globl leleka_iq3_native_order_reduce
.visible .entry leleka_iq3_native_order_reduce(
.param .u64 leleka_iq3_native_order_reduce_param_0,
.param .u64 leleka_iq3_native_order_reduce_param_1,
.param .u64 leleka_iq3_native_order_reduce_param_2,
.param .u64 leleka_iq3_native_order_reduce_param_3,
.param .u32 leleka_iq3_native_order_reduce_param_4
)
{
.reg .pred %p<22>;
.reg .b16 %rs<4>;
.reg .b32 %r<63>;
.reg .f32 %f<33>;
.reg .b64 %rd<19>;
ld.param.u64 %rd4, [leleka_iq3_native_order_reduce_param_0];
ld.param.u64 %rd5, [leleka_iq3_native_order_reduce_param_1];
ld.param.u64 %rd6, [leleka_iq3_native_order_reduce_param_2];
ld.param.u64 %rd7, [leleka_iq3_native_order_reduce_param_3];
ld.param.u32 %r19, [leleka_iq3_native_order_reduce_param_4];
add.s32 %r20, %r19, -65;
setp.lt.u32 %p1, %r20, -64;
mov.u32 %r21, %ntid.x;
setp.ne.s32 %p2, %r21, 32;
mov.u32 %r22, %ntid.y;
setp.ne.s32 %p3, %r22, 4;
or.pred %p4, %p2, %p3;
or.pred %p5, %p4, %p1;
mov.u32 %r23, %ntid.z;
setp.ne.s32 %p6, %r23, 1;
or.pred %p7, %p6, %p5;
mov.u32 %r1, %ctaid.x;
setp.gt.u32 %p8, %r1, 159;
or.pred %p9, %p8, %p7;
mov.u32 %r2, %ctaid.y;
setp.ge.u32 %p10, %r2, %r19;
or.pred %p11, %p10, %p9;
mov.u32 %r24, %ctaid.z;
setp.ne.s32 %p12, %r24, 0;
or.pred %p13, %p12, %p11;
@%p13 bra $L__BB1_6;
shl.b32 %r25, %r1, 2;
mov.u32 %r3, %tid.y;
add.s32 %r4, %r25, %r3;
mov.u32 %r5, %tid.x;
setp.gt.u32 %p14, %r5, 79;
mov.f32 %f32, 0f00000000;
@%p14 bra $L__BB1_4;
mad.lo.s32 %r26, %r2, 640, %r4;
shl.b32 %r27, %r5, 2;
and.b32 %r6, %r27, 28;
and.b32 %r28, %r5, 3;
shr.u32 %r29, %r5, 2;
mad.lo.s32 %r30, %r19, %r29, %r2;
mul.lo.s32 %r31, %r30, 36;
or.b32 %r61, %r31, %r28;
mul.lo.s32 %r8, %r19, 288;
mad.lo.s32 %r60, %r26, 80, %r5;
shr.u32 %r32, %r5, 3;
mad.lo.s32 %r33, %r1, 40, %r32;
mad.lo.s32 %r34, %r3, 10, %r33;
mul.lo.s32 %r59, %r34, 98;
cvta.to.global.u64 %rd1, %rd4;
cvta.to.global.u64 %rd2, %rd6;
cvta.to.global.u64 %rd3, %rd5;
mov.f32 %f32, 0f00000000;
cvt.u64.u32 %rd10, %r6;
mov.u32 %r62, %r5;
$L__BB1_3:
cvt.u64.u32 %rd8, %r59;
add.s64 %rd9, %rd1, %rd8;
add.s64 %rd11, %rd9, %rd10;
ld.global.u8 %rs2, [%rd11+69];
shr.u16 %rs3, %rs2, 4;
cvt.u32.u16 %r36, %rs3;
mul.wide.u32 %rd12, %r60, 4;
add.s64 %rd13, %rd2, %rd12;
ld.global.u32 %r37, [%rd13];
shr.u32 %r38, %r37, 31;
add.s32 %r39, %r37, %r38;
shr.s32 %r40, %r39, 1;
mad.lo.s32 %r41, %r37, %r36, %r40;
shr.u32 %r42, %r41, 31;
add.s32 %r43, %r41, %r42;
shr.s32 %r35, %r43, 1;
ld.global.u8 %r44, [%rd9];
ld.global.u8 %r45, [%rd9+1];
shl.b32 %r46, %r45, 8;
or.b32 %r47, %r46, %r44;
cvt.u16.u32 %rs1, %r47;
// begin inline asm
cvt.f32.f16 %f7,%rs1;
// end inline asm
mul.wide.u32 %rd14, %r61, 4;
add.s64 %rd15, %rd3, %rd14;
ld.global.f32 %f10, [%rd15];
// begin inline asm
mul.ftz.f32 %f8,%f7,%f10;
// end inline asm
// begin inline asm
cvt.rn.f32.s32 %f11,%r35;
// end inline asm
// begin inline asm
fma.rn.ftz.f32 %f32,%f8,%f11,%f32;
// end inline asm
add.s32 %r15, %r62, 32;
add.s32 %r61, %r61, %r8;
add.s32 %r60, %r60, 32;
add.s32 %r59, %r59, 392;
setp.lt.u32 %p15, %r62, 48;
mov.u32 %r62, %r15;
@%p15 bra $L__BB1_3;
$L__BB1_4:
mov.b32 %r48, %f32;
shfl.sync.bfly.b32 %r49|%p16, %r48, 16, 31, -1;
mov.b32 %f18, %r49;
// begin inline asm
add.ftz.f32 %f16,%f32,%f18;
// end inline asm
mov.b32 %r50, %f16;
shfl.sync.bfly.b32 %r51|%p17, %r50, 8, 31, -1;
mov.b32 %f21, %r51;
// begin inline asm
add.ftz.f32 %f19,%f16,%f21;
// end inline asm
mov.b32 %r52, %f19;
shfl.sync.bfly.b32 %r53|%p18, %r52, 4, 31, -1;
mov.b32 %f24, %r53;
// begin inline asm
add.ftz.f32 %f22,%f19,%f24;
// end inline asm
mov.b32 %r54, %f22;
shfl.sync.bfly.b32 %r55|%p19, %r54, 2, 31, -1;
mov.b32 %f27, %r55;
// begin inline asm
add.ftz.f32 %f25,%f22,%f27;
// end inline asm
mov.b32 %r56, %f25;
shfl.sync.bfly.b32 %r57|%p20, %r56, 1, 31, -1;
mov.b32 %f30, %r57;
// begin inline asm
add.ftz.f32 %f28,%f25,%f30;
// end inline asm
setp.ne.s32 %p21, %r5, 0;
@%p21 bra $L__BB1_6;
mad.lo.s32 %r58, %r2, 640, %r4;
cvta.to.global.u64 %rd16, %rd7;
mul.wide.u32 %rd17, %r58, 4;
add.s64 %rd18, %rd16, %rd17;
st.global.f32 [%rd18], %f28;
$L__BB1_6:
ret;
}
@@ -0,0 +1,176 @@
//! Unadmitted native IQ3 integer dots + original warp reducer; explicit policy only.
use super::*;
/// 640 rows * 80 actual Q8 groups * 64 tokens * sizeof(i32).
pub(super) const CHARGE: usize = 13_107_200;
/// Actual root GPU-hidden NVCC 12.8.93 sm_120 asset; explicit experimental policy.
pub(crate) fn asset() -> Result<&'static [u8]> {
let b = include_bytes!("iq3_native_integer_mma.ptx");
if b.len() != 17928
|| b.last() != Some(&0)
|| !b[..b.len() - 1].is_ascii()
|| b[..b.len() - 1].contains(&0)
{
return Err(Error::InvalidDriverValue(
"IQ3 native integer MMA PTX encoding",
));
}
if crate::qwen_ffi::sha256(&b[..b.len() - 1])
!= [
59, 251, 32, 197, 49, 208, 213, 116, 205, 208, 18, 218, 159, 208, 202, 224, 99, 246,
22, 209, 160, 112, 224, 32, 23, 153, 171, 17, 215, 54, 142, 99,
]
{
return Err(Error::InvalidDriverValue(
"IQ3 native integer MMA PTX digest",
));
}
Ok(b)
}
pub(super) struct NativeInteger<'ctx> {
context: &'ctx Context<'ctx>,
dots: Option<DeviceBuffer<'ctx>>,
module: Option<ffi::ModuleHandle>,
functions: Option<[ffi::FunctionHandle; 2]>,
}
impl<'ctx> NativeInteger<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
asset()?;
if context
.allocated_bytes()
.checked_add(CHARGE)
.is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
dots: None,
module: None,
functions: None,
};
let result = (|| {
owner.dots = Some(context.allocate(CHARGE)?);
let guard = context.enter()?;
let load = (|| {
let m = context.driver.api.load_iq3_native_integer()?;
owner.module = Some(m);
owner.functions = Some([
context.driver.api.iq3_native_integer_function(m, false)?,
context.driver.api.iq3_native_integer_function(m, true)?,
]);
Ok(())
})();
combine(load, guard.finish())
})();
if let Err(e) = result {
return combine(Err(e), owner.close());
}
Ok(owner)
}
pub(super) fn check(&self) -> Result<()> {
if self.context.is_poisoned()
|| self.context.handle.is_none()
|| self.module.is_none()
|| self.functions.is_none()
{
return Err(Error::ContextPoisoned);
}
let b = self.dots.as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(self.context, b.context) || b.bytes != CHARGE {
return Err(Error::ContextMismatch);
}
b.handle
.ok_or(Error::ContextPoisoned)?
.validate_projection_extent(CHARGE, 4)
}
pub(super) fn overlaps(&self, h: ffi::BufferHandle, bytes: usize) -> Result<bool> {
self.check()?;
let d = self.dots.as_ref().ok_or(Error::ContextPoisoned)?;
Ok(d.handle
.ok_or(Error::ContextPoisoned)?
.overlaps(CHARGE, h, bytes))
}
pub(super) fn append(
&self,
commands: &mut Vec<QueuedCommand>,
weights: ffi::BufferHandle,
packed: ffi::BufferHandle,
output: ffi::BufferHandle,
l: Layout,
) -> Result<()> {
self.check()?;
// GU18's exact shape/layout; this method is private to native-policy workspace.
if l.rows != 640
|| l.columns != 2560
|| l.qk != 256
|| l.block_bytes != 98
|| l.raw_weight != 627200
|| l.payload != 2880 * l.tokens as usize
|| l.packed != l.payload + 9216
|| l.output != 2560 * l.tokens as usize
|| !(1..=64).contains(&l.tokens)
{
return Err(Error::UnsupportedProjection);
}
weights.validate_projection_extent(l.weight, 2)?;
packed.validate_projection_extent(l.packed, 16)?;
output.validate_projection_extent(l.output, 4)?;
let dh = self
.dots
.as_ref()
.ok_or(Error::ContextPoisoned)?
.handle
.ok_or(Error::ContextPoisoned)?;
dh.validate_projection_extent(CHARGE, 4)?;
for (h, n) in [(weights, l.weight), (packed, l.packed), (output, l.output)] {
if dh.overlaps(CHARGE, h, n) {
return Err(Error::OutputAliasesInput);
}
}
let fs = self.functions.ok_or(Error::ContextPoisoned)?;
commands.push(QueuedCommand::NativeIntegerDot(
fs[0],
l.tokens,
ffi::Iq3NativeIntegerArguments::dot(weights, packed, dh, l.tokens),
));
commands.push(QueuedCommand::NativeIntegerReduce(
fs[1],
l.tokens,
ffi::Iq3NativeIntegerArguments::reduce(weights, packed, dh, output, l.tokens),
));
Ok(())
}
pub(super) fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.functions = None;
let a = self.dots.take().map_or(Ok(()), |b| {
if self.context.is_poisoned() {
std::mem::forget(b);
Err(Error::ContextPoisoned)
} else {
b.release()
}
});
let b = self
.module
.take()
.map_or(Ok(()), |m| match self.context.enter() {
Ok(g) => combine(self.context.driver.api.unload(m), g.finish()),
Err(e) => Err(e),
});
if a.is_err() || b.is_err() {
self.context.poisoned.set(true);
}
combine(a, b)
}
}
impl Drop for NativeInteger<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
+680 -14
View File
@@ -13,7 +13,62 @@ use std::{cell::Cell, fmt, marker::PhantomData, rc::Rc};
#[allow(unsafe_code)]
mod ffi;
#[allow(unsafe_code)]
mod original_gpu_schedule;
pub use original_gpu_schedule::{
OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph,
OriginalGpuStream, OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry,
OriginalGraphResources, OriginalStreamKind, OriginalWait,
};
mod original_expert_cache;
mod original_expert_slots;
pub use original_expert_cache::OriginalExpertCache;
mod original_moe_prompt_device;
pub use original_moe_prompt_device::{OriginalMoePromptDevice, OriginalMoePromptLayer};
mod original_prefill_arena;
pub use original_prefill_arena::{
OriginalPrefillArena, OriginalPromptLeaseIdentity, OriginalPromptRows,
};
mod original_prefill_layout;
pub use original_prefill_layout::{
OriginalPrefillLayout, PrefillKvStage, PrefillLayoutOptions, PrefillPhase, PrefillSpan,
};
mod head_greedy;
pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace};
mod gdn_state_finite_guard;
pub use gdn_state_finite_guard::GdnStateFiniteGuard;
mod routed_group_workspace;
mod routed_stage_finite_guard;
pub use routed_group_workspace::RoutedColumnsLoan;
pub use routed_group_workspace::RoutedGroupWorkspace;
pub use routed_stage_finite_guard::{RoutedFiniteStage, RoutedStageFiniteGuard};
mod gr_read_guard;
mod mmq;
mod mmq_native;
pub use mmq::resident::original_group::{
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes,
};
pub use mmq::resident::{
FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace,
};
pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqWeights};
use mmq_native::NativeWeights;
mod moe_group_down_columns;
mod moe_group_projection;
mod mtp_dense_kv;
mod original_mtp_actor;
mod original_mtp_coupled;
mod original_mtp_loader;
mod original_session_state;
mod qwen_dispatch;
pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead};
mod qsa_selected_kv;
pub use mtp_dense_kv::MtpDenseKvRing;
pub use mtp_dense_kv::{
CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8,
MtpOriginalMixed, MtpOriginalQuery,
};
pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace};
#[allow(unsafe_code)]
mod qwen_ffi;
@@ -35,6 +90,7 @@ pub enum Error {
InvalidQ5KProjectionShape,
InvalidQ6KProjectionShape,
InvalidQ8Activation,
NonFiniteMmqOutput(&'static str),
UnsupportedProjection,
UnsupportedQwenOperation,
InvalidQwenShape,
@@ -99,6 +155,7 @@ impl Error {
"projection requires exact bounded packed single-column shapes"
}
Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1",
Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output",
Self::OutputAliasesInput => "output must not alias an input",
Self::InvalidSize => "byte size must be nonzero and fit isize",
Self::BudgetExceeded => "allocation exceeds context byte budget",
@@ -223,6 +280,16 @@ impl<'driver> Device<'driver> {
q5_k_kernel: Cell::new(None),
q6_k_kernel: Cell::new(None),
common_quantizer: Cell::new(None),
grouped_iq3: Cell::new(None),
grouped_iq2: Cell::new(None),
grouped_iq3_s: Cell::new(None),
grouped_iq4_xs: Cell::new(None),
grouped_iq3_s_nc4: Cell::new(None),
grouped_iq4_xs_nc4: Cell::new(None),
grouped_swiglu: Cell::new(None),
grouped_down_iq4: Cell::new(None),
grouped_down_q2: Cell::new(None),
gr_read_guard_kernel: Cell::new(None),
projection_kernels: std::array::from_fn(|_| Cell::new(None)),
qwen_kernels: qwen_dispatch::Cache::new(),
})
@@ -241,6 +308,16 @@ pub struct Context<'driver> {
q5_k_kernel: Cell<Option<FixedPairKernels>>,
q6_k_kernel: Cell<Option<FixedPairKernels>>,
common_quantizer: Cell<Option<FixedKernel>>,
grouped_iq3: Cell<Option<FixedKernel>>,
grouped_iq2: Cell<Option<FixedKernel>>,
grouped_iq3_s: Cell<Option<FixedKernel>>,
grouped_iq4_xs: Cell<Option<FixedKernel>>,
grouped_iq3_s_nc4: Cell<Option<FixedKernel>>,
grouped_iq4_xs_nc4: Cell<Option<FixedKernel>>,
grouped_swiglu: Cell<Option<FixedKernel>>,
grouped_down_iq4: Cell<Option<FixedKernel>>,
grouped_down_q2: Cell<Option<FixedKernel>>,
gr_read_guard_kernel: Cell<Option<FixedKernel>>,
projection_kernels: [Cell<Option<ProjectionKernels>>; 8],
qwen_kernels: qwen_dispatch::Cache,
}
@@ -260,6 +337,7 @@ struct FixedPairKernels {
#[derive(Clone, Copy)]
enum FixedOperation {
VectorAdd,
GrReadFinite,
Matvec,
Q5K,
Q5KQuantize,
@@ -268,6 +346,15 @@ enum FixedOperation {
Q6KQuantize,
Q6KProject,
CommonQuantize,
GroupedIq3,
GroupedIq2,
GroupedIq3S,
GroupedIq4Xs,
GroupedIq3SNc4,
GroupedIq4XsNc4,
GroupedSwiglu,
GroupedDownIq4,
GroupedDownQ2,
Projection(ProjectionKind),
}
@@ -717,6 +804,14 @@ fn vector_shape(bytes: usize) -> Result<(u32, u32)> {
))
}
impl Context<'_> {
/// Private sticky failure primitive shared by native owners.
fn poison(&self) {
self.poisoned.set(true);
}
/// Retain the actual loaded API after uncertain completion/restoration.
fn retain_driver(&self) {
std::mem::forget(Rc::clone(&self.driver.api));
}
pub fn budget_bytes(&self) -> usize {
self.budget
}
@@ -724,12 +819,32 @@ impl Context<'_> {
pub fn allocated_bytes(&self) -> usize {
self.allocated.get()
}
/// Actual `(free, total)` physical device bytes for this current Context.
/// This is a snapshot, not a reservation guarantee; it allocates/frees nothing.
/// Zero free is valid, zero total or free above total refuses the query.
pub fn memory_info(&self) -> Result<(usize, usize)> {
let guard = self.enter()?;
let query = self.driver.api.memory_info();
if matches!(&query, Err(Error::Driver { .. })) {
// CUDA may report an earlier asynchronous failure here. Do not
// admit further resource use under an uncertain execution state.
self.poisoned.set(true);
}
// CurrentGuard verifies the popped identity and poisons on pop failure.
combine(query, guard.finish())
}
fn enter(&self) -> Result<CurrentGuard<'_, '_>> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
self.driver.api.push(handle)?;
if let Err(error) = self.driver.api.push(handle) {
// A failed current-context transport leaves the execution state
// uncertain. Every owner sharing this Context must refuse reuse.
self.poison();
self.retain_driver();
return Err(error);
}
Ok(CurrentGuard {
context: self,
active: true,
@@ -760,6 +875,10 @@ impl Context<'_> {
_thread: PhantomData,
})
}
/// Read-only sticky completion fence; never resets or changes the context.
pub fn is_poisoned(&self) -> bool {
self.poisoned.get()
}
pub fn synchronize(&self) -> Result<()> {
let guard = self.enter()?;
let sync = self.driver.api.synchronize();
@@ -1095,9 +1214,18 @@ impl Context<'_> {
activation: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
spec: ProjectionSpec,
) -> Result<()> {
self.project_q8_1_weight(NativeWeights::Raw(weights), activation, output, spec)
}
fn project_q8_1_weight(
&self,
weights: NativeWeights<'_, '_>,
activation: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
spec: ProjectionSpec,
) -> Result<()> {
let (shape, handles, temporary_bytes) =
self.projection_admission(weights, activation, output, spec)?;
self.projection_admission_weight(weights, activation, output, spec)?;
// Charge the complete scratch/status requirement before native mutation.
let total = self
@@ -1269,6 +1397,21 @@ impl Context<'_> {
output: &mut DeviceBuffer<'_>,
format: RoutedFormat,
) -> Result<()> {
self.project_routed_gate_up_prepared_weight(
NativeWeights::Raw(weights),
prepared,
output,
format,
)
}
fn project_routed_gate_up_prepared_weight(
&self,
weight_owner: NativeWeights<'_, '_>,
prepared: &RoutedGateUpQ8<'_>,
output: &mut DeviceBuffer<'_>,
format: RoutedFormat,
) -> Result<()> {
let weights = weight_owner.buffer()?;
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
@@ -1299,8 +1442,15 @@ impl Context<'_> {
rows: 640,
columns: 2560,
})?;
if weights.bytes != shape.weight_bytes
|| prepared.activation.bytes != shape.activation_bytes
weight_owner.validate(
ProjectionSpec {
kind,
rows: 640,
columns: 2560,
},
shape.weight_bytes,
)?;
if prepared.activation.bytes != shape.activation_bytes
|| scratch.bytes != shape.scratch_bytes
|| output.bytes != shape.output_bytes
{
@@ -1311,6 +1461,9 @@ impl Context<'_> {
let quantized = scratch.handle.ok_or(Error::ContextPoisoned)?;
let out = output.handle.ok_or(Error::ContextPoisoned)?;
projection_ranges(kind, &shape, [weight, original, out])?;
if out.overlaps(shape.output_bytes, weight, weights.bytes) {
return Err(Error::OutputAliasesInput);
}
quantized.validate_projection_extent(shape.scratch_bytes, 4)?;
if out.overlaps(shape.output_bytes, quantized, shape.scratch_bytes) {
return Err(Error::OutputAliasesInput);
@@ -1343,13 +1496,14 @@ impl Context<'_> {
self.complete_launch(launch, arguments, guard)
}
fn projection_admission(
fn projection_admission_weight(
&self,
weights: &DeviceBuffer<'_>,
weight_owner: NativeWeights<'_, '_>,
activation: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
spec: ProjectionSpec,
) -> Result<(ProjectionShape, [ffi::BufferHandle; 3], usize)> {
let weights = weight_owner.buffer()?;
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
@@ -1365,10 +1519,8 @@ impl Context<'_> {
return Err(Error::UnsupportedProjection);
}
let shape = projection_shape(spec)?;
if weights.bytes != shape.weight_bytes
|| activation.bytes != shape.activation_bytes
|| output.bytes != shape.output_bytes
{
weight_owner.validate(spec, shape.weight_bytes)?;
if activation.bytes != shape.activation_bytes || output.bytes != shape.output_bytes {
return Err(Error::InvalidProjectionShape);
}
let handles = [
@@ -1377,6 +1529,9 @@ impl Context<'_> {
output.handle.ok_or(Error::ContextPoisoned)?,
];
projection_ranges(spec.kind, &shape, handles)?;
if handles[2].overlaps(output.bytes, handles[0], weights.bytes) {
return Err(Error::OutputAliasesInput);
}
let temporary_bytes = shape.temporary_bytes;
let total = self
.allocated
@@ -1527,8 +1682,18 @@ impl Context<'_> {
fn kernel_slot(&self, operation: FixedOperation) -> &Cell<Option<FixedKernel>> {
match operation {
FixedOperation::VectorAdd => &self.vector_add_kernel,
FixedOperation::GrReadFinite => &self.gr_read_guard_kernel,
FixedOperation::Matvec => &self.matvec_kernel,
FixedOperation::CommonQuantize => &self.common_quantizer,
FixedOperation::GroupedIq3 => &self.grouped_iq3,
FixedOperation::GroupedIq2 => &self.grouped_iq2,
FixedOperation::GroupedIq3S => &self.grouped_iq3_s,
FixedOperation::GroupedIq4Xs => &self.grouped_iq4_xs,
FixedOperation::GroupedIq3SNc4 => &self.grouped_iq3_s_nc4,
FixedOperation::GroupedIq4XsNc4 => &self.grouped_iq4_xs_nc4,
FixedOperation::GroupedSwiglu => &self.grouped_swiglu,
FixedOperation::GroupedDownIq4 => &self.grouped_down_iq4,
FixedOperation::GroupedDownQ2 => &self.grouped_down_q2,
FixedOperation::Projection(_) => {
unreachable!("format modules publish all required entries atomically")
}
@@ -1770,14 +1935,45 @@ impl Context<'_> {
}
fn destroy(&mut self) -> Result<()> {
// Fixed teardown order; shared poison suppresses the second native unload.
let grouped_down_unload = combine(
combine(
self.unload_kernel(FixedOperation::GroupedSwiglu),
self.unload_kernel(FixedOperation::GroupedDownIq4),
),
self.unload_kernel(FixedOperation::GroupedDownQ2),
);
let unload = combine(
combine(self.unload_projections(), self.unload_qwen_kernels()),
grouped_down_unload,
combine(
combine(
self.unload_kernel(FixedOperation::VectorAdd),
self.unload_kernel(FixedOperation::Matvec),
combine(
combine(
combine(
combine(
combine(
self.unload_kernel(FixedOperation::GroupedIq3),
self.unload_kernel(FixedOperation::GroupedIq2),
),
self.unload_kernel(FixedOperation::GroupedIq3S),
),
self.unload_kernel(FixedOperation::GroupedIq4Xs),
),
self.unload_kernel(FixedOperation::GroupedIq3SNc4),
),
self.unload_kernel(FixedOperation::GroupedIq4XsNc4),
),
combine(
combine(self.unload_projections(), self.unload_qwen_kernels()),
self.unload_kernel(FixedOperation::GrReadFinite),
),
),
combine(
combine(
self.unload_kernel(FixedOperation::VectorAdd),
self.unload_kernel(FixedOperation::Matvec),
),
combine(self.unload_q5_kernels(), self.unload_q6_kernels()),
),
combine(self.unload_q5_kernels(), self.unload_q6_kernels()),
),
);
if let Some(handle) = self.handle.take() {
@@ -1871,12 +2067,62 @@ impl DeviceBuffer<'_> {
staging.copy_from_slice(input);
self.copy_staged(staging, false).map(|_| ())
}
/// Consume genuine whole-buffer host staging without an intermediate clone.
/// Byte ownership is not a source, finite or device-completion certificate.
pub fn copy_from_owned(&mut self, input: Vec<u8>) -> Result<()> {
// Preserve the original staging() shape-before-poison admission order.
if input.len() != self.bytes {
return Err(Error::ShapeMismatch {
expected: self.bytes,
actual: input.len(),
});
}
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned);
}
// Exactly the existing attempted-copy/synchronize/restore and retained
// staging rule. No source storage is released while work is uncertain.
self.copy_staged(input, false).map(|_| ())
}
/// Copy a nonempty checked subspan. Owned staging remains alive through
/// synchronization, with the same poisoning/leak rule as whole-buffer copies.
pub fn copy_from_range(&mut self, offset: usize, input: &[u8]) -> Result<()> {
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(
self.bytes,
offset,
input.len(),
)?;
let mut staging = Vec::new();
staging
.try_reserve_exact(input.len())
.map_err(|_| Error::HostAllocation)?;
staging.extend_from_slice(input);
let guard = self.context.enter()?;
let copy = self.context.driver.api.copy_from(handle, &staging);
let sync = self.context.driver.api.synchronize();
if sync.is_err() {
self.context.poisoned.set(true);
std::mem::forget(staging);
return combine(combine(copy, sync), guard.finish());
}
combine(copy, guard.finish())
}
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
let staging = self.staging(output.len())?;
let staging = self.copy_staged(staging, true)?;
output.copy_from_slice(&staging);
Ok(())
}
/// Return the completed whole-buffer readback without a second host copy.
/// The staging remains owned through the same synchronization and poison
/// handling as `copy_to`; a failed synchronization never returns its bytes.
pub fn copy_to_owned(&self, expected_bytes: usize) -> Result<Vec<u8>> {
let staging = self.staging(expected_bytes)?;
self.copy_staged(staging, true)
}
fn copy_staged(&self, mut staging: Vec<u8>, to_host: bool) -> Result<Vec<u8>> {
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
@@ -1932,6 +2178,107 @@ mod ple_value_full_gpu_tests;
#[cfg(test)]
mod tests {
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_arch = "x86_64"))]
#[test]
#[ignore = "Root-only original-first owned whole-buffer readback proof"]
fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() {
let driver = super::Driver::load().unwrap();
let context = driver
.device(0)
.unwrap()
.create_context(16 * 1024 * 1024)
.unwrap();
let mut exact_bytes = 0usize;
let mut bounds = 0usize;
// Full real recurrence state, convolution history and readout extents.
for size in [3_145_728usize, 122_880, 24_576] {
let mut buffer = context.allocate(size).unwrap();
for round in 0..2u32 {
let words = [
0u32,
0x8000_0000,
0x3f80_0000,
0xbf80_0000,
0x7f80_0000,
0xff80_0000,
0x7fc0_0101,
1,
];
let mut source = Vec::with_capacity(size);
for i in 0..size / 4 {
let word = if i < words.len() {
words[i]
} else {
(i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round)
};
source.extend_from_slice(&word.to_le_bytes());
}
buffer.copy_from(&source).unwrap();
let mut original = vec![0; size];
buffer.copy_to(&mut original).unwrap();
assert_eq!(original, source);
let owned = buffer.copy_to_owned(size).unwrap();
assert_eq!(owned, original);
// The downstream original LE conversion preserves all bits,
// including signed zero and nonfinite values (later rejected
// by the unchanged GDN finite guard).
for (a, b) in original
.as_chunks::<4>()
.0
.iter()
.zip(owned.as_chunks::<4>().0)
{
assert_eq!(
f32::from_le_bytes(*a).to_bits(),
f32::from_le_bytes(*b).to_bits()
);
}
exact_bytes += size;
for invalid in [0, size - 1, size + 1] {
assert!(matches!(buffer.copy_to_owned(invalid),
Err(super::Error::ShapeMismatch { expected, actual })
if expected == size && actual == invalid));
bounds += 1;
}
assert_eq!(buffer.copy_to_owned(size).unwrap(), original);
exact_bytes += size;
}
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
assert_eq!(exact_bytes, 13_172_736);
assert_eq!(bounds, 18);
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
println!(
"owned_gdn_readback exact_bytes={exact_bytes} bounds={bounds} original_first=true allocated=0 raw_nonfinite_preserved=true"
);
}
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_arch = "x86_64"))]
#[test]
#[ignore = "Root-only installed driver partial-copy guard proof"]
fn checked_subspan_real_copy_preserves_untouched_bytes() {
let driver = super::Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(65536).unwrap();
let mut buffer = context.allocate(1024).unwrap();
buffer.copy_from(&[0x5a; 1024]).unwrap();
buffer.copy_from_range(255, &[0x73; 513]).unwrap();
let mut out = [0; 1024];
buffer.copy_to(&mut out).unwrap();
assert_eq!(&out[..255], &[0x5a; 255]);
assert_eq!(&out[255..768], &[0x73; 513]);
assert_eq!(&out[768..], &[0x5a; 256]);
assert!(buffer.copy_from_range(1023, &[1, 2]).is_err());
assert!(buffer.copy_from_range(0, &[]).is_err());
let mut after = [0; 1024];
buffer.copy_to(&mut after).unwrap();
assert_eq!(out, after);
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
}
use super::*;
#[test]
fn sizes_and_error_composition() {
@@ -2038,6 +2385,16 @@ mod tests {
q5_k_kernel: Cell::new(None),
q6_k_kernel: Cell::new(None),
common_quantizer: Cell::new(None),
grouped_iq3: Cell::new(None),
grouped_iq2: Cell::new(None),
grouped_iq3_s: Cell::new(None),
grouped_iq4_xs: Cell::new(None),
grouped_iq3_s_nc4: Cell::new(None),
grouped_iq4_xs_nc4: Cell::new(None),
grouped_swiglu: Cell::new(None),
grouped_down_iq4: Cell::new(None),
grouped_down_q2: Cell::new(None),
gr_read_guard_kernel: Cell::new(None),
projection_kernels: std::array::from_fn(|_| Cell::new(None)),
qwen_kernels: qwen_dispatch::Cache::new(),
};
@@ -2419,3 +2776,312 @@ mod family_tests {
}
}
}
// Isolated preview only; absent from the serving qualification map.
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub mod q6_layer_preview;
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use qwen_dispatch::batch_gr_preview::GrBatchModule;
#[cfg(all(
test,
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[path = "grouped_down_columns_gpu.rs"]
mod grouped_down_columns_gpu;
pub use qwen_dispatch::qwen_shared_tail::{
SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion,
SharedTailRefusal,
};
// Additive closed MTP input transport owners.
pub use qwen_dispatch::gdn_closed_queue::{
GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use qwen_dispatch::gdn_fused_t1::{
GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix,
GdnFusedStage, GdnFusedT1,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use qwen_dispatch::gdn_native_batch::{
GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage,
GdnGemm, GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice,
OriginalGdnPromptWeights,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use qwen_dispatch::moe_prefill_batch::{
MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix,
MoeBatchStage, MoePrefillBatch, MoeRouteBatch,
};
pub use qwen_dispatch::mtp_input_workspace::{
MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "cuda-driver"))]
pub use qwen_dispatch::gr_batch_inject_workspace::{
GR_BATCH_INJECT_WORKSPACE_BYTES, GrBatchInjectShape, GrBatchInjectWorkspace,
};
// Separately selected asynchronous owned-copy adapter; original APIs unchanged.
#[allow(unsafe_code)]
mod api;
mod async_owned_copy;
pub use async_owned_copy::{
CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy,
};
// Explicit experimental resident pipeline; original entry bodies remain unchanged.
mod routed_resident_queue;
pub use routed_resident_queue::{
RoutedResidentCompletion, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights,
};
pub use qwen_dispatch::ple_closed_queue::{
PleClosedCompletion, PleClosedParts, PleClosedQueue, PleClosedRefusal, PleClosedWeights,
};
mod mapped_expert_bank;
pub use mapped_expert_bank::{
MappedExpertBank, MappedExpertCopyCompletion, MappedExpertCopyScratch, PendingMappedExpertCopy,
};
pub use qwen_dispatch::gr_native_batch::{GrNativeBatch, GrNativeProfile};
// Explicit Original prefill transport; no default selection or public raw spans.
#[allow(unsafe_code)]
pub(crate) mod ple_batch_ffi;
mod ple_batch_queue;
pub use ple_batch_queue::{
PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode,
};
mod native_batch_workspace;
pub use native_batch_workspace::{NATIVE_BATCH_WORKSPACE_BYTES, NativeBatchWorkspace};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod gdn_batch_gemm;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use gdn_batch_gemm::NativeGdnGemm;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_native_batch;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_native_batch::{
QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking,
QsaNativeProjections,
};
// Literal Original QSA prompt index assets share the admitted native stream.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[allow(unsafe_code)]
mod qsa_index_ffi;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_prompt_index;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_index::{
OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights,
QSA_PROMPT_INDEX_BYTES, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace,
QsaPromptSelection,
};
// Genuine page4 INT8 owners and literal Original prompt/decode programs.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_native_decode;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_prompt_attention;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[allow(unsafe_code)]
mod qsa_prompt_attention_ffi;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[allow(unsafe_code)]
mod qsa_prompt_host_ffi;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_prompt_kv;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod qsa_prompt_resolver;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_attention::{
QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention,
QsaPromptAttentionCompletion,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_kv::{
CompletedQsaKvAppend, QSA_PROMPT_MAPPED_HOST_BYTES, QSA_PROMPT_MAX_SNAPSHOT_METADATA_BYTES,
QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES, QSA_PROMPT_RESIDENT_BYTES, QSA_PROMPT_STAGE_BYTES,
QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_attention::OriginalQsaResidentAttention;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_index::{
OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex,
OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex,
OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub use qsa_prompt_kv::{
OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix,
OriginalQsaResidentTransport,
};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
mod moe_prompt_packet_copy;
mod qsa_native_gate;
pub use qsa_native_gate::QsaNativeGate;
mod original_sampler;
#[allow(unsafe_code)]
mod original_sampler_ffi;
#[allow(unsafe_code)]
mod original_sampler_mapped;
pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath};
mod native_prompt_device;
pub use native_prompt_device::{
OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual,
OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use mtp_dense_kv::OriginalMtpSkippedPrefix;
pub use mtp_dense_kv::{
CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding,
OriginalMtpPrefill, OriginalMtpPrefillWeights,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use mtp_dense_kv::{
CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter,
OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy,
OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod original_expert_stager;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_expert_stager::{
OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted,
OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted,
OriginalStreamAllForward, OriginalStreamAllOptions,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod native_parity;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[allow(unsafe_code)]
mod native_parity_ffi;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use native_parity::{
NativeParity, NativeParityExpert, native_parity_embed_supported, native_parity_iq_supported,
native_parity_row_bytes,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use mtp_dense_kv::{
OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy,
OriginalMtpScalarPrefill,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_gpu_schedule::OriginalStreamDrained;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod native_head;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use native_head::{
NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight,
NativeHeadSampling, NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows,
OriginalNativeHead, OriginalNativeHeadGraphResources, OriginalNativeHeadRows,
native_embed_supported, native_head_row_bytes, native_head_supported,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod original_file_expert_source;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_file_expert_source::{
OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters,
OriginalResidentOptions, OriginalSourceSwap,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) mod original_verify;
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_verify::{
OriginalVerifier, OriginalVerifyBank, OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows,
OriginalVerifyCpuSink, OriginalVerifyGdnJournal, OriginalVerifyGdnStage,
OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGraphResources,
OriginalVerifyLayout, OriginalVerifyResources, OriginalVerifyRow, OriginalVerifySpan,
OriginalVerifyWindow, OriginalVerifyWindowResult,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope};
@@ -0,0 +1,614 @@
//! Exact mode2 byte transport from opaque retained source banks. A real alias
//! attests addressability only; runtime rechecks source, whole encoded finite,
//! current row and coverage independently. No caller bytes or raw alias API.
use crate::{Context, DeviceBuffer, Error, Result, api, combine};
use leleka_model_format::qwen4exp::{
LayerRole, ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan,
TensorRole,
};
use std::{mem::size_of, rc::Rc};
const BANKS: usize = 144;
const SOURCE_CAP: usize = 52 * 1024 * 1024 * 1024;
struct RegisteredBank {
member: ResidentExpertBankMember,
alias: u64,
registered: bool,
}
pub struct MappedExpertBank<'ctx> {
context: &'ctx Context<'ctx>,
lease: ResidentExpertBankLease,
banks: Vec<RegisteredBank>,
api: Option<api::MappedApi>,
page_charge: usize,
closed: bool,
}
impl Context<'_> {
pub fn mapped_expert_bank<'ctx>(
&'ctx self,
lease: ResidentExpertBankLease,
members: Vec<ResidentExpertBankMember>,
) -> Result<MappedExpertBank<'ctx>> {
if lease.bank_count() != BANKS || members.len() != BANKS {
return Err(Error::InvalidSize);
}
let page = api::page_size()?;
let mut ranges = Vec::new();
ranges
.try_reserve_exact(BANKS)
.map_err(|_| Error::HostAllocation)?;
let mut extra = 0usize;
for (n, member) in members.iter().enumerate() {
let role = match n % 3 {
0 => LayerRole::FfnGateExperts,
1 => LayerRole::FfnUpExperts,
_ => LayerRole::FfnDownExperts,
};
if !member.belongs_to_lease(&lease)
|| member.role()
!= (TensorRole::Layer {
layer: (n / 3) as u8,
role,
})
|| member.bytes().is_empty()
|| !member.bytes().len().is_multiple_of(512 * 16)
{
return Err(Error::InvalidSize);
}
let start = member.bytes().as_ptr() as usize;
if !start.is_multiple_of(16) {
return Err(Error::InvalidSize);
}
let end = start
.checked_add(member.bytes().len())
.ok_or(Error::InvalidSize)?;
let rounded_start = start & !(page - 1);
let rounded_end = end.checked_add(page - 1).ok_or(Error::InvalidSize)? & !(page - 1);
if ranges
.iter()
.any(|&(a, b)| rounded_start < b && a < rounded_end)
{
return Err(Error::OutputAliasesInput);
}
extra = extra
.checked_add(rounded_end - rounded_start - member.bytes().len())
.ok_or(Error::BudgetExceeded)?;
ranges.push((rounded_start, rounded_end));
}
// Registered exact ptr/len only; rounded pages are accounted and checked
// for overlap, never exposed as owned bytes or a broader device range.
let member_capacity = members.capacity();
let mut banks = Vec::new();
banks
.try_reserve_exact(BANKS)
.map_err(|_| Error::HostAllocation)?;
let metadata = member_capacity
.checked_mul(size_of::<ResidentExpertBankMember>())
.and_then(|n| n.checked_add(banks.capacity() * size_of::<RegisteredBank>()))
.and_then(|n| n.checked_add(ranges.capacity() * size_of::<(usize, usize)>()))
.and_then(|n| n.checked_add(size_of::<MappedExpertBank<'_>>() + 2 * size_of::<usize>()))
.ok_or(Error::BudgetExceeded)?;
if metadata > 16 * 1024 * 1024
|| usize::try_from(lease.charged_source_bytes())
.ok()
.and_then(|n| n.checked_add(extra))
.and_then(|n| n.checked_add(metadata))
.is_none_or(|n| n > SOURCE_CAP)
{
return Err(Error::BudgetExceeded);
}
for member in members {
banks.push(RegisteredBank {
member,
alias: 0,
registered: false,
});
}
let mut owner = MappedExpertBank {
context: self,
lease,
banks,
api: None,
page_charge: extra,
closed: false,
};
let guard = self.enter()?;
let operation = (|| {
owner.api = Some(api::MappedApi::load()?);
for bank in &mut owner.banks {
owner
.api
.as_ref()
.expect("actual loaded ABI")
.register_bank(bank.member.bytes())?;
bank.registered = true;
bank.alias = owner
.api
.as_ref()
.expect("actual loaded ABI")
.bank_alias(bank.member.bytes())?;
}
Ok(())
})();
if matches!(&operation, Err(Error::Driver { .. })) {
self.poisoned.set(true);
}
let result = combine(operation, guard.finish());
match result {
Ok(()) => Ok(owner),
Err(primary) => combine(Err(primary), owner.close_inner()),
}
}
}
impl<'ctx> MappedExpertBank<'ctx> {
pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool {
!self.closed && std::ptr::eq(self.context, context)
}
/// Validate the retained registered owner before the literal queued H2D
/// cache fill. The device alias is deliberately not exported to runtime.
pub(crate) fn cache_source(&self, span: &ResidentExpertBankSpan) -> Result<&[u8]> {
self.alias(span)?;
let layer = match span.role() {
TensorRole::Layer { layer, .. } => layer,
_ => return Err(Error::InvalidSize),
};
let role = match span.role() {
TensorRole::Layer { role, .. } => role,
_ => return Err(Error::InvalidSize),
};
let n = usize::from(layer) * 3
+ match role {
LayerRole::FfnGateExperts => 0,
LayerRole::FfnUpExperts => 1,
LayerRole::FfnDownExperts => 2,
_ => return Err(Error::InvalidSize),
};
let bank = self.banks.get(n).ok_or(Error::InvalidSize)?;
let end = span
.offset()
.checked_add(span.bytes().len())
.ok_or(Error::InvalidSize)?;
bank.member
.bytes()
.get(span.offset()..end)
.ok_or(Error::InvalidSize)
}
pub(crate) fn retained_span_handle(
&self,
span: &ResidentExpertBankSpan,
) -> Result<crate::ffi::BufferHandle> {
crate::ffi::BufferHandle::registered_bank_alias(self.alias(span)?, span.bytes().len())
}
pub fn page_overhead_bytes(&self) -> usize {
self.page_charge
}
pub fn source_bytes(&self) -> u64 {
self.lease.source_bytes()
}
pub fn metadata_bytes(&self) -> usize {
size_of::<Self>()
+ 2 * size_of::<usize>()
+ self.banks.capacity() * size_of::<RegisteredBank>()
}
fn alias(&self, span: &ResidentExpertBankSpan) -> Result<u64> {
if self.closed || self.context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let n = match span.role() {
TensorRole::Layer { layer, role } if layer < 48 => {
usize::from(layer) * 3
+ match role {
LayerRole::FfnGateExperts => 0,
LayerRole::FfnUpExperts => 1,
LayerRole::FfnDownExperts => 2,
_ => return Err(Error::InvalidSize),
}
}
_ => return Err(Error::InvalidSize),
};
let bank = &self.banks[n];
if !bank.registered
|| !span.belongs_to(&bank.member)
|| span.bytes().is_empty()
|| span
.offset()
.checked_add(span.bytes().len())
.is_none_or(|n| n > bank.member.bytes().len())
|| !span.offset().is_multiple_of(16)
|| !span.bytes().len().is_multiple_of(16)
{
return Err(Error::InvalidSize);
}
bank.alias
.checked_add(span.offset() as u64)
.ok_or(Error::InvalidSize)
}
pub fn eligible(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool {
let layer = match spans[0].role() {
TensorRole::Layer { layer, .. } => layer,
_ => return false,
};
spans.iter().enumerate().all(|(n, span)| {
let role = match n {
0 => LayerRole::FfnGateExperts,
1 => LayerRole::FfnUpExperts,
_ => LayerRole::FfnDownExperts,
};
span.role() == TensorRole::Layer { layer, role }
&& span.expert() == spans[0].expert()
&& self.alias(span).is_ok()
})
}
pub fn copy_triplet(
self: &Rc<Self>,
spans: [ResidentExpertBankSpan; 3],
destinations: [DeviceBuffer<'ctx>; 3],
mut scratch: MappedExpertCopyScratch<'ctx>,
) -> Result<PendingMappedExpertCopy<'ctx>> {
let admitted = (|| {
if self.context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
if !self.eligible(&spans) {
return Err(Error::InvalidSize);
}
if !std::ptr::eq(scratch.context, self.context)
|| scratch.tables.len() != 6
|| scratch.arguments.len() != 3
{
return Err(Error::ContextMismatch);
}
for (n, (span, destination)) in spans.iter().zip(&destinations).enumerate() {
self.alias(span)?;
if !std::ptr::eq(destination.context, self.context) {
return Err(Error::ContextMismatch);
}
if destination.bytes != span.bytes().len() {
return Err(Error::ShapeMismatch {
expected: span.bytes().len(),
actual: destination.bytes,
});
}
let handle = destination.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_extent(destination.bytes)?;
for prior in &destinations[..n] {
if handle.overlaps(
destination.bytes,
prior.handle.ok_or(Error::ContextPoisoned)?,
prior.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
})();
if let Err(primary) = admitted {
return Err(primary);
}
// Exact fixed table/count owners per role. These completed tiny uploads
// precede the original byte kernels; no detached expert staging exists.
for (n, span) in spans.iter().enumerate() {
scratch.tables[n * 2].copy_from(&self.alias(span)?.to_le_bytes())?;
scratch.tables[n * 2 + 1].copy_from(&1i32.to_le_bytes())?;
}
let tables = std::mem::take(&mut scratch.tables);
let arguments = std::mem::take(&mut scratch.arguments);
let mut pending = PendingMappedExpertCopy {
bank: Some(Rc::clone(self)),
spans: Some(spans),
destinations: Some(destinations),
tables,
arguments,
stream: None,
event: None,
attempted: false,
recorded: false,
complete: false,
};
let guard = self.context.enter()?;
let launched = (|| {
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
pending.stream = Some(api.stream()?);
pending.event = Some(api.event()?);
for n in 0..3 {
let actual = pending.destinations.as_ref().expect("owned triplet");
pending.attempted = true;
pending.arguments[n] = api::MappedCopyArguments {
source: pending.tables[n * 2]
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address(),
count: pending.tables[n * 2 + 1]
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address(),
destination: actual[n]
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address(),
words: (actual[n].bytes / 16) as i64,
};
api.copy_kernel(
&mut pending.arguments[n],
pending.stream.expect("actual stream"),
)?;
}
api.record(
pending.event.expect("actual event"),
pending.stream.expect("actual stream"),
)?;
pending.recorded = true;
Ok(())
})();
match combine(launched, guard.finish()) {
Ok(()) => Ok(pending),
Err(primary) => {
if pending.attempted || self.context.is_poisoned() {
pending.retain_uncertain();
} else {
let _ = pending.cleanup();
}
Err(primary)
}
}
}
fn close_inner(&mut self) -> Result<()> {
if self.closed {
return Ok(());
}
if self.context.is_poisoned() {
self.retain_uncertain();
return Err(Error::ContextPoisoned);
}
let guard = self.context.enter()?;
let mut result = Ok(());
if let Some(api) = &self.api {
for bank in &mut self.banks {
if bank.registered {
let unregister = api.unregister_bank(bank.member.bytes());
if unregister.is_ok() {
bank.registered = false;
}
result = combine(result, unregister);
}
}
}
result = combine(result, guard.finish());
if result.is_err() {
self.context.poisoned.set(true);
self.retain_uncertain();
return result;
}
if let Some(api) = &mut self.api {
let guard = self.context.enter()?;
result = combine(api.close(), guard.finish());
}
if result.is_err() {
self.context.poisoned.set(true);
self.retain_uncertain();
return result;
}
self.closed = true;
Ok(())
}
fn retain_uncertain(&mut self) {
self.context.poisoned.set(true);
if let Some(api) = self.api.take() {
std::mem::forget(api);
}
std::mem::forget(std::mem::take(&mut self.banks));
// Banks retain the identical original Rc<Box> catalog bytes.
self.closed = true;
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
}
impl Drop for MappedExpertBank<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
pub struct PendingMappedExpertCopy<'ctx> {
bank: Option<Rc<MappedExpertBank<'ctx>>>,
spans: Option<[ResidentExpertBankSpan; 3]>,
destinations: Option<[DeviceBuffer<'ctx>; 3]>,
tables: Vec<DeviceBuffer<'ctx>>,
arguments: Vec<api::MappedCopyArguments>,
stream: Option<api::Stream>,
event: Option<api::Event>,
attempted: bool,
recorded: bool,
complete: bool,
}
impl<'ctx> PendingMappedExpertCopy<'ctx> {
pub fn destination_bytes(&self) -> usize {
self.destinations
.as_ref()
.map_or(0, |b| b.iter().map(DeviceBuffer::len).sum())
}
fn observe(&mut self, wait: bool) -> Result<bool> {
if self.complete {
return Ok(true);
}
let bank = Rc::clone(self.bank.as_ref().ok_or(Error::ContextPoisoned)?);
if !self.recorded || bank.context.is_poisoned() {
self.retain_uncertain();
return Err(Error::ContextPoisoned);
}
let guard = match bank.context.enter() {
Ok(guard) => guard,
Err(primary) => {
self.retain_uncertain();
return Err(primary);
}
};
let api = bank.api.as_ref().ok_or(Error::ContextPoisoned)?;
let result = if wait {
api.wait(self.event.ok_or(Error::ContextPoisoned)?)
.map(|()| true)
} else {
api.query(self.event.ok_or(Error::ContextPoisoned)?)
};
match combine(result, guard.finish()) {
Ok(true) => {
self.complete = true;
Ok(true)
}
Ok(false) => Ok(false),
Err(primary) => {
self.retain_uncertain();
Err(primary)
}
}
}
fn cleanup(&mut self) -> Result<()> {
if self.attempted && !self.complete {
self.observe(true)?;
}
let Some(bank) = self.bank.as_ref().map(Rc::clone) else {
return Ok(());
};
let guard = match bank.context.enter() {
Ok(guard) => guard,
Err(primary) => {
self.retain_uncertain();
return Err(primary);
}
};
let api = bank.api.as_ref().ok_or(Error::ContextPoisoned)?;
let mut result = Ok(());
if let Some(event) = self.event.take() {
result = combine(result, api.destroy_event(event));
}
if let Some(stream) = self.stream.take() {
result = combine(result, api.destroy_stream(stream));
}
result = combine(result, guard.finish());
if result.is_err() {
self.retain_uncertain();
return result;
}
for buffer in std::mem::take(&mut self.tables) {
result = combine(result, buffer.release());
}
if result.is_err() {
self.retain_uncertain();
}
result
}
fn retain_uncertain(&mut self) {
if let Some(bank) = self.bank.take() {
bank.context.poisoned.set(true);
std::mem::forget(bank);
}
if let Some(spans) = self.spans.take() {
std::mem::forget(spans);
}
if let Some(destinations) = self.destinations.take() {
std::mem::forget(destinations);
}
std::mem::forget(std::mem::take(&mut self.tables));
std::mem::forget(std::mem::take(&mut self.arguments));
self.stream = None;
self.event = None;
self.attempted = false;
}
pub fn wait(mut self) -> Result<MappedExpertCopyCompletion<'ctx>> {
self.observe(true)?;
let tables = std::mem::take(&mut self.tables);
let arguments = std::mem::take(&mut self.arguments);
// Event/stream cleanup is complete before usable destination exposure.
// Keep fixed table owners for the same actual slot's next invocation.
if let Err(primary) = self.cleanup() {
if self.bank.as_ref().is_none_or(|b| b.context.is_poisoned()) {
std::mem::forget(tables);
std::mem::forget(arguments);
}
return Err(primary);
}
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
let scratch = MappedExpertCopyScratch {
context: bank.context,
tables,
arguments,
};
drop(self.spans.take());
Ok(MappedExpertCopyCompletion {
destinations: self.destinations.take().ok_or(Error::ContextPoisoned)?,
scratch,
})
}
pub fn close(mut self) -> Result<()> {
self.cleanup()?;
let mut result = Ok(());
if let Some(destinations) = self.destinations.take() {
for buffer in destinations {
result = combine(result, buffer.release());
}
}
drop(self.spans.take());
result
}
}
impl Drop for PendingMappedExpertCopy<'_> {
fn drop(&mut self) {
let _ = self.cleanup();
}
}
/// Six genuine fixed table/count owners, 36B. Eager admission is separate from
/// source registration and no caller-selected device address is exposed.
pub struct MappedExpertCopyScratch<'ctx> {
context: &'ctx Context<'ctx>,
tables: Vec<DeviceBuffer<'ctx>>,
arguments: Vec<api::MappedCopyArguments>,
}
impl Context<'_> {
pub fn mapped_expert_copy_scratch<'ctx>(&'ctx self) -> Result<MappedExpertCopyScratch<'ctx>> {
let mut tables = Vec::new();
tables
.try_reserve_exact(6)
.map_err(|_| Error::HostAllocation)?;
let mut arguments = Vec::new();
arguments
.try_reserve_exact(3)
.map_err(|_| Error::HostAllocation)?;
arguments.resize(3, api::MappedCopyArguments::default());
for _ in 0..3 {
tables.push(self.allocate(8)?);
tables.push(self.allocate(4)?);
}
Ok(MappedExpertCopyScratch {
context: self,
tables,
arguments,
})
}
}
impl MappedExpertCopyScratch<'_> {
pub fn allocated_bytes(&self) -> usize {
self.tables.iter().map(DeviceBuffer::len).sum()
}
pub fn metadata_bytes(&self) -> usize {
size_of::<Self>()
+ self.tables.capacity() * size_of::<DeviceBuffer<'_>>()
+ self.arguments.capacity() * size_of::<api::MappedCopyArguments>()
}
pub fn close(mut self) -> Result<()> {
let mut result = Ok(());
for table in std::mem::take(&mut self.tables) {
result = combine(result, table.release());
}
result
}
}
pub struct MappedExpertCopyCompletion<'ctx> {
destinations: [DeviceBuffer<'ctx>; 3],
scratch: MappedExpertCopyScratch<'ctx>,
}
impl<'ctx> MappedExpertCopyCompletion<'ctx> {
pub fn into_parts(self) -> ([DeviceBuffer<'ctx>; 3], MappedExpertCopyScratch<'ctx>) {
(self.destinations, self.scratch)
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+445
View File
@@ -0,0 +1,445 @@
//! Closed ABI storage for immutable upstream MMQ entries; owned through sync.
use super::*;
use crate::mmq::Layout;
use std::ffi::c_void;
#[repr(C)]
struct Storage {
addresses: [u64; 7],
wide: [i64; 5],
integers: [i32; 11],
divisors: [[u32; 3]; 6],
parameters: [*mut c_void; 24],
}
struct Owned(std::ptr::NonNull<Storage>);
impl Owned {
fn new() -> Self {
let p = Box::into_raw(Box::new(Storage {
addresses: [0; 7],
wide: [0; 5],
integers: [0; 11],
divisors: [[0; 3]; 6],
parameters: [std::ptr::null_mut(); 24],
}));
Self(std::ptr::NonNull::new(p).expect("Box is non-null"))
}
fn parameters(&mut self) -> *mut *mut c_void {
// SAFETY: stable uniquely owned storage, retained by caller through completion.
unsafe { (&raw mut (*self.0.as_ptr()).parameters).cast() }
}
}
impl Drop for Owned {
fn drop(&mut self) {
// SAFETY: owner is reconstructed once after completion; facade forgets on uncertainty.
unsafe { drop(Box::from_raw(self.0.as_ptr())) }
}
}
fn fastdiv(d: u32) -> [u32; 3] {
let l = 32 - (d - 1).leading_zeros();
[
(((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32,
l,
d,
]
}
pub(crate) struct MmqQuantArguments(Owned);
impl MmqQuantArguments {
pub(crate) fn new(input: BufferHandle, packed: BufferHandle, l: Layout) -> Self {
let owner = Owned::new();
// SAFETY: private construction admits closed shape, matching exact 11-param ABI.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..3].copy_from_slice(&[input.0, 0, packed.0]);
s.wide = [
i64::from(l.columns),
i64::from(l.columns),
i64::from(l.columns * l.tokens),
i64::from(l.columns * l.tokens),
i64::from(l.padded_columns),
];
s.integers[..3].copy_from_slice(&[l.tokens as i32, 1, 0]);
for i in 0..3 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
for i in 0..5 {
s.parameters[i + 3] = (&raw mut s.wide[i]).cast();
}
for i in 0..3 {
s.parameters[i + 8] = (&raw mut s.integers[i]).cast();
}
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
pub(crate) struct MmqArguments(Owned);
impl MmqArguments {
pub(crate) fn new(
weights: BufferHandle,
packed: BufferHandle,
output: BufferHandle,
tmp: Option<BufferHandle>,
l: Layout,
) -> Self {
let owner = Owned::new();
// SAFETY: private exact upstream 24-param ABI, null unused one-expert inputs.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses = [
weights.0,
packed.0,
0,
0,
output.0,
tmp.map_or(0, |p| p.0),
0,
];
s.divisors = [
fastdiv(l.columns / l.qk),
fastdiv(1),
fastdiv(1),
fastdiv(1),
fastdiv(1),
fastdiv(1),
];
s.integers = [
l.rows as i32,
l.tokens as i32,
(l.columns / l.qk) as i32,
l.tokens as i32,
l.rows as i32,
(l.rows * l.columns / l.qk) as i32,
(l.payload / 4) as i32,
(l.rows * l.tokens) as i32,
(l.rows * l.columns / l.qk) as i32,
(l.payload / 4) as i32,
(l.rows * l.tokens) as i32,
];
for i in 0..7 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
s.parameters[7] = (&raw mut s.divisors[0]).cast();
for i in 0..5 {
s.parameters[i + 8] = (&raw mut s.integers[i]).cast();
}
s.parameters[13] = (&raw mut s.divisors[1]).cast();
s.parameters[14] = (&raw mut s.divisors[2]).cast();
for i in 0..3 {
s.parameters[i + 15] = (&raw mut s.integers[i + 5]).cast();
}
s.parameters[18] = (&raw mut s.divisors[3]).cast();
s.parameters[19] = (&raw mut s.divisors[4]).cast();
for i in 0..3 {
s.parameters[i + 20] = (&raw mut s.integers[i + 8]).cast();
}
s.parameters[23] = (&raw mut s.divisors[5]).cast();
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
pub(crate) struct MmqFixupArguments(Owned);
impl MmqFixupArguments {
pub(crate) fn new(output: BufferHandle, tmp: BufferHandle, l: Layout) -> Self {
let owner = Owned::new();
// SAFETY: private exact 13-param fixed fixup ABI; same original divisors and strides.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..4].copy_from_slice(&[0, 0, output.0, tmp.0]);
s.divisors[..4].copy_from_slice(&[
fastdiv(l.columns / l.qk),
fastdiv(1),
fastdiv(1),
fastdiv(1),
]);
s.integers[..5].copy_from_slice(&[
l.rows as i32,
l.tokens as i32,
l.rows as i32,
(l.rows * l.tokens) as i32,
(l.rows * l.tokens) as i32,
]);
for i in 0..4 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
s.parameters[4] = (&raw mut s.divisors[0]).cast();
for i in 0..3 {
s.parameters[i + 5] = (&raw mut s.integers[i]).cast();
}
s.parameters[8] = (&raw mut s.divisors[1]).cast();
s.parameters[9] = (&raw mut s.integers[3]).cast();
s.parameters[10] = (&raw mut s.divisors[2]).cast();
s.parameters[11] = (&raw mut s.integers[4]).cast();
s.parameters[12] = (&raw mut s.divisors[3]).cast();
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
// Exact integer helper ABI; private owned storage retained through completion.
pub(crate) struct MmqResidentArguments(Owned);
impl MmqResidentArguments {
pub(crate) fn native_resident_d4(
source: BufferHandle,
out: BufferHandle,
status: BufferHandle,
columns: u32,
tokens: u32,
) -> Self {
let owner = Owned::new();
// SAFETY: fixed three-pointer/two-u32 ABI, closed admitted extents, stable owned Box.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..3].copy_from_slice(&[source.0, out.0, status.0]);
s.integers[..2].copy_from_slice(&[columns as i32, tokens as i32]);
for i in 0..3 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
for i in 0..2 {
s.parameters[i + 3] = (&raw mut s.integers[i]).cast();
}
}
Self(owner)
}
pub(crate) fn zero(out: BufferHandle, words: u32) -> Self {
let owner = Owned::new();
// SAFETY: two fixed ABI fields in stable Box; no borrowed stack args.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[0] = out.0;
s.integers[0] = words as i32;
s.parameters[0] = (&raw mut s.addresses[0]).cast();
s.parameters[1] = (&raw mut s.integers[0]).cast();
}
Self(owner)
}
pub(crate) fn finite(
source: BufferHandle,
status: BufferHandle,
mode: u32,
amount: u32,
tail: u32,
) -> Self {
let owner = Owned::new();
// SAFETY: fixed five-param pointer/pointer/u32/u32/u32 ABI in stable Box.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..2].copy_from_slice(&[source.0, status.0]);
s.integers[..3].copy_from_slice(&[mode as i32, amount as i32, tail as i32]);
for i in 0..2 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
for i in 0..3 {
s.parameters[i + 2] = (&raw mut s.integers[i]).cast();
}
}
Self(owner)
}
pub(crate) fn gather(
source: BufferHandle,
ids: BufferHandle,
out: BufferHandle,
total: u32,
group: u32,
blocks: u32,
) -> Self {
let owner = Owned::new();
// SAFETY: fixed six-param ABI and closed checked row/block layout, stable Box.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..3].copy_from_slice(&[source.0, ids.0, out.0]);
s.integers[..3].copy_from_slice(&[total as i32, group as i32, blocks as i32]);
for i in 0..3 {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
s.parameters[i + 3] = (&raw mut s.integers[i]).cast();
}
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
// Exact new IQ3 raw-dot/reducer ABI. No caller-selected kernels or parameter counts.
pub(crate) struct Iq3NativeIntegerArguments(Owned);
impl Iq3NativeIntegerArguments {
pub(crate) fn dot(
weights: BufferHandle,
packed: BufferHandle,
dots: BufferHandle,
tokens: u32,
) -> Self {
Self::new([weights.0, packed.0, dots.0, 0], 3, tokens)
}
pub(crate) fn reduce(
weights: BufferHandle,
packed: BufferHandle,
dots: BufferHandle,
output: BufferHandle,
tokens: u32,
) -> Self {
Self::new([weights.0, packed.0, dots.0, output.0], 4, tokens)
}
fn new(addresses: [u64; 4], pointers: usize, tokens: u32) -> Self {
let owner = Owned::new();
// SAFETY: fixed private 3-/4-pointer plus u32 ABI, admitted closed extents.
// Box pointees remain stable through queue launch, synchronize and context pop.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..4].copy_from_slice(&addresses);
s.integers[0] = tokens as i32;
for i in 0..pointers {
s.parameters[i] = (&raw mut s.addresses[i]).cast();
}
s.parameters[pointers] = (&raw mut s.integers[0]).cast();
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
impl MmqQuantArguments {
pub(crate) fn original_indexed(
input: BufferHandle,
ids: Option<BufferHandle>,
packed: BufferHandle,
l: Layout,
) -> Self {
let owner = Self::new(input, packed, l);
// SAFETY: same original non-scatter ABI. IDs are a genuine admitted owner;
// its exact rows all index the retained whole activation matrix.
unsafe {
(*owner.0.0.as_ptr()).addresses[1] = ids.map_or(0, |h| h.0);
(*owner.0.0.as_ptr()).integers[2] = 1;
}
owner
}
}
impl MmqArguments {
#[allow(clippy::too_many_arguments)]
pub(crate) fn original_group(
weights: BufferHandle,
packed: BufferHandle,
ids: BufferHandle,
bounds: BufferHandle,
output: BufferHandle,
tmp: Option<BufferHandle>,
l: Layout,
experts: u32,
max_rows: u32,
width: u32,
) -> Self {
let owner = Self::new(weights, packed, output, tmp, l);
// SAFETY: literal Original Product -> mmq_args, channel expert stride
// includes Gate followed by Up; no per-expert padding. Stable exact ABI.
unsafe {
let s = &mut *owner.0.0.as_ptr();
s.addresses[2] = ids.0;
s.addresses[3] = bounds.0;
s.divisors[2] = fastdiv(experts);
s.divisors[5] = fastdiv(max_rows.div_ceil(width));
s.integers[6] = 0;
s.integers[7] = 0;
s.integers[8] = 0;
s.integers[9] = 0;
s.integers[10] = 0;
}
owner
}
}
impl MmqFixupArguments {
#[allow(clippy::too_many_arguments)]
pub(crate) fn original_group(
ids: BufferHandle,
bounds: BufferHandle,
output: BufferHandle,
tmp: BufferHandle,
l: Layout,
experts: u32,
max_rows: u32,
width: u32,
) -> Self {
let owner = Self::new(output, tmp, l);
// SAFETY: same ids/bounds, channel count and ntx as the exact preceding
// Original stream-K producer. Both destination channel/sample strides0.
unsafe {
let s = &mut *owner.0.0.as_ptr();
s.addresses[0] = ids.0;
s.addresses[1] = bounds.0;
s.divisors[1] = fastdiv(experts);
s.divisors[3] = fastdiv(max_rows.div_ceil(width));
s.integers[3] = 0;
s.integers[4] = 0;
}
owner
}
}
pub(crate) struct MmqOriginalSwigluArguments(Owned);
impl MmqOriginalSwigluArguments {
pub(crate) fn new(gu: BufferHandle, hidden: BufferHandle, rows: u32) -> Self {
let owner = Owned::new();
// SAFETY: literal Original split-GU float kernel, fixed n_ff640 and
// interleaved=false, stable pointer/pointer/i64/i64/bool ABI.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..2].copy_from_slice(&[gu.0, hidden.0]);
s.wide[..2].copy_from_slice(&[i64::from(rows), 640]);
s.integers[0] = 0;
s.parameters[0] = (&raw mut s.addresses[0]).cast();
s.parameters[1] = (&raw mut s.addresses[1]).cast();
s.parameters[2] = (&raw mut s.wide[0]).cast();
s.parameters[3] = (&raw mut s.wide[1]).cast();
s.parameters[4] = (&raw mut s.integers[0]).cast();
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
pub(crate) struct MmqOriginalGatherArguments(Owned);
impl MmqOriginalGatherArguments {
pub(crate) fn new(
raw: [BufferHandle; 3],
gu: BufferHandle,
down: BufferHandle,
gu_bytes: usize,
down_bytes: usize,
) -> Self {
let owner = Owned::new();
// SAFETY: literal Original copy16 pointer/i64 ABI. All actual whole
// inputs and closed destination subspans admitted before construction.
unsafe {
let s = &mut *owner.0.as_ptr();
s.addresses[..5].copy_from_slice(&[raw[0].0, raw[1].0, gu.0, raw[2].0, down.0]);
s.wide[..3].copy_from_slice(&[
(gu_bytes / 16) as i64,
(gu_bytes / 16) as i64,
(down_bytes / 16) as i64,
]);
s.parameters[0] = (&raw mut s.addresses[0]).cast();
s.parameters[1] = (&raw mut s.wide[0]).cast();
s.parameters[2] = (&raw mut s.addresses[1]).cast();
s.parameters[3] = (&raw mut s.wide[1]).cast();
s.parameters[4] = (&raw mut s.addresses[2]).cast();
s.parameters[5] = (&raw mut s.addresses[3]).cast();
s.parameters[6] = (&raw mut s.wide[2]).cast();
s.parameters[7] = (&raw mut s.addresses[4]).cast();
}
Self(owner)
}
pub(crate) fn parameters(&mut self) -> *mut *mut c_void {
self.0.parameters()
}
}
+36
View File
@@ -0,0 +1,36 @@
//! Producer-certified logical native weight span without a fabricated buffer view.
use super::*;
pub(crate) enum NativeWeights<'borrow, 'ctx> {
Raw(&'borrow DeviceBuffer<'ctx>),
Dual(&'borrow mmq::MmqWeights<'ctx>),
}
impl<'ctx> NativeWeights<'_, 'ctx> {
pub(crate) fn buffer(&self) -> Result<&DeviceBuffer<'ctx>> {
match self {
Self::Raw(b) => Ok(b),
Self::Dual(w) => w.native_buffer(),
}
}
pub(crate) fn validate(&self, spec: ProjectionSpec, logical: usize) -> Result<()> {
let b = self.buffer()?;
match self {
Self::Raw(_) if b.bytes == logical => Ok(()),
Self::Dual(w) => {
let expected = w.native_spec();
let l = w.native_layout()?;
if spec.kind != expected.kind
|| spec.rows != expected.rows
|| spec.columns != expected.columns
|| logical != l.raw_weight
|| b.bytes != l.weight
{
return Err(Error::InvalidProjectionShape);
}
b.handle
.ok_or(Error::ContextPoisoned)?
.validate_projection_extent(b.bytes, spec.kind.weight_alignment())
}
_ => Err(Error::InvalidProjectionShape),
}
}
}
@@ -0,0 +1,150 @@
//! Explicit native-activation policy; original D4 producer remains unchanged.
use super::*;
pub(super) const CHARGE: usize = 184320;
pub(crate) fn asset() -> Result<&'static [u8]> {
let b = include_bytes!("mmq_native_resident_d4.ptx");
if b.len() != 5200
|| b.last() != Some(&0)
|| !b[..b.len() - 1].is_ascii()
|| b[..b.len() - 1].contains(&0)
|| crate::qwen_ffi::sha256(&b[..b.len() - 1]) != EXPECTED_RAW_SHA
{
return Err(Error::InvalidDriverValue("native resident D4 artifact"));
}
Ok(b)
}
const EXPECTED_RAW_SHA: [u8; 32] = [
0xea, 0x33, 0xd3, 0xd1, 0xdb, 0xc3, 0xc6, 0x39, 0x81, 0x55, 0xef, 0xa1, 0x92, 0xb5, 0xbb, 0x4d,
0x5a, 0x25, 0xf7, 0x3f, 0x6e, 0x8a, 0xf6, 0x5f, 0x2d, 0xdc, 0x1b, 0x91, 0x95, 0xbb, 0x3e, 0xeb,
];
pub(super) struct NativeActivation<'ctx> {
context: &'ctx Context<'ctx>,
buffer: Option<DeviceBuffer<'ctx>>,
module: Option<ffi::ModuleHandle>,
function: Option<ffi::FunctionHandle>,
}
impl<'ctx> NativeActivation<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if context
.allocated_bytes()
.checked_add(CHARGE)
.is_none_or(|n| n > context.budget)
{
return Err(Error::BudgetExceeded);
}
let mut owner = Self {
context,
buffer: None,
module: None,
function: None,
};
let result = (|| {
owner.buffer = Some(context.allocate(CHARGE)?);
let guard = context.enter()?;
let load = (|| {
let m = context.driver.api.load_native_resident_d4()?;
owner.module = Some(m);
owner.function = Some(context.driver.api.native_resident_d4_function(m)?);
Ok(())
})();
combine(load, guard.finish())
})();
if let Err(e) = result {
return combine(Err(e), owner.close());
}
Ok(owner)
}
pub(super) fn check(&self) -> Result<()> {
if self.context.is_poisoned()
|| self.context.handle.is_none()
|| self.module.is_none()
|| self.function.is_none()
{
return Err(Error::ContextPoisoned);
}
let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(self.context, b.context) || b.bytes != CHARGE {
return Err(Error::ContextMismatch);
}
b.handle
.ok_or(Error::ContextPoisoned)?
.validate_projection_extent(CHARGE, 4)
}
pub(super) fn buffer(&self) -> Result<&DeviceBuffer<'ctx>> {
self.check()?;
self.buffer.as_ref().ok_or(Error::ContextPoisoned)
}
pub(super) fn append(
&self,
commands: &mut Vec<QueuedCommand>,
input: ffi::BufferHandle,
packed: ffi::BufferHandle,
status: ffi::BufferHandle,
l: Layout,
) -> Result<()> {
self.check()?;
if !matches!(l.columns, 640 | 2560) || !(1..=64).contains(&l.tokens) {
return Err(Error::InvalidProjectionShape);
}
let native = self.buffer()?.handle.ok_or(Error::ContextPoisoned)?;
let n = l.columns as usize / 32 * l.tokens as usize * 36;
native.validate_projection_extent(n, 4)?;
if input.overlaps(l.input, native, CHARGE)
|| packed.overlaps(l.packed, native, CHARGE)
|| status.overlaps(4, native, CHARGE)
{
return Err(Error::OutputAliasesInput);
}
let guard = self.context.enter()?;
let k = combine(
self.context.fixed_kernel(FixedOperation::CommonQuantize),
guard.finish(),
)?;
commands.push(QueuedCommand::NativeQuantize(
k.function,
(l.columns * l.tokens).div_ceil(256),
ffi::Q8QuantizeArguments::new(input, native, status, l.columns * l.tokens),
));
commands.push(QueuedCommand::Helper(
self.function.ok_or(Error::ContextPoisoned)?,
(l.packed / 4) as u32,
ffi::MmqResidentArguments::native_resident_d4(
native, packed, status, l.columns, l.tokens,
),
));
Ok(())
}
pub(super) fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.function = None;
let a = self.buffer.take().map_or(Ok(()), |b| {
if self.context.is_poisoned() {
std::mem::forget(b);
Err(Error::ContextPoisoned)
} else {
b.release()
}
});
let b = self
.module
.take()
.map_or(Ok(()), |m| match self.context.enter() {
Ok(g) => combine(self.context.driver.api.unload(m), g.finish()),
Err(e) => Err(e),
});
if a.is_err() || b.is_err() {
self.context.poisoned.set(true);
}
combine(a, b)
}
}
impl Drop for NativeActivation<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
+73
View File
@@ -0,0 +1,73 @@
//! IntegerIQ3 policy only: preserve the original Down20/42 emitted arithmetic.
//! Reuse actual native Q8_1 already produced from this owned hidden lease.
use super::*;
impl MmqWorkspace<'_> {
pub(super) fn project_native_down(&self, weights: &MmqWeights<'_>, tokens: u32) -> Result<()> {
self.check()?;
if self.native_integer.is_none() || !(1..=64).contains(&tokens) {
return Err(Error::UnsupportedProjection);
}
let (format, operation) = match weights.format {
MmqFormat::Iq4NlDown => (RoutedFormat::IQ4_NL, FixedOperation::GroupedDownIq4),
MmqFormat::Q2Down => (RoutedFormat::Q2_0, FixedOperation::GroupedDownQ2),
_ => return Err(Error::UnsupportedProjection),
};
let spec = ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 2560,
columns: 640,
};
let shape = projection_shape(spec)?;
let owner = NativeWeights::Dual(weights);
owner.validate(spec, shape.weight_bytes)?;
let weight = owner.buffer()?;
let native = self
.native_activation
.as_ref()
.ok_or(Error::UnsupportedProjection)?
.buffer()?;
if !std::ptr::eq(self.context, weights.context)
|| !std::ptr::eq(self.context, weight.context)
|| !std::ptr::eq(self.context, native.context)
{
return Err(Error::ContextMismatch);
}
let wh = weight.handle.ok_or(Error::ContextPoisoned)?;
let qh = native.handle.ok_or(Error::ContextPoisoned)?;
let oh = self.handle(DOWN, tokens as usize * 10240, 4)?;
let q8_bytes = tokens as usize * 720;
if q8_bytes > native.bytes {
return Err(Error::InvalidProjectionShape);
}
qh.validate_projection_extent(native.bytes, 4)?;
let spans = [
(wh, weight.bytes),
(qh, native.bytes),
(oh, self.buffer(DOWN)?.bytes),
];
for i in 0..spans.len() {
for j in i + 1..spans.len() {
if spans[i].0.overlaps(spans[i].1, spans[j].0, spans[j].1) {
return Err(Error::OutputAliasesInput);
}
}
}
// quantize_native(HIDDEN, DOWN_Q8, layout) completed directly before
// this call, including the original quantizer status and finite proof.
// Its native Q8 owner remains live; no gather/quantizer can overwrite it
// while this exclusive MmqHidden lease is consumed by Down.
let guard = self.context.enter()?;
let kernel = combine(self.context.fixed_kernel(operation), guard.finish())?;
let mut queued = commands()?;
queued.push(QueuedCommand::NativeDown(
kernel.function,
tokens,
ffi::ProjectionArguments::new(wh, qh, oh, 2560, 640),
));
// Keep original grouped kernel geometry (640,T)/(32,4) and same stream.
// The queued ABI Box survives launch/sync/pop. Only the existing actual
// finite output witness can mint FiniteMmqOutput; cleanup is unchanged.
self.finish_finite(queued, DOWN, tokens as usize * 2560, false)
}
}
@@ -0,0 +1,27 @@
// Exact native-certified Q8_1 transport only; columns is closed640 or2560, T1..64.
__device__ __forceinline__ unsigned promote_half_bits(unsigned h) {
unsigned sign=(h&0x8000u)<<16,e=(h>>10)&31u,m=h&1023u;
if(e==0u){if(m==0u)return sign;unsigned ef=113u;while((m&1024u)==0u){m<<=1;--ef;}return sign|(ef<<23)|((m&1023u)<<13);}
return sign|((e+112u)<<23)|(m<<13);
}
extern "C" __global__ void leleka_native_resident_d4(const unsigned char* source,unsigned* out,unsigned* status,unsigned columns,unsigned tokens) {
unsigned i=blockIdx.x*blockDim.x+threadIdx.x;
if((columns!=640u&&columns!=2560u)||tokens==0u||tokens>64u){if(i==0u)atomicOr(status,1u);return;}
unsigned padded=(columns+511u)/512u*512u, payload=padded/128u*tokens*36u;
if(i>=payload+2304u)return;
if(i>=payload){out[i]=0u;return;}
unsigned lane=i%36u,row=(i/36u)%tokens,block=i/(36u*tokens),value=0u;
if(lane<4u){
unsigned native_block=block*4u+lane;
if(native_block<columns/32u){
unsigned base=(row*(columns/32u)+native_block)*36u;
unsigned d=unsigned(source[base])|(unsigned(source[base+1u])<<8),s=unsigned(source[base+2u])|(unsigned(source[base+3u])<<8);
if((d&0x7c00u)==0x7c00u||(s&0x7c00u)==0x7c00u){atomicOr(status,1u);out[i]=0u;return;}
value=promote_half_bits(d);
}
}else{
unsigned code=(lane-4u)*4u,native_block=block*4u+code/32u;
if(native_block<columns/32u){unsigned base=(row*(columns/32u)+native_block)*36u+4u+code%32u;value=unsigned(source[base])|(unsigned(source[base+1u])<<8)|(unsigned(source[base+2u])<<16)|(unsigned(source[base+3u])<<24);}
}
out[i]=value;
}
Binary file not shown.
@@ -0,0 +1,563 @@
//! Actual public fixed-ID input and independently extracted expert215; diagnostic, not GateB.
use super::*;
use std::collections::BTreeMap;
use std::fs::{DirBuilder, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
fn digest(b: &[u8]) -> String {
use std::fmt::Write;
let mut s = String::with_capacity(64);
for v in crate::qwen_ffi::sha256(b) {
write!(&mut s, "{v:02x}").unwrap();
}
s
}
fn read(path: &Path, max: usize) -> Vec<u8> {
let mut f = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
.unwrap();
let before = f.metadata().unwrap();
assert!(before.is_file() && before.len() <= max as u64);
let mut b = Vec::new();
std::io::Read::by_ref(&mut f)
.take(max as u64 + 1)
.read_to_end(&mut b)
.unwrap();
let after = f.metadata().unwrap();
assert_eq!(
(
before.dev(),
before.ino(),
before.len(),
before.mtime(),
before.mtime_nsec(),
before.ctime(),
before.ctime_nsec()
),
(
after.dev(),
after.ino(),
after.len(),
after.mtime(),
after.mtime_nsec(),
after.ctime(),
after.ctime_nsec()
)
);
assert_eq!(b.len() as u64, before.len());
b
}
fn fixture() -> [Vec<u8>; 4] {
let root = PathBuf::from(std::env::var("LELEKA_REAL_GU_DIR").unwrap());
assert!(root.is_absolute());
assert_eq!(root.canonicalize().unwrap(), root);
let manifest = read(&root.join("ROOT-GU-DOWN.tsv"), 8192);
assert_eq!(
digest(&manifest),
std::env::var("LELEKA_REAL_GU_MANIFEST_SHA").unwrap()
);
assert_eq!(
digest(&manifest),
"6f3b0df514a1228340377fb3566d135ce3e7a8a4055d602db13d7250e98b89b5"
);
let text = std::str::from_utf8(&manifest).unwrap();
let mut lines = text.lines();
assert_eq!(lines.next(), Some("schema\tstra169-real-gu-v1"));
let mut pins = BTreeMap::new();
for line in lines {
let p: Vec<_> = line.split('\t').collect();
assert_eq!(p.len(), 4);
assert_eq!(p[0], "file");
assert!(matches!(
p[1],
"EXTRACTION.json" | "input.f32" | "gate.raw" | "up.raw" | "down.raw"
));
assert!(
pins.insert(p[1], (p[2].parse::<usize>().unwrap(), p[3]))
.is_none()
);
}
assert_eq!(pins.len(), 5);
let mut values = BTreeMap::new();
for (name, (size, sha)) in pins {
let limit = match name {
"EXTRACTION.json" => 65536,
"input.f32" => 20480,
"down.raw" => 921600,
_ => 627200,
};
if name != "EXTRACTION.json" {
assert_eq!(size, limit);
} else {
assert!((1..=limit).contains(&size));
}
assert_eq!(sha.len(), 64);
let b = read(&root.join(name), limit);
assert_eq!(b.len(), size);
assert_eq!(digest(&b), sha);
values.insert(name, b);
}
let input = values.remove("input.f32").unwrap();
assert_eq!(
digest(&input),
"db757265bb72da9435ef26bf0158b77ec661ad95e635fcb94d0025d378c0d267"
);
assert_eq!(
digest(&input[..10240]),
"76a3b4c4db8e86b89c4966a4db6068fc46cac2648c6356811ac167e13e8fc8ea"
);
assert_eq!(
digest(&input[10240..]),
"bdca56ede51d8ff62b3af41ad9bf04ffed09707b4c7e4037f39e7363c18a708c"
);
assert!(finite_f32(&input));
// ROOT pins EXTRACTION.json only after actual GGUF topology/offset and matrix-byte checks.
[
input,
values.remove("gate.raw").unwrap(),
values.remove("up.raw").unwrap(),
values.remove("down.raw").unwrap(),
]
}
fn upload<'c>(c: &'c Context<'c>, b: &[u8]) -> DeviceBuffer<'c> {
let mut d = c.allocate(b.len()).unwrap();
d.copy_from(b).unwrap();
d
}
fn download(b: &DeviceBuffer<'_>) -> Vec<u8> {
let mut out = vec![0; b.bytes];
b.copy_to(&mut out).unwrap();
out
}
fn half_bits(h: u16) -> u32 {
let sign = u32::from(h & 0x8000) << 16;
let e = u32::from(h >> 10 & 31);
let mut m = u32::from(h & 1023);
if e == 0 {
if m == 0 {
return sign;
}
let mut exp = 113;
while m & 1024 == 0 {
m <<= 1;
exp -= 1;
}
return sign | exp << 23 | (m & 1023) << 13;
}
assert_ne!(e, 31);
sign | (e + 112) << 23 | m << 13
}
// Independent literal mapping: native rows are contiguous; D4 is block-major, row-minor.
fn associate(native: &[u8], d4: &[u8], columns: usize) {
let native_blocks = columns / 32;
let padded_blocks = columns.div_ceil(512) * 4;
assert_eq!(native.len(), 2 * native_blocks * 36);
let payload = 2 * padded_blocks * 144;
assert_eq!(d4.len(), payload + 9216);
for row in 0..2 {
for block in 0..padded_blocks {
let out = &d4[(block * 2 + row) * 144..(block * 2 + row + 1) * 144];
for sub in 0..4 {
let nb = block * 4 + sub;
if nb < native_blocks {
let n = &native
[(row * native_blocks + nb) * 36..(row * native_blocks + nb + 1) * 36];
let scale = half_bits(u16::from_le_bytes([n[0], n[1]]));
assert_ne!(u16::from_le_bytes([n[2], n[3]]) & 0x7c00, 0x7c00);
assert_eq!(&out[sub * 4..sub * 4 + 4], &scale.to_le_bytes());
assert_eq!(&out[16 + sub * 32..16 + (sub + 1) * 32], &n[4..]);
} else {
assert!(out[sub * 4..sub * 4 + 4].iter().all(|v| *v == 0));
assert!(
out[16 + sub * 32..16 + (sub + 1) * 32]
.iter()
.all(|v| *v == 0)
);
}
}
}
}
assert!(d4[payload..].iter().all(|v| *v == 0));
}
fn write_file(root: &Path, name: &str, b: &[u8]) {
let mut f = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(root.join(name))
.unwrap();
f.write_all(b).unwrap();
}
fn ordered(v: f32) -> u32 {
let b = v.to_bits();
if b >> 31 != 0 { !b } else { b | 0x80000000 }
}
fn measure(row: usize, role: &str, arm: &str, a: &[u8], b: &[u8]) -> String {
assert_eq!(a.len(), b.len());
assert!(finite_f32(a) && finite_f32(b));
let mut diff = 0;
let mut first = None;
let mut abs = 0.0f64;
let mut ulp = 0u32;
for (i, (x, y)) in a
.as_chunks::<4>()
.0
.iter()
.zip(b.as_chunks::<4>().0)
.enumerate()
{
let x = f32::from_le_bytes(*x);
let y = f32::from_le_bytes(*y);
if x.to_bits() != y.to_bits() {
diff += 1;
first.get_or_insert(i);
}
abs = abs.max((f64::from(x) - f64::from(y)).abs());
ulp = ulp.max(ordered(x).abs_diff(ordered(y)));
}
format!(
"{{\"row\":{row},\"role\":\"{role}\",\"arm\":\"{arm}\",\"words\":{},\"different\":{diff},\"first\":{},\"max_abs\":{abs},\"max_ulp\":{ulp},\"quality_pass\":false}}\n",
a.len() / 4,
first.map_or("null".to_owned(), |v| v.to_string())
)
}
fn prefix(b: &DeviceBuffer<'_>, amount: usize) -> Vec<u8> {
download(b)[..amount].to_vec()
}
fn floats(b: &[u8]) -> Vec<f32> {
assert!(finite_f32(b));
b.as_chunks::<4>()
.0
.iter()
.map(|v| f32::from_le_bytes(*v))
.collect()
}
// The original CommonQuantize kernel, independently invoked on a real native hidden row.
fn native_hidden_q8(context: &Context<'_>, input: &DeviceBuffer<'_>) -> Vec<u8> {
let q = context.allocate(720).unwrap();
let mut status = context.allocate(4).unwrap();
status.copy_from(&[0; 4]).unwrap();
let guard = context.enter().unwrap();
let k = context
.fixed_kernel(FixedOperation::CommonQuantize)
.unwrap();
guard.finish().unwrap();
let mut args = ffi::Q8QuantizeArguments::new(
input.handle.unwrap(),
q.handle.unwrap(),
status.handle.unwrap(),
640,
);
let guard = context.enter().unwrap();
let launch = context
.driver
.api
.launch_q8_quantize(k.function, 3, &mut args);
context.complete_launch(launch, args, guard).unwrap();
assert_eq!(download(&status), [0; 4]);
let result = download(&q);
status.release().unwrap();
q.release().unwrap();
result
}
// Restoration happens on panic too; never let two actual allocations drop the same handle.
struct Alias<'a, 'c> {
workspace: &'a mut MmqWorkspace<'c>,
saved: Option<ffi::BufferHandle>,
}
impl Drop for Alias<'_, '_> {
fn drop(&mut self) {
self.workspace.buffers[CHUNK].as_mut().unwrap().handle = self.saved;
}
}
#[test]
#[ignore = "root-only actual expert215 T2 native transport diagnostic; no quality gate"]
fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() {
assert_eq!(
std::env::var("LELEKA_RUN_REAL_NATIVE_D4").as_deref(),
Ok("yes")
);
let [data, gate, up, down] = fixture();
// Exact independent raw expert slices, not a whole-model provenance claim.
for (b, sha) in [
(
&gate,
"fd6f70d60c177b98b30e194c68323a30a4b6c2cb2599ba85f3ab1a73ae6338aa",
),
(
&up,
"228f1c166face5f392c4f52f33dc5c68194c6c2bc12a451d29f58a690d09ffd4",
),
(
&down,
"c02a439a67cca4fe52c303595e8d5aa38ad4734c11d9e95ffe159ad563ff5b75",
),
] {
assert_eq!(digest(b), sha);
}
let root = PathBuf::from(std::env::var("LELEKA_REAL_GU_OUTPUT_DIR").unwrap());
assert!(root.is_absolute() && !root.exists());
assert_eq!(
root.parent().unwrap().canonicalize().unwrap(),
root.parent().unwrap()
);
DirBuilder::new().mode(0o700).create(&root).unwrap();
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
// Foreign context outlives every operand and loan in the test.
let foreign = device.create_context(4 * 1024 * 1024).unwrap();
let context = device.create_context(32 * 1024 * 1024).unwrap();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let weights = [
context.mmq_weights(MmqFormat::Iq3XxsGateUp, &gate).unwrap(),
context.mmq_weights(MmqFormat::Iq3XxsGateUp, &up).unwrap(),
context.mmq_weights(MmqFormat::Iq4NlDown, &down).unwrap(),
];
let immutable_weights: Vec<_> = weights
.iter()
.map(|w| download(w.native_buffer().unwrap()))
.collect();
for (actual, raw) in immutable_weights.iter().zip([&gate, &up, &down]) {
assert_eq!(&actual[..raw.len()], raw);
assert!(actual[raw.len()..].iter().all(|v| *v == 0));
}
let mut native = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
let mut native_gu_q8 = Vec::new();
let mut native_down_q8 = Vec::new();
// Native FIRST: both genuine scalar GU, original SwiGLU, scalar Down, full finite reads.
for row in 0..2 {
let input = upload(&context, &data[row * 10240..(row + 1) * 10240]);
let prepared = context.prepare_routed_gate_up_q8(&input).unwrap();
native_gu_q8.extend(download(prepared.scratch.as_ref().unwrap()));
let mut outputs = [
context.allocate(2560).unwrap(),
context.allocate(2560).unwrap(),
];
for i in 0..2 {
weights[i]
.native_gate_up_prepared(&prepared, &mut outputs[i])
.unwrap();
let b = download(&outputs[i]);
assert!(finite_f32(&b));
native[i].extend(b);
}
let mut hidden = context.allocate(2560).unwrap();
context
.moe_swiglu_f32(&outputs[0], &outputs[1], &mut hidden)
.unwrap();
let b = download(&hidden);
assert!(finite_f32(&b));
native[2].extend(b);
native_down_q8.extend(native_hidden_q8(&context, &hidden));
let mut output = context.allocate(10240).unwrap();
weights[2].native_q8_1(&hidden, &mut output).unwrap();
let b = download(&output);
assert!(finite_f32(&b));
native[3].extend(b);
assert_eq!(download(&input), data[row * 10240..(row + 1) * 10240]);
for b in outputs.into_iter().chain([hidden, output]) {
b.release().unwrap();
}
prepared.close().unwrap();
input.release().unwrap();
}
let mut w = context.native_mmq_workspace().unwrap();
let mut original = context.mmq_workspace().unwrap();
assert_eq!(w.allocated_bytes() - original.allocated_bytes(), 184320);
let gu_layout = MmqFormat::Iq3XxsGateUp.layout(2).unwrap();
let down_layout = MmqFormat::Iq4NlDown.layout(2).unwrap();
assert_eq!((gu_layout.payload, gu_layout.packed), (5760, 14976));
assert_eq!((down_layout.payload, down_layout.packed), (2304, 11520));
let source = floats(&data);
{
let mut chunk = w.prepare_gate_up_chunk(&source, 2).unwrap();
let packed = prefix(chunk.workspace.buffer(CHUNK).unwrap(), 14976);
let q = prefix(
chunk
.workspace
.native_activation
.as_ref()
.unwrap()
.buffer()
.unwrap(),
5760,
);
assert_eq!(q, native_gu_q8);
associate(&q, &packed, 2560);
write_file(&root, "gu.native_q8.bin", &q);
write_file(&root, "gu.native_d4.bin", &packed);
let group = chunk.gather_gate_up(&[0, 1]).unwrap();
assert_eq!(
prefix(group.workspace.buffer(GROUP).unwrap(), 14976),
packed
);
let hidden = group.gate_up(&weights[0], &weights[1]).unwrap();
for (slot, name) in [(GATE, "gate"), (UP, "up"), (HIDDEN, "hidden")] {
let b = prefix(hidden.workspace.buffer(slot).unwrap(), 5120);
assert!(finite_f32(&b));
write_file(&root, &format!("{name}.native_compatible.f32"), &b);
}
let output = hidden.down(&weights[2]).unwrap();
let b = prefix(output.workspace.buffer(DOWN).unwrap(), 20480);
assert!(finite_f32(&b));
write_file(&root, "down_chain.native_compatible.f32", &b);
}
{
let mut chunk = original.prepare_gate_up_chunk(&source, 2).unwrap();
let oldq = prefix(chunk.workspace.buffer(CHUNK).unwrap(), 14976);
assert!(oldq[5760..].iter().all(|v| *v == 0));
write_file(&root, "gu.original_d4.bin", &oldq);
let hidden = chunk
.gather_gate_up(&[0, 1])
.unwrap()
.gate_up(&weights[0], &weights[1])
.unwrap();
for (slot, name) in [(GATE, "gate"), (UP, "up"), (HIDDEN, "hidden")] {
let b = prefix(hidden.workspace.buffer(slot).unwrap(), 5120);
assert!(finite_f32(&b));
write_file(&root, &format!("{name}.original_d4.f32"), &b);
}
let output = hidden.down(&weights[2]).unwrap();
let b = prefix(output.workspace.buffer(DOWN).unwrap(), 20480);
assert!(finite_f32(&b));
write_file(&root, "down_chain.original_d4.f32", &b);
}
// Same native-hidden isolation uses only an actual raw scratch upload + private numeric helpers.
// No MmqHidden product is forged from host data.
for (workspace, arm) in [
(&mut w, "native_compatible"),
(&mut original, "original_d4"),
] {
workspace.buffers[HIDDEN]
.as_mut()
.unwrap()
.copy_from_range(0, &native[2])
.unwrap();
workspace.quantize(HIDDEN, DOWN_Q8, down_layout).unwrap();
let packed = prefix(workspace.buffer(DOWN_Q8).unwrap(), 11520);
assert!(packed[2304..].iter().all(|v| *v == 0));
if arm == "native_compatible" {
let q = prefix(
workspace
.native_activation
.as_ref()
.unwrap()
.buffer()
.unwrap(),
1440,
);
assert_eq!(q, native_down_q8);
associate(&q, &packed, 640);
write_file(&root, "down.native_q8.bin", &q);
}
write_file(&root, &format!("down.{arm}.d4.bin"), &packed);
workspace.project(&weights[2], DOWN_Q8, DOWN, 2).unwrap();
let b = prefix(workspace.buffer(DOWN).unwrap(), 20480);
assert!(finite_f32(&b));
write_file(&root, &format!("down_same_source.{arm}.f32"), &b);
}
let mut metrics = String::new();
for (i, role) in ["gate", "up", "hidden", "down_chain"]
.into_iter()
.enumerate()
{
write_file(&root, &format!("{role}.native.f32"), &native[i]);
for arm in ["native_compatible", "original_d4"] {
let b = read(&root.join(format!("{role}.{arm}.f32")), native[i].len());
metrics.push_str(&measure(2, role, arm, &native[i], &b));
}
}
for arm in ["native_compatible", "original_d4"] {
let b = read(&root.join(format!("down_same_source.{arm}.f32")), 20480);
metrics.push_str(&measure(2, "down_same_source", arm, &native[3], &b));
}
// Closed new-policy guards, all before any output publication.
assert!(matches!(
w.prepare_gate_up_chunk(&source, 0),
Err(Error::InvalidProjectionShape)
));
assert!(matches!(
w.prepare_gate_up_chunk(&source, 65),
Err(Error::InvalidProjectionShape)
));
assert!(matches!(
w.prepare_gate_up_chunk(&source[..source.len() - 1], 2),
Err(Error::InvalidQ8Activation)
));
let foreign_weights = foreign.mmq_weights(MmqFormat::Iq3XxsGateUp, &gate).unwrap();
assert_eq!(
w.project(&foreign_weights, CHUNK, GATE, 2),
Err(Error::ContextMismatch)
);
foreign_weights.close().unwrap();
let saved = w.buffers[CHUNK].as_ref().unwrap().handle;
w.buffers[CHUNK].as_mut().unwrap().handle = w.buffers[INPUT].as_ref().unwrap().handle;
{
let alias = Alias {
workspace: &mut w,
saved,
};
assert_eq!(
alias.workspace.quantize(INPUT, CHUNK, gu_layout),
Err(Error::OutputAliasesInput)
);
}
// Actual late device NaN: native status admission refuses, context stays unpoisoned.
for (slot, packed, layout, valid) in [
(INPUT, CHUNK, gu_layout, &data),
(HIDDEN, DOWN_Q8, down_layout, &native[2]),
] {
let mut bad = valid.to_vec();
let n = bad.len();
bad[n - 4..].copy_from_slice(&f32::NAN.to_le_bytes());
w.buffers[slot]
.as_mut()
.unwrap()
.copy_from_range(0, &bad)
.unwrap();
assert_eq!(
w.quantize(slot, packed, layout),
Err(Error::InvalidQ8Activation)
);
assert!(!context.is_poisoned());
w.buffers[slot]
.as_mut()
.unwrap()
.copy_from_range(0, valid)
.unwrap();
w.quantize(slot, packed, layout).unwrap();
}
let small = device.create_context(184319).unwrap();
assert!(matches!(
small.native_mmq_workspace(),
Err(Error::BudgetExceeded)
));
assert_eq!(small.allocated_bytes(), 0);
small.close().unwrap();
assert_eq!(prefix(w.buffer(INPUT).unwrap(), 20480), data);
w.close().unwrap();
original.close().unwrap();
for (weight, before) in weights.into_iter().zip(immutable_weights) {
assert_eq!(download(weight.native_buffer().unwrap()), before);
weight.close().unwrap();
}
write_file(&root, "DIAGNOSTICS.jsonl", metrics.as_bytes());
}));
let sync = context.synchronize();
let allocated = context.allocated_bytes();
let closed = context.close();
let foreign_allocated = foreign.allocated_bytes();
let foreign_closed = foreign.close();
if let Err(panic) = result {
std::panic::resume_unwind(panic);
}
sync.unwrap();
assert_eq!(allocated, 0);
closed.unwrap();
assert_eq!(foreign_allocated, 0);
foreign_closed.unwrap();
write_file(&root,"COMPLETE.json",b"{\"completed\":true,\"rows\":2,\"association_codes\":6400,\"association_scales\":200,\"guards\":8,\"diagnostic_pairs\":10,\"allocated\":0,\"quality_pass\":false,\"model_gate_b_pass\":false}\n");
}
+418
View File
@@ -0,0 +1,418 @@
//! Ignored original-first MMQ proof. References are produced and pinned by ROOT.
use super::*;
use std::collections::BTreeMap;
use std::fs::OpenOptions;
use std::io::Read;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
use std::path::{Component, Path, PathBuf};
const SOURCE_SHA: &str = "a0134e0ac281d743089c54b09a3c221e645cc09a0a7a19041822230c3951ed7d";
const UPSTREAM: &str = "3cf03257f219afbe7334045ff7c6a06ac68c627d";
const CASE_FILES: [&str; 7] = [
"weights.bin",
"input.f32",
"reference_q8.bin",
"reference_streamk.f32",
"reference_fixed_j64_streamk.f32",
"reference_tiling.f32",
"metadata.json",
];
const BUDGET: usize = 32 * 1024 * 1024;
fn digest(bytes: &[u8]) -> String {
use std::fmt::Write;
let mut out = String::with_capacity(64);
for byte in qwen_ffi::sha256(bytes) {
write!(&mut out, "{byte:02x}").unwrap();
}
out
}
fn hex(value: &str) {
assert_eq!(value.len(), 64, "SHA256 length");
assert!(
value
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
"SHA256 encoding"
);
}
fn read_regular(path: &Path, limit: usize) -> Vec<u8> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
.expect("open pinned regular file");
let before = file.metadata().unwrap();
assert!(
before.is_file() && before.len() <= limit as u64,
"bounded regular fixture"
);
let mut bytes = Vec::new();
file.by_ref()
.take(limit as u64 + 1)
.read_to_end(&mut bytes)
.unwrap();
let after = file.metadata().unwrap();
assert_eq!(
(before.dev(), before.ino(), before.len()),
(after.dev(), after.ino(), after.len())
);
assert_eq!(bytes.len() as u64, before.len(), "fixture changed length");
bytes
}
struct Pin {
bytes: usize,
sha: String,
}
struct Receipt {
root: PathBuf,
files: BTreeMap<String, Pin>,
}
impl Receipt {
fn load(root: PathBuf, expected: &str) -> Self {
hex(expected);
assert!(root.is_absolute());
assert_eq!(
root.canonicalize().unwrap(),
root,
"canonical fixture directory"
);
let bytes = read_regular(&root.join("ROOT-REFERENCE.tsv"), 64 * 1024);
assert_eq!(digest(&bytes), expected, "ROOT manifest pin");
let text = std::str::from_utf8(&bytes).unwrap();
let mut headers = BTreeMap::new();
let mut files = BTreeMap::new();
for line in text.lines() {
let fields: Vec<_> = line.split('\t').collect();
match fields.as_slice() {
["file", name, length, sha] => {
assert!(
Path::new(name)
.components()
.all(|c| matches!(c, Component::Normal(_)))
);
hex(sha);
let bytes: usize = length.parse().unwrap();
assert!(bytes > 0 && bytes <= 64 * 1024 * 1024);
assert!(
files
.insert(
(*name).to_owned(),
Pin {
bytes,
sha: (*sha).to_owned()
}
)
.is_none(),
"duplicate file"
);
}
[key, value] => {
assert!(headers.insert(*key, *value).is_none(), "duplicate header");
}
_ => panic!("closed ROOT manifest record"),
}
}
assert_eq!(headers.len(), 6);
for (key, value) in [
("schema", "stra169-mmq-reference-v1"),
("upstream", UPSTREAM),
("source_sha", SOURCE_SHA),
("nvcc", "12.8.93"),
("profile", "sm120-fastmath-adaptive-original-first"),
("cases", "12"),
] {
assert_eq!(
headers.get(key).copied(),
Some(value),
"ROOT provenance {key}"
);
}
let mut allowed = vec![
"COMPLETE.json".to_owned(),
"original_mmq_oracle".to_owned(),
"ORACLE-SOURCE-MANIFEST.json".to_owned(),
];
for kind in [18, 22, 20, 42] {
for tokens in [4, 16, 64] {
for name in CASE_FILES {
allowed.push(format!("type{kind}-t{tokens}/{name}"));
}
}
}
allowed.sort();
assert_eq!(
files.keys().cloned().collect::<Vec<_>>(),
allowed,
"exact 87 pinned files"
);
let receipt = Self { root, files };
for name in receipt.files.keys() {
let _ = receipt.read(name);
}
assert_eq!(
digest(&receipt.read("ORACLE-SOURCE-MANIFEST.json")),
SOURCE_SHA
);
assert!(receipt.read("original_mmq_oracle").starts_with(b"\x7fELF"));
let complete = String::from_utf8(receipt.read("COMPLETE.json")).unwrap();
for (key, value) in [
("schema", "1"),
("cases", "12"),
("original_first", "true"),
("sm_major", "12"),
("sm_minor", "0"),
("host_admission_guards", "5"),
] {
assert_eq!(field(&complete, key), value);
}
assert!(complete.contains("\"original_adaptive_streamk_primary\""));
assert!(complete.contains("\"fixed_j64_streamk\""));
receipt
}
fn read(&self, name: &str) -> Vec<u8> {
let pin = self.files.get(name).expect("closed pinned fixture");
let bytes = read_regular(&self.root.join(name), pin.bytes);
assert_eq!(bytes.len(), pin.bytes);
assert_eq!(digest(&bytes), pin.sha, "fixture SHA {name}");
bytes
}
}
fn field<'a>(json: &'a str, key: &str) -> &'a str {
let needle = format!("\"{key}\":");
assert_eq!(json.matches(&needle).count(), 1, "unique metadata key");
json.split_once(&needle)
.unwrap()
.1
.trim_start()
.split([',', '}'])
.next()
.unwrap()
.trim()
}
fn integer(json: &str, key: &str) -> usize {
field(json, key).parse().unwrap()
}
fn finite(bytes: &[u8]) {
let (words, tail) = bytes.as_chunks::<4>();
assert!(tail.is_empty());
assert!(
words.iter().all(|v| f32::from_le_bytes(*v).is_finite()),
"full finite reference"
);
}
fn compare(values: &[f32], reference: &[u8], label: &str) {
let (words, tail) = reference.as_chunks::<4>();
assert!(tail.is_empty());
assert_eq!(values.len(), words.len());
for (index, (actual, expected)) in values.iter().zip(words).enumerate() {
assert!(actual.is_finite());
assert_eq!(
actual.to_bits(),
u32::from_le_bytes(*expected),
"{label} word {index}"
);
}
}
struct Case {
tokens: u32,
input: Vec<u8>,
q8: Vec<u8>,
adaptive: Vec<u8>,
fixed: Vec<u8>,
metadata: String,
}
fn cases(
receipt: &Receipt,
kind: u32,
rows: usize,
columns: usize,
raw: usize,
tail: usize,
) -> (Vec<u8>, Vec<Case>) {
let weights = receipt.read(&format!("type{kind}-t4/weights.bin"));
assert_eq!(weights.len(), raw);
let mut cases = Vec::new();
for tokens in [4_u32, 16, 64] {
let prefix = format!("type{kind}-t{tokens}");
let read = |name| receipt.read(&format!("{prefix}/{name}"));
assert_eq!(read("weights.bin"), weights, "same matrix once per format");
let input = read("input.f32");
let q8 = read("reference_q8.bin");
let adaptive = read("reference_streamk.f32");
let fixed = read("reference_fixed_j64_streamk.f32");
let metadata = String::from_utf8(read("metadata.json")).unwrap();
let padded = columns.div_ceil(512) * 512;
let selected_j = (tokens as usize).max(8);
let shared = 40992 + (selected_j - 8) * 132 + usize::from(kind == 22) * 4096;
for (key, expected) in [
("type", kind as usize),
("k", columns),
("m", rows),
("tokens", tokens as usize),
("weight_bytes", raw),
("weight_zero_tail", tail),
("q8_bytes", padded / 128 * tokens as usize * 144 + 9216),
("q8_payload_bytes", padded / 128 * tokens as usize * 144),
("q8_zero_tail", 9216),
("original_selected_j", selected_j),
("original_i", 128),
("original_nthreads", 256),
("shared", shared),
("fixed_j64_shared", 48384 + usize::from(kind == 22) * 4096),
] {
assert_eq!(integer(&metadata, key), expected, "metadata {key}");
}
let sms = integer(&metadata, "nsm");
assert!((1..=256).contains(&sms));
let tiles = rows / 128;
let grid = if 100 * tiles / (sms * tiles.div_ceil(sms)) >= 90 {
tiles
} else {
sms
};
for key in ["original_streamk_grid", "fixed_j64_streamk_grid"] {
assert_eq!(integer(&metadata, key), grid);
}
for key in ["original_streamk_fixup", "fixed_j64_streamk_fixup"] {
assert_eq!(
field(&metadata, key),
if tiles.is_multiple_of(grid) {
"false"
} else {
"true"
}
);
}
assert_eq!(integer(&metadata, "auxiliary_tiling_grid"), tiles);
for key in [
"original_first",
"input_column_major",
"inputs_weights_unchanged",
"model_free",
] {
assert_eq!(field(&metadata, key), "true");
}
assert_eq!(input.len(), columns * tokens as usize * 4);
finite(&input);
assert_eq!(adaptive.len(), rows * tokens as usize * 4);
finite(&adaptive);
assert_eq!(fixed.len(), adaptive.len());
finite(&fixed);
finite(&read("reference_tiling.f32"));
assert_eq!(q8.len(), padded / 128 * tokens as usize * 144 + 9216);
assert!(q8[q8.len() - 9216..].iter().all(|b| *b == 0));
for block in q8[..q8.len() - 9216].as_chunks::<144>().0 {
finite(&block[..16]);
}
cases.push(Case {
tokens,
input,
q8,
adaptive,
fixed,
metadata,
});
}
(weights, cases)
}
#[test]
#[ignore = "ROOT-only original-first pinned reference; actual CUDA, never automatic suite"]
fn original_first_mmq_adaptive_and_distinct_fixed_profiles_exact() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(),
Ok("yes"),
"explicit GPU opt-in"
);
let root = PathBuf::from(
std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").expect("ROOT reference directory"),
);
let pin =
std::env::var("LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA").expect("ROOT reference pin");
let receipt = Receipt::load(root, &pin);
let inputs: Vec<_> = [
(18, MmqFormat::Iq3XxsGateUp, 640, 2560, 627200, 0),
(22, MmqFormat::Iq2SGateUp, 640, 2560, 524800, 0),
(20, MmqFormat::Iq4NlDown, 2560, 640, 921600, 216),
(42, MmqFormat::Q2Down, 2560, 640, 460800, 108),
]
.map(|(kind, format, rows, columns, raw, tail)| {
(format, cases(&receipt, kind, rows, columns, raw, tail))
})
.into();
let driver = Driver::load().unwrap();
let context = driver.device(0).unwrap().create_context(BUDGET).unwrap();
let experiment = context.mmq_experiment().unwrap();
assert!(
(1..=256).contains(&experiment.sms),
"closed fixture SM budget"
);
let mut words = 0_usize;
let mut packed_bytes = 0_usize;
let mut launches = 0_usize;
for (format, (raw, cases)) in inputs {
let weights = experiment.weights(format, &raw).unwrap();
let wb = weights.buffer.as_ref().unwrap();
let mut before = vec![0; wb.bytes];
wb.copy_to(&mut before).unwrap();
assert_eq!(&before[..raw.len()], raw);
assert!(before[raw.len()..].iter().all(|b| *b == 0));
for case in cases {
assert_eq!(integer(&case.metadata, "nsm"), experiment.sms as usize);
let mut input = context.allocate(case.input.len()).unwrap();
input.copy_from(&case.input).unwrap();
let mut output = context.allocate(case.adaptive.len()).unwrap();
for (profile, reference) in [
(MmqProfile::OriginalAdaptive, &case.adaptive),
(MmqProfile::OriginalStreamK, &case.fixed),
] {
if profile == MmqProfile::OriginalStreamK && case.tokens == 64 {
continue;
}
output.copy_from(&vec![0xff; reference.len()]).unwrap();
let charge = context.allocated_bytes();
let (values, q8) = experiment
.project_observed(profile, &weights, &input, case.tokens, &mut output)
.unwrap();
assert_eq!(&*q8, case.q8.as_slice(), "complete original D4Q8 bytes");
compare(&values, reference, "MMQ exact original profile");
let mut actual = vec![0; reference.len()];
output.copy_to(&mut actual).unwrap();
assert_eq!(&actual, reference);
assert_eq!(
context.allocated_bytes(),
charge,
"all projection scratch freed"
);
let mut source_after = vec![0; case.input.len()];
input.copy_to(&mut source_after).unwrap();
assert_eq!(source_after, case.input);
let mut weights_after = vec![0; before.len()];
wb.copy_to(&mut weights_after).unwrap();
assert_eq!(weights_after, before);
packed_bytes += q8.len();
words += values.len();
launches += 1;
}
let mut actual = vec![0; case.input.len()];
input.copy_to(&mut actual).unwrap();
assert_eq!(actual, case.input);
let mut after = vec![0; before.len()];
wb.copy_to(&mut after).unwrap();
assert_eq!(after, before);
output.release().unwrap();
input.release().unwrap();
}
weights.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
experiment.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
assert!(!context.is_poisoned());
context.close().unwrap();
assert_eq!((launches, words, packed_bytes), (20, 665600, 1022976));
println!(
"MMQ original-first exact: 12adaptive+8distinct-fixed profiles, {words}F32words/{packed_bytes}Q8bytes, allocated0"
);
}
@@ -0,0 +1,223 @@
//! Private closed on-stream ABI for Original prompt grouping. Registered as a
//! child of ffi: only admitted real MMQ modules/arguments can reach these calls.
use super::{
BufferHandle, FunctionHandle, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments,
MmqOriginalSwigluArguments, MmqQuantArguments, MmqResidentArguments,
};
use crate::mmq::Layout;
use crate::{Error, Result};
/// Each variant retains the same fixed owned ABI as the old synchronous entry.
/// No public caller can supply an arbitrary function, raw parameter list or grid.
pub(crate) enum Command {
Gather(FunctionHandle, u32, MmqOriginalGatherArguments),
Helper(FunctionHandle, u32, MmqResidentArguments),
Swiglu(FunctionHandle, u32, MmqOriginalSwigluArguments),
Quantize(FunctionHandle, Layout, MmqQuantArguments),
Project(FunctionHandle, Layout, u32, MmqArguments),
Fixup(FunctionHandle, u32, MmqFixupArguments),
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod platform {
use super::*;
use std::ffi::{CStr, c_void};
type Handle = *mut c_void;
type Launch = unsafe extern "C" fn(
Handle,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
Handle,
*mut *mut c_void,
*mut *mut c_void,
) -> i32;
type H2D = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32;
struct Library(Handle);
impl Drop for Library {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
libc::dlclose(self.0);
}
}
}
}
pub(crate) struct Api {
_library: Library,
launch: Launch,
copy: H2D,
}
fn check(name: &'static str, n: i32) -> Result<()> {
if n == 0 {
Ok(())
} else {
Err(Error::Driver {
operation: name,
code: n,
})
}
}
impl Api {
pub(crate) fn load() -> Result<Self> {
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);
}
fn symbol(l: &Library, n: &'static CStr) -> Result<Handle> {
let p = unsafe { libc::dlsym(l.0, n.as_ptr()) };
if p.is_null() {
Err(Error::MissingSymbol(
n.to_str().unwrap_or("Original ring symbol"),
))
} else {
Ok(p)
}
}
let launch = unsafe {
std::mem::transmute::<Handle, Launch>(symbol(&library, c"cuLaunchKernel")?)
};
let copy = unsafe {
std::mem::transmute::<Handle, H2D>(symbol(&library, c"cuMemcpyHtoDAsync_v2")?)
};
Ok(Self {
_library: library,
launch,
copy,
})
}
/// Sources are the actual registered immutable bank slices, retained by
/// the ring owner until used/drain. Destination is a real arena slot.
pub(crate) fn copy_registered(
&self,
destination: BufferHandle,
source: &[u8],
stream: usize,
) -> Result<()> {
if stream == 0 || source.is_empty() {
return Err(Error::InvalidProjectionShape);
}
destination.validate_projection_extent(source.len(), 16)?;
check("cuMemcpyHtoDAsync_v2", unsafe {
(self.copy)(
destination.0,
source.as_ptr().cast(),
source.len(),
stream as Handle,
)
})
}
pub(crate) fn enqueue(&self, command: &mut Command, stream: usize) -> Result<()> {
if stream == 0 {
return Err(Error::InvalidProjectionShape);
}
let (f, gx, gy, bx, by, shared, parameters) = match command {
Command::Gather(f, words, a) => {
if *words == 0 || *words > 172800 {
return Err(Error::InvalidProjectionShape);
}
(*f, words.div_ceil(256), 1, 256, 1, 0, a.parameters())
}
Command::Helper(f, words, a) => {
if *words == 0 || *words > 209715200 {
return Err(Error::InvalidProjectionShape);
}
(*f, words.div_ceil(256), 1, 256, 1, 0, a.parameters())
}
Command::Swiglu(f, rows, a) => {
if !(1..=81920).contains(rows) {
return Err(Error::InvalidProjectionShape);
}
(
*f,
(*rows * 640).div_ceil(256),
1,
256,
1,
0,
a.parameters(),
)
}
Command::Quantize(f, l, a) => {
if l.tokens == 0 || l.tokens > 81920 || !l.padded_columns.is_multiple_of(512) {
return Err(Error::InvalidProjectionShape);
}
(
*f,
l.tokens,
l.padded_columns / 512,
128,
1,
0,
a.parameters(),
)
}
Command::Project(f, l, grid, a) => {
if *grid == 0 {
return Err(Error::InvalidProjectionShape);
}
(*f, *grid, 1, 32, 8, l.shared, a.parameters())
}
Command::Fixup(f, grid, a) => {
if *grid == 0 {
return Err(Error::InvalidProjectionShape);
}
(*f, *grid, 4, 32, 4, 0, a.parameters())
}
};
// Same literal launch geometries/owned ABI as ffi.rs old methods;
// only the genuine private scheduling stream replaces null/default.
check("cuLaunchKernel", unsafe {
(self.launch)(
f.0 as Handle,
gx,
gy,
1,
bx,
by,
1,
shared,
stream as Handle,
parameters,
std::ptr::null_mut(),
)
})
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) use platform::Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) struct Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
impl Api {
pub(crate) fn load() -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_registered(&self, _: BufferHandle, _: &[u8], _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn enqueue(&self, _: &mut Command, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
@@ -0,0 +1,118 @@
// Explicit instantiations only; all device bodies are the unchanged pinned
// llama.cpp/ggml 3cf03257f219afbe7334045ff7c6a06ac68c627d mmq.cuh.
// ROOT-only CUDA12.8.93/sm120 --use_fast_math compilation; no serving entry.
#include "mmq.cuh"
static_assert(int(GGML_TYPE_IQ3_S) == 21 && int(GGML_TYPE_IQ4_XS) == 23);
static_assert(sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
@@ -0,0 +1,76 @@
// Explicit instantiations only; all device bodies are the unchanged pinned
// llama.cpp/ggml 3cf03257f219afbe7334045ff7c6a06ac68c627d mmq.cuh.
// ROOT-only CUDA12.8.93/sm120 --use_fast_math compilation; no serving entry.
#include "mmq.cuh"
static_assert(int(GGML_TYPE_IQ3_S) == 21 && int(GGML_TYPE_IQ4_XS) == 23);
static_assert(sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,335 @@
// Exact explicit instantiations: unchanged pinned llama.cpp 3cf03257 kernel bodies.
// Source only; ROOT must compile CUDA12.8.93 sm120 --use_fast_math and seal actual bytes.
#include "mmq.cuh"
static_assert(int(GGML_TYPE_IQ3_XXS)==18 && int(GGML_TYPE_IQ2_S)==22 && int(GGML_TYPE_IQ3_S)==21);
static_assert(int(GGML_TYPE_IQ4_XS)==23 && int(GGML_TYPE_IQ4_NL)==20 && int(GGML_TYPE_Q2_0)==42);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_XXS, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ2_S, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ3_S, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_XS, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_IQ4_NL, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 8, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 16, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 24, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 32, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 40, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 48, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 64, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 80, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 96, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 112, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
template __global__ void mul_mat_q_stream_k_fixup<GGML_TYPE_Q2_0, 128, false>(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
const int stride_sample_dst, const uint3 ntx);
Binary file not shown.
@@ -0,0 +1,533 @@
// Exact explicit instantiations: unchanged pinned llama.cpp 3cf03257 kernel bodies.
// Source only; ROOT must compile CUDA12.8.93 sm120 --use_fast_math and seal actual bytes.
#include "mmq.cuh"
static_assert(int(GGML_TYPE_IQ3_XXS)==18 && int(GGML_TYPE_IQ2_S)==22 && int(GGML_TYPE_IQ3_S)==21);
static_assert(int(GGML_TYPE_IQ4_XS)==23 && int(GGML_TYPE_IQ4_NL)==20 && int(GGML_TYPE_Q2_0)==42);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_XXS, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ2_S, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ3_S, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_XS, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_IQ4_NL, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 8, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 16, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 24, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 32, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 40, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 48, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 64, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 80, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 96, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 112, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
template __global__ void mul_mat_q<GGML_TYPE_Q2_0, 128, false>(
const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const float * __restrict__ y_scale,
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const uint3 ntx);
Binary file not shown.
@@ -0,0 +1,29 @@
#include <cuda_runtime.h>
// Literal prefill/moe_mmq.cu swiglu_kernel; only export name changes.
extern "C" __global__ void leleka_original_mmq_swiglu(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff, bool interleaved) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= rows * n_ff) return;
const int64_t r = i / n_ff, k = i % n_ff;
const float* row = gu + r * 2 * n_ff;
const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k];
h[i] = g / (1.0f + __expf(-g)) * u;
}
// Literal Original gather_native aligned branch (copy16_kernel export only).
extern "C" __global__ void leleka_original_mmq_gather(const uint4* __restrict__ a, int64_t na,
const uint4* __restrict__ b, int64_t nb, uint4* __restrict__ ab_dst,
const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i < na) ab_dst[i] = a[i];
else if (i < na + nb) ab_dst[i] = b[i - na];
else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb];
}
// Required whole numerical guard: no arithmetic, no masks or sampling.
// Separate Gate/Up bits preserve source-order numerical refusal precedence.
extern "C" __global__ void leleka_original_mmq_gu_finite(const unsigned* source,
unsigned* status,unsigned mode,unsigned amount,unsigned tail) {
const unsigned i=blockIdx.x*blockDim.x+threadIdx.x;
if(i<amount && (source[i]&0x7f800000u)==0x7f800000u)
atomicOr(status,i%1280u<640u?1u:2u);
}
Binary file not shown.
+643
View File
@@ -0,0 +1,643 @@
//! Literal Original ordinary-walk copy ring, prefill.cpp1693–1830. The actual
//! arena row loan, registered source bank and all stable ABI owners outlive work.
use super::*;
use crate::ffi::original_enqueue::{Api, Command};
use crate::original_gpu_schedule::{
OriginalEventKind, OriginalGpuEvent, OriginalGpuStream, OriginalStreamKind,
};
use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole};
use std::rc::Rc;
const COMMAND_CAP: usize = 2048;
trait RingArena: GroupArena {
fn stage_slots(&self) -> Result<usize>;
fn stage_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)>;
fn cache_span(&self, layer: usize, expert: usize)
-> Result<Option<(ffi::BufferHandle, usize)>>;
fn matches_context(&self, c: &Context<'_>) -> bool;
}
impl RingArena for crate::OriginalDeviceGrRead<'_, '_, '_> {
fn stage_slots(&self) -> Result<usize> {
self.lease().copy_ring_slots()
}
fn stage_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> {
self.lease().copy_ring_span(index)
}
fn cache_span(&self, l: usize, e: usize) -> Result<Option<(ffi::BufferHandle, usize)>> {
self.lease().cache_expert_span(l, e)
}
fn matches_context(&self, c: &Context<'_>) -> bool {
self.context_matches(c) && !self.lease().is_failed()
}
}
struct Slot {
span: ffi::BufferHandle,
bytes: usize,
live: bool,
gathered: bool,
}
struct Events<'ctx> {
copied: Option<OriginalGpuEvent<'ctx>>,
used: Option<OriginalGpuEvent<'ctx>>,
}
/// Persistent Original Prefill copy/compute streams and copied/used event arrays.
/// The caller supplies the actual physical arena's ring count, not a guessed
/// device/queue capacity. Its exclusive borrow spans every whole layer drain.
pub struct OriginalMmqCopySchedule<'ctx> {
context: &'ctx Context<'ctx>,
api: Option<Rc<Api>>,
copy: Option<OriginalGpuStream<'ctx>>,
compute: Option<OriginalGpuStream<'ctx>>,
events: Vec<Events<'ctx>>,
failed: bool,
closed: bool,
host_metadata_outside: usize,
}
impl Context<'_> {
pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result<OriginalMmqCopySchedule<'_>> {
if !(8..=512).contains(&slots) {
return Err(Error::InvalidProjectionShape);
}
if self.is_poisoned() {
return Err(Error::ContextPoisoned);
}
let mut owner = OriginalMmqCopySchedule {
context: self,
api: None,
copy: None,
compute: None,
events: Vec::new(),
failed: false,
closed: false,
host_metadata_outside: 0,
};
let result = (|| {
owner
.events
.try_reserve_exact(slots)
.map_err(|_| Error::HostAllocation)?;
if owner.metadata_bytes()? > 16 * 1024 * 1024 {
return Err(Error::BudgetExceeded);
}
owner.api = Some(Rc::new(Api::load()?));
owner.copy = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
owner.compute = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
for _ in 0..slots {
owner.events.push(Events {
copied: None,
used: None,
});
let e = owner.events.last_mut().ok_or(Error::ContextPoisoned)?;
e.copied = Some(self.original_gpu_event(OriginalEventKind::Completion)?);
e.used = Some(self.original_gpu_event(OriginalEventKind::Completion)?);
}
// Opaque driver stream/event residency is not called zero bytes;
// physical headroom is queried after creation before profile fills.
if self
.allocated_bytes()
.checked_add(128 * 1024 * 1024)
.is_none_or(|n| n > self.budget)
|| self.memory_info()?.0 < 128 * 1024 * 1024
{
return Err(Error::BudgetExceeded);
}
Ok(())
})();
if let Err(primary) = result {
return combine(Err(primary), owner.close_inner());
}
Ok(owner)
}
}
impl OriginalMmqCopySchedule<'_> {
/// Byte accounting only: the real caller computes retained bank, source
/// vector and current router-layer capacities before this exclusive loan.
pub fn retain_host_metadata_charge(&mut self, bytes: usize) -> Result<()> {
if self.is_failed() {
return Err(Error::ContextPoisoned);
}
if self
.metadata_bytes()?
.checked_add(bytes)
.is_none_or(|n| n > 16 << 20)
{
return Err(Error::BudgetExceeded);
}
self.host_metadata_outside = bytes;
Ok(())
}
pub fn ring_slots(&self) -> usize {
self.events.len()
}
/// Bounded Rust metadata includes conservative actual private event/API/Rc
/// storage. CUDA's opaque residency remains actual physical room, not zero.
pub fn metadata_bytes(&self) -> Result<usize> {
self.events
.capacity()
.checked_mul(std::mem::size_of::<Events<'_>>() + 1024)
.and_then(|n| n.checked_add(std::mem::size_of::<Self>() + 1024))
.ok_or(Error::BudgetExceeded)
}
pub fn validate_context(&self, c: &Context<'_>) -> Result<()> {
if !std::ptr::eq(c, self.context) {
return Err(Error::ContextMismatch);
}
if self.failed || self.closed || c.is_poisoned() {
return Err(Error::ContextPoisoned);
}
self.copy
.as_ref()
.ok_or(Error::ContextPoisoned)?
.validate_context(c)?;
self.compute
.as_ref()
.ok_or(Error::ContextPoisoned)?
.validate_context(c)
}
pub fn is_failed(&self) -> bool {
self.failed || self.closed || self.context.is_poisoned()
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
if self.closed {
return Ok(());
}
self.closed = true;
let copy = self
.copy
.as_ref()
.map_or(Ok(()), OriginalGpuStream::synchronize);
let compute = self
.compute
.as_ref()
.map_or(Ok(()), OriginalGpuStream::synchronize);
let mut result = combine(copy, compute);
for events in &mut self.events {
if let Some(e) = events.copied.take() {
result = combine(result, e.close());
}
if let Some(e) = events.used.take() {
result = combine(result, e.close());
}
}
if let Some(s) = self.copy.take() {
result = combine(result, s.close());
}
if let Some(s) = self.compute.take() {
result = combine(result, s.close());
}
if result.is_err() {
self.failed = true;
if let Some(api) = self.api.take() {
std::mem::forget(api);
}
}
result
}
}
impl Drop for OriginalMmqCopySchedule<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
struct Source<'read> {
spans: &'read [ResidentExpertBankSpan; 3],
resident: Option<[ffi::BufferHandle; 3]>,
slot: Option<usize>,
}
/// Private owner: no external pointer/ready event can manufacture a stage.
/// The actual source Rc prevents unregister/free during H2D or gathered use.
pub(super) struct Ring<'read, 'ctx> {
context: &'ctx Context<'ctx>,
read: &'read dyn RingArena,
bank: Option<Rc<crate::MappedExpertBank<'ctx>>>,
schedule: &'read mut OriginalMmqCopySchedule<'ctx>,
slots: Vec<Slot>,
sources: Vec<Source<'read>>,
commands: Vec<Command>,
status: Option<DeviceBuffer<'ctx>>,
flags: Vec<u8>,
stage_next: usize,
submitted: bool,
drained: bool,
closed: bool,
}
impl<'read, 'ctx> Ring<'read, 'ctx> {
pub(super) fn new(
context: &'ctx Context<'ctx>,
read: &'read crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
layer: usize,
schedule: &'read mut OriginalMmqCopySchedule<'ctx>,
bank: Rc<crate::MappedExpertBank<'ctx>>,
formats: [MmqFormat; 3],
spans: &'read [[ResidentExpertBankSpan; 3]],
groups: usize,
) -> Result<Self> {
if !read.context_matches(context)
|| !bank.cache_context_matches(context)
|| layer >= 48
|| spans.is_empty()
|| spans.len() > 512
|| groups != spans.len().div_ceil(16)
|| formats[0] != formats[1]
|| !FORMATS[..5].contains(&formats[0])
|| !FORMATS[5..].contains(&formats[2])
{
return Err(Error::InvalidProjectionShape);
}
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let blob = gu
.checked_mul(2)
.and_then(|n| n.checked_add(down))
.ok_or(Error::InvalidSize)?;
let admitted: &dyn RingArena = read;
let count = admitted.stage_slots()?;
schedule.validate_context(context)?;
if schedule.ring_slots() != count {
return Err(Error::InvalidProjectionShape);
}
let mut owner = Self {
context,
read,
bank: Some(bank),
schedule,
slots: Vec::new(),
sources: Vec::new(),
commands: Vec::new(),
status: None,
flags: Vec::new(),
stage_next: 0,
submitted: false,
drained: false,
closed: false,
};
let result = (|| {
owner
.slots
.try_reserve_exact(count)
.map_err(|_| Error::HostAllocation)?;
owner
.sources
.try_reserve_exact(spans.len())
.map_err(|_| Error::HostAllocation)?;
owner
.commands
.try_reserve_exact(COMMAND_CAP)
.map_err(|_| Error::HostAllocation)?;
owner
.flags
.try_reserve_exact(groups * 16)
.map_err(|_| Error::HostAllocation)?;
owner.flags.resize(groups * 16, 0);
// Includes actual fixed ABI storage conservatively (<=512B each),
// plus actual vector capacities; no second unbounded launch list.
if owner
.metadata_bytes()?
.checked_add(owner.schedule.metadata_bytes()?)
.and_then(|n| n.checked_add(owner.schedule.host_metadata_outside))
.is_none_or(|n| n > 16 * 1024 * 1024)
{
return Err(Error::BudgetExceeded);
}
for index in 0..count {
let (h, n) = admitted.stage_span(index)?;
if n < blob {
return Err(Error::InvalidSize);
}
h.validate_projection_extent(n, 256)?;
for slot in &owner.slots {
if h.overlaps(n, slot.span, slot.bytes) {
return Err(Error::OutputAliasesInput);
}
}
for role in 0..TMP {
let (a, n) = GroupArena::span(read, role)?;
if h.overlaps(blob, a, n) {
return Err(Error::OutputAliasesInput);
}
}
owner.slots.push(Slot {
span: h,
bytes: n,
live: false,
gathered: false,
});
}
let bank = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?;
for (i, spans) in spans.iter().enumerate() {
if !bank.eligible(spans)
|| !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==layer)
|| i > 0 && spans[0].expert() <= owner.sources[i - 1].spans[0].expert()
{
return Err(Error::InvalidProjectionShape);
}
for (role, span) in spans.iter().enumerate() {
let actual = bank.cache_source(span)?;
if span.raw_kind() != kind(formats[role])
|| actual.len() != if role < 2 { gu } else { down }
{
return Err(Error::InvalidProjectionShape);
}
}
let resident = admitted
.cache_span(layer, spans[0].expert() as usize)?
.map(|(h, n)| {
if n < blob {
return Err(Error::InvalidSize);
}
Ok([
h.checked_subspan(n, 0, gu)?,
h.checked_subspan(n, gu, gu)?,
h.checked_subspan(n, gu * 2, down)?,
])
})
.transpose()?;
owner.sources.push(Source {
spans,
resident,
slot: None,
});
}
let charge = groups * 16;
let required = charge
.checked_add(128 * 1024 * 1024)
.ok_or(Error::BudgetExceeded)?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
owner.status = Some(context.allocate(charge)?);
// The old input quantization/metadata upload used default stream.
// Admit that dependency once before starting nonblocking producers.
context.synchronize()?;
Ok(())
})();
if let Err(primary) = result {
return combine(Err(primary), owner.close_inner());
}
Ok(owner)
}
pub(super) fn metadata_bytes(&self) -> Result<usize> {
self.slots
.capacity()
.checked_mul(std::mem::size_of::<Slot>())
.and_then(|n| n.checked_add(self.sources.capacity() * std::mem::size_of::<Source>()))
.and_then(|n| {
n.checked_add(self.commands.capacity() * (std::mem::size_of::<Command>() + 512))
})
.and_then(|n| n.checked_add(self.flags.capacity() + std::mem::size_of::<Self>()))
.ok_or(Error::BudgetExceeded)
}
pub(super) fn enqueue(&mut self, command: Command) -> Result<()> {
if self.closed
|| self.commands.len() == COMMAND_CAP
|| !self.read.matches_context(self.context)
{
return Err(Error::InvalidProjectionShape);
}
self.commands.push(command);
self.submitted = true;
self.drained = false;
let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
let command = self.commands.last_mut().ok_or(Error::ContextPoisoned)?;
self.schedule
.compute
.as_mut()
.ok_or(Error::ContextPoisoned)?
.with_enqueue(|stream| api.enqueue(command, stream))
}
pub(super) fn flag(&self, group: usize, stage: usize) -> Result<ffi::BufferHandle> {
if stage >= 4 {
return Err(Error::InvalidProjectionShape);
}
let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(
b.bytes,
group
.checked_mul(16)
.and_then(|n| n.checked_add(stage * 4))
.ok_or(Error::InvalidSize)?,
4,
)
}
pub(super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> {
let source = self
.sources
.get(index)
.ok_or(Error::InvalidProjectionShape)?;
if source.resident.is_some() {
return Ok(());
}
if source.slot.is_some() {
return Err(Error::InvalidProjectionShape);
}
let sl = self.stage_next;
let next = (sl + 1) % self.slots.len();
let slot = &mut self.slots[sl];
let events = &mut self.schedule.events[sl];
let copy = self.schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
if slot.live {
if !slot.gathered {
return Err(Error::InvalidProjectionShape);
}
// Re-recorded copied and used events have the same real source
// streams; the copy stream waits the previous gather before reuse.
events
.used
.as_mut()
.ok_or(Error::ContextPoisoned)?
.wait_on(copy)?;
}
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let sources = [
bank.cache_source(&source.spans[0])?,
bank.cache_source(&source.spans[1])?,
bank.cache_source(&source.spans[2])?,
];
let destinations = [
slot.span.checked_subspan(slot.bytes, 0, gu)?,
slot.span.checked_subspan(slot.bytes, gu, gu)?,
slot.span.checked_subspan(slot.bytes, gu * 2, down)?,
];
self.submitted = true;
self.drained = false;
copy.with_enqueue(|stream| {
// Physical role-major bank layout requires three H2Ds. Same source
// bytes and literal blob G/U/D layout; no decode/conversion/copy tmp.
for (destination, source) in destinations.into_iter().zip(sources) {
api.copy_registered(destination, source, stream)?;
}
Ok(())
})?;
events
.copied
.as_mut()
.ok_or(Error::ContextPoisoned)?
.record(copy)?;
slot.live = true;
slot.gathered = false;
self.sources[index].slot = Some(sl);
self.stage_next = next;
Ok(())
}
pub(super) fn gather(
&mut self,
index: usize,
formats: [MmqFormat; 3],
f: ffi::FunctionHandle,
gate_up: ffi::BufferHandle,
down_out: ffi::BufferHandle,
) -> Result<()> {
let source = self
.sources
.get(index)
.ok_or(Error::InvalidProjectionShape)?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let sl = source.slot;
let raw = if let Some(raw) = source.resident {
raw
} else {
let sl = sl.ok_or(Error::InvalidProjectionShape)?;
let slot = &mut self.slots[sl];
let events = &mut self.schedule.events[sl];
if !slot.live || slot.gathered {
return Err(Error::InvalidProjectionShape);
}
events
.copied
.as_mut()
.ok_or(Error::ContextPoisoned)?
.wait_on(
self.schedule
.compute
.as_ref()
.ok_or(Error::ContextPoisoned)?,
)?;
[
slot.span.checked_subspan(slot.bytes, 0, gu)?,
slot.span.checked_subspan(slot.bytes, gu, gu)?,
slot.span.checked_subspan(slot.bytes, gu * 2, down)?,
]
};
// Destination checks are closed to actual group-bank ranges. All source
// buffers/arena slots were pre-admitted, and are held by this owner.
gate_up.validate_projection_extent(gu * 2, 16)?;
down_out.validate_projection_extent(down, 16)?;
if gate_up.overlaps(gu * 2, down_out, down) {
return Err(Error::OutputAliasesInput);
}
for (i, h) in raw.iter().enumerate() {
let n = if i < 2 { gu } else { down };
if h.overlaps(n, gate_up, gu * 2) || h.overlaps(n, down_out, down) {
return Err(Error::OutputAliasesInput);
}
}
self.enqueue(Command::Gather(
f,
((gu * 2 + down) / 16) as u32,
ffi::MmqOriginalGatherArguments::new(raw, gate_up, down_out, gu, down),
))?;
if let Some(sl) = sl {
let slot = &mut self.slots[sl];
let events = &mut self.schedule.events[sl];
events.used.as_mut().ok_or(Error::ContextPoisoned)?.record(
self.schedule
.compute
.as_ref()
.ok_or(Error::ContextPoisoned)?,
)?;
slot.gathered = true;
}
Ok(())
}
/// Every status is copied only after BOTH real streams drain. Numeric
/// refusal remains stage/group ordered; later transport failure is primary.
pub(super) fn finish_statuses(&mut self) -> Result<&[u8]> {
self.drain()?;
let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let copy = self.context.driver.api.copy_to(
status.handle.ok_or(Error::ContextPoisoned)?,
&mut self.flags,
);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
}
combine(combine(copy, sync), pop)?;
Ok(&self.flags)
}
fn drain(&mut self) -> Result<()> {
if self.drained {
return Ok(());
}
// Do not short-circuit the second producer on a first drain failure.
let copy = self
.schedule
.copy
.as_ref()
.map_or(Ok(()), OriginalGpuStream::synchronize);
let compute = self
.schedule
.compute
.as_ref()
.map_or(Ok(()), OriginalGpuStream::synchronize);
let result = combine(copy, compute);
self.drained = result.is_ok();
if result.is_err() {
self.schedule.failed = true;
}
result
}
pub(super) fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
if self.closed {
return Ok(());
}
self.closed = true;
let mut result = if self.submitted { self.drain() } else { Ok(()) };
if self.context.is_poisoned() || result.is_err() {
self.context.poison();
self.context.retain_driver();
// Retain actual registered-bank lease and all actual command ABI,
// not merely a charge/ready bit. Context retains arena VRAM itself.
if let Some(bank) = self.bank.take() {
std::mem::forget(bank);
}
self.schedule.failed = true;
if let Some(api) = self.schedule.api.take() {
std::mem::forget(api);
}
std::mem::forget(std::mem::take(&mut self.sources));
std::mem::forget(std::mem::take(&mut self.commands));
std::mem::forget(std::mem::take(&mut self.flags));
} else {
self.commands.clear();
self.sources.clear();
self.bank.take();
}
if let Some(status) = self.status.take() {
result = combine(result, status.release());
}
result
}
}
impl Drop for Ring<'_, '_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
@@ -0,0 +1,616 @@
//! Closed actual persistent MMQ bank producer for the global Original issuer.
//! Raw Stage members are read only by gather; copied group storage is then the
//! sole weight source. Every owned command/status survives the provided stream.
use super::*;
use crate::ffi::original_enqueue::{Api, Command};
use crate::original_expert_stager::{
OriginalStreamAllGatheredGroup, OriginalStreamAllGroupProducer, OriginalStreamAllMember,
};
use crate::original_gpu_schedule::OriginalGpuStream;
const COMMAND_CAP: usize = 2048;
struct Transport<'ctx> {
context: &'ctx Context<'ctx>,
api: Option<Api>,
commands: Vec<Command>,
status: Option<DeviceBuffer<'ctx>>,
flags: Vec<u8>,
submitted: bool,
drained: bool,
}
impl<'ctx> Transport<'ctx> {
fn new(context: &'ctx Context<'ctx>, groups: usize, host_allowance: usize) -> Result<Self> {
if !(1..=32).contains(&groups) || context.is_poisoned() {
return Err(Error::InvalidProjectionShape);
}
let mut owner = Self {
context,
api: None,
commands: Vec::new(),
status: None,
flags: Vec::new(),
submitted: false,
drained: false,
};
owner
.commands
.try_reserve_exact(COMMAND_CAP)
.map_err(|_| Error::HostAllocation)?;
owner
.flags
.try_reserve_exact(groups * 16)
.map_err(|_| Error::HostAllocation)?;
owner.flags.resize(groups * 16, 0);
let metadata = owner
.commands
.capacity()
.checked_mul(std::mem::size_of::<Command>() + 512)
.and_then(|n| {
n.checked_add(owner.flags.capacity() + std::mem::size_of::<Self>() + 1024)
})
.ok_or(Error::BudgetExceeded)?;
if owner.commands.capacity() > COMMAND_CAP
|| metadata > host_allowance
|| metadata > 16 << 20
{
return Err(Error::BudgetExceeded);
}
let required = (groups * 16)
.checked_add(128 << 20)
.ok_or(Error::BudgetExceeded)?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
return Err(Error::BudgetExceeded);
}
owner.api = Some(Api::load()?);
owner.status = Some(context.allocate(groups * 16)?);
Ok(owner)
}
fn flag(&self, group: usize, stage: usize) -> Result<ffi::BufferHandle> {
if stage >= 4 {
return Err(Error::InvalidProjectionShape);
}
let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(
b.bytes,
group
.checked_mul(16)
.and_then(|n| n.checked_add(stage * 4))
.ok_or(Error::InvalidSize)?,
4,
)
}
fn enqueue(&mut self, command: Command, stream: &mut OriginalGpuStream<'_>) -> Result<()> {
stream.validate_context(self.context)?;
if self.context.is_poisoned() || self.commands.len() >= COMMAND_CAP {
return Err(Error::ContextPoisoned);
}
self.commands.push(command);
self.submitted = true;
self.drained = false;
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
let command = self.commands.last_mut().ok_or(Error::ContextPoisoned)?;
stream.with_enqueue(|s| api.enqueue(command, s))
}
fn statuses(&mut self, stream: &mut OriginalGpuStream<'_>) -> Result<&[u8]> {
stream.validate_context(self.context)?;
let wait = stream.synchronize();
self.drained = wait.is_ok();
wait?;
let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter().inspect_err(|_| {
self.context.poison();
self.context.retain_driver();
})?;
let copy = self
.context
.driver
.api
.copy_to(b.handle.ok_or(Error::ContextPoisoned)?, &mut self.flags);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.context.poison();
self.context.retain_driver();
}
if sync.is_err() || pop.is_err() {
self.drained = false;
}
combine(combine(copy, sync), pop)?;
Ok(&self.flags)
}
fn close_inner(&mut self) -> Result<()> {
if self.submitted && !self.drained || self.context.is_poisoned() {
self.context.poison();
self.context.retain_driver();
std::mem::forget(std::mem::take(&mut self.commands));
std::mem::forget(std::mem::take(&mut self.flags));
if let Some(v) = self.api.take() {
std::mem::forget(v);
}
if let Some(v) = self.status.take() {
std::mem::forget(v);
}
return Err(Error::ContextPoisoned);
}
self.commands.clear();
self.api.take();
self.status.take().map_or(Ok(()), DeviceBuffer::release)
}
}
impl Drop for Transport<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
struct Producer<'producer, 'layer, 'ctx> {
layer: &'producer mut OriginalMmqLayer<'layer, 'ctx>,
transport: Transport<'ctx>,
formats: [MmqFormat; 3],
experts: &'producer [u32],
layer_id: u8,
}
impl Drop for Producer<'_, '_, '_> {
fn drop(&mut self) {
if self.transport.submitted && !self.transport.drained
|| self.transport.context.is_poisoned()
{
let workspace = &mut *self.layer.workspace;
workspace.failed = true;
workspace.functions = None;
workspace.context.poison();
workspace.context.retain_driver();
std::mem::forget((
workspace.original_group.take(),
workspace.helper.take(),
workspace.experiment.take(),
));
}
}
}
impl<'ctx> OriginalStreamAllGroupProducer<'ctx> for Producer<'_, '_, 'ctx> {
fn validate(
&self,
context: &Context<'ctx>,
rows: &crate::OriginalPromptRows<'_, '_, 'ctx>,
layer: u8,
) -> Result<()> {
let p = &*self.layer;
p.workspace.check()?;
if !std::ptr::eq(context, p.workspace.context)
|| !std::ptr::eq(context, rows.context())
|| rows.is_failed()
|| layer != self.layer_id
|| rows.rows() as u32 != p.total / 10
|| p.next != 0
|| p.staged != 0
|| p.completed
|| p.formats.is_some()
|| p.arena.is_none()
|| self.experts.len() != p.counts.len()
{
return Err(Error::InvalidProjectionShape);
}
for index in 0..TMP {
let (a, n) = p.span(index)?;
let (b, m) = rows_group_span(rows, index)?;
if n != m || a.qwen_address() != b.qwen_address() {
return Err(Error::ContextMismatch);
}
}
if self.formats[0] != self.formats[1]
|| !FORMATS[..5].contains(&self.formats[0])
|| !FORMATS[5..].contains(&self.formats[2])
{
return Err(Error::UnsupportedProjection);
}
Ok(())
}
fn gather(
&mut self,
member: &OriginalStreamAllMember<'_, 'ctx>,
slot: usize,
stream: &mut OriginalGpuStream<'ctx>,
) -> Result<()> {
let p = &mut *self.layer;
if !std::ptr::eq(member.context(), p.workspace.context)
|| slot != p.staged
|| p.completed
|| p.next + p.staged >= self.experts.len()
|| member.expert() != self.experts[p.next + p.staged]
|| slot >= 16
{
return Err(Error::InvalidProjectionShape);
}
let gu = self.formats[0].layout(1)?.raw_weight;
let down = self.formats[2].layout(1)?.raw_weight;
let amount = gu
.checked_mul(2)
.and_then(|n| n.checked_add(down))
.ok_or(Error::InvalidSize)?;
let (blob, extent) = member.checked_blob()?;
if extent < amount {
return Err(Error::InvalidSize);
}
let raw = [
blob.checked_subspan(extent, 0, gu)?,
blob.checked_subspan(extent, gu, gu)?,
blob.checked_subspan(extent, gu * 2, down)?,
];
let wh = p.handle(WG, slot * gu * 2, gu * 2, 16)?;
let dh = p.handle(WD, slot * down, down, 16)?;
if wh.overlaps(gu * 2, dh, down) {
return Err(Error::OutputAliasesInput);
}
for (i, h) in raw.iter().enumerate() {
let n = if i < 2 { gu } else { down };
h.validate_projection_extent(n, 16)?;
p.reject_arena_alias(*h, n)?;
if h.overlaps(n, wh, gu * 2) || h.overlaps(n, dh, down) {
return Err(Error::OutputAliasesInput);
}
}
let f = p.bank()?.gather.ok_or(Error::ContextPoisoned)?;
self.transport.enqueue(
Command::Gather(
f,
(amount / 16) as u32,
ffi::MmqOriginalGatherArguments::new(raw, wh, dh, gu, down),
),
stream,
)?;
p.formats = Some(self.formats);
p.staged += 1;
Ok(())
}
fn project(
&mut self,
group: &OriginalStreamAllGatheredGroup<'_>,
stream: &mut OriginalGpuStream<'ctx>,
) -> Result<()> {
let p = &mut *self.layer;
if group.first() != p.next
|| group.experts() != &self.experts[p.next..p.next + p.staged]
|| p.staged == 0
|| p.staged != (p.counts.len() - p.next).min(16)
{
return Err(Error::InvalidProjectionShape);
}
p.enqueue_global_group(&mut self.transport, stream, self.formats)?;
p.next += p.staged;
p.staged = 0;
p.formats = None;
Ok(())
}
}
fn rows_group_span(
rows: &crate::OriginalPromptRows<'_, '_, '_>,
index: usize,
) -> Result<(ffi::BufferHandle, usize)> {
use crate::PrefillPhase as P;
match index {
X => rows.common_span(crate::original_prefill_arena::OriginalPromptSpan::Mixed),
ROW_IDS => rows.span(P::Moe, "src_dev"),
IDENTITY => rows.span(P::Common, "ids_identity"),
BOUNDS => rows.span(P::Common, "bounds_dev"),
WG => rows.span(P::Common, "grp_gu"),
WD => rows.span(P::Common, "grp_d"),
GU => rows.span(P::Moe, "GU"),
H => rows.span(P::Moe, "H"),
HQ => rows.span(P::Moe, "Hq"),
XQ => rows.span(P::Moe, "Xq"),
D => rows.span(P::Moe, "Dm"),
_ => Err(Error::InvalidProjectionShape),
}
}
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
fn enqueue_global_group(
&self,
transport: &mut Transport<'ctx>,
stream: &mut OriginalGpuStream<'ctx>,
formats: [MmqFormat; 3],
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let group = self.next / 16;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
for stage in 0..4 {
let flag = transport.flag(group, stage)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(0)?,
1,
ffi::MmqResidentArguments::zero(flag, 1),
),
stream,
)?;
}
for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] {
let h = self.handle(index, bytes, 4096, 4)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(0)?,
1024,
ffi::MmqResidentArguments::zero(h, 1024),
),
stream,
)?;
}
self.enqueue_global_project(
transport,
stream,
formats[0],
WG,
XQ,
GU,
false,
self.width(formats[0])?,
)?;
let b = self.bank()?;
let gu_source = self.handle(
GU,
self.bounds[self.next] as usize * 1280 * 4,
nr as usize * 1280 * 4,
4,
)?;
let gu_flag = transport.flag(group, 0)?;
transport.enqueue(
Command::Helper(
b.gu_finite.ok_or(Error::ContextPoisoned)?,
nr * 1280,
ffi::MmqResidentArguments::finite(gu_source, gu_flag, 0, nr * 1280, 0),
),
stream,
)?;
let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?;
transport.enqueue(
Command::Swiglu(
b.swiglu.ok_or(Error::ContextPoisoned)?,
nr,
ffi::MmqOriginalSwigluArguments::new(gu_source, h, nr),
),
stream,
)?;
let h_flag = transport.flag(group, 1)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(1)?,
nr * 640,
ffi::MmqResidentArguments::finite(h, h_flag, 0, nr * 640, 0),
),
stream,
)?;
let ql = layout(MmqFormat::Iq4NlDown, 2560, nr, 64)?;
let q = self.handle(HQ, 0, ql.packed, 16)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(0)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::zero(q, (ql.packed / 4) as u32),
),
stream,
)?;
transport.enqueue(
Command::Quantize(
self.workspace
.experiment
.as_ref()
.ok_or(Error::ContextPoisoned)?
.quantizer
.ok_or(Error::ContextPoisoned)?,
ql,
ffi::MmqQuantArguments::original_indexed(h, None, q, ql),
),
stream,
)?;
let q_flag = transport.flag(group, 2)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(1)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::finite(
q,
q_flag,
1,
(ql.payload / 144) as u32,
(128 * 144) as u32,
),
),
stream,
)?;
self.enqueue_global_project(
transport,
stream,
formats[2],
WD,
HQ,
D,
true,
self.width(formats[2])?,
)?;
let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?;
let d_flag = transport.flag(group, 3)?;
transport.enqueue(
Command::Helper(
self.workspace.kernel(1)?,
nr * 2560,
ffi::MmqResidentArguments::finite(d, d_flag, 0, nr * 2560, 0),
),
stream,
)?;
Ok(())
}
fn enqueue_global_project(
&self,
transport: &mut Transport<'ctx>,
stream: &mut OriginalGpuStream<'ctx>,
format: MmqFormat,
weights: usize,
packed: usize,
out: usize,
down: bool,
width: u32,
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let b = self.bank()?;
let experts = self.staged as u32;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let rows = if down { 2560 } else { 1280 };
let tokens = if down { nr } else { self.total };
let l = layout(format, rows, tokens, width)?;
let fi = format_index(format)?;
let ti = WIDTHS
.iter()
.position(|j| *j == width)
.ok_or(Error::UnsupportedProjection)?;
let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?;
let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?;
let maxr = self.counts[self.next..self.next + self.staged]
.iter()
.copied()
.max()
.ok_or(Error::InvalidProjectionShape)?;
let ntx = maxr.div_ceil(width);
let tiles = (rows / 128)
.checked_mul(ntx)
.and_then(|n| n.checked_mul(experts))
.ok_or(Error::InvalidProjectionShape)?;
if tiles
.checked_mul(l.columns / l.qk)
.is_none_or(|n| n >= 1 << 30)
{
return Err(Error::InvalidProjectionShape);
}
let sms = self
.workspace
.experiment
.as_ref()
.ok_or(Error::ContextPoisoned)?
.sms;
let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms));
let grid = if efficiency >= 90 { tiles } else { sms };
let needs_fix = !tiles.is_multiple_of(grid);
let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?;
let ph = self.handle(packed, 0, l.packed, 16)?;
let oh = self.handle(out, 0, l.output, 4)?;
let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?;
let offset = if down {
self.counts.len() + 1 + (self.next / 16) * 17
} else {
self.next
};
let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?;
let tmp = if needs_fix {
Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?)
} else {
None
};
transport.enqueue(
Command::Project(
f,
l,
grid,
ffi::MmqArguments::original_group(
wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width,
),
),
stream,
)?;
if let Some(tmp) = tmp {
transport.enqueue(
Command::Fixup(
fix,
grid,
ffi::MmqFixupArguments::original_group(
ids, bounds, oh, tmp, l, experts, maxr, width,
),
),
stream,
)?;
}
Ok(())
}
pub fn execute_original_stream_all(
&mut self,
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
forward: &mut crate::OriginalStreamAllForward<'_, '_, '_, '_, 'ctx>,
layer: u8,
experts: &[u32],
formats: [MmqFormat; 3],
host_allowance: usize,
) -> Result<()> {
if !read.context_matches(self.workspace.context)
|| experts.len() != self.counts.len()
|| experts.is_empty()
|| experts.len() > 512
|| experts.windows(2).any(|p| p[0] >= p[1])
|| experts.iter().any(|e| *e >= 512)
{
return Err(Error::InvalidProjectionShape);
}
let transport = Transport::new(
self.workspace.context,
experts.len().div_ceil(16),
host_allowance,
)?;
let mut producer = Producer {
layer: self,
transport,
formats,
experts,
layer_id: layer,
};
let operation = forward.consume_layer_grouped(read.lease(), layer, experts, &mut producer);
let succeeded = operation.is_ok();
let drained = forward.with_compute(|stream| {
if !succeeded {
let wait = stream.synchronize();
producer.transport.drained = wait.is_ok();
return wait;
}
let flags = producer.transport.statuses(stream)?;
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
let gu = u32::from_le_bytes(words[0]);
let h = u32::from_le_bytes(words[1]);
let q = u32::from_le_bytes(words[2]);
let down = u32::from_le_bytes(words[3]);
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
}
Ok(())
});
let result = combine(operation, drained);
if result.is_err() {
producer.layer.next = 0;
producer.layer.completed = true;
}
let close = producer.transport.close_inner();
combine(result, close)
}
}
@@ -0,0 +1,131 @@
//! Actual Original prompt-only whole three-weight upload.
//! The existing closed triplet producer is retained; this separate constructor
//! admits the actual additional Original GU formats without changing old APIs.
use super::*;
impl Context<'_> {
pub fn mmq_original_weight_triplet(
&self,
formats: [MmqFormat; 3],
raw: [&[u8]; 3],
) -> Result<[MmqWeights<'_>; 3]> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !formats[..2].iter().all(|format| {
matches!(
format,
MmqFormat::Iq3XxsGateUp
| MmqFormat::Iq2SGateUp
| MmqFormat::Iq3SGateUp
| MmqFormat::Iq4XsGateUp
| MmqFormat::Iq4NlGateUp
)
}) || !matches!(formats[2], MmqFormat::Iq4NlDown | MmqFormat::Q2Down)
{
return Err(Error::InvalidProjectionShape);
}
let layouts = [
formats[0].layout(1)?,
formats[1].layout(1)?,
formats[2].layout(1)?,
];
let mut charge = 0usize;
// Validate every source before allocating staging or entering CUDA.
for (source, layout) in raw.iter().zip(layouts) {
if source.len() != layout.raw_weight {
return Err(Error::InvalidProjectionShape);
}
if source
.chunks_exact(layout.block_bytes)
.any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00)
{
return Err(Error::InvalidQ8Activation);
}
charge = charge
.checked_add(layout.weight)
.ok_or(Error::BudgetExceeded)?;
}
if self
.allocated
.get()
.checked_add(charge)
.is_none_or(|n| n > self.budget)
{
return Err(Error::BudgetExceeded);
}
let mut staging = [
bytes(layouts[0].weight)?,
bytes(layouts[1].weight)?,
bytes(layouts[2].weight)?,
];
for (padded, source) in staging.iter_mut().zip(raw) {
padded[..source.len()].copy_from_slice(source);
}
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for (slot, layout) in layouts.iter().enumerate() {
match self.allocate(layout.weight) {
Ok(buffer) => buffers[slot] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
let operation = (|| {
let handles = [
buffers[0]
.as_ref()
.and_then(|b| b.handle)
.ok_or(Error::ContextPoisoned)?,
buffers[1]
.as_ref()
.and_then(|b| b.handle)
.ok_or(Error::ContextPoisoned)?,
buffers[2]
.as_ref()
.and_then(|b| b.handle)
.ok_or(Error::ContextPoisoned)?,
];
let guard = self.enter()?;
let mut copy = Ok(());
for (handle, padded) in handles.into_iter().zip(&staging) {
copy = self.driver.api.copy_from(handle, padded);
if copy.is_err() {
break;
}
}
// Drain every attempted copy, including reported command errors.
let sync = self.driver.api.synchronize();
let restored = guard.finish();
if sync.is_err() || restored.is_err() {
self.poisoned.set(true);
// Even successful synchronous-looking H2D calls are not a
// lifetime certificate after failed completion/restoration.
std::mem::forget(std::mem::take(&mut staging));
}
combine(combine(copy, sync), restored)
})();
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
unreachable!("all triplet allocations completed before upload")
};
Ok([
MmqWeights {
context: self,
format: formats[0],
buffer: Some(gate),
},
MmqWeights {
context: self,
format: formats[1],
buffer: Some(up),
},
MmqWeights {
context: self,
format: formats[2],
buffer: Some(down),
},
])
}
}
+960
View File
@@ -0,0 +1,960 @@
//! Exclusive resident transport. Every proof owns its actual workspace lease.
use super::*;
#[path = "mmq_native_activation.rs"]
pub(crate) mod native_activation;
#[path = "mmq_native_down.rs"]
mod native_down;
#[path = "iq3_native_integer_mma.rs"]
pub(crate) mod native_integer;
#[path = "mmq_original_group.rs"]
pub(crate) mod original_group;
const INPUT: usize = 0;
const CHUNK: usize = 1;
const GROUP: usize = 2;
const GATE: usize = 3;
const UP: usize = 4;
const HIDDEN: usize = 5;
const DOWN_Q8: usize = 6;
const DOWN: usize = 7;
const SCRATCH: usize = 8;
const IDS: usize = 9;
const STATUS: usize = 10;
// PTX is supplied only by ROOT's pinned GPU-hidden compiler. No placeholder artifact.
pub(crate) fn asset() -> Result<&'static [u8]> {
let b = include_bytes!("mmq_resident_helpers.ptx");
if b.last() != Some(&0) || !b[..b.len() - 1].is_ascii() || b[..b.len() - 1].contains(&0) {
return Err(Error::InvalidDriverValue("MMQ resident artifact"));
}
if b.len() != 4046
|| crate::qwen_ffi::sha256(&b[..b.len() - 1])
!= [
0x87, 0x0c, 0x6b, 0xc8, 0xa6, 0xec, 0x32, 0x0a, 0x05, 0x9c, 0x50, 0xbe, 0x9d, 0x5c,
0x96, 0x2f, 0xed, 0xec, 0x86, 0x63, 0x4d, 0x98, 0x8f, 0xc0, 0xe6, 0xb9, 0xd7, 0xed,
0xea, 0x11, 0x8d, 0x89,
]
{
return Err(Error::InvalidDriverValue("MMQ resident artifact digest"));
}
Ok(b)
}
// Each command owns its fixed ABI Box. Moving the vector never moves the
// pointees; all owners remain live until the final synchronize and context pop.
type DownCopyHandles = (ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle);
enum QueuedCommand {
Helper(ffi::FunctionHandle, u32, ffi::MmqResidentArguments),
OriginalSwiglu(ffi::FunctionHandle, u32, ffi::MmqOriginalSwigluArguments),
OriginalHelper(ffi::FunctionHandle, u32, ffi::MmqResidentArguments),
OriginalGather(ffi::FunctionHandle, u32, ffi::MmqOriginalGatherArguments),
Quantize(ffi::FunctionHandle, Layout, ffi::MmqQuantArguments),
NativeQuantize(ffi::FunctionHandle, u32, ffi::Q8QuantizeArguments),
Project(ffi::FunctionHandle, Layout, u32, ffi::MmqArguments),
Fixup(ffi::FunctionHandle, u32, ffi::MmqFixupArguments),
Swiglu(ffi::FunctionHandle, u32, ffi::ProjectionArguments),
NativeDown(ffi::FunctionHandle, u32, ffi::ProjectionArguments),
NativeIntegerDot(ffi::FunctionHandle, u32, ffi::Iq3NativeIntegerArguments),
NativeIntegerReduce(ffi::FunctionHandle, u32, ffi::Iq3NativeIntegerArguments),
}
impl QueuedCommand {
fn launch(&mut self, context: &Context<'_>) -> Result<()> {
match self {
Self::OriginalGather(f, words, args) => context
.driver
.api
.launch_mmq_original_gather(*f, *words, args),
Self::OriginalHelper(f, words, args) => context
.driver
.api
.launch_mmq_original_group_helper(*f, *words, args),
Self::OriginalSwiglu(f, rows, args) => context
.driver
.api
.launch_mmq_original_swiglu(*f, *rows, args),
Self::NativeIntegerDot(f, tokens, args) => context
.driver
.api
.launch_iq3_native_integer(*f, *tokens, false, args),
Self::NativeIntegerReduce(f, tokens, args) => context
.driver
.api
.launch_iq3_native_integer(*f, *tokens, true, args),
Self::Helper(f, words, args) => {
context.driver.api.launch_mmq_resident(*f, *words, args)
}
Self::Quantize(f, layout, args) => context.driver.api.quantize_mmq(*f, *layout, args),
Self::NativeQuantize(f, grid, args) => {
context.driver.api.launch_q8_quantize(*f, *grid, args)
}
Self::Project(f, layout, grid, args) => {
context.driver.api.project_mmq(*f, *layout, *grid, args)
}
Self::Fixup(f, grid, args) => context.driver.api.fixup_mmq(*f, *grid, args),
Self::NativeDown(f, tokens, args) => context
.driver
.api
.launch_grouped_projection(*f, 640, *tokens, args),
Self::Swiglu(f, tokens, args) => context
.driver
.api
.launch_grouped_swiglu(*f, 5, *tokens, args),
}
}
}
fn commands() -> Result<Vec<QueuedCommand>> {
let mut result = Vec::new();
// Closed stages need at most five commands, never an unbounded launch list.
result
.try_reserve_exact(5)
.map_err(|_| Error::HostAllocation)?;
Ok(result)
}
/// Explicit experimental workspace, precharged before lazy expert cache growth.
pub struct MmqWorkspace<'ctx> {
experiment: Option<MmqExperiment<'ctx>>,
context: &'ctx Context<'ctx>,
helper: Option<ffi::ModuleHandle>,
functions: Option<[ffi::FunctionHandle; 3]>,
buffers: [Option<DeviceBuffer<'ctx>>; 11],
failed: bool,
native_activation: Option<native_activation::NativeActivation<'ctx>>,
native_integer: Option<native_integer::NativeInteger<'ctx>>,
original_group: Option<original_group::OriginalGroupBank<'ctx>>,
}
pub struct MmqChunkActivation<'lease, 'ctx> {
workspace: &'lease mut MmqWorkspace<'ctx>,
tokens: u32,
original: bool,
}
pub struct MmqGroupActivation<'lease, 'ctx> {
workspace: &'lease mut MmqWorkspace<'ctx>,
tokens: u32,
original: bool,
}
pub struct MmqHidden<'lease, 'ctx> {
workspace: &'lease mut MmqWorkspace<'ctx>,
tokens: u32,
original: bool,
}
/// Immutable actual finite Down output. No public mutable device view.
pub struct FiniteMmqOutput<'lease, 'ctx> {
workspace: &'lease mut MmqWorkspace<'ctx>,
tokens: u32,
}
impl Context<'_> {
pub fn mmq_workspace(&self) -> Result<MmqWorkspace<'_>> {
MmqWorkspace::new(self, false, false)
}
}
impl Context<'_> {
/// Explicit experimental native-half-Q8 policy, eagerly charged before cache growth.
pub fn native_mmq_workspace(&self) -> Result<MmqWorkspace<'_>> {
MmqWorkspace::new(self, true, false)
}
}
impl Context<'_> {
/// Experimental GU18 only: exact native Q8/HALF transport, raw int32 MMA dots,
/// original integer truncation and warp float reduction. Separately charged 12.5 MiB.
/// Requires ROOT's sealed PTX and numerical admission; serving never selects this API.
pub fn native_integer_iq3_mmq_workspace(&self) -> Result<MmqWorkspace<'_>> {
MmqWorkspace::new(self, true, true)
}
}
impl Context<'_> {
/// Explicit Original prompt kernels alongside the unchanged optional native
/// operators. Unsealed additional templates refuse before any allocation.
pub fn native_integer_iq3_mmq_original_formats_workspace(&self) -> Result<MmqWorkspace<'_>> {
original_formats_asset(5)?;
original_formats_asset(6)?;
let mut owner = MmqWorkspace::new(self, true, true)?;
let result = owner
.experiment
.as_mut()
.ok_or(Error::ContextPoisoned)?
.enable_original_formats();
if let Err(error) = result {
return combine(Err(error), owner.close());
}
Ok(owner)
}
}
impl<'ctx> MmqWorkspace<'ctx> {
fn new(
context: &'ctx Context<'ctx>,
native_policy: bool,
integer_policy: bool,
) -> Result<Self> {
if integer_policy {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
// Refuse before allocating any module/buffer until compiled artifact is sealed.
native_integer::asset()?;
if !native_policy {
return Err(Error::UnsupportedProjection);
}
}
let experiment = context.mmq_experiment()?;
let scratch = (experiment.sms as usize)
.checked_mul(64 * 128 * 4)
.ok_or(Error::BudgetExceeded)?;
let sizes = [
655360, 193536, 193536, 163840, 163840, 163840, 82944, 655360, scratch, 256, 4,
];
let charge = sizes.iter().try_fold(
if native_policy {
native_activation::CHARGE
+ if integer_policy {
native_integer::CHARGE
} else {
0
}
} else {
0
},
|a, b| a.checked_add(*b).ok_or(Error::BudgetExceeded),
)?;
if context
.allocated_bytes()
.checked_add(charge)
.is_none_or(|n| n > context.budget)
{
return combine(Err(Error::BudgetExceeded), experiment.close());
}
let mut owner = Self {
experiment: Some(experiment),
context,
helper: None,
functions: None,
buffers: std::array::from_fn(|_| None),
failed: false,
native_activation: None,
native_integer: None,
original_group: None,
};
let result = (|| {
if native_policy {
owner.native_activation = Some(native_activation::NativeActivation::new(context)?);
}
if integer_policy {
owner.native_integer = Some(native_integer::NativeInteger::new(context)?);
}
let guard = context.enter()?;
let loaded = (|| {
let m = context.driver.api.load_mmq_resident()?;
owner.helper = Some(m);
let mut fs = Vec::new();
fs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
for k in 0..3 {
fs.push(context.driver.api.mmq_resident_function(m, k)?);
}
owner.functions = Some(fs.try_into().map_err(|_| Error::InvalidProjectionShape)?);
Ok(())
})();
combine(loaded, guard.finish())?;
for (i, size) in sizes.into_iter().enumerate() {
owner.buffers[i] = Some(context.allocate(size)?);
}
Ok(())
})();
if let Err(e) = result {
return combine(Err(e), owner.close());
}
Ok(owner)
}
pub fn allocated_bytes(&self) -> usize {
self.buffers
.iter()
.flatten()
.map(|b| b.bytes)
.sum::<usize>()
+ self
.original_group
.as_ref()
.map_or(0, |b| b.allocated_bytes())
+ self
.native_activation
.as_ref()
.map_or(0, |_| native_activation::CHARGE)
+ self
.native_integer
.as_ref()
.map_or(0, |_| native_integer::CHARGE)
}
fn check(&self) -> Result<()> {
if self.failed
|| self.context.is_poisoned()
|| self.context.handle.is_none()
|| self.functions.is_none()
|| self.experiment.is_none()
|| self.buffers.iter().any(Option::is_none)
{
return Err(Error::ContextPoisoned);
}
if let Some(integer) = &self.native_integer {
integer.check()?;
let native = self
.native_activation
.as_ref()
.ok_or(Error::UnsupportedProjection)?
.buffer()?;
if integer.overlaps(native.handle.ok_or(Error::ContextPoisoned)?, native.bytes)? {
return Err(Error::OutputAliasesInput);
}
}
if let Some(native) = &self.native_activation {
native.check()?;
}
Ok(())
}
fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
self.check()?;
self.buffers[index].as_ref().ok_or(Error::ContextPoisoned)
}
fn handle(&self, index: usize, bytes: usize, alignment: u64) -> Result<ffi::BufferHandle> {
let b = self.buffer(index)?;
if bytes == 0 || bytes > b.bytes {
return Err(Error::InvalidProjectionShape);
}
if !std::ptr::eq(self.context, b.context) {
return Err(Error::ContextMismatch);
}
let h = b.handle.ok_or(Error::ContextPoisoned)?;
h.validate_projection_extent(b.bytes, alignment)?;
Ok(h)
}
fn kernel(&self, kind: usize) -> Result<ffi::FunctionHandle> {
self.check()?;
self.functions
.ok_or(Error::ContextPoisoned)
.map(|f| f[kind])
}
fn fail<T>(&mut self, r: Result<T>) -> Result<T> {
if r.is_err() {
self.failed = true;
}
r
}
fn zero_command(&self, index: usize, bytes: usize) -> Result<QueuedCommand> {
if !bytes.is_multiple_of(4) {
return Err(Error::InvalidProjectionShape);
}
let h = self.handle(index, bytes, 4)?;
Ok(QueuedCommand::Helper(
self.kernel(0)?,
(bytes / 4) as u32,
ffi::MmqResidentArguments::zero(h, (bytes / 4) as u32),
))
}
#[cfg(test)]
fn zero(&self, index: usize, bytes: usize) -> Result<()> {
let mut commands = commands()?;
commands.push(self.zero_command(index, bytes)?);
self.run_queued(commands, None).map(|_| ())
}
fn run_queued(
&self,
mut commands: Vec<QueuedCommand>,
status: Option<ffi::BufferHandle>,
) -> Result<u32> {
self.check()?;
if commands.is_empty() || commands.len() > 5 {
return Err(Error::InvalidProjectionShape);
}
// Owned host destination, never a borrowed stack slice given to CUDA.
// Even a failed copy can describe prior work and must retain its storage.
let mut staging = bytes(4)?;
let guard = self.context.enter()?;
let mut operation = Ok(());
for command in &mut commands {
operation = command.launch(self.context);
if operation.is_err() {
break;
}
}
if operation.is_ok()
&& let Some(status) = status
{
operation = self.context.driver.api.copy_to(status, &mut staging);
}
if operation.is_err() {
self.context.poisoned.set(true);
}
// Identical primary/sync/pop precedence to Context::complete_launch.
// No argument or status owner can drop before all attempted work ends.
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if sync.is_err() || pop.is_err() {
self.context.poisoned.set(true);
std::mem::forget((commands, staging));
return combine(combine(operation, sync), pop).map(|_| 0);
}
combine(combine(operation, sync), pop)?;
Ok(u32::from_le_bytes(staging.as_chunks::<4>().0[0]))
}
fn finish_finite(
&self,
mut commands: Vec<QueuedCommand>,
index: usize,
amount: usize,
q8: bool,
) -> Result<()> {
let tail = if q8 { 9216 } else { 0 };
let bytes = if q8 {
amount.checked_mul(144).and_then(|n| n.checked_add(tail))
} else {
amount.checked_mul(4)
}
.ok_or(Error::InvalidProjectionShape)?;
let source = self.handle(index, bytes, 4)?;
let status = self.handle(STATUS, 4, 4)?;
if source.overlaps(self.buffer(index)?.bytes, status, 4) {
return Err(Error::OutputAliasesInput);
}
// All validation and owner construction precede the first launch.
if commands.len() > 3 {
return Err(Error::InvalidProjectionShape);
}
commands.push(self.zero_command(STATUS, 4)?);
commands.push(QueuedCommand::Helper(
self.kernel(1)?,
(bytes / 4) as u32,
ffi::MmqResidentArguments::finite(
source,
status,
u32::from(q8),
amount as u32,
tail as u32,
),
));
match self.run_queued(commands, Some(status))? {
0 => Ok(()),
1 | 3 if q8 => Err(Error::InvalidQ8Activation),
2 if q8 => Err(Error::InvalidDriverValue("MMQ dirty Q8 tail")),
1 if !q8 => Err(Error::NonFiniteMmqOutput(match index {
GATE => "Gate",
UP => "Up",
HIDDEN => "SwiGLU",
DOWN => "Down",
_ => "unknown",
})),
_ => Err(Error::InvalidDriverValue("MMQ finite witness")),
}
}
#[cfg(test)]
fn finite(&self, index: usize, amount: usize, q8: bool) -> Result<()> {
self.finish_finite(commands()?, index, amount, q8)
}
fn quantize(&self, input: usize, packed: usize, l: Layout) -> Result<()> {
self.quantize_with_operator(input, packed, l, false)
}
fn quantize_with_operator(
&self,
input: usize,
packed: usize,
l: Layout,
original: bool,
) -> Result<()> {
if !original && self.native_activation.is_some() {
return self.quantize_native(input, packed, l);
}
let ih = self.handle(input, l.input, 16)?;
let qh = self.handle(packed, l.packed, 16)?;
if ih.overlaps(self.buffer(input)?.bytes, qh, self.buffer(packed)?.bytes) {
return Err(Error::OutputAliasesInput);
}
let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?;
e.check()?;
let mut commands = commands()?;
commands.push(self.zero_command(packed, l.packed)?);
commands.push(QueuedCommand::Quantize(
e.quantizer.ok_or(Error::ContextPoisoned)?,
l,
ffi::MmqQuantArguments::new(ih, qh, l),
));
self.finish_finite(commands, packed, l.payload / 144, true)
}
fn quantize_native(&self, input: usize, packed: usize, l: Layout) -> Result<()> {
self.check()?;
let ih = self.handle(input, l.input, 16)?;
let qh = self.handle(packed, l.packed, 16)?;
let sh = self.handle(STATUS, 4, 4)?;
let sources = [
(ih, self.buffer(input)?.bytes),
(qh, self.buffer(packed)?.bytes),
(sh, 4),
];
for i in 0..sources.len() {
for j in i + 1..sources.len() {
if sources[i]
.0
.overlaps(sources[i].1, sources[j].0, sources[j].1)
{
return Err(Error::OutputAliasesInput);
}
}
}
let n = self
.native_activation
.as_ref()
.ok_or(Error::InvalidProjectionShape)?;
let nh = n.buffer()?.handle.ok_or(Error::ContextPoisoned)?;
for b in self.buffers.iter().flatten() {
if nh.overlaps(
native_activation::CHARGE,
b.handle.ok_or(Error::ContextPoisoned)?,
b.bytes,
) {
return Err(Error::OutputAliasesInput);
}
}
let mut cmds = commands()?;
cmds.push(self.zero_command(STATUS, 4)?);
n.append(&mut cmds, ih, qh, sh, l)?;
// Preserve native status bits: never zero between native quantize and proof.
cmds.push(QueuedCommand::Helper(
self.kernel(1)?,
(l.packed / 4) as u32,
ffi::MmqResidentArguments::finite(qh, sh, 1, (l.payload / 144) as u32, 9216),
));
match self.run_queued(cmds, Some(sh))? {
0 => Ok(()),
_ => Err(Error::InvalidQ8Activation),
}
}
fn project(
&self,
weights: &MmqWeights<'_>,
packed: usize,
out: usize,
tokens: u32,
) -> Result<()> {
self.project_with_operator(weights, packed, out, tokens, false)
}
fn project_with_operator(
&self,
weights: &MmqWeights<'_>,
packed: usize,
out: usize,
tokens: u32,
original: bool,
) -> Result<()> {
self.check()?;
let l = weights
.format
.adaptive_layout(tokens, MmqProfile::OriginalAdaptive)?;
let w = weights.native_buffer()?;
if !std::ptr::eq(self.context, weights.context) {
return Err(Error::ContextMismatch);
}
let wh = w.handle.ok_or(Error::ContextPoisoned)?;
wh.validate_projection_extent(w.bytes, 2)?;
let ph = self.handle(packed, l.packed, 16)?;
let oh = self.handle(out, l.output, 4)?;
for (h, n) in [
(ph, self.buffer(packed)?.bytes),
(oh, self.buffer(out)?.bytes),
] {
if wh.overlaps(w.bytes, h, n) {
return Err(Error::OutputAliasesInput);
}
}
if ph.overlaps(self.buffer(packed)?.bytes, oh, self.buffer(out)?.bytes) {
return Err(Error::OutputAliasesInput);
}
if let Some(integer) = &self.native_integer
&& !original
{
if matches!(weights.format, MmqFormat::Iq2SGateUp) {
return Err(Error::UnsupportedProjection);
}
if matches!(weights.format, MmqFormat::Iq3XxsGateUp) {
if self.native_activation.is_none() || packed != GROUP || !matches!(out, GATE | UP)
{
return Err(Error::UnsupportedProjection);
}
for b in self.buffers.iter().flatten() {
if integer.overlaps(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)? {
return Err(Error::OutputAliasesInput);
}
}
let mut queued = commands()?;
integer.append(&mut queued, wh, ph, oh, l)?;
return self.finish_finite(queued, out, l.output / 4, false);
}
}
let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?;
e.check()?;
let tiles = l.rows / 128;
let efficiency = 100 * tiles / (e.sms * tiles.div_ceil(e.sms));
let grid = if efficiency >= 90 { tiles } else { e.sms };
let fixup = !tiles.is_multiple_of(grid);
let temp = if fixup {
let n = grid as usize * l.tile.width() as usize * 128 * 4;
let th = self.handle(SCRATCH, n, 4)?;
for (h, b) in [
(wh, w.bytes),
(ph, self.buffer(packed)?.bytes),
(oh, self.buffer(out)?.bytes),
] {
if th.overlaps(self.buffer(SCRATCH)?.bytes, h, b) {
return Err(Error::OutputAliasesInput);
}
}
Some(th)
} else {
None
};
let mut commands = commands()?;
if fixup {
commands.push(
self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?,
);
}
let f = e.function(weights.format, l.tile, false)?;
commands.push(QueuedCommand::Project(
f,
l,
grid,
ffi::MmqArguments::new(wh, ph, oh, temp, l),
));
if let Some(th) = temp {
let f = e.function(weights.format, l.tile, true)?;
commands.push(QueuedCommand::Fixup(
f,
grid,
ffi::MmqFixupArguments::new(oh, th, l),
));
}
self.finish_finite(commands, out, l.output / 4, false)
}
pub fn prepare_gate_up_chunk<'lease>(
&'lease mut self,
values: &[f32],
tokens: u32,
) -> Result<MmqChunkActivation<'lease, 'ctx>> {
self.prepare_gate_up_chunk_with_operator(values, tokens, false)
}
/// Mint an affine Original-prompt activation using the actual D4 quantizer,
/// independently of this workspace's optional native integer operators.
pub fn prepare_original_gate_up_chunk<'lease>(
&'lease mut self,
values: &[f32],
tokens: u32,
) -> Result<MmqChunkActivation<'lease, 'ctx>> {
self.check()?;
let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?;
if e.original_functions.is_none() || e.original_fixups.is_none() {
return Err(Error::UnsupportedProjection);
}
self.prepare_gate_up_chunk_with_operator(values, tokens, true)
}
fn prepare_gate_up_chunk_with_operator<'lease>(
&'lease mut self,
values: &[f32],
tokens: u32,
original: bool,
) -> Result<MmqChunkActivation<'lease, 'ctx>> {
self.check()?;
let l = MmqFormat::Iq3XxsGateUp.layout(tokens)?;
if values.len() != l.input / 4 || values.iter().any(|x| !x.is_finite()) {
return Err(Error::InvalidQ8Activation);
}
let mut b = bytes(l.input)?;
for (v, d) in values.iter().zip(b.as_chunks_mut::<4>().0) {
*d = v.to_le_bytes();
}
let r = (|| {
let dst = self.buffers[INPUT].as_mut().ok_or(Error::ContextPoisoned)?;
// Only the complete current source prefix is read by the closed quantizer.
dst.copy_from_range(0, &b)?;
self.quantize_with_operator(INPUT, CHUNK, l, original)
})();
if matches!(
&r,
Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext)
) {
self.context.poisoned.set(true);
}
self.fail(r)?;
Ok(MmqChunkActivation {
workspace: self,
tokens,
original,
})
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
self.functions = None;
let mut r = self.original_group.take().map_or(Ok(()), |n| n.close());
r = combine(r, self.native_integer.take().map_or(Ok(()), |n| n.close()));
r = combine(
r,
self.native_activation.take().map_or(Ok(()), |n| n.close()),
);
for b in &mut self.buffers {
if let Some(b) = b.take() {
let step = b.release();
if step.is_err() {
self.context.poisoned.set(true);
}
r = combine(r, step);
}
}
if let Some(m) = self.helper.take() {
let step = match self.context.enter() {
Ok(g) => combine(self.context.driver.api.unload(m), g.finish()),
Err(e) => Err(e),
};
if step.is_err() {
self.context.poisoned.set(true);
}
r = combine(r, step);
}
if let Some(e) = self.experiment.take() {
r = combine(r, e.close());
}
r
}
}
impl Drop for MmqWorkspace<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
impl<'ctx> MmqChunkActivation<'_, 'ctx> {
pub fn gather_gate_up<'lease>(
&'lease mut self,
indices: &[u32],
) -> Result<MmqGroupActivation<'lease, 'ctx>> {
self.workspace.check()?;
if indices.is_empty()
|| indices.len() > 64
|| indices.iter().any(|i| *i >= self.tokens)
|| indices.windows(2).any(|w| w[0] >= w[1])
{
return Err(Error::InvalidProjectionShape);
}
let t = indices.len() as u32;
let l = MmqFormat::Iq3XxsGateUp.layout(t)?;
let w = &mut *self.workspace;
let r = (|| {
let mut ids = [0u8; 256];
for (i, x) in indices.iter().enumerate() {
ids[i * 4..i * 4 + 4].copy_from_slice(&x.to_le_bytes());
}
w.buffers[IDS]
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from(&ids)?;
let source = w.handle(
CHUNK,
MmqFormat::Iq3XxsGateUp.layout(self.tokens)?.packed,
16,
)?;
let out = w.handle(GROUP, l.packed, 16)?;
let ids = w.handle(IDS, 256, 4)?;
for (a, an, b, bn) in [
(source, w.buffer(CHUNK)?.bytes, out, w.buffer(GROUP)?.bytes),
(ids, 256, out, w.buffer(GROUP)?.bytes),
] {
if a.overlaps(an, b, bn) {
return Err(Error::OutputAliasesInput);
}
}
let mut commands = commands()?;
commands.push(w.zero_command(GROUP, l.packed)?);
commands.push(QueuedCommand::Helper(
w.kernel(2)?,
(l.payload / 4) as u32,
ffi::MmqResidentArguments::gather(
source,
ids,
out,
self.tokens,
t,
l.padded_columns / 128,
),
));
w.finish_finite(commands, GROUP, l.payload / 144, true)
})();
w.fail(r)?;
Ok(MmqGroupActivation {
workspace: w,
tokens: t,
original: self.original,
})
}
}
impl<'lease, 'ctx> MmqGroupActivation<'lease, 'ctx> {
pub fn gate_up(
self,
gate: &MmqWeights<'_>,
up: &MmqWeights<'_>,
) -> Result<MmqHidden<'lease, 'ctx>> {
let admitted = |format| {
matches!(format, MmqFormat::Iq3XxsGateUp | MmqFormat::Iq2SGateUp)
|| (self.original
&& matches!(
format,
MmqFormat::Iq3SGateUp | MmqFormat::Iq4XsGateUp | MmqFormat::Iq4NlGateUp
))
};
if !admitted(gate.format) || !admitted(up.format) {
return Err(Error::InvalidProjectionShape);
}
let w = self.workspace;
let t = self.tokens;
if !self.original
&& w.native_integer.is_some()
&& (gate.format != MmqFormat::Iq3XxsGateUp || up.format != MmqFormat::Iq3XxsGateUp)
{
return Err(Error::UnsupportedProjection);
}
let r = (|| {
if self.original {
w.project_with_operator(gate, GROUP, GATE, t, true)?;
w.project_with_operator(up, GROUP, UP, t, true)?;
} else {
w.project(gate, GROUP, GATE, t)?;
w.project(up, GROUP, UP, t)?;
}
let a = w.handle(GATE, t as usize * 2560, 4)?;
let b = w.handle(UP, t as usize * 2560, 4)?;
let c = w.handle(HIDDEN, t as usize * 2560, 4)?;
if c.overlaps(w.buffer(HIDDEN)?.bytes, a, w.buffer(GATE)?.bytes)
|| c.overlaps(w.buffer(HIDDEN)?.bytes, b, w.buffer(UP)?.bytes)
{
return Err(Error::OutputAliasesInput);
}
let guard = w.context.enter()?;
let k = combine(
w.context.fixed_kernel(FixedOperation::GroupedSwiglu),
guard.finish(),
)?;
let mut commands = commands()?;
commands.push(QueuedCommand::Swiglu(
k.function,
t,
ffi::ProjectionArguments::new(a, b, c, 640, 640),
));
w.finish_finite(commands, HIDDEN, t as usize * 640, false)
})();
w.fail(r)?;
Ok(MmqHidden {
workspace: w,
tokens: t,
original: self.original,
})
}
}
impl<'lease, 'ctx> MmqHidden<'lease, 'ctx> {
pub fn down(self, weights: &MmqWeights<'_>) -> Result<FiniteMmqOutput<'lease, 'ctx>> {
if !matches!(weights.format, MmqFormat::Iq4NlDown | MmqFormat::Q2Down) {
return Err(Error::InvalidProjectionShape);
}
let w = self.workspace;
let t = self.tokens;
let r = (|| {
let l = weights.format.layout(t)?;
if self.original {
w.quantize_with_operator(HIDDEN, DOWN_Q8, l, true)?;
w.project_with_operator(weights, DOWN_Q8, DOWN, t, true)
} else {
w.quantize(HIDDEN, DOWN_Q8, l)?;
if w.native_integer.is_some() {
w.project_native_down(weights, t)
} else {
w.project(weights, DOWN_Q8, DOWN, t)
}
}
})();
w.fail(r)?;
Ok(FiniteMmqOutput {
workspace: w,
tokens: t,
})
}
}
impl FiniteMmqOutput<'_, '_> {
pub fn tokens(&self) -> u32 {
self.tokens
}
pub fn copy_down_column_to_slot(
&self,
column: u32,
destination: &mut DeviceBuffer<'_>,
slot: u32,
) -> Result<()> {
self.copy_down_columns_to_slots(&mut [(column, destination, slot)])
}
/// Copy a bounded group of actual finite Down columns into disjoint whole
/// ten-slot packets. All copies finish before return; the caller publishes
/// its route/coverage proofs only after this method succeeds.
pub fn copy_down_columns_to_slots(
&self,
copies: &mut [(u32, &mut DeviceBuffer<'_>, u32)],
) -> Result<()> {
let w = &*self.workspace;
w.check()?;
if copies.is_empty()
|| copies.len() > 64
|| copies.windows(2).any(|pair| pair[0].0 >= pair[1].0)
{
return Err(Error::InvalidProjectionShape);
}
let source = w.handle(DOWN, self.tokens as usize * 10240, 4)?;
let mut handles = Vec::new();
handles
.try_reserve_exact(copies.len())
.map_err(|_| Error::HostAllocation)?;
// No device operation occurs until every owner/span is admitted.
for (column, destination, slot) in copies.iter() {
if *column >= self.tokens || *slot >= 10 || destination.bytes != 102400 {
return Err(Error::InvalidProjectionShape);
}
if !std::ptr::eq(w.context, destination.context) {
return Err(Error::ContextMismatch);
}
let target = destination.handle.ok_or(Error::ContextPoisoned)?;
target.validate_projection_extent(102400, 4)?;
if source.overlaps(w.buffer(DOWN)?.bytes, target, 102400)
|| handles
.iter()
.any(|(whole, _, _): &DownCopyHandles| whole.overlaps(102400, target, 102400))
{
return Err(Error::OutputAliasesInput);
}
let part =
source.checked_subspan(w.buffer(DOWN)?.bytes, *column as usize * 10240, 10240)?;
handles.push((target, target.moe_down_slot(*slot)?, part));
}
let guard = w.context.enter()?;
let mut copy = Ok(());
for (_, target, source) in &handles {
copy = w.context.driver.api.copy_moe_down(*target, *source);
if copy.is_err() {
break;
}
}
let sync = w.context.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
w.context.poisoned.set(true);
}
// These are value-only handles; actual allocations stay borrowed and
// context poisoning prevents uncertain release/reuse after any failure.
combine(combine(copy, sync), pop)
}
}
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "mmq_resident_gpu.rs"]
mod mmq_resident_gpu_tests;
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "mmq_native_resident_gpu.rs"]
mod mmq_native_resident_gpu_tests;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
// Integer-only transport and compact complete finite witnesses. No inference arithmetic.
extern "C" __global__ void leleka_mmq_zero(unsigned* out, unsigned words) {
unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < words) out[i] = 0;
}
extern "C" __global__ void leleka_mmq_finite(const unsigned* source, unsigned* status, unsigned mode, unsigned amount, unsigned tail_bytes) {
unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
unsigned payload_words = mode ? amount * 36u : amount;
unsigned words = payload_words + (mode ? tail_bytes / 4u : 0u);
if (i >= words) return;
unsigned value = source[i];
if (i < payload_words) {
if ((!mode || i % 36u < 4u) && (value & 0x7f800000u) == 0x7f800000u) atomicOr(status, 1u);
} else if (value != 0u) atomicOr(status, 2u);
}
extern "C" __global__ void leleka_mmq_gather(const unsigned* source, const unsigned* ids, unsigned* out, unsigned source_tokens, unsigned group_tokens, unsigned blocks) {
unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
unsigned words = blocks * group_tokens * 36u;
if (i >= words) return;
unsigned lane = i % 36u;
unsigned row = (i / 36u) % group_tokens;
unsigned block = i / (36u * group_tokens);
out[i] = source[(block * source_tokens + ids[row]) * 36u + lane];
}
Binary file not shown.
+5 -1
View File
@@ -16,7 +16,11 @@ fn words(slot: usize, zero: bool) -> Vec<u8> {
(0..2560)
.flat_map(|i| {
let value = if zero {
if (slot + i).is_multiple_of(2) { -0.0f32 } else { 0. }
if (slot + i).is_multiple_of(2) {
-0.0f32
} else {
0.
}
} else {
(((slot * 17 + i * 3) % 97) as f32 - 48.) / 64.
};
@@ -0,0 +1,279 @@
//! Closed grouped native SwiGLU/Down20/42; each column retains scalar arithmetic.
use super::*;
type NativeDownCopyHandles = (ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle);
impl Context<'_> {
/// Closed byte transport from completed native Down columns to whole
/// disjoint ten-slot packets. Runtime owns the finite/route publication.
pub fn copy_routed_down_columns_to_slots(
&self,
source: &DeviceBuffer<'_>,
total: usize,
copies: &mut [(u32, &mut DeviceBuffer<'_>, u32)],
) -> Result<()> {
self.grouped_buffers(&[source])?;
if !(1..=64).contains(&total) || source.bytes != total * 10240 || copies.len() != total {
return Err(Error::InvalidProjectionShape);
}
let source_handle = source.handle.ok_or(Error::ContextPoisoned)?;
let mut handles: Vec<NativeDownCopyHandles> = Vec::new();
handles
.try_reserve_exact(total)
.map_err(|_| Error::HostAllocation)?;
for (index, (column, destination, slot)) in copies.iter().enumerate() {
if *column as usize != index || *slot >= 10 || destination.bytes != 102400 {
return Err(Error::InvalidProjectionShape);
}
self.grouped_buffers(&[destination])?;
let target = destination.handle.ok_or(Error::ContextPoisoned)?;
if source_handle.overlaps(source.bytes, target, 102400)
|| handles
.iter()
.any(|(whole, _, _)| whole.overlaps(102400, target, 102400))
{
return Err(Error::OutputAliasesInput);
}
handles.push((
target,
target.moe_down_slot(*slot)?,
source_handle.moe_group_down_column(total, index)?,
));
}
// Every real owner and mapping is admitted before the first copy.
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let mut copy = Ok(());
for (_, target, source) in &handles {
copy = self.driver.api.copy_moe_down(*target, *source);
if copy.is_err() {
break;
}
}
// Always drain and restore, including failed copies; original primary
// copy -> synchronize -> restore ordering and uncertainty poisoning.
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
fn grouped_buffers(&self, buffers: &[&DeviceBuffer<'_>]) -> Result<()> {
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
for buffer in buffers {
if !std::ptr::eq(self, buffer.context) {
return Err(Error::ContextMismatch);
}
buffer
.handle
.ok_or(Error::ContextPoisoned)?
.validate_projection_extent(buffer.bytes, 4)?;
}
Ok(())
}
/// One 5×T CUDA launch; exactly the original per-column native SwiGLU.
pub fn moe_swiglu_columns(
&self,
gate: &DeviceBuffer<'_>,
up: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
total: usize,
) -> Result<()> {
self.grouped_buffers(&[gate, up, output])?;
if !(1..=64).contains(&total) || [gate.bytes, up.bytes, output.bytes] != [total * 2560; 3] {
return Err(Error::InvalidProjectionShape);
}
let handles = [
gate.handle.unwrap(),
up.handle.unwrap(),
output.handle.unwrap(),
];
if handles[2].overlaps(output.bytes, handles[0], gate.bytes)
|| handles[2].overlaps(output.bytes, handles[1], up.bytes)
{
return Err(Error::OutputAliasesInput);
}
let kernel = {
let guard = self.enter()?;
let result = self.fixed_kernel(FixedOperation::GroupedSwiglu);
combine(result, guard.finish())?
};
let mut arguments =
ffi::ProjectionArguments::new(handles[0], handles[1], handles[2], 640, 640);
let guard = self.enter()?;
let result =
self.driver
.api
.launch_grouped_swiglu(kernel.function, 5, total as u32, &mut arguments);
self.complete_launch(result, arguments, guard)
}
/// Fresh original Q8_1 for every contiguous 640-value hidden column; one
/// original-lane Down projection launch for all columns using one weight.
pub fn project_routed_down_columns(
&self,
weights: &DeviceBuffer<'_>,
hidden: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
total: usize,
format: RoutedFormat,
) -> Result<()> {
self.project_routed_down_columns_weight(
NativeWeights::Raw(weights),
hidden,
output,
total,
format,
)
}
pub(super) fn project_routed_down_columns_weight(
&self,
weight_owner: NativeWeights<'_, '_>,
hidden: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
total: usize,
format: RoutedFormat,
) -> Result<()> {
let weights = weight_owner.buffer()?;
self.grouped_buffers(&[weights, hidden, output])?;
let operation = match format {
RoutedFormat::IQ4_NL => FixedOperation::GroupedDownIq4,
RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2,
_ => return Err(Error::UnsupportedProjection),
};
let shape = projection_shape(ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 2560,
columns: 640,
})?;
weight_owner.validate(
ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 2560,
columns: 640,
},
shape.weight_bytes,
)?;
if !(1..=64).contains(&total)
|| hidden.bytes != total * 2560
|| output.bytes != total * 10240
{
return Err(Error::InvalidProjectionShape);
}
let handles = [
weights.handle.unwrap(),
hidden.handle.unwrap(),
output.handle.unwrap(),
];
projection_ranges(ProjectionKind::Routed(format), &shape, handles)?;
// projection_ranges checks one-column overlap; require full grouped extents.
if handles[2].overlaps(output.bytes, handles[0], weights.bytes)
|| handles[2].overlaps(output.bytes, handles[1], hidden.bytes)
{
return Err(Error::OutputAliasesInput);
}
let scratch_bytes = total * 720;
if self
.allocated
.get()
.checked_add(scratch_bytes + 4)
.is_none_or(|v| v > self.budget)
{
return Err(Error::BudgetExceeded);
}
let scratch = self.allocate(scratch_bytes)?;
let mut status = match self.allocate(4) {
Ok(value) => value,
Err(error) => {
if self.poisoned.get() {
std::mem::forget(scratch);
return Err(error);
}
return combine(Err(error), scratch.release());
}
};
let result = (|| {
let q8 = scratch.handle.ok_or(Error::ContextPoisoned)?;
let flag = status.handle.ok_or(Error::ContextPoisoned)?;
q8.validate_projection_extent(scratch_bytes, 4)?;
flag.validate_projection_extent(4, 4)?;
for (h, n) in [
(handles[0], weights.bytes),
(handles[1], hidden.bytes),
(handles[2], output.bytes),
] {
if q8.overlaps(scratch_bytes, h, n) || flag.overlaps(4, h, n) {
return Err(Error::OutputAliasesInput);
}
}
if flag.overlaps(4, q8, scratch_bytes) {
return Err(Error::OutputAliasesInput);
}
status.copy_from(&[0; 4])?;
let (quantizer, projector) = {
let guard = self.enter()?;
let result = self
.fixed_kernel(FixedOperation::CommonQuantize)
.and_then(|q| self.fixed_kernel(operation).map(|p| (q, p)));
combine(result, guard.finish())?
};
// 640 is a multiple of32: flattening columns preserves every Q8
// block, lane schedule, scale/sum and per-column original order.
let mut args =
ffi::Q8QuantizeArguments::new(handles[1], q8, flag, (640 * total) as u32);
let guard = self.enter()?;
let launch = self.driver.api.launch_q8_quantize(
quantizer.function,
(640 * total).div_ceil(256) as u32,
&mut args,
);
self.complete_launch(launch, args, guard)?;
let mut bytes = [0; 4];
status.copy_to(&mut bytes)?;
if u32::from_le_bytes(bytes) != 0 {
return Err(Error::InvalidQ8Activation);
}
let mut args = ffi::ProjectionArguments::new(handles[0], q8, handles[2], 2560, 640);
let guard = self.enter()?;
let launch = self.driver.api.launch_grouped_projection(
projector.function,
640,
total as u32,
&mut args,
);
self.complete_launch(launch, args, guard)
})();
self.release_quantized_temporaries(result, scratch, status)
}
pub fn copy_routed_down_column(
&self,
source: &DeviceBuffer<'_>,
total: usize,
index: usize,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.grouped_buffers(&[source, output])?;
if !(1..=64).contains(&total) || source.bytes != total * 10240 || output.bytes != 10240 {
return Err(Error::InvalidProjectionShape);
}
let src = source.handle.unwrap();
let out = output.handle.unwrap();
if out.overlaps(output.bytes, src, source.bytes) {
return Err(Error::OutputAliasesInput);
}
let column = src.moe_group_down_column(total, index)?;
let guard = self.enter()?;
let copy = self.driver.api.copy_moe_down(out, column);
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
}
@@ -0,0 +1,271 @@
// Exact scalar column widening from iq4_nl_q8_1.ptx, SHA256 189b02cee8186379fb7b0bd07a831e1fb2764d29a98a17fd2b516c5459f9d4ce.
// IQ4_NL packed Dense/Routed projection, original native Fmt20/SmallK schedules.
// Derived from llama.cpp/ggml. Copyright (c) 2023-2026 The ggml authors.
// Native source SHA256 f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f
// Routed source SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// MIT License
//
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-36424714
// Cuda compilation tools, release 13.0, V13.0.88
// Based on NVVM 20.0.0
//
.version 9.0
.target sm_120
.address_size 64
// .globl leleka_iq4_nl_q8_1_dense
.const .align 1 .b8 values[16] = {129, 152, 173, 191, 207, 221, 234, 246, 1, 13, 25, 38, 53, 69, 89, 113};
// _ZZ5denseILb1EEvPKhPK2Q8PfjjE7partial has been demoted
// _ZZ5denseILb0EEvPKhPK2Q8PfjjE7partial has been demoted
.visible .entry leleka_iq4_nl_q8_1_routed_columns(
.param .u64 .ptr .align 1 leleka_iq4_nl_q8_1_routed_columns_param_0,
.param .u64 .ptr .align 1 leleka_iq4_nl_q8_1_routed_columns_param_1,
.param .u64 .ptr .align 1 leleka_iq4_nl_q8_1_routed_columns_param_2,
.param .u32 leleka_iq4_nl_q8_1_routed_columns_param_3,
.param .u32 leleka_iq4_nl_q8_1_routed_columns_param_4
)
.maxntid 128
{
.reg .pred %p<10>;
.reg .b16 %rs<11>;
.reg .b32 %r<98>;
.reg .b32 %f<22>;
.reg .b64 %rd<65>;
// Column address only; original scalar instructions below unchanged.
mov.u32 %r97, %ctaid.y;
mul.wide.u32 %rd63, %r97, 720;
mul.wide.u32 %rd64, %r97, 10240;
ld.param.u64 %rd8, [leleka_iq4_nl_q8_1_routed_columns_param_0];
ld.param.u64 %rd9, [leleka_iq4_nl_q8_1_routed_columns_param_1];
add.u64 %rd9, %rd9, %rd63;
ld.param.u64 %rd10, [leleka_iq4_nl_q8_1_routed_columns_param_2];
add.u64 %rd10, %rd10, %rd64;
ld.param.u32 %r7, [leleka_iq4_nl_q8_1_routed_columns_param_3];
ld.param.u32 %r6, [leleka_iq4_nl_q8_1_routed_columns_param_4];
mov.u32 %r1, %tid.x;
mov.u32 %r8, %ctaid.x;
shl.b32 %r9, %r8, 2;
mov.u32 %r10, %tid.y;
add.s32 %r2, %r9, %r10;
setp.ge.u32 %p1, %r2, %r7;
@%p1 bra $L__BB1_6;
shr.u32 %r11, %r6, 4;
and.b32 %r3, %r11, 268435454;
setp.ge.u32 %p2, %r1, %r3;
mov.f32 %f21, 0f00000000;
@%p2 bra $L__BB1_4;
shr.u32 %r12, %r6, 5;
mul.wide.u32 %rd11, %r12, %r2;
cvt.u64.u32 %rd12, %r1;
shr.u64 %rd13, %rd12, 1;
add.s64 %rd14, %rd13, %rd11;
cvta.to.global.u64 %rd15, %rd8;
mad.lo.s64 %rd16, %rd14, 18, %rd15;
add.s64 %rd62, %rd16, 8;
and.b32 %r13, %r1, 1;
mul.wide.u32 %rd2, %r13, 8;
cvta.to.global.u64 %rd17, %rd9;
mad.lo.s64 %rd18, %rd13, 36, %rd17;
add.s64 %rd61, %rd18, 20;
mov.f32 %f21, 0f00000000;
mov.u64 %rd21, values;
mov.u32 %r96, %r1;
$L__BB1_3:
add.s64 %rd19, %rd62, %rd2;
ld.global.u16 %rs3, [%rd19+-4];
cvt.u32.u16 %r30, %rs3;
ld.global.u16 %rs4, [%rd19+-6];
cvt.u32.u16 %r31, %rs4;
and.b32 %r32, %r31, 15;
cvt.u64.u32 %rd20, %r32;
add.s64 %rd22, %rd21, %rd20;
ld.const.u8 %r33, [%rd22];
shr.u32 %r34, %r31, 4;
and.b32 %r35, %r34, 15;
cvt.u64.u32 %rd23, %r35;
add.s64 %rd24, %rd21, %rd23;
ld.const.u8 %r36, [%rd24];
shr.u32 %r37, %r31, 8;
and.b32 %r38, %r37, 15;
cvt.u64.u32 %rd25, %r38;
add.s64 %rd26, %rd21, %rd25;
ld.const.u8 %rs5, [%rd26];
mul.wide.u16 %r39, %rs5, 256;
or.b32 %r40, %r39, %r33;
cvt.u64.u16 %rd27, %rs4;
shr.u64 %rd28, %rd27, 12;
add.s64 %rd29, %rd21, %rd28;
ld.const.u8 %rs6, [%rd29];
mul.wide.u16 %r41, %rs6, 256;
or.b32 %r42, %r41, %r36;
and.b32 %r43, %r30, 15;
cvt.u64.u32 %rd30, %r43;
add.s64 %rd31, %rd21, %rd30;
ld.const.u8 %r44, [%rd31];
shl.b32 %r45, %r44, 16;
or.b32 %r46, %r45, %r40;
shr.u32 %r47, %r30, 4;
and.b32 %r48, %r47, 15;
cvt.u64.u32 %rd32, %r48;
add.s64 %rd33, %rd21, %rd32;
ld.const.u8 %r49, [%rd33];
shl.b32 %r50, %r49, 16;
or.b32 %r51, %r50, %r42;
shr.u32 %r52, %r30, 8;
and.b32 %r53, %r52, 15;
cvt.u64.u32 %rd34, %r53;
add.s64 %rd35, %rd21, %rd34;
ld.const.u8 %r54, [%rd35];
shl.b32 %r55, %r54, 24;
or.b32 %r15, %r55, %r46;
cvt.u64.u16 %rd36, %rs3;
shr.u64 %rd37, %rd36, 12;
add.s64 %rd38, %rd21, %rd37;
ld.const.u8 %r56, [%rd38];
shl.b32 %r57, %r56, 24;
or.b32 %r19, %r57, %r51;
add.s64 %rd39, %rd61, %rd2;
ld.global.u32 %r16, [%rd39+-16];
mov.b32 %r17, 0;
// begin inline asm
dp4a.s32.s32 %r14, %r15, %r16, %r17;
// end inline asm
ld.global.u32 %r20, [%rd39];
// begin inline asm
dp4a.s32.s32 %r18, %r19, %r20, %r14;
// end inline asm
ld.global.u16 %rs7, [%rd19];
cvt.u32.u16 %r58, %rs7;
ld.global.u16 %rs8, [%rd19+-2];
cvt.u32.u16 %r59, %rs8;
and.b32 %r60, %r59, 15;
cvt.u64.u32 %rd40, %r60;
add.s64 %rd41, %rd21, %rd40;
ld.const.u8 %r61, [%rd41];
shr.u32 %r62, %r59, 4;
and.b32 %r63, %r62, 15;
cvt.u64.u32 %rd42, %r63;
add.s64 %rd43, %rd21, %rd42;
ld.const.u8 %r64, [%rd43];
shr.u32 %r65, %r59, 8;
and.b32 %r66, %r65, 15;
cvt.u64.u32 %rd44, %r66;
add.s64 %rd45, %rd21, %rd44;
ld.const.u8 %rs9, [%rd45];
mul.wide.u16 %r67, %rs9, 256;
or.b32 %r68, %r67, %r61;
cvt.u64.u16 %rd46, %rs8;
shr.u64 %rd47, %rd46, 12;
add.s64 %rd48, %rd21, %rd47;
ld.const.u8 %rs10, [%rd48];
mul.wide.u16 %r69, %rs10, 256;
or.b32 %r70, %r69, %r64;
and.b32 %r71, %r58, 15;
cvt.u64.u32 %rd49, %r71;
add.s64 %rd50, %rd21, %rd49;
ld.const.u8 %r72, [%rd50];
shl.b32 %r73, %r72, 16;
or.b32 %r74, %r73, %r68;
shr.u32 %r75, %r58, 4;
and.b32 %r76, %r75, 15;
cvt.u64.u32 %rd51, %r76;
add.s64 %rd52, %rd21, %rd51;
ld.const.u8 %r77, [%rd52];
shl.b32 %r78, %r77, 16;
or.b32 %r79, %r78, %r70;
shr.u32 %r80, %r58, 8;
and.b32 %r81, %r80, 15;
cvt.u64.u32 %rd53, %r81;
add.s64 %rd54, %rd21, %rd53;
ld.const.u8 %r82, [%rd54];
shl.b32 %r83, %r82, 24;
or.b32 %r23, %r83, %r74;
cvt.u64.u16 %rd55, %rs7;
shr.u64 %rd56, %rd55, 12;
add.s64 %rd57, %rd21, %rd56;
ld.const.u8 %r84, [%rd57];
shl.b32 %r85, %r84, 24;
or.b32 %r27, %r85, %r79;
ld.global.u32 %r24, [%rd39+-12];
// begin inline asm
dp4a.s32.s32 %r22, %r23, %r24, %r18;
// end inline asm
ld.global.u32 %r28, [%rd39+4];
// begin inline asm
dp4a.s32.s32 %r26, %r27, %r28, %r22;
// end inline asm
ld.global.u16 %rs1, [%rd62+-8];
// begin inline asm
{ cvt.f32.f16 %f7, %rs1;}
// end inline asm
ld.global.u16 %rs2, [%rd61+-20];
// begin inline asm
{ cvt.f32.f16 %f8, %rs2;}
// end inline asm
mul.ftz.f32 %f9, %f7, %f8;
cvt.rn.f32.s32 %f10, %r26;
fma.rn.ftz.f32 %f21, %f9, %f10, %f21;
add.s32 %r96, %r96, 32;
add.s64 %rd62, %rd62, 288;
add.s64 %rd61, %rd61, 576;
setp.lt.u32 %p3, %r96, %r3;
@%p3 bra $L__BB1_3;
$L__BB1_4:
mov.b32 %r86, %f21;
shfl.sync.bfly.b32 %r87|%p4, %r86, 16, 31, -1;
mov.b32 %f11, %r87;
add.ftz.f32 %f12, %f21, %f11;
mov.b32 %r88, %f12;
shfl.sync.bfly.b32 %r89|%p5, %r88, 8, 31, -1;
mov.b32 %f13, %r89;
add.ftz.f32 %f14, %f12, %f13;
mov.b32 %r90, %f14;
shfl.sync.bfly.b32 %r91|%p6, %r90, 4, 31, -1;
mov.b32 %f15, %r91;
add.ftz.f32 %f16, %f14, %f15;
mov.b32 %r92, %f16;
shfl.sync.bfly.b32 %r93|%p7, %r92, 2, 31, -1;
mov.b32 %f17, %r93;
add.ftz.f32 %f18, %f16, %f17;
mov.b32 %r94, %f18;
shfl.sync.bfly.b32 %r95|%p8, %r94, 1, 31, -1;
mov.b32 %f19, %r95;
add.ftz.f32 %f4, %f18, %f19;
setp.ne.s32 %p9, %r1, 0;
@%p9 bra $L__BB1_6;
cvta.to.global.u64 %rd58, %rd10;
mul.wide.u32 %rd59, %r2, 4;
add.s64 %rd60, %rd58, %rd59;
st.global.f32 [%rd60], %f4;
$L__BB1_6:
ret;
}
@@ -0,0 +1,430 @@
// Exact scalar column widening from q2_0_q8_1.ptx, SHA256 8e81dbbaa76d8516476339c168f1d9c172341a78ccecda08714a13a5687e3b6e.
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh}
// and ggml/src/ggml-common.h. Shared Q8_1 admission and quantization; original emitted math preserved.
// Native source: native_mmvq.cu (SHA-256 f2fc636e).
//
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-36424714
// Cuda compilation tools, release 13.0, V13.0.88
// Based on NVVM 20.0.0
//
.version 9.0
.target sm_120
.address_size 64
// .globl leleka_quantize_q8_1
// N%32 whole-warp tails are guarded before memory access/collectives.
.visible .entry leleka_q2_0_q8_1_routed_columns(
.param .u64 .ptr .align 1 leleka_q2_0_q8_1_routed_columns_param_0,
.param .u64 .ptr .align 1 leleka_q2_0_q8_1_routed_columns_param_1,
.param .u64 .ptr .align 1 leleka_q2_0_q8_1_routed_columns_param_2,
.param .u32 leleka_q2_0_q8_1_routed_columns_param_3,
.param .u32 leleka_q2_0_q8_1_routed_columns_param_4
)
{
.reg .pred %p<12>;
.reg .b16 %rs<16>;
.reg .b32 %r<218>;
.reg .b32 %f<37>;
.reg .b64 %rd<52>;
// Column address only; original scalar instructions below unchanged.
mov.u32 %r217, %ctaid.y;
mul.wide.u32 %rd50, %r217, 720;
mul.wide.u32 %rd51, %r217, 10240;
ld.param.u64 %rd16, [leleka_q2_0_q8_1_routed_columns_param_0];
ld.param.u64 %rd18, [leleka_q2_0_q8_1_routed_columns_param_1];
add.u64 %rd18, %rd18, %rd50;
ld.param.u32 %r11, [leleka_q2_0_q8_1_routed_columns_param_3];
ld.param.u32 %r10, [leleka_q2_0_q8_1_routed_columns_param_4];
cvta.to.global.u64 %rd1, %rd18;
mov.u32 %r12, %ctaid.x;
shl.b32 %r13, %r12, 2;
mov.u32 %r14, %tid.y;
add.s32 %r1, %r13, %r14;
setp.ge.u32 %p1, %r1, %r11;
@%p1 bra $L__BB0_9;
cvta.to.global.u64 %rd48, %rd16;
mov.u32 %r2, %tid.x;
shr.u32 %r15, %r10, 6;
mul.wide.u32 %rd3, %r15, %r1;
shl.b32 %r3, %r15, 1;
setp.ge.u32 %p2, %r2, %r3;
mov.f32 %f36, 0f00000000;
@%p2 bra $L__BB0_7;
and.b32 %r4, %r2, 1;
not.b32 %r16, %r2;
add.s32 %r5, %r3, %r16;
and.b32 %r17, %r5, 32;
setp.ne.s32 %p3, %r17, 0;
mov.f32 %f36, 0f00000000;
mov.u32 %r216, %r2;
@%p3 bra $L__BB0_4;
shl.b32 %r51, %r4, 2;
and.b32 %r52, %r2, 1022;
shr.u32 %r53, %r2, 1;
cvt.u64.u32 %rd19, %r53;
add.s64 %rd20, %rd3, %rd19;
mad.lo.s64 %rd21, %rd20, 18, %rd48;
ld.global.nc.u16 %rs1, [%rd21];
// begin inline asm
{ cvt.f32.f16 %f11, %rs1;}
// end inline asm
or.b32 %r54, %r52, %r4;
mul.wide.u32 %rd22, %r54, 36;
add.s64 %rd23, %rd1, %rd22;
mul.wide.u32 %rd24, %r51, 2;
add.s64 %rd25, %rd21, %rd24;
ld.global.nc.u16 %rs2, [%rd25+2];
cvt.s32.s16 %r55, %rs2;
ld.global.nc.u32 %r19, [%rd23+4];
ld.global.nc.u32 %r23, [%rd23+8];
and.b32 %r56, %r55, 30583;
mov.b32 %r57, 33620223;
prmt.b32 %r58, %r57, %r57, %r56;
shr.u32 %r59, %r55, 2;
and.b32 %r60, %r59, 30583;
prmt.b32 %r61, %r57, %r57, %r60;
mov.b32 %r62, 20800;
prmt.b32 %r20, %r58, %r61, %r62;
mov.b32 %r63, 29538;
prmt.b32 %r24, %r58, %r61, %r63;
mov.b32 %r21, 0;
// begin inline asm
dp4a.s32.s32 %r18, %r19, %r20, %r21;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r22, %r23, %r24, %r18;
// end inline asm
ld.global.nc.u16 %rs3, [%rd25+4];
cvt.s32.s16 %r64, %rs3;
ld.global.nc.u32 %r27, [%rd23+12];
ld.global.nc.u32 %r31, [%rd23+16];
and.b32 %r65, %r64, 30583;
prmt.b32 %r66, %r57, %r57, %r65;
shr.u32 %r67, %r64, 2;
and.b32 %r68, %r67, 30583;
prmt.b32 %r69, %r57, %r57, %r68;
prmt.b32 %r28, %r66, %r69, %r62;
prmt.b32 %r32, %r66, %r69, %r63;
// begin inline asm
dp4a.s32.s32 %r26, %r27, %r28, %r22;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r30, %r31, %r32, %r26;
// end inline asm
ld.global.nc.u16 %rs4, [%rd25+6];
cvt.s32.s16 %r70, %rs4;
ld.global.nc.u32 %r35, [%rd23+20];
ld.global.nc.u32 %r39, [%rd23+24];
and.b32 %r71, %r70, 30583;
prmt.b32 %r72, %r57, %r57, %r71;
shr.u32 %r73, %r70, 2;
and.b32 %r74, %r73, 30583;
prmt.b32 %r75, %r57, %r57, %r74;
prmt.b32 %r36, %r72, %r75, %r62;
prmt.b32 %r40, %r72, %r75, %r63;
// begin inline asm
dp4a.s32.s32 %r34, %r35, %r36, %r30;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r38, %r39, %r40, %r34;
// end inline asm
ld.global.nc.u16 %rs5, [%rd25+8];
cvt.s32.s16 %r76, %rs5;
ld.global.nc.u32 %r43, [%rd23+28];
ld.global.nc.u32 %r47, [%rd23+32];
and.b32 %r77, %r76, 30583;
prmt.b32 %r78, %r57, %r57, %r77;
shr.u32 %r79, %r76, 2;
and.b32 %r80, %r79, 30583;
prmt.b32 %r81, %r57, %r57, %r80;
prmt.b32 %r44, %r78, %r81, %r62;
prmt.b32 %r48, %r78, %r81, %r63;
// begin inline asm
dp4a.s32.s32 %r42, %r43, %r44, %r38;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r46, %r47, %r48, %r42;
// end inline asm
ld.global.nc.u32 %r50, [%rd23];
// begin inline asm
{.reg .f16 low,high;
mov.b32 {low,high},%r50;
cvt.f32.f16 %f12, low;}
// end inline asm
mul.ftz.f32 %f13, %f11, %f12;
cvt.rn.f32.s32 %f14, %r46;
fma.rn.ftz.f32 %f36, %f13, %f14, 0f00000000;
add.s32 %r216, %r2, 32;
$L__BB0_4:
setp.lt.u32 %p4, %r5, 32;
@%p4 bra $L__BB0_7;
and.b32 %r82, %r216, 2046;
or.b32 %r83, %r82, %r4;
mul.wide.u32 %rd26, %r83, 36;
add.s64 %rd27, %rd26, %rd1;
add.s64 %rd49, %rd27, 16;
cvt.u64.u32 %rd28, %r216;
shr.u64 %rd29, %rd28, 1;
add.s64 %rd30, %rd29, %rd3;
mul.lo.s64 %rd5, %rd30, 18;
add.s64 %rd31, %rd28, 32;
shr.u64 %rd32, %rd31, 1;
add.s64 %rd33, %rd32, %rd3;
mul.lo.s64 %rd6, %rd33, 18;
mul.wide.u32 %rd34, %r4, 8;
add.s64 %rd35, %rd6, %rd34;
add.s64 %rd7, %rd35, 4;
add.s64 %rd36, %rd5, %rd34;
add.s64 %rd8, %rd36, 8;
add.s32 %r85, %r216, 32;
and.b32 %r86, %r85, 4094;
or.b32 %r87, %r86, %r4;
mul.wide.u32 %rd37, %r87, 36;
add.s64 %rd38, %rd37, %rd1;
add.s64 %rd47, %rd38, 16;
$L__BB0_6:
add.s64 %rd39, %rd48, %rd5;
ld.global.nc.u16 %rs6, [%rd39];
// begin inline asm
{ cvt.f32.f16 %f15, %rs6;}
// end inline asm
add.s64 %rd40, %rd48, %rd8;
ld.global.nc.u16 %rs8, [%rd40+-6];
cvt.s32.s16 %r154, %rs8;
ld.global.nc.u32 %r89, [%rd49+-12];
ld.global.nc.u32 %r93, [%rd49+-8];
and.b32 %r155, %r154, 30583;
mov.b32 %r156, 33620223;
prmt.b32 %r157, %r156, %r156, %r155;
shr.u32 %r158, %r154, 2;
and.b32 %r159, %r158, 30583;
prmt.b32 %r160, %r156, %r156, %r159;
mov.b32 %r161, 20800;
prmt.b32 %r90, %r157, %r160, %r161;
mov.b32 %r162, 29538;
prmt.b32 %r94, %r157, %r160, %r162;
mov.b32 %r124, 0;
// begin inline asm
dp4a.s32.s32 %r88, %r89, %r90, %r124;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r92, %r93, %r94, %r88;
// end inline asm
ld.global.nc.u16 %rs9, [%rd40+-4];
cvt.s32.s16 %r163, %rs9;
ld.global.nc.u32 %r97, [%rd49+-4];
ld.global.nc.u32 %r101, [%rd49];
and.b32 %r164, %r163, 30583;
prmt.b32 %r165, %r156, %r156, %r164;
shr.u32 %r166, %r163, 2;
and.b32 %r167, %r166, 30583;
prmt.b32 %r168, %r156, %r156, %r167;
prmt.b32 %r98, %r165, %r168, %r161;
prmt.b32 %r102, %r165, %r168, %r162;
// begin inline asm
dp4a.s32.s32 %r96, %r97, %r98, %r92;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r100, %r101, %r102, %r96;
// end inline asm
ld.global.nc.u16 %rs10, [%rd40+-2];
cvt.s32.s16 %r169, %rs10;
ld.global.nc.u32 %r105, [%rd49+4];
ld.global.nc.u32 %r109, [%rd49+8];
and.b32 %r170, %r169, 30583;
prmt.b32 %r171, %r156, %r156, %r170;
shr.u32 %r172, %r169, 2;
and.b32 %r173, %r172, 30583;
prmt.b32 %r174, %r156, %r156, %r173;
prmt.b32 %r106, %r171, %r174, %r161;
prmt.b32 %r110, %r171, %r174, %r162;
// begin inline asm
dp4a.s32.s32 %r104, %r105, %r106, %r100;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r108, %r109, %r110, %r104;
// end inline asm
ld.global.nc.u16 %rs11, [%rd40];
cvt.s32.s16 %r175, %rs11;
ld.global.nc.u32 %r113, [%rd49+12];
ld.global.nc.u32 %r117, [%rd49+16];
and.b32 %r176, %r175, 30583;
prmt.b32 %r177, %r156, %r156, %r176;
shr.u32 %r178, %r175, 2;
and.b32 %r179, %r178, 30583;
prmt.b32 %r180, %r156, %r156, %r179;
prmt.b32 %r114, %r177, %r180, %r161;
prmt.b32 %r118, %r177, %r180, %r162;
// begin inline asm
dp4a.s32.s32 %r112, %r113, %r114, %r108;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r116, %r117, %r118, %r112;
// end inline asm
ld.global.nc.u32 %r120, [%rd49+-16];
// begin inline asm
{.reg .f16 low,high;
mov.b32 {low,high},%r120;
cvt.f32.f16 %f16, low;}
// end inline asm
mul.ftz.f32 %f19, %f15, %f16;
cvt.rn.f32.s32 %f20, %r116;
fma.rn.ftz.f32 %f21, %f19, %f20, %f36;
add.s64 %rd41, %rd48, %rd6;
ld.global.nc.u16 %rs7, [%rd41];
// begin inline asm
{ cvt.f32.f16 %f17, %rs7;}
// end inline asm
add.s64 %rd42, %rd48, %rd7;
ld.global.nc.u16 %rs12, [%rd42+-2];
cvt.s32.s16 %r181, %rs12;
ld.global.nc.u32 %r122, [%rd47+-12];
ld.global.nc.u32 %r126, [%rd47+-8];
and.b32 %r182, %r181, 30583;
prmt.b32 %r183, %r156, %r156, %r182;
shr.u32 %r184, %r181, 2;
and.b32 %r185, %r184, 30583;
prmt.b32 %r186, %r156, %r156, %r185;
prmt.b32 %r123, %r183, %r186, %r161;
prmt.b32 %r127, %r183, %r186, %r162;
// begin inline asm
dp4a.s32.s32 %r121, %r122, %r123, %r124;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r125, %r126, %r127, %r121;
// end inline asm
ld.global.nc.u16 %rs13, [%rd42];
cvt.s32.s16 %r187, %rs13;
ld.global.nc.u32 %r130, [%rd47+-4];
ld.global.nc.u32 %r134, [%rd47];
and.b32 %r188, %r187, 30583;
prmt.b32 %r189, %r156, %r156, %r188;
shr.u32 %r190, %r187, 2;
and.b32 %r191, %r190, 30583;
prmt.b32 %r192, %r156, %r156, %r191;
prmt.b32 %r131, %r189, %r192, %r161;
prmt.b32 %r135, %r189, %r192, %r162;
// begin inline asm
dp4a.s32.s32 %r129, %r130, %r131, %r125;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r133, %r134, %r135, %r129;
// end inline asm
ld.global.nc.u16 %rs14, [%rd42+2];
cvt.s32.s16 %r193, %rs14;
ld.global.nc.u32 %r138, [%rd47+4];
ld.global.nc.u32 %r142, [%rd47+8];
and.b32 %r194, %r193, 30583;
prmt.b32 %r195, %r156, %r156, %r194;
shr.u32 %r196, %r193, 2;
and.b32 %r197, %r196, 30583;
prmt.b32 %r198, %r156, %r156, %r197;
prmt.b32 %r139, %r195, %r198, %r161;
prmt.b32 %r143, %r195, %r198, %r162;
// begin inline asm
dp4a.s32.s32 %r137, %r138, %r139, %r133;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r141, %r142, %r143, %r137;
// end inline asm
ld.global.nc.u16 %rs15, [%rd42+4];
cvt.s32.s16 %r199, %rs15;
ld.global.nc.u32 %r146, [%rd47+12];
ld.global.nc.u32 %r150, [%rd47+16];
and.b32 %r200, %r199, 30583;
prmt.b32 %r201, %r156, %r156, %r200;
shr.u32 %r202, %r199, 2;
and.b32 %r203, %r202, 30583;
prmt.b32 %r204, %r156, %r156, %r203;
prmt.b32 %r147, %r201, %r204, %r161;
prmt.b32 %r151, %r201, %r204, %r162;
// begin inline asm
dp4a.s32.s32 %r145, %r146, %r147, %r141;
// end inline asm
// begin inline asm
dp4a.s32.s32 %r149, %r150, %r151, %r145;
// end inline asm
ld.global.nc.u32 %r153, [%rd47+-16];
// begin inline asm
{.reg .f16 low,high;
mov.b32 {low,high},%r153;
cvt.f32.f16 %f18, low;}
// end inline asm
mul.ftz.f32 %f22, %f17, %f18;
cvt.rn.f32.s32 %f23, %r149;
fma.rn.ftz.f32 %f36, %f22, %f23, %f21;
add.s32 %r216, %r216, 64;
add.s64 %rd49, %rd49, 2304;
add.s64 %rd48, %rd48, 576;
add.s64 %rd47, %rd47, 2304;
setp.lt.u32 %p5, %r216, %r3;
@%p5 bra $L__BB0_6;
$L__BB0_7:
mov.b32 %r205, %f36;
shfl.sync.bfly.b32 %r206|%p6, %r205, 16, 31, -1;
mov.b32 %f24, %r206;
add.ftz.f32 %f25, %f36, %f24;
mov.b32 %r207, %f25;
shfl.sync.bfly.b32 %r208|%p7, %r207, 8, 31, -1;
mov.b32 %f26, %r208;
add.ftz.f32 %f27, %f25, %f26;
mov.b32 %r209, %f27;
shfl.sync.bfly.b32 %r210|%p8, %r209, 4, 31, -1;
mov.b32 %f28, %r210;
add.ftz.f32 %f29, %f27, %f28;
mov.b32 %r211, %f29;
shfl.sync.bfly.b32 %r212|%p9, %r211, 2, 31, -1;
mov.b32 %f30, %r212;
add.ftz.f32 %f31, %f29, %f30;
mov.b32 %r213, %f31;
shfl.sync.bfly.b32 %r214|%p10, %r213, 1, 31, -1;
mov.b32 %f32, %r214;
add.ftz.f32 %f7, %f31, %f32;
setp.ne.s32 %p11, %r2, 0;
@%p11 bra $L__BB0_9;
ld.param.u64 %rd46, [leleka_q2_0_q8_1_routed_columns_param_2];
add.u64 %rd46, %rd46, %rd51;
cvta.to.global.u64 %rd43, %rd46;
mul.wide.u32 %rd44, %r1, 4;
add.s64 %rd45, %rd43, %rd44;
st.global.f32 [%rd45], %f7;
$L__BB0_9:
ret;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,391 @@
// Bounded true-column port: exact scalar per-column arithmetic; no MMQ tensorcore rounding.
// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh}
// and ggml/src/ggml-common.h. IQ3_XXS x Q8_1 fixed routed projection only.
// Native source: iq_kernels.cu (SHA-256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537).
//
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-36424714
// Cuda compilation tools, release 13.0, V13.0.88
// Based on NVVM 20.0.0
//
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-36424714
// Cuda compilation tools, release 13.0, V13.0.88
// Based on NVVM 20.0.0
//
.version 9.0
.target sm_120
.address_size 64
// .globl leleka_iq3_xxs_q8_1_routed
.const .align 4 .b8 grid[1024] = {4, 4, 4, 4, 20, 4, 4, 4, 36, 4, 4, 4, 12, 12, 4, 4, 28, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 4, 20, 20, 4, 4, 12, 28, 4, 4, 20, 36, 4, 4, 28, 62, 4, 4, 44, 62, 4, 4, 12, 4, 12, 4, 28, 4, 12, 4, 4, 12, 12, 4, 20, 12, 12, 4, 12, 20, 12, 4, 44, 20, 12, 4, 4, 28, 12, 4, 20, 28, 12, 4, 12, 36, 12, 4, 36, 44, 12, 4, 4, 62, 12, 4, 4, 4, 20, 4, 20, 4, 20, 4, 36, 4, 20, 4, 12, 12, 20, 4, 4, 20, 20, 4, 20, 20, 20, 4, 12, 28, 20, 4, 28, 28, 20, 4, 62, 28, 20, 4, 12, 44, 20, 4, 62, 44, 20, 4, 44, 62, 20, 4, 12, 4, 28, 4, 62, 4, 28, 4, 4, 12, 28, 4, 20, 12, 28, 4, 44, 20, 28, 4, 4, 62, 28, 4, 28, 12, 36, 4, 62, 28, 36, 4, 36, 36, 36, 4, 62, 44, 36, 4, 28, 62, 36, 4, 44, 62, 36, 4, 12, 4, 44, 4, 62, 4, 44, 4, 20, 28, 44, 4, 20, 44, 44, 4, 44, 28, 52, 4, 36, 52, 52, 4, 4, 12, 62, 4, 36, 12, 62, 4, 52, 12, 62, 4, 28, 36, 62, 4, 12, 52, 62, 4, 12, 4, 4, 12, 28, 4, 4, 12, 4, 12, 4, 12, 20, 12, 4, 12, 12, 20, 4, 12, 28, 20, 4, 12, 4, 28, 4, 12, 20, 28, 4, 12, 36, 28, 4, 12, 62, 36, 4, 12, 4, 44, 4, 12, 4, 4, 12, 12, 20, 4, 12, 12, 12, 12, 12, 12, 4, 20, 12, 12, 20, 20, 12, 12, 12, 4, 20, 12, 28, 4, 20, 12, 4, 12, 20, 12, 20, 12, 20, 12, 12, 20, 20, 12, 4, 28, 20, 12, 20, 62, 20, 12, 4, 4, 28, 12, 20, 4, 28, 12, 4, 20, 28, 12, 12, 28, 28, 12, 52, 36, 28, 12, 52, 52, 28, 12, 12, 4, 36, 12, 44, 4, 36, 12, 4, 44, 36, 12, 4, 20, 44, 12, 36, 20, 44, 12, 52, 36, 44, 12, 12, 62, 44, 12, 44, 4, 52, 12, 20, 20, 62, 12, 4, 36, 62, 12, 4, 4, 4, 20, 20, 4, 4, 20, 12, 12, 4, 20, 28, 12, 4, 20, 4, 20, 4, 20, 20, 20, 4, 20, 52, 20, 4, 20, 12, 28, 4, 20, 20, 36, 4, 20, 12, 4, 12, 20, 28, 4, 12, 20, 44, 4, 12, 20, 4, 12, 12, 20, 20, 12, 12, 20, 12, 20, 12, 20, 4, 28, 12, 20, 28, 52, 12, 20, 62, 52, 12, 20, 4, 62, 12, 20, 4, 4, 20, 20, 20, 4, 20, 20, 12, 12, 20, 20, 62, 12, 20, 20, 4, 20, 20, 20, 20, 20, 20, 20, 62, 28, 20, 20, 4, 36, 20, 20, 44, 44, 20, 20, 12, 4, 28, 20, 4, 12, 28, 20, 36, 12, 28, 20, 4, 62, 28, 20, 36, 62, 28, 20, 44, 28, 36, 20, 28, 44, 36, 20, 28, 4, 44, 20, 62, 20, 44, 20, 12, 36, 44, 20, 36, 62, 44, 20, 12, 4, 62, 20, 28, 4, 62, 20, 52, 12, 62, 20, 44, 36, 62, 20, 12, 4, 4, 28, 4, 12, 4, 28, 20, 12, 4, 28, 12, 20, 4, 28, 28, 20, 4, 28, 4, 44, 4, 28, 44, 52, 4, 28, 20, 62, 4, 28, 4, 4, 12, 28, 20, 4, 12, 28, 4, 20, 12, 28, 12, 28, 12, 28, 36, 36, 12, 28, 52, 36, 12, 28, 12, 4, 20, 28, 28, 4, 20, 28, 4, 12, 20, 28, 44, 20, 20, 28, 20, 44, 20, 28, 20, 62, 20, 28, 12, 12, 28, 28, 28, 28, 28, 28, 4, 28, 36, 28, 62, 36, 36, 28, 20, 62, 36, 28, 4, 4, 44, 28, 52, 4, 44, 28, 20, 20, 44, 28, 44, 44, 44, 28, 36, 12, 52, 28, 52, 28, 52, 28, 28, 52, 52, 28, 28, 28, 62, 28, 4, 52, 62, 28, 36, 4, 4, 36, 62, 12, 4, 36, 44, 28, 4, 36, 62, 28, 4, 36, 28, 44, 4, 36, 62, 44, 4, 36, 36, 62, 12, 36, 4, 20, 20, 36, 62, 28, 20, 36, 4, 36, 20, 36, 4, 52, 20, 36, 52, 52, 20, 36, 62, 4, 28, 36, 44, 36, 28, 36, 36, 4, 36, 36, 12, 44, 36, 36, 36, 52, 36, 36, 44, 20, 44, 36, 28, 36, 44, 36, 4, 62, 44, 36, 44, 4, 62, 36, 4, 12, 62, 36, 20, 12, 62, 36, 4, 28, 62, 36, 20, 12, 4, 44, 12, 36, 4, 44, 4, 62, 4, 44, 4, 4, 12, 44, 52, 4, 12, 44, 52, 20, 12, 44, 44, 44, 12, 44, 36, 12, 20, 44, 20, 28, 20, 44, 20, 62, 20, 44, 20, 4, 28, 44, 28, 44, 28, 44, 4, 12, 36, 44, 28, 20, 36, 44, 62, 20, 36, 44, 20, 62, 36, 44, 20, 4, 44, 44, 12, 28, 44, 44, 4, 44, 52, 44, 36, 20, 62, 44, 20, 36, 62, 44, 36, 20, 4, 52, 36, 36, 4, 52, 52, 36, 4, 52, 36, 52, 4, 52, 12, 20, 12, 52, 12, 52, 12, 52, 62, 12, 20, 52, 36, 52, 20, 52, 4, 28, 28, 52, 52, 28, 28, 52, 36, 36, 36, 52, 44, 4, 44, 52, 20, 44, 44, 52, 28, 28, 52, 52, 28, 4, 62, 52, 12, 20, 62, 52, 28, 4, 4, 62, 44, 4, 4, 62, 62, 4, 4, 62, 4, 12, 4, 62, 20, 28, 4, 62, 20, 44, 4, 62, 52, 20, 12, 62, 4, 36, 12, 62, 20, 12, 20, 62, 44, 36, 20, 62, 20, 44, 20, 62, 4, 4, 28, 62, 44, 12, 28, 62, 28, 28, 28, 62, 4, 52, 28, 62, 12, 20, 36, 62, 12, 36, 36, 62, 4, 4, 44, 62, 20, 4, 44, 62, 36, 20, 44, 62, 4, 28, 52, 62};
.visible .entry leleka_iq3_xxs_q8_1_routed_columns(
.param .u64 .ptr .align 1 leleka_iq3_xxs_q8_1_routed_columns_param_0,
.param .u64 .ptr .align 1 leleka_iq3_xxs_q8_1_routed_columns_param_1,
.param .u64 .ptr .align 1 leleka_iq3_xxs_q8_1_routed_columns_param_2,
.param .u32 leleka_iq3_xxs_q8_1_routed_columns_param_3,
.param .u32 leleka_iq3_xxs_q8_1_routed_columns_param_4
)
.maxntid 128
{
.reg .pred %p<10>;
.reg .b16 %rs<14>;
.reg .b32 %r<194>;
.reg .b32 %f<22>;
.reg .b64 %rd<50>;
.reg .b32 %group_col;
.reg .b64 %group_offset, %group_entry;
ld.param.u64 %rd9, [leleka_iq3_xxs_q8_1_routed_columns_param_0];
ld.param.u64 %rd10, [leleka_iq3_xxs_q8_1_routed_columns_param_1];
ld.param.u64 %rd11, [leleka_iq3_xxs_q8_1_routed_columns_param_2];
ld.param.u32 %r8, [leleka_iq3_xxs_q8_1_routed_columns_param_3];
ld.param.u32 %r7, [leleka_iq3_xxs_q8_1_routed_columns_param_4];
// Closed T1..64 grid-y column; table and destination extents validated by Rust.
mov.u32 %group_col, %ctaid.y;
mul.wide.u32 %group_offset, %group_col, 8;
add.u64 %group_entry, %rd10, %group_offset;
ld.global.u64 %rd10, [%group_entry];
mul.wide.u32 %group_offset, %group_col, 2560;
add.u64 %rd11, %rd11, %group_offset;
mov.u32 %r9, %ctaid.x;
shl.b32 %r10, %r9, 2;
mov.u32 %r11, %tid.y;
add.s32 %r1, %r10, %r11;
setp.ge.u32 %p1, %r1, %r8;
@%p1 bra $L__BB0_6;
shr.u32 %r2, %r7, 8;
mov.u32 %r3, %tid.x;
shl.b32 %r4, %r2, 3;
setp.ge.u32 %p2, %r3, %r4;
mov.f32 %f21, 0f00000000;
@%p2 bra $L__BB0_4;
shl.b32 %r12, %r3, 2;
and.b32 %r13, %r12, 28;
cvt.u64.u32 %rd12, %r13;
mul.wide.u32 %rd13, %r3, 36;
cvta.to.global.u64 %rd14, %rd10;
add.s64 %rd15, %rd13, %rd14;
add.s64 %rd49, %rd15, 16;
cvt.u64.u32 %rd16, %r3;
shr.u64 %rd17, %rd16, 3;
mul.wide.u32 %rd18, %r2, %r1;
add.s64 %rd19, %rd17, %rd18;
cvta.to.global.u64 %rd20, %rd9;
mad.lo.s64 %rd48, %rd19, 98, %rd20;
and.b32 %r14, %r3, 7;
mul.wide.u32 %rd21, %r14, 8;
or.b64 %rd3, %rd21, 4;
add.s64 %rd4, %rd12, 68;
mov.f32 %f21, 0f00000000;
mov.u64 %rd26, grid;
mov.u32 %r193, %r3;
$L__BB0_3:
add.s64 %rd22, %rd48, %rd3;
ld.global.u16 %rs2, [%rd22+-2];
ld.global.u16 %rs3, [%rd22];
ld.global.u16 %rs4, [%rd22+2];
ld.global.u16 %rs5, [%rd22+4];
add.s64 %rd23, %rd48, %rd4;
ld.global.u16 %r64, [%rd23+-2];
ld.global.u16 %r65, [%rd23];
shl.b32 %r66, %r65, 16;
or.b32 %r67, %r66, %r64;
shl.b16 %rs6, %rs2, 2;
cvt.u64.u16 %rd24, %rs6;
and.b64 %rd25, %rd24, 1020;
add.s64 %rd27, %rd26, %rd25;
ld.const.u32 %r68, [%rd27];
shr.u16 %rs7, %rs2, 8;
cvt.u32.u16 %r69, %rs7;
mul.wide.u32 %rd28, %r69, 4;
add.s64 %rd29, %rd26, %rd28;
ld.const.u32 %r70, [%rd29];
and.b32 %r71, %r64, 255;
popc.b32 %r72, %r71;
shl.b32 %r73, %r72, 7;
and.b32 %r74, %r73, 128;
xor.b32 %r75, %r74, %r71;
mul.lo.s32 %r76, %r75, 16843009;
and.b32 %r77, %r76, 134480385;
add.s32 %r78, %r77, 2139062143;
or.b32 %r15, %r78, %r77;
// begin inline asm
prmt.b32 %r15, %r15, 0, 0xba98;
// end inline asm
and.b32 %r79, %r76, -2143281136;
or.b32 %r80, %r79, -2139062144;
add.s32 %r81, %r80, -16843009;
or.b32 %r17, %r81, %r79;
// begin inline asm
prmt.b32 %r17, %r17, 0, 0xba98;
// end inline asm
xor.b32 %r82, %r15, %r68;
or.b32 %r83, %r82, -2139062144;
and.b32 %r84, %r15, 2139062143;
and.b32 %r85, %r68, -2139062144;
sub.s32 %r86, %r83, %r84;
xor.b32 %r87, %r85, %r86;
xor.b32 %r20, %r87, -2139062144;
xor.b32 %r88, %r17, %r70;
or.b32 %r89, %r88, -2139062144;
and.b32 %r90, %r17, 2139062143;
and.b32 %r91, %r70, -2139062144;
sub.s32 %r92, %r89, %r90;
xor.b32 %r93, %r91, %r92;
xor.b32 %r24, %r93, -2139062144;
ld.global.u32 %r21, [%rd49+-12];
mov.b32 %r22, 0;
// begin inline asm
dp4a.s32.s32 %r19, %r20, %r21, %r22;
// end inline asm
ld.global.u32 %r25, [%rd49+-8];
// begin inline asm
dp4a.s32.s32 %r23, %r24, %r25, %r19;
// end inline asm
shl.b16 %rs8, %rs3, 2;
cvt.u64.u16 %rd30, %rs8;
and.b64 %rd31, %rd30, 1020;
add.s64 %rd32, %rd26, %rd31;
ld.const.u32 %r94, [%rd32];
shr.u16 %rs9, %rs3, 8;
cvt.u32.u16 %r95, %rs9;
mul.wide.u32 %rd33, %r95, 4;
add.s64 %rd34, %rd26, %rd33;
ld.const.u32 %r96, [%rd34];
shr.u32 %r97, %r64, 7;
and.b32 %r98, %r97, 255;
popc.b32 %r99, %r98;
shl.b32 %r100, %r99, 7;
and.b32 %r101, %r100, 128;
xor.b32 %r102, %r101, %r98;
mul.lo.s32 %r103, %r102, 16843009;
and.b32 %r104, %r103, 134480385;
add.s32 %r105, %r104, 2139062143;
or.b32 %r27, %r105, %r104;
// begin inline asm
prmt.b32 %r27, %r27, 0, 0xba98;
// end inline asm
and.b32 %r106, %r103, -2143281136;
or.b32 %r107, %r106, -2139062144;
add.s32 %r108, %r107, -16843009;
or.b32 %r29, %r108, %r106;
// begin inline asm
prmt.b32 %r29, %r29, 0, 0xba98;
// end inline asm
xor.b32 %r109, %r27, %r94;
or.b32 %r110, %r109, -2139062144;
and.b32 %r111, %r27, 2139062143;
and.b32 %r112, %r94, -2139062144;
sub.s32 %r113, %r110, %r111;
xor.b32 %r114, %r112, %r113;
xor.b32 %r32, %r114, -2139062144;
xor.b32 %r115, %r29, %r96;
or.b32 %r116, %r115, -2139062144;
and.b32 %r117, %r29, 2139062143;
and.b32 %r118, %r96, -2139062144;
sub.s32 %r119, %r116, %r117;
xor.b32 %r120, %r118, %r119;
xor.b32 %r36, %r120, -2139062144;
ld.global.u32 %r33, [%rd49+-4];
// begin inline asm
dp4a.s32.s32 %r31, %r32, %r33, %r23;
// end inline asm
ld.global.u32 %r37, [%rd49];
// begin inline asm
dp4a.s32.s32 %r35, %r36, %r37, %r31;
// end inline asm
shl.b16 %rs10, %rs4, 2;
cvt.u64.u16 %rd35, %rs10;
and.b64 %rd36, %rd35, 1020;
add.s64 %rd37, %rd26, %rd36;
ld.const.u32 %r121, [%rd37];
shr.u16 %rs11, %rs4, 8;
cvt.u32.u16 %r122, %rs11;
mul.wide.u32 %rd38, %r122, 4;
add.s64 %rd39, %rd26, %rd38;
ld.const.u32 %r123, [%rd39];
shr.u32 %r124, %r67, 14;
and.b32 %r125, %r124, 255;
popc.b32 %r126, %r125;
shl.b32 %r127, %r126, 7;
and.b32 %r128, %r127, 128;
xor.b32 %r129, %r128, %r125;
mul.lo.s32 %r130, %r129, 16843009;
and.b32 %r131, %r130, 134480385;
add.s32 %r132, %r131, 2139062143;
or.b32 %r39, %r132, %r131;
// begin inline asm
prmt.b32 %r39, %r39, 0, 0xba98;
// end inline asm
and.b32 %r133, %r130, -2143281136;
or.b32 %r134, %r133, -2139062144;
add.s32 %r135, %r134, -16843009;
or.b32 %r41, %r135, %r133;
// begin inline asm
prmt.b32 %r41, %r41, 0, 0xba98;
// end inline asm
xor.b32 %r136, %r39, %r121;
or.b32 %r137, %r136, -2139062144;
and.b32 %r138, %r39, 2139062143;
and.b32 %r139, %r121, -2139062144;
sub.s32 %r140, %r137, %r138;
xor.b32 %r141, %r139, %r140;
xor.b32 %r44, %r141, -2139062144;
xor.b32 %r142, %r41, %r123;
or.b32 %r143, %r142, -2139062144;
and.b32 %r144, %r41, 2139062143;
and.b32 %r145, %r123, -2139062144;
sub.s32 %r146, %r143, %r144;
xor.b32 %r147, %r145, %r146;
xor.b32 %r48, %r147, -2139062144;
ld.global.u32 %r45, [%rd49+4];
// begin inline asm
dp4a.s32.s32 %r43, %r44, %r45, %r35;
// end inline asm
ld.global.u32 %r49, [%rd49+8];
// begin inline asm
dp4a.s32.s32 %r47, %r48, %r49, %r43;
// end inline asm
shl.b16 %rs12, %rs5, 2;
cvt.u64.u16 %rd40, %rs12;
and.b64 %rd41, %rd40, 1020;
add.s64 %rd42, %rd26, %rd41;
ld.const.u32 %r148, [%rd42];
shr.u16 %rs13, %rs5, 8;
cvt.u32.u16 %r149, %rs13;
mul.wide.u32 %rd43, %r149, 4;
add.s64 %rd44, %rd26, %rd43;
ld.const.u32 %r150, [%rd44];
shr.u32 %r151, %r65, 5;
and.b32 %r152, %r151, 255;
popc.b32 %r153, %r152;
shl.b32 %r154, %r153, 7;
and.b32 %r155, %r154, 128;
xor.b32 %r156, %r155, %r152;
mul.lo.s32 %r157, %r156, 16843009;
and.b32 %r158, %r157, 134480385;
add.s32 %r159, %r158, 2139062143;
or.b32 %r51, %r159, %r158;
// begin inline asm
prmt.b32 %r51, %r51, 0, 0xba98;
// end inline asm
and.b32 %r160, %r157, -2143281136;
or.b32 %r161, %r160, -2139062144;
add.s32 %r162, %r161, -16843009;
or.b32 %r53, %r162, %r160;
// begin inline asm
prmt.b32 %r53, %r53, 0, 0xba98;
// end inline asm
xor.b32 %r163, %r51, %r148;
or.b32 %r164, %r163, -2139062144;
and.b32 %r165, %r51, 2139062143;
and.b32 %r166, %r148, -2139062144;
sub.s32 %r167, %r164, %r165;
xor.b32 %r168, %r166, %r167;
xor.b32 %r56, %r168, -2139062144;
xor.b32 %r169, %r53, %r150;
or.b32 %r170, %r169, -2139062144;
and.b32 %r171, %r53, 2139062143;
and.b32 %r172, %r150, -2139062144;
sub.s32 %r173, %r170, %r171;
xor.b32 %r174, %r172, %r173;
xor.b32 %r60, %r174, -2139062144;
ld.global.u32 %r57, [%rd49+12];
// begin inline asm
dp4a.s32.s32 %r55, %r56, %r57, %r47;
// end inline asm
ld.global.u32 %r61, [%rd49+16];
// begin inline asm
dp4a.s32.s32 %r59, %r60, %r61, %r55;
// end inline asm
shr.u32 %r175, %r65, 12;
shr.u32 %r176, %r59, 31;
add.s32 %r177, %r59, %r176;
shr.s32 %r178, %r177, 1;
mad.lo.s32 %r179, %r59, %r175, %r178;
shr.u32 %r180, %r179, 31;
add.s32 %r181, %r179, %r180;
shr.s32 %r182, %r181, 1;
ld.global.u16 %rs1, [%rd48];
// begin inline asm
{ cvt.f32.f16 %f7, %rs1;}
// end inline asm
ld.global.u32 %r63, [%rd49+-16];
// begin inline asm
{.reg .f16 low,high;
mov.b32 {low,high},%r63;
cvt.f32.f16 %f8, low;}
// end inline asm
mul.ftz.f32 %f9, %f7, %f8;
cvt.rn.f32.s32 %f10, %r182;
fma.rn.ftz.f32 %f21, %f9, %f10, %f21;
add.s32 %r193, %r193, 32;
add.s64 %rd49, %rd49, 1152;
add.s64 %rd48, %rd48, 392;
setp.lt.u32 %p3, %r193, %r4;
@%p3 bra $L__BB0_3;
$L__BB0_4:
mov.b32 %r183, %f21;
shfl.sync.bfly.b32 %r184|%p4, %r183, 16, 31, -1;
mov.b32 %f11, %r184;
add.ftz.f32 %f12, %f21, %f11;
mov.b32 %r185, %f12;
shfl.sync.bfly.b32 %r186|%p5, %r185, 8, 31, -1;
mov.b32 %f13, %r186;
add.ftz.f32 %f14, %f12, %f13;
mov.b32 %r187, %f14;
shfl.sync.bfly.b32 %r188|%p6, %r187, 4, 31, -1;
mov.b32 %f15, %r188;
add.ftz.f32 %f16, %f14, %f15;
mov.b32 %r189, %f16;
shfl.sync.bfly.b32 %r190|%p7, %r189, 2, 31, -1;
mov.b32 %f17, %r190;
add.ftz.f32 %f18, %f16, %f17;
mov.b32 %r191, %f18;
shfl.sync.bfly.b32 %r192|%p8, %r191, 1, 31, -1;
mov.b32 %f19, %r192;
add.ftz.f32 %f4, %f18, %f19;
setp.ne.s32 %p9, %r3, 0;
@%p9 bra $L__BB0_6;
cvta.to.global.u64 %rd45, %rd11;
mul.wide.u32 %rd46, %r1, 4;
add.s64 %rd47, %rd45, %rd46;
st.global.f32 [%rd47], %f4;
$L__BB0_6:
ret;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,308 @@
//! Closed genuine grouped-column GU18/GU22 and experimental GU21/GU23 projections; scalar arithmetic unchanged.
use super::*;
impl Context<'_> {
pub fn project_routed_gate_up_columns(
&self,
weights: &DeviceBuffer<'_>,
columns: &[&RoutedGateUpQ8<'_>],
output: &mut DeviceBuffer<'_>,
format: RoutedFormat,
) -> Result<()> {
self.project_routed_gate_up_columns_weight(
NativeWeights::Raw(weights),
columns,
output,
format,
)
}
pub(super) fn project_routed_gate_up_columns_weight(
&self,
weight_owner: NativeWeights<'_, '_>,
columns: &[&RoutedGateUpQ8<'_>],
output: &mut DeviceBuffer<'_>,
format: RoutedFormat,
) -> Result<()> {
let weights = weight_owner.buffer()?;
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let operation = match format {
RoutedFormat::IQ3_XXS => FixedOperation::GroupedIq3,
RoutedFormat::IQ2_S => FixedOperation::GroupedIq2,
RoutedFormat::IQ3_S if columns.len() > 1 => FixedOperation::GroupedIq3SNc4,
RoutedFormat::IQ3_S => FixedOperation::GroupedIq3S,
RoutedFormat::IQ4_XS if columns.len() > 1 => FixedOperation::GroupedIq4XsNc4,
RoutedFormat::IQ4_XS => FixedOperation::GroupedIq4Xs,
_ => return Err(Error::UnsupportedProjection),
};
if !(1..=64).contains(&columns.len()) {
return Err(Error::InvalidProjectionShape);
}
let shape = projection_shape(ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 640,
columns: 2560,
})?;
weight_owner.validate(
ProjectionSpec {
kind: ProjectionKind::Routed(format),
rows: 640,
columns: 2560,
},
shape.weight_bytes,
)?;
if output.bytes != columns.len() * 2560 {
return Err(Error::InvalidProjectionShape);
}
if !std::ptr::eq(self, weights.context) || !std::ptr::eq(self, output.context) {
return Err(Error::ContextMismatch);
}
let weight = weights.handle.ok_or(Error::ContextPoisoned)?;
let out = output.handle.ok_or(Error::ContextPoisoned)?;
weight.validate_projection_extent(
shape.weight_bytes,
ProjectionKind::Routed(format).weight_alignment(),
)?;
out.validate_projection_extent(output.bytes, 4)?;
if out.overlaps(output.bytes, weight, weights.bytes) {
return Err(Error::OutputAliasesInput);
}
let mut pointers = Vec::new();
pointers
.try_reserve_exact(columns.len() * 8)
.map_err(|_| Error::BudgetExceeded)?;
for column in columns {
let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
for buffer in [column.activation, scratch] {
if !std::ptr::eq(self, buffer.context) {
return Err(Error::ContextMismatch);
}
let handle = buffer.handle.ok_or(Error::ContextPoisoned)?;
handle.validate_projection_extent(buffer.bytes, 4)?;
if out.overlaps(output.bytes, handle, buffer.bytes) {
return Err(Error::OutputAliasesInput);
}
}
if column.activation.bytes != 10240
|| scratch.bytes != 2880
|| self.common_quantizer.get().is_none()
{
return Err(Error::InvalidProjectionShape);
}
pointers.extend_from_slice(
&scratch
.handle
.ok_or(Error::ContextPoisoned)?
.qwen_address()
.to_le_bytes(),
);
}
let mut table = self.allocate(pointers.len())?;
let result = (|| {
table.copy_from(&pointers)?;
let table_handle = table.handle.ok_or(Error::ContextPoisoned)?;
table_handle.validate_projection_extent(pointers.len(), 8)?;
if table_handle.overlaps(pointers.len(), out, output.bytes)
|| table_handle.overlaps(pointers.len(), weight, weights.bytes)
{
return Err(Error::OutputAliasesInput);
}
let kernel = {
let guard = self.enter()?;
let kernel = match self.fixed_kernel(operation) {
Ok(value) => value,
Err(error) => return combine(Err(error), guard.finish()),
};
combine(Ok(kernel), guard.finish())?
};
let mut arguments = ffi::ProjectionArguments::new(weight, table_handle, out, 640, 2560);
let guard = self.enter()?;
let launch = self.driver.api.launch_grouped_projection(
kernel.function,
160,
columns.len() as u32,
&mut arguments,
);
self.complete_launch(launch, arguments, guard)
})();
combine(result, table.release())
}
pub fn copy_routed_gate_up_column(
&self,
source: &DeviceBuffer<'_>,
total: usize,
index: usize,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, source.context) || !std::ptr::eq(self, output.context) {
return Err(Error::ContextMismatch);
}
if !(1..=64).contains(&total) || source.bytes != total * 2560 || output.bytes != 2560 {
return Err(Error::InvalidProjectionShape);
}
let source_handle = source.handle.ok_or(Error::ContextPoisoned)?;
let destination = output.handle.ok_or(Error::ContextPoisoned)?;
destination.validate_projection_extent(2560, 4)?;
if destination.overlaps(2560, source_handle, source.bytes) {
return Err(Error::OutputAliasesInput);
}
let column = source_handle.moe_group_column(total, index)?;
let guard = self.enter()?;
let copy = self.driver.api.copy_moe_group_column(destination, column);
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
}
#[cfg(all(
test,
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod installed_tests {
use super::*;
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> DeviceBuffer<'a> {
let mut output = context.allocate(bytes.len()).unwrap();
output.copy_from(bytes).unwrap();
output
}
fn read(buffer: &DeviceBuffer<'_>, length: usize) -> Vec<u8> {
let mut values = vec![0; length];
buffer.copy_to(&mut values).unwrap();
values
}
#[test]
#[ignore = "root-only installed CUDA grouped projection gate"]
fn installed_grouped_native_gu18_gu22_matches_actual_scalar_columns() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_MOE_GROUP").unwrap(),
"yes"
);
let driver = Driver::load().unwrap();
let context = driver
.device(0)
.unwrap()
.create_context(8 * 1024 * 1024)
.unwrap();
let mut words = 0;
for (format, block_bytes) in [(RoutedFormat::IQ3_XXS, 98), (RoutedFormat::IQ2_S, 82)] {
let stride = 10 * block_bytes;
let mut raw = vec![0; 640 * stride];
for (row, bytes) in raw.chunks_exact_mut(stride).enumerate() {
for (block, bytes) in bytes.chunks_exact_mut(block_bytes).enumerate() {
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = ((row * 17 + block * 29 + i * 37 + 11) % 256) as u8;
}
bytes[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
}
}
let weights = upload(&context, &raw);
for total in [4, 16, 64] {
let inputs: Vec<_> = (0..total)
.map(|column| {
let bytes: Vec<_> = (0..2560)
.flat_map(|i| {
let value = if column % 11 == 0 {
if i % 2 == 0 { -0.0f32 } else { 0.0 }
} else {
((i % 31) as f32 - 15.0) / 8.0 + (column as f32) / 64.0
};
value.to_le_bytes()
})
.collect();
upload(&context, &bytes)
})
.collect();
let prepared: Vec<_> = inputs
.iter()
.map(|input| context.prepare_routed_gate_up_q8(input).unwrap())
.collect();
let refs: Vec<_> = prepared.iter().collect();
let mut grouped = upload(&context, &vec![0xa5; total * 2560]);
let allocated = context.allocated_bytes();
context
.project_routed_gate_up_columns(&weights, &refs, &mut grouped, format)
.unwrap();
assert_eq!(context.allocated_bytes(), allocated);
let actual = read(&grouped, total * 2560);
let mut scalar = context.allocate(2560).unwrap();
let mut copied = context.allocate(2560).unwrap();
for column in 0..total {
context
.project_routed_gate_up_prepared(
&weights,
refs[column],
&mut scalar,
format,
)
.unwrap();
let expected = read(&scalar, 2560);
for word in expected.as_chunks::<4>().0 {
assert!(f32::from_le_bytes(*word).is_finite());
}
assert_eq!(
&actual[column * 2560..(column + 1) * 2560],
expected,
"{format:?} T{total} col{column}"
);
context
.copy_routed_gate_up_column(&grouped, total, column, &mut copied)
.unwrap();
assert_eq!(read(&copied, 2560), expected);
words += 640;
}
let saved = read(&grouped, total * 2560);
assert_eq!(
context.project_routed_gate_up_columns(&weights, &[], &mut grouped, format),
Err(Error::InvalidProjectionShape)
);
assert_eq!(read(&grouped, total * 2560), saved);
assert_eq!(
context.copy_routed_gate_up_column(&grouped, total, total, &mut copied),
Err(Error::InvalidProjectionShape)
);
scalar.release().unwrap();
copied.release().unwrap();
grouped.release().unwrap();
for owner in prepared {
owner.close().unwrap();
}
for input in inputs {
input.release().unwrap();
}
assert_eq!(context.allocated_bytes(), raw.len());
}
assert_eq!(read(&weights, raw.len()), raw);
weights.release().unwrap();
}
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
println!("MOE_GROUP PASS exact_words={words} formats=18,22 groups=4,16,64 no_model");
}
}
#[cfg(all(
test,
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[path = "grouped_gu21_gu23_gpu.rs"]
mod grouped_gu21_gu23_gpu;
#[cfg(all(
test,
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
#[path = "grouped_gu21_gu23_nc4_gpu.rs"]
mod grouped_gu21_gu23_nc4_gpu;
+127
View File
@@ -0,0 +1,127 @@
// Exact scalar column widening from moe_fixed.ptx, SHA256 eb25f45f2bf1cd3be57e0b5f326a63f666059a58706d7a2bd470526c22c0f67a.
// Fixed STRA-167 default-profile MoE assets. Offline regeneration only.
// Pinned upstream d9ab8435f654c368c586340d490915f6addf56a3.
// shared_expert.cu SHA256 bcb63f8b6f2dd92d5035ceae33f9b6b513fe34e3e2c5c54a4c9bbf867dbad4ca
// Native SwiGLU62-68; default scalar109-125; scale128-130; legacy combine143-156.
// bf16_bits.hpp supplies exact ties-even integer conversion.
// Regenerate: nvcc --ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false
// No global --use_fast_math: original shared_expert.cu uses ordinary flags;
// native SwiGLU explicitly invokes __expf/__fdividef.
// This candidate source is not the independent original-source oracle.
// Exact Context-owned whole buffers; grid/block fixed in the private registry.
// Source-defined positiveInf exponential saturation remains admissible.
// Invalid input/NaN/invalid denominator/nonfinite output signals canonical qNaN.
// Cargo neither builds nor links CUDA; no Toolkit/Strata serving dependency.
//
// MIT License
//
// Copyright (c) 2026 Niko1221 and the Strata contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-35583870
// Cuda compilation tools, release 12.8, V12.8.93
// Based on NVVM 20.0.0
//
.version 8.7
.target sm_120
.address_size 64
// .globl leleka_moe_swiglu_f32
// _ZZ31leleka_moe_shared_gate_f32_bf16E7scratch has been demoted
// _ZZ31leleka_moe_shared_gate_f32_bf16E15invalid_scratch has been demoted
.visible .entry leleka_moe_swiglu_f32_columns(
.param .u64 leleka_moe_swiglu_f32_columns_param_0,
.param .u64 leleka_moe_swiglu_f32_columns_param_1,
.param .u64 leleka_moe_swiglu_f32_columns_param_2
)
{
.reg .pred %p<9>;
.reg .b32 %r<8>;
.reg .f32 %f<15>;
.reg .b64 %rd<18>;
// Column address only; original scalar instructions below unchanged.
mov.u32 %r7, %ctaid.y;
mul.wide.u32 %rd17, %r7, 2560;
ld.param.u64 %rd3, [leleka_moe_swiglu_f32_columns_param_0];
add.u64 %rd3, %rd3, %rd17;
ld.param.u64 %rd4, [leleka_moe_swiglu_f32_columns_param_1];
add.u64 %rd4, %rd4, %rd17;
ld.param.u64 %rd5, [leleka_moe_swiglu_f32_columns_param_2];
add.u64 %rd5, %rd5, %rd17;
cvta.to.global.u64 %rd1, %rd5;
mov.u32 %r2, %ctaid.x;
mov.u32 %r3, %ntid.x;
mov.u32 %r4, %tid.x;
mad.lo.s32 %r1, %r2, %r3, %r4;
setp.gt.u32 %p1, %r1, 639;
@%p1 bra $L__BB0_6;
cvta.to.global.u64 %rd6, %rd3;
cvta.to.global.u64 %rd7, %rd4;
cvt.u64.u32 %rd2, %r1;
mul.wide.u32 %rd8, %r1, 4;
add.s64 %rd9, %rd6, %rd8;
ld.global.f32 %f1, [%rd9];
add.s64 %rd10, %rd7, %rd8;
ld.global.f32 %f2, [%rd10];
abs.f32 %f4, %f1;
setp.ne.f32 %p2, %f4, 0f7F800000;
abs.f32 %f5, %f2;
setp.ne.f32 %p3, %f5, 0f7F800000;
and.pred %p4, %p2, %p3;
@%p4 bra $L__BB0_3;
shl.b64 %rd15, %rd2, 2;
add.s64 %rd16, %rd1, %rd15;
mov.b32 %r6, 2143289344;
st.global.u32 [%rd16], %r6;
bra.uni $L__BB0_6;
$L__BB0_3:
mul.f32 %f7, %f1, 0fBFB8AA3B;
ex2.approx.f32 %f8, %f7;
add.f32 %f9, %f8, 0f3F800000;
abs.f32 %f10, %f8;
setp.num.f32 %p5, %f10, %f10;
setp.gt.f32 %p6, %f9, 0f00000000;
and.pred %p7, %p5, %p6;
@%p7 bra $L__BB0_5;
shl.b64 %rd13, %rd2, 2;
add.s64 %rd14, %rd1, %rd13;
mov.b32 %r5, 2143289344;
st.global.u32 [%rd14], %r5;
bra.uni $L__BB0_6;
$L__BB0_5:
div.approx.f32 %f11, %f1, %f9;
mul.f32 %f12, %f2, %f11;
abs.f32 %f13, %f12;
setp.equ.f32 %p8, %f13, 0f7F800000;
selp.f32 %f14, 0f7FC00000, %f12, %p8;
shl.b64 %rd11, %rd2, 2;
add.s64 %rd12, %rd1, %rd11;
st.global.f32 [%rd12], %f14;
$L__BB0_6:
ret;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,30 @@
// Driver entry points for the Strata-prefill MoE router / shared-expert module. This file is `include!`d inside
// `ffi::enabled` (items only, hence no inner attributes) for access to the private symbol table. The PTX image is a
// privately pinned immutable candidate asset of `moe_prefill_batch`; no caller can supply code or an entry name.
// Launching reuses `launch_gdn_native` (generic fixed-ABI storage + adapter stream); the shared-expert dequantizers
// are the already pinned `gdn_native_batch` module (`load_gdn_native_module(true)`, `gdn_native_function`).
use crate::qwen_dispatch::moe_prefill_batch::{self as moe, MoeKernel};
impl Api {
pub(crate) fn load_moe_prefill_module(&self) -> Result<ModuleHandle> {
let ptx = moe::prefill_asset()?;
let mut module = std::ptr::null_mut();
// SAFETY: fixed NUL-terminated pinned PTX and the current owning context.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, ptx.as_ptr().cast())
})?;
ModuleHandle::qwen_success(module as usize)
}
pub(crate) fn moe_prefill_function(
&self,
module: ModuleHandle,
kernel: MoeKernel,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: closed kernel-to-entry map, live retained module of the matching family, writable output pointer.
check("cuModuleGetFunction", unsafe {
(self.get_function)(&mut function, module.0 as *mut c_void, kernel.entry().as_ptr())
})?;
FunctionHandle::qwen_success(function as usize)
}
}
@@ -0,0 +1,622 @@
//! Root-only ignored smoke of the Strata-prefill MoE router / shared-expert program. It proves transport, order,
//! geometry, refusal and cleanup of the new program with synthetic data and a host-side stand-in for the closed
//! cuBLAS adapter. It is NOT the Original17 prefill numerical gate: tensors produced by the real adapter and the
//! captured prompt-path references are compared by that separate gate.
use super::*;
use crate::Driver;
use std::cell::{Cell, RefCell};
const ENABLE: &str = "LELEKA_STRA169_RUN_MOE_PREFILL_BATCH";
const Q8_0_BLOCK: usize = 34;
// ---------------------------------------------------------------- host numerics helpers
fn bytes_of(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn words_of(bytes: &[u8]) -> Vec<f32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| f32::from_le_bytes(*w))
.collect()
}
fn halves_of(bytes: &[u8]) -> Vec<u16> {
bytes
.as_chunks::<2>()
.0
.iter()
.map(|w| u16::from_le_bytes(*w))
.collect()
}
fn f16_bits(f: f32) -> u16 {
let x = f.to_bits();
let sign = ((x >> 16) & 0x8000) as u16;
let exp = ((x >> 23) & 0xff) as i32;
let man = x & 0x7f_ffff;
if exp == 0xff {
return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 };
}
let e = exp - 127 + 15;
if e >= 0x1f {
return sign | 0x7c00;
}
if e <= 0 {
if e < -10 {
return sign;
}
let m = man | 0x80_0000;
let shift = (14 - e) as u32;
let mut h = (m >> shift) as u16;
let rem = m & ((1 << shift) - 1);
let mid = 1 << (shift - 1);
if rem > mid || (rem == mid && h & 1 == 1) {
h += 1;
}
return sign | h;
}
let mut h = ((e as u32) << 10) | (man >> 13);
let rem = man & 0x1fff;
if rem > 0x1000 || (rem == 0x1000 && h & 1 == 1) {
h += 1;
}
sign | h as u16
}
fn f16_value(h: u16) -> f32 {
let sign = ((h & 0x8000) as u32) << 16;
let exp = ((h >> 10) & 0x1f) as i32;
let man = (h & 0x3ff) as u32;
if exp == 0 {
let v = man as f32 * 2f32.powi(-24);
return if sign != 0 { -v } else { v };
}
if exp == 0x1f {
return f32::from_bits(sign | 0x7f80_0000 | (man << 13));
}
f32::from_bits(sign | (((exp - 15 + 127) as u32) << 23) | (man << 13))
}
fn bf_bits(f: f32) -> u16 {
let mut u = f.to_bits();
u = u.wrapping_add(0x7fff + ((u >> 16) & 1));
(u >> 16) as u16
}
fn bf_value(b: u16) -> f32 {
f32::from_bits((b as u32) << 16)
}
fn sigm(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec<f32> {
(0..count)
.map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset)
.collect()
}
fn close(a: f32, b: f32, tolerance: f32) -> bool {
(a - b).abs() <= tolerance * (1.0 + b.abs())
}
/// Q8_0 blocks of a `rows x cols` matrix and its exact FP16 dequantization.
fn q8_0(rows: usize, cols: usize, salt: usize) -> (Vec<u8>, Vec<u16>) {
let mut blocks = Vec::with_capacity(rows * cols / 32 * Q8_0_BLOCK);
let mut half = Vec::with_capacity(rows * cols);
for r in 0..rows {
for b in 0..cols / 32 {
let scale = f16_bits(0.0078125 * (1 + (r + b + salt) % 3) as f32);
blocks.extend_from_slice(&scale.to_le_bytes());
for j in 0..32 {
let q = ((r * 31 + b * 17 + j * 5 + salt) % 41) as i32 - 20;
blocks.push(q as i8 as u8);
half.push(f16_bits(q as f32 * f16_value(scale)));
}
}
}
(blocks, half)
}
// ---------------------------------------------------------------- host stand-in for the cuBLAS adapter
#[derive(Default, Clone, Copy)]
struct Poison {
logits: bool,
sg: bool,
dm: bool,
}
#[derive(Default)]
struct Captured {
scratch: Vec<(usize, Vec<u16>)>, // (rows, FP16 matrix prefix) of every f16 call
x: Vec<(usize, Vec<u8>)>, // (depth, activation bytes) of every call
y: Vec<(usize, Vec<f32>)>, // (rows, result words) of every call
}
struct HostGemm {
poison: Poison,
captured: RefCell<Captured>,
calls: Cell<usize>,
}
impl HostGemm {
fn run(
&self,
bf16: bool,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.calls.set(self.calls.get() + 1);
let mut xb = vec![0u8; x.len()];
x.copy_to(&mut xb)?;
let mut wb = vec![0u8; w.len()];
w.copy_to(&mut wb)?;
let mut yb = vec![0u8; y.len()];
y.copy_to(&mut yb)?;
let value = |bits: u16| {
if bf16 {
bf_value(bits)
} else {
f16_value(bits)
}
};
let xh = halves_of(&xb);
let wh = halves_of(&wb);
let mut out = words_of(&yb);
let GemmShape {
tokens,
rows,
depth,
ldy,
y_offset,
beta,
} = shape;
if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy {
return Err(Error::InvalidQwenShape);
}
for t in 0..tokens {
for n in 0..rows {
let mut acc = 0f32;
for k in 0..4 {
acc += value(xh[t * depth + (7 * n + k) % depth])
* value(wh[n * depth + (3 * k + n) % depth]);
}
// A tiny per-column ramp keeps every router logit distinct (no ties in the top-10 reference).
let at = t * ldy + y_offset + n;
out[at] = acc + n as f32 * 1e-4 + beta * out[at];
}
}
if self.poison.logits && rows == EXPERTS {
out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001);
}
if self.poison.sg && rows == 1 {
out[tokens - 1] = f32::from_bits(0x7fc0_0001);
}
y.context
.driver
.api
.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?;
let mut captured = self.captured.borrow_mut();
if !bf16 {
captured.scratch.push((rows, wh[..rows * depth].to_vec()));
}
captured.x.push((depth, xb));
captured.y.push((rows, out));
Ok(())
}
}
impl GdnGemm for HostGemm {
fn stream(&self) -> GdnStream {
// The host stand-in copies synchronously on the default stream.
GdnStream::default_stream()
}
fn f16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.run(false, x, w, y, shape)
}
fn bf16(
&self,
x: &DeviceBuffer<'_>,
w: &DeviceBuffer<'_>,
y: &DeviceBuffer<'_>,
shape: GemmShape,
) -> Result<()> {
self.run(true, x, w, y, shape)
}
}
// ---------------------------------------------------------------- buffers
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
match buffer.copy_from(bytes) {
Ok(()) => Ok(buffer),
Err(primary) => combine(Err(primary), buffer.release()).map(|()| unreachable!()),
}
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut out = vec![0; buffer.len()];
buffer.copy_to(&mut out)?;
Ok(out)
}
fn mismatch<T>(what: &'static str) -> Result<T> {
Err(Error::InvalidDriverValue(what))
}
struct Fixture<'a> {
mixed: DeviceBuffer<'a>,
mixed_h: DeviceBuffer<'a>,
mixed_bf: DeviceBuffer<'a>,
mixed_bf_lo: DeviceBuffer<'a>,
router_w: DeviceBuffer<'a>,
logits: DeviceBuffer<'a>,
ids: DeviceBuffer<'a>,
weights: DeviceBuffer<'a>,
gate_w: DeviceBuffer<'a>,
up_w: DeviceBuffer<'a>,
down_w: DeviceBuffer<'a>,
scalar_w: DeviceBuffer<'a>,
scratch: DeviceBuffer<'a>,
sgate: DeviceBuffer<'a>,
sup: DeviceBuffer<'a>,
sh_h: DeviceBuffer<'a>,
shared: DeviceBuffer<'a>,
sg: DeviceBuffer<'a>,
dm: DeviceBuffer<'a>,
bo: DeviceBuffer<'a>,
host_mixed: Vec<f32>,
host_dm: Vec<f32>,
}
impl<'a> Fixture<'a> {
fn new(context: &'a Context<'_>, tokens: usize, poison: Poison) -> Result<Self> {
let blank = |bytes: usize| upload(context, &vec![0; bytes]);
let host_mixed = pattern(tokens * N, 1, 37, 1.0 / 32.0, 0.5);
let mut host_dm = pattern(tokens * SELECTED * N, 5, 31, 1.0 / 64.0, 0.25);
if poison.dm {
host_dm[0] = f32::from_bits(0x7fc0_0001);
}
let bf16_matrix = |count: usize, salt: usize| -> Vec<u8> {
pattern(count, salt, 11, 1.0 / 64.0, 0.08)
.into_iter()
.flat_map(|v| bf_bits(v).to_le_bytes())
.collect()
};
Ok(Self {
mixed: upload(context, &bytes_of(&host_mixed))?,
mixed_h: blank(tokens * N * 2)?,
mixed_bf: blank(tokens * N * 2)?,
mixed_bf_lo: blank(tokens * N * 2)?,
router_w: upload(context, &bf16_matrix(EXPERTS * N, 7))?,
logits: blank(tokens * EXPERTS * 4)?,
ids: blank(tokens * SELECTED * 4)?,
weights: blank(tokens * SELECTED * 4)?,
gate_w: upload(context, &q8_0(FF, N, 1).0)?,
up_w: upload(context, &q8_0(FF, N, 2).0)?,
down_w: upload(context, &q8_0(N, FF, 3).0)?,
scalar_w: upload(context, &bf16_matrix(N, 9))?,
scratch: blank(MOE_BATCH_SCRATCH_BYTES)?,
sgate: blank(tokens * FF * 4)?,
sup: blank(tokens * FF * 4)?,
sh_h: blank(tokens * FF * 2)?,
shared: blank(tokens * N * 4)?,
sg: blank(tokens * 4)?,
dm: upload(context, &bytes_of(&host_dm))?,
bo: blank(tokens * N * 4)?,
host_mixed,
host_dm,
})
}
fn release(self) -> Result<()> {
let mut result = Ok(());
for buffer in [
self.mixed,
self.mixed_h,
self.mixed_bf,
self.mixed_bf_lo,
self.router_w,
self.logits,
self.ids,
self.weights,
self.gate_w,
self.up_w,
self.down_w,
self.scalar_w,
self.scratch,
self.sgate,
self.sup,
self.sh_h,
self.shared,
self.sg,
self.dm,
self.bo,
] {
result = combine(result, buffer.release());
}
result
}
}
/// One complete program for `tokens` rows with or without the optional combine and the lo passes.
fn run_case(
context: &Context<'_>,
batch: &mut MoePrefillBatch<'_>,
tokens: usize,
poison: Poison,
with_combine: bool,
with_lo: bool,
expect: Option<MoeBatchStage>,
) -> Result<()> {
let fixture = Fixture::new(context, tokens, poison)?;
let gemm = HostGemm {
poison,
captured: RefCell::new(Captured::default()),
calls: Cell::new(0),
};
// A reversed permutation: the combine must follow the row map, not the identity.
let slot: Vec<i32> = (0..(tokens * SELECTED) as i32).rev().collect();
let result = (|| -> Result<()> {
let mut prefix = batch.begin(tokens, &gemm)?;
let lo = with_lo.then_some(&fixture.mixed_bf_lo);
let program = (|| -> Result<()> {
prefix.pack_mixed(&fixture.mixed, &fixture.mixed_h, &fixture.mixed_bf, lo)?;
prefix.route(
&fixture.router_w,
&fixture.logits,
&fixture.ids,
&fixture.weights,
)?;
prefix.shared_gate(
GdnNativeFormat::Q8_0,
&fixture.gate_w,
&fixture.scratch,
&fixture.sgate,
)?;
prefix.shared_up(
GdnNativeFormat::Q8_0,
&fixture.up_w,
&fixture.scratch,
&fixture.sup,
)?;
prefix.swiglu(&fixture.sh_h)?;
prefix.shared_down(
GdnNativeFormat::Q8_0,
&fixture.down_w,
&fixture.scratch,
&fixture.shared,
)?;
prefix.shared_scalar(&fixture.scalar_w, &fixture.sg)?;
if with_combine {
prefix.combine(&fixture.dm, &slot, &fixture.bo)?;
}
Ok(())
})();
let completion = prefix.finish();
program?;
let completion = completion?;
if completion.numerical_refusal() != expect {
return mismatch("refusal stage differs from the expected earliest stage");
}
let route = completion.into_route();
if expect.is_some() {
return match route {
Err(stage) if Some(stage) == expect => Ok(()),
_ => mismatch("refused window must withhold its route"),
};
}
let route = route.map_err(|_| Error::InvalidDriverValue("clean window lost its route"))?;
check_clean(
&fixture,
&gemm,
tokens,
&route,
with_combine,
with_lo,
&slot,
)
})();
combine(result, fixture.release())
}
fn check_clean(
f: &Fixture<'_>,
gemm: &HostGemm,
tokens: usize,
route: &MoeRouteBatch,
with_combine: bool,
with_lo: bool,
slot: &[i32],
) -> Result<()> {
let captured = gemm.captured.borrow();
// router (hi [+ lo]), gate, up, down, scalar (hi [+ lo])
let expected_calls = 1 + usize::from(with_lo) + 3 + 1 + usize::from(with_lo);
if gemm.calls.get() != expected_calls || captured.x.len() != expected_calls {
return mismatch("unexpected GEMM call sequence");
}
// Dequantization is exact against the host transcription of group32<Q8_0>.
for ((rows, half), (r, c, salt)) in
captured
.scratch
.iter()
.zip([(FF, N, 1usize), (FF, N, 2), (N, FF, 3)])
{
if *rows != r || half != &q8_0(r, c, salt).1 {
return mismatch(
"dequantized FP16 shared weights differ from the original group32<Q8_0>",
);
}
}
// The images of `mixed`.
let (h_img, bf_img) = (
halves_of(&read(&f.mixed_h)?),
halves_of(&read(&f.mixed_bf)?),
);
let lo_img = if with_lo {
halves_of(&read(&f.mixed_bf_lo)?)
} else {
Vec::new()
};
for (i, &s) in f.host_mixed.iter().enumerate() {
let hi = bf_bits(s);
if h_img[i] != f16_bits(s)
|| bf_img[i] != hi
|| (with_lo && lo_img[i] != bf_bits(s - bf_value(hi)))
{
return mismatch("mixed images differ from bf()/bf_lo()/hf()");
}
}
// Route against a host softmax / top-10 of the adapter's own logits.
let logits = captured
.y
.iter()
.rev()
.find(|(rows, _)| *rows == EXPERTS)
.map(|(_, y)| y)
.ok_or(Error::InvalidDriverValue("router call missing"))?;
for t in 0..tokens {
let row = &logits[t * EXPERTS..(t + 1) * EXPERTS];
let max = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
let probabilities: Vec<f32> = {
let exps: Vec<f32> = row.iter().map(|v| (v - max).exp()).collect();
let total: f32 = exps.iter().sum();
exps.iter().map(|v| v / total).collect()
};
let mut order: Vec<usize> = (0..EXPERTS).collect();
order.sort_by(|&a, &b| {
probabilities[b]
.total_cmp(&probabilities[a])
.then(a.cmp(&b))
});
let picked = &order[..SELECTED];
let sum: f32 = picked
.iter()
.map(|&e| probabilities[e])
.sum::<f32>()
.max(6.103515625e-5);
for (rank, &expert) in picked.iter().enumerate() {
if route.ids[t * SELECTED + rank] != expert as i32
|| !close(
route.weights[t * SELECTED + rank],
probabilities[expert] / sum,
2e-4,
)
{
return mismatch("route differs from the host softmax / top-10");
}
}
}
// Shared expert H = hf_sat(silu(gate) * up) as FP16.
let by_rows = |rows: usize, nth: usize| -> Option<&Vec<f32>> {
captured
.y
.iter()
.filter(|(r, _)| *r == rows)
.nth(nth)
.map(|(_, y)| y)
};
let gate = by_rows(FF, 0).ok_or(Error::InvalidDriverValue("gate call missing"))?;
let up = by_rows(FF, 1).ok_or(Error::InvalidDriverValue("up call missing"))?;
let h = halves_of(&read(&f.sh_h)?);
for i in 0..tokens * FF {
let a = gate[i];
let want = (a / (1.0 + (-a).exp()) * up[i]).clamp(-65504.0, 65504.0);
if !close(f16_value(h[i]), f16_value(f16_bits(want)), 4e-3) {
return mismatch("swiglu_pair differs from the host reference");
}
}
// The down GEMM consumed exactly the device H.
let down_x = captured
.x
.get(3 + usize::from(with_lo))
.ok_or(Error::InvalidDriverValue("down call missing"))?;
if down_x.0 != FF || halves_of(&down_x.1) != h {
return mismatch("down GEMM did not read the H image");
}
if with_combine {
let shared = by_rows(N, 0).ok_or(Error::InvalidDriverValue("down result missing"))?;
let sg = captured
.y
.last()
.map(|(_, y)| y)
.ok_or(Error::InvalidDriverValue("scalar call missing"))?;
let bo = words_of(&read(&f.bo)?);
for t in 0..tokens {
for d in 0..N {
let mut s = 0f32;
for k in 0..SELECTED {
s = route.weights[t * SELECTED + k]
.mul_add(f.host_dm[slot[t * SELECTED + k] as usize * N + d], s);
}
let want = s + shared[t * N + d] * sigm(sg[t]);
if !close(bo[t * N + d], want, 2e-4) {
return mismatch("combine differs from the host reference");
}
}
}
}
Ok(())
}
#[test]
#[ignore = "Root-only GPU qualification; never run by the source owner"]
fn strata_prefill_moe_program_runs_in_order_refuses_earliest_and_cleans_up() {
assert_eq!(std::env::var(ENABLE).as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(512 * 1024 * 1024).unwrap();
let result = (|| -> Result<()> {
let mut batch = context.moe_prefill_batch()?;
if batch.allocated_bytes() != STATUS_BYTES + SLOT_BYTES {
return mismatch("unexpected owner charge");
}
let clean = Poison::default();
// Router only + shared, combine, lo passes, and the bounds of one window.
run_case(&context, &mut batch, 3, clean, true, false, None)?;
run_case(&context, &mut batch, 64, clean, false, false, None)?;
run_case(&context, &mut batch, 9, clean, true, true, None)?;
run_case(&context, &mut batch, 1, clean, true, false, None)?;
// Earliest stage in program order wins and the owner stays usable.
run_case(
&context,
&mut batch,
4,
Poison {
logits: true,
sg: true,
..clean
},
false,
false,
Some(MoeBatchStage::Logits),
)?;
run_case(
&context,
&mut batch,
4,
Poison { sg: true, ..clean },
false,
false,
Some(MoeBatchStage::Sg),
)?;
run_case(
&context,
&mut batch,
4,
Poison { dm: true, ..clean },
true,
false,
Some(MoeBatchStage::Bo),
)?;
run_case(&context, &mut batch, 3, clean, true, false, None)?;
// Admission refusals leave nothing behind.
let idle = HostGemm {
poison: clean,
captured: RefCell::new(Captured::default()),
calls: Cell::new(0),
};
if batch.begin(0, &idle).is_ok() || batch.begin(MOE_BATCH_MAX_TOKENS + 1, &idle).is_ok() {
return mismatch("token bounds not enforced");
}
batch.close()
})();
let leaked = context.allocated_bytes();
assert!(result.is_ok(), "{result:?}");
assert_eq!(leaked, 0, "bytes still allocated after close");
}
@@ -0,0 +1,150 @@
//! Closed byte-only copy of one genuine whole ten-slot MoE packet into a prompt row.
//! This is neither a finite-result proof nor a binding/route/transaction certificate.
use crate::{Context, DeviceBuffer, Error, Result, combine};
const PACKET_BYTES: usize = 102_400;
impl Context<'_> {
/// Admit all whole row owners before the first copy, then drain the entire
/// window once. This remains byte transport; no producer proof is minted.
pub fn copy_moe_prompt_packets(
&self,
sources: &[&DeviceBuffer<'_>],
destination: &mut DeviceBuffer<'_>,
) -> Result<()> {
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !(1..=64).contains(&sources.len()) {
return Err(Error::InvalidQwenShape);
}
let bytes = sources
.len()
.checked_mul(PACKET_BYTES)
.ok_or(Error::InvalidQwenShape)?;
if !std::ptr::eq(self, destination.context) {
return Err(Error::ContextMismatch);
}
if destination.bytes != bytes {
return Err(Error::InvalidQwenShape);
}
let target = destination.handle.ok_or(Error::ContextPoisoned)?;
target.validate_projection_extent(bytes, 4)?;
let mut copies = [None; 640];
for (row, source) in sources.iter().enumerate() {
if !std::ptr::eq(self, source.context) {
return Err(Error::ContextMismatch);
}
if source.bytes != PACKET_BYTES {
return Err(Error::InvalidQwenShape);
}
let from = source.handle.ok_or(Error::ContextPoisoned)?;
from.validate_projection_extent(PACKET_BYTES, 4)?;
if from.overlaps(PACKET_BYTES, target, bytes) {
return Err(Error::OutputAliasesInput);
}
for previous in &sources[..row] {
let old = previous.handle.ok_or(Error::ContextPoisoned)?;
if from.overlaps(PACKET_BYTES, old, PACKET_BYTES) {
return Err(Error::OutputAliasesInput);
}
}
let packet = target.checked_subspan(bytes, row * PACKET_BYTES, PACKET_BYTES)?;
for slot in 0..10 {
copies[row * 10 + slot] = Some((
packet.moe_down_slot(slot as u32)?,
from.moe_down_slot(slot as u32)?,
));
}
}
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let mut copy = Ok(());
for (target, from) in copies.into_iter().flatten() {
copy = self.driver.api.copy_moe_down(target, from);
if copy.is_err() {
break;
}
}
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
/// Both actual whole allocations stay borrowed through all attempted copies,
/// synchronization and Context restoration. The caller owns complete ten-slot
/// producer coverage, current row authority and publication after cancellation.
pub fn copy_moe_prompt_packet(
&self,
source: &DeviceBuffer<'_>,
destination: &mut DeviceBuffer<'_>,
total: usize,
row: usize,
) -> Result<()> {
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, source.context) || !std::ptr::eq(self, destination.context) {
return Err(Error::ContextMismatch);
}
if !(1..=64).contains(&total) || row >= total {
return Err(Error::InvalidQwenShape);
}
let bytes = total
.checked_mul(PACKET_BYTES)
.ok_or(Error::InvalidQwenShape)?;
if source.bytes != PACKET_BYTES || destination.bytes != bytes {
return Err(Error::InvalidQwenShape);
}
let source_handle = source.handle.ok_or(Error::ContextPoisoned)?;
let destination_handle = destination.handle.ok_or(Error::ContextPoisoned)?;
source_handle.validate_projection_extent(PACKET_BYTES, 4)?;
destination_handle.validate_projection_extent(bytes, 4)?;
if source_handle.overlaps(PACKET_BYTES, destination_handle, bytes) {
return Err(Error::OutputAliasesInput);
}
let offset = row
.checked_mul(PACKET_BYTES)
.ok_or(Error::InvalidQwenShape)?;
let packet = destination_handle.checked_subspan(bytes, offset, PACKET_BYTES)?;
// The ten private interior handles are fully admitted before any command.
// No public subview/DeviceBuffer is fabricated and no host allocation occurs.
let mut copies = [None; 10];
for (slot, pair) in copies.iter_mut().enumerate() {
*pair = Some((
packet.moe_down_slot(slot as u32)?,
source_handle.moe_down_slot(slot as u32)?,
));
}
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let mut copy = Ok(());
for (target, from) in copies.into_iter().flatten() {
copy = self.driver.api.copy_moe_down(target, from);
if copy.is_err() {
break;
}
}
// A failed copy may report earlier work: always attempt drain AND pop.
// Preserve the existing primary copy -> synchronize -> restore ordering.
let sync = self.driver.api.synchronize();
let restore = guard.finish();
if copy.is_err() || sync.is_err() || restore.is_err() {
self.poisoned.set(true);
}
combine(combine(copy, sync), restore)
}
}
+219
View File
@@ -0,0 +1,219 @@
//! Bounded duplicated FP16 MTP KV ring. No attention arithmetic or raw views.
use crate::{Context, DeviceBuffer, Error, Result, combine};
const WINDOW: usize = 32768;
const ROW: usize = 1024;
pub(super) const HALF_RING_BYTES: usize = 2 * WINDOW * ROW;
/// Both mirrored halves stay owned through every synchronized attention call.
pub struct MtpDenseKvRing<'ctx> {
context: &'ctx Context<'ctx>,
keys: Option<DeviceBuffer<'ctx>>,
values: Option<DeviceBuffer<'ctx>>,
next_position: Option<u32>,
failed: bool,
}
fn shape(position: u32) -> Result<(usize, usize)> {
if position >= 262144 {
return Err(Error::InvalidQwenShape);
}
let next = position as usize + 1;
let width = next.min(WINDOW);
Ok((width, (next - width) % WINDOW))
}
fn finite(bytes: &[u8], expected: usize) -> Result<()> {
if bytes.len() != expected {
return Err(Error::InvalidQwenShape);
}
if bytes
.as_chunks::<2>()
.0
.iter()
.any(|w| u16::from_le_bytes(*w) & 0x7c00 == 0x7c00)
{
return Err(Error::InvalidQwenShape);
}
Ok(())
}
impl<'ctx> Context<'ctx> {
/// Explicit caller charge:128MiB, before its weight LRU can grow.
pub fn mtp_dense_kv_ring(&'ctx self) -> Result<MtpDenseKvRing<'ctx>> {
if self.is_poisoned() {
return Err(Error::ContextPoisoned);
}
if self
.allocated_bytes()
.checked_add(2 * HALF_RING_BYTES)
.is_none_or(|n| n > self.budget_bytes())
{
return Err(Error::BudgetExceeded);
}
let keys = self.allocate(HALF_RING_BYTES)?;
let values = match self.allocate(HALF_RING_BYTES) {
Ok(v) => v,
Err(e) => {
let _ = keys.release();
return Err(e);
}
};
Ok(MtpDenseKvRing {
context: self,
keys: Some(keys),
values: Some(values),
next_position: None,
failed: false,
})
}
}
impl MtpDenseKvRing<'_> {
pub fn validate_context(&self, context: &Context<'_>) -> Result<()> {
if !std::ptr::eq(self.context, context) {
return Err(Error::ContextMismatch);
}
self.live()
}
pub fn allocated_bytes(&self) -> usize {
2 * HALF_RING_BYTES
}
fn live(&self) -> Result<()> {
if self.failed || self.context.is_poisoned() {
Err(Error::ContextPoisoned)
} else {
Ok(())
}
}
fn transport(&mut self, result: Result<()>) -> Result<()> {
if result.is_err() {
self.failed = true;
self.next_position = None;
// The original copy API alone poisons the Context when completion
// is uncertain. A completed partial mirror refuses reuse while its
// buffers remain reclaimable under that unchanged cleanup policy.
}
result
}
/// Full canonical chronological reload after a branch/reset/nonlinear move.
pub fn reload(&mut self, position: u32, keys: &[u8], values: &[u8]) -> Result<()> {
self.live()?;
let (width, start) = shape(position)?;
finite(keys, width * ROW)?;
finite(values, width * ROW)?;
let first = width.min(WINDOW - start) * ROW;
let result = (|| {
for (buffer, bytes) in [(self.keys.as_mut(), keys), (self.values.as_mut(), values)] {
let buffer = buffer.ok_or(Error::ContextPoisoned)?;
for mirror in [0, WINDOW * ROW] {
buffer.copy_from_range(mirror + start * ROW, &bytes[..first])?;
if first < bytes.len() {
buffer.copy_from_range(mirror, &bytes[first..])?;
}
}
}
Ok(())
})();
self.transport(result)?;
self.next_position = Some(position + 1);
Ok(())
}
/// Only an immediate successor appends, duplicating the two canonical cells.
pub fn append(&mut self, position: u32, key: &[u8], value: &[u8]) -> Result<()> {
self.live()?;
shape(position)?;
if self.next_position != Some(position) {
return Err(Error::InvalidQwenShape);
}
finite(key, ROW)?;
finite(value, ROW)?;
let offset = position as usize % WINDOW * ROW;
let result = (|| {
for (buffer, bytes) in [(self.keys.as_mut(), key), (self.values.as_mut(), value)] {
let buffer = buffer.ok_or(Error::ContextPoisoned)?;
buffer.copy_from_range(offset, bytes)?;
buffer.copy_from_range(offset + WINDOW * ROW, bytes)?;
}
Ok(())
})();
self.transport(result)?;
self.next_position = Some(position + 1);
Ok(())
}
/// Opaque ownership selects the active span; no DeviceBuffer is fabricated.
pub fn attend(
&mut self,
query: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
position: u32,
) -> Result<()> {
self.live()?;
let (_, start) = shape(position)?;
if self.next_position != Some(position + 1) {
return Err(Error::InvalidQwenShape);
}
let result = self.context.mtp_dense_attend_ring_f16(
query,
self.keys.as_ref().ok_or(Error::ContextPoisoned)?,
self.values.as_ref().ok_or(Error::ContextPoisoned)?,
output,
position,
start * ROW,
);
// Prelaunch refusal does not mutate the mirror. Transport/context failures
// invalidate its numerical reuse along with the actor's failure flag.
if result.is_err() {
self.next_position = None;
}
result
}
pub fn close(mut self) -> Result<()> {
let keys = self.keys.take().map_or(Ok(()), DeviceBuffer::release);
let values = self.values.take().map_or(Ok(()), DeviceBuffer::release);
combine(keys, values)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn duplicated_window_chronological_span_boundaries() {
for p in [
0, 1, 63, 64, 32767, 32768, 32769, 65535, 170000, 190000, 262143,
] {
let (width, start) = shape(p).unwrap();
assert!(start + width <= 2 * WINDOW);
let oldest = p as usize + 1 - width;
for i in [0, width / 2, width - 1] {
assert_eq!((start + i) % WINDOW, (oldest + i) % WINDOW);
}
}
assert!(shape(262144).is_err());
assert!(finite(&[0, 0x7c], 2).is_err());
assert!(finite(&[0], 2).is_err());
}
}
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "mtp_dense_kv_ring_gpu.rs"]
mod gpu_tests;
// Separate literal Original INT8 drafter; the historical F16 owner stays unchanged.
#[path = "mtp_original_int8.rs"]
mod original_int8;
pub use original_int8::{
CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8,
MtpOriginalMixed, MtpOriginalQuery, OriginalMtpSkippedPrefix,
};
pub use original_int8::{
CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding,
OriginalMtpPrefill, OriginalMtpPrefillWeights,
};
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub use original_int8::{
CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter,
OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant,
OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights,
OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput,
};
@@ -0,0 +1,129 @@
//! New bounded transport parity fixture; Root schedules sole GPU execution.
use super::*;
use crate::Driver;
fn cell(position: usize, value: bool) -> Vec<u8> {
(0..512)
.flat_map(|i| {
let sign = if (position + i + usize::from(value)).is_multiple_of(3) {
0x8000
} else {
0
};
let word: u16 =
sign | 0x3000 | ((position * 17 + i * 11 + usize::from(value) * 7) % 1024) as u16;
word.to_le_bytes()
})
.collect()
}
fn window(position: u32, value: bool) -> Vec<u8> {
let width = (position as usize + 1).min(WINDOW);
let first = position as usize + 1 - width;
(first..first + width)
.flat_map(|p| cell(p, value))
.collect()
}
fn exact(
context: &Context<'_>,
ring: &mut MtpDenseKvRing<'_>,
query: &DeviceBuffer<'_>,
position: u32,
) {
let kb = window(position, false);
let vb = window(position, true);
let mut k = context.allocate(kb.len()).unwrap();
let mut v = context.allocate(vb.len()).unwrap();
k.copy_from(&kb).unwrap();
v.copy_from(&vb).unwrap();
let mut old = context.allocate(6144 * 4).unwrap();
let mut new = context.allocate(6144 * 4).unwrap();
context
.mtp_dense_attend_f16(query, &k, &v, &mut old, position)
.unwrap();
ring.attend(query, &mut new, position).unwrap();
let mut a = vec![0; 6144 * 4];
let mut b = vec![0; 6144 * 4];
old.copy_to(&mut a).unwrap();
new.copy_to(&mut b).unwrap();
assert_eq!(a, b, "chronological ring differs at position {position}");
assert!(
a.as_chunks::<4>()
.0
.iter()
.all(|w| f32::from_le_bytes(*w).is_finite())
);
for buffer in [k, v, old, new] {
buffer.release().unwrap();
}
}
#[test]
#[ignore = "Root-only explicitly scheduled new MTP KV transport parity; no model load"]
fn duplicated_ring_same_attention_reload_append_wrap() {
assert_eq!(
std::env::var("LELEKA_STRA169_RUN_MTP_KV_RING_PROOF").as_deref(),
Ok("yes")
);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let refused = device.create_context(128 * 1024 * 1024 - 1).unwrap();
assert!(matches!(
refused.mtp_dense_kv_ring(),
Err(Error::BudgetExceeded)
));
assert_eq!(refused.allocated_bytes(), 0);
refused.close().unwrap();
let context = device.create_context(256 * 1024 * 1024).unwrap();
let mut ring = context.mtp_dense_kv_ring().unwrap();
assert_eq!(ring.allocated_bytes(), 128 * 1024 * 1024);
let mut query = context.allocate(6144 * 4).unwrap();
let q: Vec<u8> = (0..6144)
.flat_map(|i| (((i % 23) as f32 - 11.0) / 32.0).to_le_bytes())
.collect();
query.copy_from(&q).unwrap();
for start in [0, 62, 63, 32766, 32767, 65535, 170000, 190000, 262142] {
ring.reload(start, &window(start, false), &window(start, true))
.unwrap();
exact(&context, &mut ring, &query, start);
if start == 190000 {
// A valid immediate successor and exact row extents reach the
// driver's finite check before any transfer or state mutation.
let before = context.allocated_bytes();
let mut bad = cell(start as usize + 1, false);
bad[..2].copy_from_slice(&0x7e00_u16.to_le_bytes());
assert!(matches!(
ring.append(start + 1, &bad, &cell(start as usize + 1, true)),
Err(Error::InvalidQwenShape)
));
assert_eq!(before, context.allocated_bytes());
exact(&context, &mut ring, &query, start);
}
ring.append(
start + 1,
&cell(start as usize + 1, false),
&cell(start as usize + 1, true),
)
.unwrap();
exact(&context, &mut ring, &query, start + 1);
// Same numerical span may be read repeatedly without another publication.
exact(&context, &mut ring, &query, start + 1);
assert!(
ring.append(
start + 1,
&cell(start as usize + 1, false),
&cell(start as usize + 1, true)
)
.is_err()
);
}
let before = context.allocated_bytes();
assert!(ring.reload(262144, &[], &[]).is_err());
// Mature-window reload must reject short extents independently.
assert!(
ring.reload(262143, &cell(262143, false), &cell(262143, true))
.is_err()
);
assert_eq!(before, context.allocated_bytes());
query.release().unwrap();
ring.close().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
}
@@ -0,0 +1,708 @@
//! Closed original MTP input branch. Only admitted stages enter this queue.
//! The runtime retains genuine frame/role/source checks at their original seams.
use super::*;
use crate::{DenseFormat, ProjectionKind, ProjectionSpec, projection_ranges, projection_shape};
const SIZES: [usize; 9] = [10240, 40960, 10240, 10240, 40960, 40960, 40960, 2880, 52];
const TOTAL: usize = 197_492;
const RESERVE: usize = 128 * 1024 * 1024;
const OPERATIONS: [Operation; 3] = [
Operation::MtpEmbeddingNorm,
Operation::MtpHiddenNorm,
Operation::MtpBroadcast,
];
const STAGES: [&str; 13] = [
"embedding-norm",
"embedding-quant",
"embedding-projection",
"hidden-norm",
"hidden-0-quant",
"hidden-0-projection",
"hidden-1-quant",
"hidden-1-projection",
"hidden-2-quant",
"hidden-2-projection",
"hidden-3-quant",
"hidden-3-projection",
"broadcast",
];
const QUANT: [usize; 5] = [1, 4, 6, 8, 10];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MtpInputRefusal {
NonFinite,
InvalidQ8Activation,
}
struct Kernels {
qwen: [ffi::FunctionHandle; 3],
quant: ffi::FunctionHandle,
project: ffi::FunctionHandle,
guard: [ffi::FunctionHandle; 2],
}
/// Nine eagerly charged whole owners; no caller chooses dimensions or ranges.
pub struct MtpInputWorkspace<'ctx> {
context: &'ctx Context<'ctx>,
buffers: [Option<DeviceBuffer<'ctx>>; 9],
module: Option<ffi::ModuleHandle>,
kernels: Option<Kernels>,
generation: u64,
failed: bool,
}
/// A fixed ordered prefix; no command is launched by construction or appending.
pub struct MtpInputPrefix<'lease, 'ctx> {
workspace: &'lease mut MtpInputWorkspace<'ctx>,
weights: Vec<&'lease DeviceBuffer<'lease>>,
commands: Vec<Command>,
embedding: Vec<u8>,
streams: Vec<u8>,
phase: usize,
checks: usize,
refusal: Option<Error>,
}
/// Completed exclusive borrow; no usable stream is returned on numerical refusal.
pub struct MtpInputCompletion<'lease, 'ctx> {
workspace: &'lease mut MtpInputWorkspace<'ctx>,
_weights: Vec<&'lease DeviceBuffer<'lease>>,
statuses: [u32; 13],
refusal: Option<(MtpInputRefusal, &'static str)>,
values: Box<[f32]>,
generation: u64,
}
impl MtpInputCompletion<'_, '_> {
pub fn numerical_refusal(&self) -> Option<MtpInputRefusal> {
self.refusal.map(|r| r.0)
}
pub fn refusal_stage(&self) -> Option<&'static str> {
self.refusal.map(|r| r.1)
}
pub fn into_streams(self) -> std::result::Result<Box<[f32]>, MtpInputRefusal> {
if let Some((error, _)) = self.refusal {
return Err(error);
}
debug_assert_eq!(self.workspace.generation, self.generation);
debug_assert!(self.statuses.iter().all(|s| *s == 0));
Ok(self.values)
}
}
impl Context<'_> {
pub fn mtp_input_workspace(&self) -> Result<MtpInputWorkspace<'_>> {
MtpInputWorkspace::new(self)
}
}
impl<'ctx> MtpInputWorkspace<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
if context.is_poisoned() || context.handle.is_none() {
return Err(Error::ContextPoisoned);
}
for operation in OPERATIONS {
qwen_ffi::asset(operation)
.ok_or(Error::UnsupportedQwenOperation)?
.validate(operation)?;
}
let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if context
.allocated_bytes()
.checked_add(required)
.is_none_or(|n| n > context.budget)
|| context.memory_info()?.0 < required
{
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(owner)
}
fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
self.buffers[index].as_ref().ok_or(Error::ContextPoisoned)
}
fn handles(&self) -> Result<[ffi::BufferHandle; 9]> {
if self.is_failed() || self.kernels.is_none() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
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;
}
if self.context.allocated_bytes() > self.context.budget {
return Err(Error::BudgetExceeded);
}
Ok(handles)
}
pub fn is_failed(&self) -> bool {
self.failed || self.context.is_poisoned() || self.context.handle.is_none()
}
pub fn allocated_bytes(&self) -> usize {
self.buffers.iter().flatten().map(|b| b.bytes).sum()
}
/// Owned host staging only. Acquire the first genuine weight at its original seam.
pub fn begin<'lease>(
&'lease mut self,
embedding: &[f32],
streams: &[f32],
) -> Result<MtpInputPrefix<'lease, 'ctx>> {
self.handles()?;
if embedding.len() != 2560 || streams.len() != 10240 {
return Err(Error::InvalidQwenShape);
}
if embedding.iter().chain(streams).any(|x| !x.is_finite()) {
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 mut commands = Vec::new();
commands
.try_reserve_exact(24)
.map_err(|_| Error::HostAllocation)?;
let mut weights = Vec::new();
weights
.try_reserve_exact(7)
.map_err(|_| Error::HostAllocation)?;
Ok(MtpInputPrefix {
workspace: self,
weights,
commands,
embedding: e,
streams: r,
phase: 0,
checks: 0,
refusal: None,
})
}
pub fn close(mut self) -> Result<()> {
self.close_inner()
}
}
impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> {
fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize) -> Result<ffi::BufferHandle> {
let owned = self.workspace.handles()?;
if !std::ptr::eq(self.workspace.context, weight.context) {
return Err(Error::ContextMismatch);
}
if weight.bytes != bytes {
return Err(Error::InvalidQwenShape);
}
let h = weight.handle.ok_or(Error::ContextPoisoned)?;
h.validate_projection_extent(bytes, 4)?;
for (i, out) in owned.into_iter().enumerate() {
if h.overlaps(bytes, out, SIZES[i]) {
return Err(Error::OutputAliasesInput);
}
}
Ok(h)
}
fn ready(&self, phase: usize) -> Result<()> {
if let Some(error) = &self.refusal {
return Err(error.clone());
}
if self.phase != phase {
return Err(Error::InvalidQwenShape);
}
self.workspace.handles()?;
Ok(())
}
fn latch(&mut self, result: Result<()>) -> Result<()> {
if let Err(error) = &result {
self.refusal.get_or_insert_with(|| error.clone());
}
result
}
fn status(&self, index: usize) -> Result<ffi::BufferHandle> {
self.workspace.handles()?[8].checked_subspan(52, index * 4, 4)
}
fn finite(&mut self, source: ffi::BufferHandle, words: u32, index: usize) -> Result<()> {
let function = self
.workspace
.kernels
.as_ref()
.ok_or(Error::ContextPoisoned)?
.guard[1];
let status = self.status(index)?;
self.commands.push(Command::Guard(
function,
words,
ffi::MmqResidentArguments::finite(source, status, 0, words, 0),
));
self.checks = index + 1;
Ok(())
}
pub fn embedding_norm(&mut self, weight: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
self.ready(0)?;
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)),
));
self.finite(self.workspace.handles()?[2], 2560, 0)?;
self.weights.push(weight);
self.phase = 1;
Ok(())
})();
self.latch(result)
}
fn projection(
&mut self,
weight: &'lease DeviceBuffer<'lease>,
source: ffi::BufferHandle,
output: ffi::BufferHandle,
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,
})?;
projection_ranges(
ProjectionKind::Dense(DenseFormat::Q8_0),
&shape,
[w, source, output],
)?;
let handles = self.workspace.handles()?;
let status = self.status(quant_index)?;
let kernels = self
.workspace
.kernels
.as_ref()
.ok_or(Error::ContextPoisoned)?;
self.commands.push(Command::Quant(
kernels.quant,
shape.quant_grid,
ffi::Q8QuantizeArguments::new(source, handles[7], status, 2560),
));
self.commands.push(Command::Common(
kernels.project,
shape.projection_grid,
ffi::ProjectionArguments::new(w, handles[7], output, 2560, 2560),
));
self.finite(output, 2560, quant_index + 1)?;
self.weights.push(weight);
Ok(())
}
pub fn embedding_projection(&mut self, weight: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
self.ready(1)?;
let h = self.workspace.handles()?;
self.projection(weight, h[2], h[3], 1)?;
self.phase = 2;
Ok(())
})();
self.latch(result)
}
pub fn hidden_norm(&mut self, weight: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
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)),
));
self.finite(self.workspace.handles()?[4], 10240, 3)?;
self.weights.push(weight);
self.phase = 3;
Ok(())
})();
self.latch(result)
}
/// Exactly the next of four fixed original hidden projections; no caller range.
pub fn hidden_projection(&mut self, weight: &'lease DeviceBuffer<'lease>) -> Result<()> {
let result = (|| {
if !(3..=6).contains(&self.phase) {
return Err(Error::InvalidQwenShape);
}
self.ready(self.phase)?;
let i = self.phase - 3;
let h = self.workspace.handles()?;
let source = h[4].checked_subspan(40960, i * 10240, 10240)?;
let output = h[5].checked_subspan(40960, i * 10240, 10240)?;
self.projection(weight, source, output, 4 + 2 * i)?;
self.phase += 1;
Ok(())
})();
self.latch(result)
}
/// Drain only already admitted work, then arbitrate earlier numeric refusal.
pub fn drain_prefix(self) -> Result<Option<MtpInputRefusal>> {
let completed = self.drain(false)?;
if let Some((error, _)) = completed.refusal {
return Ok(Some(error));
}
if let Some(error) = completed.deferred {
return Err(error);
}
Ok(None)
}
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(())
})();
if let Err(error) = admission {
self.refusal.get_or_insert(error);
}
let completed = self.drain(true)?;
if completed.refusal.is_none()
&& let Some(error) = completed.deferred
{
return Err(error);
}
Ok(MtpInputCompletion {
workspace: completed.workspace,
_weights: completed.weights,
statuses: completed.statuses,
refusal: completed.refusal,
values: completed.values,
generation: completed.generation,
})
}
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);
}
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)?;
}
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);
let allowed = if QUANT.contains(&i) { 3 } else { 1 };
if *out & !allowed != 0 || (i >= self.checks && *out != 0) {
self.workspace.failed = true;
self.workspace.context.poisoned.set(true);
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,
})
}
}
struct Drained<'lease, 'ctx> {
workspace: &'lease mut MtpInputWorkspace<'ctx>,
weights: Vec<&'lease DeviceBuffer<'lease>>,
statuses: [u32; 13],
refusal: Option<(MtpInputRefusal, &'static str)>,
deferred: Option<Error>,
values: Box<[f32]>,
generation: u64,
}
impl MtpInputWorkspace<'_> {
fn close_inner(&mut self) -> Result<()> {
self.failed = true;
self.kernels = None;
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);
}
}
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
}
}
impl Drop for MtpInputWorkspace<'_> {
fn drop(&mut self) {
let _ = self.close_inner();
}
}
fn staging(bytes: usize) -> Result<Vec<u8>> {
let mut result = Vec::new();
result
.try_reserve_exact(bytes)
.map_err(|_| Error::HostAllocation)?;
result.resize(bytes, 0);
Ok(result)
}
enum Command {
Guard(ffi::FunctionHandle, u32, ffi::MmqResidentArguments),
Quant(ffi::FunctionHandle, u32, ffi::Q8QuantizeArguments),
Common(ffi::FunctionHandle, u32, ffi::ProjectionArguments),
Qwen(ffi::FunctionHandle, Operation, Box<Arguments>),
}
impl Command {
fn launch(&mut self, context: &Context<'_>) -> Result<()> {
let api = &context.driver.api;
match self {
Self::Guard(f, grid, a) => api.launch_mmq_resident(*f, *grid, a),
Self::Quant(f, grid, a) => api.launch_q8_quantize(*f, *grid, a),
Self::Common(f, grid, a) => api.launch_projection(*f, *grid, a),
Self::Qwen(f, operation, a) => api.launch_qwen(*f, *operation, a),
}
}
}
#[cfg(all(
test,
feature = "cuda-driver",
target_os = "linux",
target_arch = "x86_64"
))]
#[path = "mtp_input_workspace_gpu.rs"]
mod gpu;
@@ -0,0 +1,449 @@
//! 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;
const ENABLE: &str = "LELEKA_STRA172_RUN_MTP_INPUT_PREFIX";
#[derive(Default, Debug)]
struct Report {
products: usize,
words: usize,
differences: usize,
guards: usize,
refusals: usize,
numeric: usize,
witness_errors: usize,
}
#[derive(Debug, PartialEq, Eq)]
struct Numeric {
error: MtpInputRefusal,
stage: &'static str,
}
type Observed = std::result::Result<Vec<Vec<u8>>, Numeric>;
fn bytes(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result<DeviceBuffer<'a>> {
let mut buffer = context.allocate(bytes.len())?;
match buffer.copy_from(bytes) {
Ok(()) => Ok(buffer),
Err(primary) => combine(Err(primary), buffer.release()),
}
}
fn read(buffer: &DeviceBuffer<'_>) -> Result<Vec<u8>> {
let mut bytes = vec![0; buffer.len()];
buffer.copy_to(&mut bytes)?;
Ok(bytes)
}
fn full_finite(bytes: &[u8]) -> bool {
bytes
.as_chunks::<4>()
.0
.iter()
.all(|b| f32::from_le_bytes(*b).is_finite())
}
fn raw(salt: usize) -> Vec<u8> {
let mut bytes = vec![0; 6_963_200];
for (i, block) in bytes.chunks_exact_mut(34).enumerate() {
block[..2].copy_from_slice(&0x1400u16.to_le_bytes());
for (j, value) in block[2..].iter_mut().enumerate() {
*value = (((i * 7 + j * 13 + salt) % 63) as i8 - 31) as u8;
}
}
bytes
}
fn inputs(case: usize) -> (Vec<f32>, Vec<f32>) {
let make = |i: usize| {
if case == 2 {
f32::from_bits(if i.is_multiple_of(2) { 0x8000_0000 } else { 0 })
} else {
((i * 13 + case * 11) % 47) as f32 / 16.0 - 1.5
}
};
(
(0usize..2560).map(make).collect(),
(0usize..10240).map(|i| make(i + 31)).collect(),
)
}
fn compare(old: &[u8], actual: &[u8], report: &mut Report) {
report.products += 1;
report.witness_errors +=
usize::from(old.len() != actual.len() || !full_finite(old) || !full_finite(actual));
for (a, b) in old.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0) {
report.words += 1;
report.differences += usize::from(a != b);
}
}
fn refuse<T>(result: Result<T>, expected: Error, report: &mut Report) -> Result<()> {
report.guards += 1;
match result {
Err(error) if error == expected => {
report.refusals += 1;
Ok(())
}
Ok(_) => {
report.witness_errors += 1;
Ok(())
}
Err(error) => Err(error),
}
}
// Independent original allocation/upload/projection/full readback sequence.
// H0..3 each use a real whole 10240B activation owner, not candidate subspans.
fn original(
context: &Context<'_>,
embedding: &[f32],
streams: &[f32],
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 mut cleanup = Ok(());
for buffer in owned {
cleanup = combine(cleanup, buffer.release());
}
combine(operation, cleanup)
}
fn queue<'a, 'ctx>(
workspace: &'a mut MtpInputWorkspace<'ctx>,
embedding: &[f32],
streams: &[f32],
weights: [&'a DeviceBuffer<'a>; 7],
) -> Result<MtpInputCompletion<'a, 'ctx>> {
let mut prefix = workspace.begin(embedding, streams)?;
prefix.embedding_norm(weights[0])?;
prefix.embedding_projection(weights[1])?;
prefix.hidden_norm(weights[2])?;
for weight in &weights[3..] {
prefix.hidden_projection(weight)?;
}
prefix.finish()
}
fn finite_case(
workspace: &mut MtpInputWorkspace<'_>,
context: &Context<'_>,
weights: [&DeviceBuffer<'_>; 7],
case: usize,
report: &mut Report,
) -> Result<()> {
let (embedding, streams) = inputs(case);
let old = original(context, &embedding, &streams, weights)?
.map_err(|_| Error::InvalidDriverValue("original finite MTP corpus"))?;
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)?)?);
for (old, actual) in old.iter().zip(&actual) {
compare(old, actual, report);
}
let final_values = completed
.into_streams()
.map_err(|_| Error::InvalidDriverValue("finite MTP completion"))?;
report.witness_errors += usize::from(
bytes(&final_values) != old[7]
|| context.allocated_bytes() != before
|| workspace.is_failed(),
);
Ok(())
}
fn numeric_case(
workspace: &mut MtpInputWorkspace<'_>,
context: &Context<'_>,
weights: [&DeviceBuffer<'_>; 7],
expected: Numeric,
report: &mut Report,
) -> Result<()> {
let (embedding, streams) = inputs(0);
// Original refusal occurs FIRST at its original full product/status seam.
let old = original(context, &embedding, &streams, weights)?;
report.witness_errors += usize::from(old != Err(expected));
let completed = queue(workspace, &embedding, &streams, weights)?;
let numeric = completed.numerical_refusal();
let stage = completed.refusal_stage();
let actual = numeric
.zip(stage)
.map(|(error, stage)| Numeric { error, stage });
// The old observed refusal also supplies the expected stage independently.
let expected = match old {
Err(value) => value,
Ok(_) => return Err(Error::InvalidDriverValue("original numerical corpus")),
};
report.witness_errors += usize::from(actual.as_ref() != Some(&expected));
report.witness_errors +=
usize::from(completed.into_streams() != Err(expected.error) || workspace.is_failed());
report.numeric += 1;
Ok(())
}
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 mut cleanup = workspace.take().map_or(Ok(()), MtpInputWorkspace::close);
drop(workspace);
for buffer in owned {
cleanup = combine(cleanup, buffer.release());
}
combine(operation, cleanup)
}
#[test]
#[ignore = "Root schedules the changed admitted-prefix transport only"]
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 = device.create_context(256 * 1024 * 1024).expect("Context");
let foreign = match device.create_context(1024 * 1024) {
Ok(value) => value,
Err(primary) => {
let cleanup = context.close();
panic!("foreign {primary:?}; cleanup={cleanup:?}");
}
};
let budget = match device.create_context(TOTAL + RESERVE - 1) {
Ok(value) => value,
Err(primary) => {
let cleanup = combine(context.close(), foreign.close());
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);
assert!(!poisoned);
assert_eq!(report.products, 80);
assert_eq!(report.words, 358400);
assert_eq!(report.differences, 0);
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"
);
}
@@ -0,0 +1,232 @@
// Literal Original qsa_decode_attn.cu fixed INT8 mode1; no prompt arithmetic substitution.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <cfloat>
#include <cstdint>
#include <cmath>
constexpr int KV_Q8_GROUP=64,QK4_0=32,kStepCount=4,kStepWidth=3;
struct block_q4_0{uint16_t d;uint8_t qs[16];};
struct QsaAttnPools{const int8_t*k_q,*v_q;const uint16_t*k_scale,*v_scale;const int32_t*page_table;
const uint16_t*k_pool=nullptr,*v_pool=nullptr;const uint8_t*k_q4=nullptr,*v_q4=nullptr;
int keyless_n_rot=0;const int32_t*keyless_mrope=nullptr;const float*keyless_cos=nullptr,*keyless_sin=nullptr;};
__device__ int mrope_pos(const int32_t*,int,int); // discarded KV_MODE4 branch, never linked or selected
constexpr int HD = 256; // head_dim
constexpr int G = 12; // query heads per KV head (24 / 2)
constexpr int CHUNK = 64; // cells per block
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float warp_max(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
return v;
}
// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8).
// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side.
__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0;
const uint4 raw = *reinterpret_cast<const uint4*>(base);
const __half2* h2 = reinterpret_cast<const __half2*>(&raw);
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float2 f = __half22float2(h2[j]);
out[2 * j] = f.x;
out[2 * j + 1] = f.y;
}
}
__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0;
const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP];
const float sc = __half2float(__ushort_as_half(sbits));
const uint2 raw = *reinterpret_cast<const uint2*>(codes);
const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
#pragma unroll
for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc;
}
__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = d0 / QK4_0;
const int rem = d0 % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = (rem == 0 || rem == 16) ? 0 : 8;
const uint8_t* bytes = blk->qs + j;
if (rem < 16) {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d;
} else {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d;
}
}
template <int KV_MODE>
__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out);
else if constexpr (KV_MODE == 3) {
// hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
// reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
if (value) load8_q4(p, value, row, d0, out);
else load8_q8(p, value, row, d0, out);
} else load8_q4(p, value, row, d0, out);
}
constexpr int KV_MODE=1;
extern "C" __global__ void __launch_bounds__(THREADS) leleka_qsa_decode_chunk(const float* __restrict__ q,const int8_t*kq,const int8_t*vq,const uint16_t*ks,const uint16_t*vs,const int32_t*table,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
int page_size, float scale, float* __restrict__ part_acc,
float* __restrict__ part_m, float* __restrict__ part_l,
int n_chunks, int cap = 0, long long scratch_stride = 0) {
const QsaAttnPools p{kq,vq,ks,vs,table};
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads
__shared__ float sp[G][CHUNK]; // scores, then probabilities
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int c0 = chunk * CHUNK;
const int n_here = min(CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (n_here <= 0) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, KV_MODE == 4, srow[c], lane * 8, k8);
if constexpr (KV_MODE == 4) {
const int d0 = lane * 8, half = p.keyless_n_rot / 2;
if (d0 < p.keyless_n_rot) {
float paired[8];
load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired);
const int cell = ids[c0 + c];
for (int d = 0; d < 8; ++d) {
const int pair = (d0 + d) % half;
const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair);
const float co = p.keyless_cos[(size_t)rotary_pos * half + pair];
const float si = p.keyless_sin[(size_t)rotary_pos * half + pair];
k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si;
}
}
}
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
if (lane == 0) sp[h][c] = s * scale;
}
}
__syncthreads();
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
} else if constexpr (KV_MODE == 1 || KV_MODE == 4) {
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
v = (float) p.v_q[srow[c] * HD + t] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = t / QK4_0;
const int rem = t % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
v = (float) nibble * d;
}
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
}
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
extern "C" __global__ void __launch_bounds__(HD) leleka_qsa_decode_merge(const float* __restrict__ part_acc,
const float* __restrict__ part_m,
const float* __restrict__ part_l, int n_chunks,
float* __restrict__ attn, long long scratch_stride = 0) {
part_acc += (size_t) blockIdx.y * (size_t) scratch_stride;
part_m += (size_t) blockIdx.y * (size_t) scratch_stride;
part_l += (size_t) blockIdx.y * (size_t) scratch_stride;
attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD;
const int h = blockIdx.x; // global query head
const int kvh = h / G, hl = h % G;
const int d = threadIdx.x;
float M = -FLT_MAX;
for (int c = 0; c < n_chunks; ++c) M = fmaxf(M, part_m[(kvh * n_chunks + c) * G + hl]);
float L = 0.0f, acc = 0.0f;
for (int c = 0; c < n_chunks; ++c) {
const int slot = kvh * n_chunks + c;
const float m = part_m[slot * G + hl];
if (m == -FLT_MAX) continue;
const float w = __expf(m - M);
L = fmaf(part_l[slot * G + hl], w, L);
acc = fmaf(part_acc[((size_t) slot * G + hl) * HD + d], w, acc);
}
attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
}
extern "C" __global__ void leleka_qsa_prompt_guard(const float*q,const int32_t*ids,const int32_t*steps,int T,int cap,int end,int*status){
for(int i=blockIdx.x*blockDim.x+threadIdx.x;i<T*6144;i+=gridDim.x*blockDim.x)if(!isfinite(q[i]))atomicOr(status,1);
for(int r=blockIdx.x*blockDim.x+threadIdx.x;r<T;r+=gridDim.x*blockDim.x){
int pos=steps[r*4],n=steps[r*4+3];
if(pos<0||pos>=end||steps[r*4+1]!=pos+1||steps[r*4+2]!=(pos+1)/4||n!=min(pos+1,cap)){atomicOr(status,2);continue;}
for(int j=0;j<n;++j){int id=ids[r*cap+j];if(id<0||id>pos||(j&&id<=ids[r*cap+j-1]))atomicOr(status,2);}
}
}
extern "C" __global__ void leleka_qsa_prompt_output_guard(const float*x,int n,int*status){
for(int i=blockIdx.x*blockDim.x+threadIdx.x;i<n;i+=gridDim.x*blockDim.x)if(!isfinite(x[i]))atomicOr(status,1);
}

Some files were not shown because too many files have changed in this diff Show More