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:
co-authored by
Claude Sonnet 5.5
parent
5a06a29b9a
commit
7f896a8bb8
Generated
+10
@@ -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
@@ -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]
|
||||
|
||||
@@ -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`
|
||||
@@ -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.
@@ -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)
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
| ||||