From a9d80333b431572b720675101ebf6a4deca9ca0e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 12:53:35 +0100 Subject: [PATCH] STRA-338 size: large inline modules of 15 engine-crate files move to files (extract_modules.py now emits #[path] only for files that are themselves loaded through #[path]); test lists identical (1793). Ratchets raised with reason: path-include +3 cuda-driver, +4 engine, +7 model-format... are the child declarations of files that sit under a #[path]-loaded parent (their children cannot be found otherwise); the follow-up that removes them is turning those parents into directory modules --- architecture-baseline.json | 20 +- crates/cuda-driver/src/api.rs | 366 +------ crates/cuda-driver/src/api/enabled.rs | 365 +++++++ crates/cuda-driver/src/gdn_native_batch.rs | 185 +--- .../cuda-driver/src/gdn_native_batch/tests.rs | 183 ++++ crates/cuda-driver/src/moe_prefill_batch.rs | 210 +--- .../src/moe_prefill_batch/tests.rs | 208 ++++ .../cuda-driver/src/mtp_original_int8_ffi.rs | 494 +--------- .../src/mtp_original_int8_ffi/enabled.rs | 227 +++++ .../src/mtp_original_int8_ffi/host_enabled.rs | 263 ++++++ crates/cuda-driver/src/native_head.rs | 68 +- .../src/native_head/alias_tests.rs | 67 ++ .../src/original_gpu_schedule_ffi.rs | 434 +-------- .../src/original_gpu_schedule_ffi/platform.rs | 88 ++ .../platform/impl_api.rs | 250 +++++ .../platform/impl_api_2.rs | 85 ++ .../platform/impl_drop_for_library.rs | 43 + crates/cuda-driver/src/ple_batch_ffi.rs | 576 +---------- .../cuda-driver/src/ple_batch_ffi/enabled.rs | 89 ++ .../src/ple_batch_ffi/enabled/impl_blas.rs | 256 +++++ .../src/ple_batch_ffi/enabled/impl_blas_2.rs | 222 +++++ .../src/ple_batch_ffi/enabled/impl_library.rs | 34 + .../src/backend_original_serve.rs | 821 +--------------- .../src/backend_original_serve/runner.rs | 115 +++ .../runner/generate_fn.rs | 152 +++ .../runner/gpu_probe_fn.rs | 202 ++++ .../backend_original_serve/runner/run_fn.rs | 288 ++++++ .../src/backend_original_serve/tests.rs | 102 ++ .../src/model_binding/qwen4exp_kar_ple.rs | 856 +---------------- .../qwen4exp_kar_ple/pinned_profile_tests.rs | 131 +++ .../qwen4exp_kar_ple/private_copy.rs | 322 +++++++ .../private_copy/checked_reader_fn.rs | 80 ++ .../qwen4exp_kar_ple/private_copy/inode_fn.rs | 239 +++++ .../qwen4exp_kar_ple/win_archive.rs | 122 +++ .../src/model_binding/qwen4exp_mtp.rs | 481 +--------- .../src/model_binding/qwen4exp_mtp/backing.rs | 381 ++++++++ .../engine-qwen35-cuda/src/qwen_forward/gr.rs | 886 +---------------- .../qwen_forward/gr/output_workspace_gpu.rs | 493 ++++++++++ .../output_workspace_gpu/check_handoff_fn.rs | 128 +++ .../gr/output_workspace_gpu/fresh_read_fn.rs | 133 +++ .../src/qwen_forward/gr/tests.rs | 155 +++ .../src/qwen_forward/kar_ple_cache.rs | 599 +----------- .../qwen_forward/kar_ple_cache/lru_tests.rs | 311 ++++++ .../kar_ple_cache/row_parity_probe.rs | 102 ++ .../qwen_forward/kar_ple_cache/slot_tests.rs | 183 ++++ crates/leleka-memory/src/lock.rs | 351 +------ crates/leleka-memory/src/lock/sys.rs | 350 +++++++ crates/model-format/src/gguf.rs | 894 +----------------- crates/model-format/src/gguf/tests.rs | 89 ++ .../admits_flash_metadata_and_rejects.rs | 284 ++++++ ...uffered_cursor_preserves_offsets_parsin.rs | 239 +++++ ...empty_owned_tensor_validation_preserves.rs | 142 +++ .../original_first_source_fence_retains.rs | 168 ++++ crates/model-format/src/qwen4exp.rs | 358 +------ .../whole_dense_matrix_transport_tests.rs | 229 +++++ .../src/qwen4exp/whole_moe_matrix_sdet.rs | 127 +++ scripts/dev/extract_modules.py | 28 +- scripts/dev/rustsplit/testsplit.py | 3 +- 58 files changed, 7709 insertions(+), 7568 deletions(-) create mode 100644 crates/cuda-driver/src/api/enabled.rs create mode 100644 crates/cuda-driver/src/gdn_native_batch/tests.rs create mode 100644 crates/cuda-driver/src/moe_prefill_batch/tests.rs create mode 100644 crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs create mode 100644 crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs create mode 100644 crates/cuda-driver/src/native_head/alias_tests.rs create mode 100644 crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs create mode 100644 crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs create mode 100644 crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs create mode 100644 crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs create mode 100644 crates/cuda-driver/src/ple_batch_ffi/enabled.rs create mode 100644 crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs create mode 100644 crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs create mode 100644 crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs create mode 100644 crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs create mode 100644 crates/leleka-memory/src/lock/sys.rs create mode 100644 crates/model-format/src/gguf/tests.rs create mode 100644 crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs create mode 100644 crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs create mode 100644 crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs create mode 100644 crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs create mode 100644 crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs create mode 100644 crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs diff --git a/architecture-baseline.json b/architecture-baseline.json index f5e5ec44..d4f0ce06 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -20,21 +20,15 @@ "crates/cpu-sys/src/lib.rs": 1007, "crates/cpu-sys/src/simd.rs": 1503, "crates/cpu-worker/tests/serve_loop.rs": 477, - "crates/cuda-driver/src/api.rs": 423, "crates/cuda-driver/src/experimental.rs": 407, - "crates/cuda-driver/src/gdn_native_batch.rs": 557, "crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618, "crates/cuda-driver/src/lib.rs": 938, "crates/cuda-driver/src/mmq_resident_gpu.rs": 517, - "crates/cuda-driver/src/moe_prefill_batch.rs": 476, "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621, "crates/cuda-driver/src/mtp_original_full_symbols.rs": 445, - "crates/cuda-driver/src/mtp_original_int8_ffi.rs": 543, "crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 676, "crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 622, - "crates/cuda-driver/src/native_head.rs": 533, - "crates/cuda-driver/src/original_gpu_schedule_ffi.rs": 454, - "crates/cuda-driver/src/ple_batch_ffi.rs": 625, + "crates/cuda-driver/src/native_head.rs": 467, "crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420, "crates/cuda-driver/src/qwen_ffi.rs": 876, "crates/cuda-driver/src/sm86_table.rs": 933, @@ -56,18 +50,15 @@ "crates/deploy/src/supervisor.rs": 1863, "crates/deploy/tests/e2e.rs": 2118, "crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs": 474, - "crates/engine-qwen35-cuda/src/backend_original_serve.rs": 961, "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851, "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 447, "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs": 979, "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs": 1648, "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs": 540, - "crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs": 1026, - "crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 1124, + "crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 651, "crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980, "crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466, - "crates/engine-qwen35-cuda/src/qwen_forward/gr.rs": 1036, - "crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs": 730, + "crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs": 493, "crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs": 454, "crates/experimental-ref/tests/emulated_kernels.rs": 467, "crates/gateway-domain/src/responses/render.rs": 405, @@ -81,9 +72,6 @@ "crates/gptoss/tests/synthetic_model.rs": 922, "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 440, - "crates/leleka-memory/src/lock.rs": 432, - "crates/model-format/src/gguf.rs": 1099, - "crates/model-format/src/qwen4exp.rs": 625, "crates/native-cpu-expert/examples/kernel_ab.rs": 3347, "crates/openvino/src/lib.rs": 676, "crates/quant-core/src/iq2s_grid.rs": 1032, @@ -157,7 +145,7 @@ "instant-now:leleka-obs": 3, "instant-now:strata-control": 23, "instant-now:strata-desktop-core": 15, - "path-include:leleka-cuda-driver": 115, + "path-include:leleka-cuda-driver": 118, "path-include:leleka-engine-qwen35-cuda": 100, "path-include:leleka-model-format": 12, "path-include:leleka-native-cpu-expert": 2, diff --git a/crates/cuda-driver/src/api.rs b/crates/cuda-driver/src/api.rs index da898cd5..466cc243 100644 --- a/crates/cuda-driver/src/api.rs +++ b/crates/cuda-driver/src/api.rs @@ -21,371 +21,7 @@ pub(crate) struct MappedCopyArguments { any(target_os = "linux", target_os = "windows"), 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 { - // 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 { - 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")); - } - crate::compute_drain::register(handle as usize); - Ok(Stream(handle as usize)) - } - pub(crate) fn create_event(&self) -> Result { - 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 { - // 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<()> { - crate::compute_drain::unregister(stream.0); - // 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 { - 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, crate::arch_ptx::image(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 { - 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()) - }) - } - /// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains - /// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and - /// copies from them are DMA instead of staged. - pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> { - // SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`. - check("cuMemHostRegister_v2", unsafe { - (self.inner.register)(start as *mut c_void, len, 8) - }) - } - pub(crate) fn unregister_at(&self, start: usize) -> Result<()> { - // SAFETY: identical live registered base from `register_read_only`; all consumers drained. - check("cuMemHostUnregister", unsafe { (self.inner.unregister)(start as *mut c_void) }) - } - /// Page-lock `len` bytes at page-aligned `start` of a writable host allocation the caller owns (flags 0): - /// the prompt path's host staging buffers, so their H2D copies are DMA. Released by `unregister_at`. - pub(crate) fn register_staging(&self, start: usize, len: usize) -> Result<()> { - // SAFETY: the caller passes a live page-aligned allocation it retains until `unregister_at`. - check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 0) }) - } - 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 { - self.inner.create_stream() - } - pub(crate) fn event(&self) -> Result { - 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 { - 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 { - // 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) - } -} +mod enabled; #[cfg(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), diff --git a/crates/cuda-driver/src/api/enabled.rs b/crates/cuda-driver/src/api/enabled.rs new file mode 100644 index 00000000..e2e45a48 --- /dev/null +++ b/crates/cuda-driver/src/api/enabled.rs @@ -0,0 +1,365 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +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 { + // 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 { + 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")); + } + crate::compute_drain::register(handle as usize); + Ok(Stream(handle as usize)) + } + pub(crate) fn create_event(&self) -> Result { + 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 { + // 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<()> { + crate::compute_drain::unregister(stream.0); + // 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 { + 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, crate::arch_ptx::image(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 { + 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()) + }) + } + /// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains + /// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and + /// copies from them are DMA instead of staged. + pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> { + // SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`. + check("cuMemHostRegister_v2", unsafe { + (self.inner.register)(start as *mut c_void, len, 8) + }) + } + pub(crate) fn unregister_at(&self, start: usize) -> Result<()> { + // SAFETY: identical live registered base from `register_read_only`; all consumers drained. + check("cuMemHostUnregister", unsafe { (self.inner.unregister)(start as *mut c_void) }) + } + /// Page-lock `len` bytes at page-aligned `start` of a writable host allocation the caller owns (flags 0): + /// the prompt path's host staging buffers, so their H2D copies are DMA. Released by `unregister_at`. + pub(crate) fn register_staging(&self, start: usize, len: usize) -> Result<()> { + // SAFETY: the caller passes a live page-aligned allocation it retains until `unregister_at`. + check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 0) }) + } + 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 { + self.inner.create_stream() + } + pub(crate) fn event(&self) -> Result { + 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 { + 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 { + // 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) +} diff --git a/crates/cuda-driver/src/gdn_native_batch.rs b/crates/cuda-driver/src/gdn_native_batch.rs index 177256a0..6f76a120 100644 --- a/crates/cuda-driver/src/gdn_native_batch.rs +++ b/crates/cuda-driver/src/gdn_native_batch.rs @@ -337,189 +337,8 @@ struct Drained { } #[cfg(test)] -mod tests { - use super::*; - - fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|word| word.to_le_bytes()).collect() - } - - #[test] - fn stage_slots_follow_program_order_and_sizes_match_roles() { - for (index, stage) in STAGES.into_iter().enumerate() { - assert_eq!(stage.slot(), index); - } - assert_eq!(GdnBatchStage::NextState.bytes(7), 3_145_728); - assert_eq!(GdnBatchStage::NextHistory.bytes(7), 122_880); - assert_eq!(GdnBatchStage::Qkv.bytes(3), 3 * 40_960); - assert_eq!(GdnBatchStage::Ab.elements(5), 5 * 96); - assert_eq!(GdnBatchStage::Y16.bytes(2), 2 * 6144 * 2); - assert_eq!(GdnBatchStage::MixedH.bytes(2), 2 * 2560 * 2); - assert_eq!(GdnBatchStage::Bo.bytes(2), 2 * 2560 * 4); - assert!(GdnBatchStage::MixedH.is_half() && GdnBatchStage::Y16.is_half()); - assert!(!GdnBatchStage::Y.is_half()); - } - - #[test] - fn program_has_one_fixed_order_and_ends() { - let mut step = Step::Images; - let mut seen = Vec::new(); - while step != Step::Done { - seen.push(step); - step = step.next(); - } - assert_eq!( - seen, - [ - Step::Images, - Step::Qkv, - Step::Z, - Step::Ab, - Step::Gates, - Step::Conv, - Step::L2, - Step::Recurrence, - Step::OutNorm, - Step::Out - ] - ); - assert_eq!(Step::Done.next(), Step::Done); - } - - #[test] - fn earliest_status_in_program_order_is_the_refusal() { - let mut words = [0u32; SLOTS]; - assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); - words[GdnBatchStage::Beta.slot()] = 1; - words[GdnBatchStage::NextState.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(GdnBatchStage::Beta) - ); - words[GdnBatchStage::Qkv.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(GdnBatchStage::Qkv) - ); - } - - #[test] - fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { - let mut words = [0u32; SLOTS]; - words[GdnBatchStage::Y.slot()] = 1; - assert!(matches!( - decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()), - Err(Error::InvalidDriverValue(_)) - )); - words[GdnBatchStage::Y.slot()] = 2; - assert!(matches!( - decode_statuses(&bytes(&words), SLOTS), - Err(Error::InvalidDriverValue(_)) - )); - assert!(matches!( - decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), - Err(Error::InvalidQwenShape) - )); - } - - #[test] - fn native_formats_have_the_original_block_geometry() { - assert_eq!( - GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(), - 21_504_000 - ); - assert_eq!( - GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(), - 2 * 2 * 34 - ); - assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(1, 32).unwrap(), 18); - assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(1, 256).unwrap(), 136); - assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(1, 256).unwrap(), 144); - assert_eq!(GdnNativeFormat::Q5K.matrix_bytes(1, 256).unwrap(), 176); - for (rows, cols) in [(0, 256), (1, 0), (1, 255)] { - assert!(GdnNativeFormat::Q6K.matrix_bytes(rows, cols).is_err()); - } - let types: Vec = [ - GdnNativeFormat::Q8_0, - GdnNativeFormat::Q4K, - GdnNativeFormat::Q5K, - GdnNativeFormat::Q6K, - GdnNativeFormat::Iq4Nl, - GdnNativeFormat::Iq4Xs, - ] - .into_iter() - .map(GdnNativeFormat::ggml_type) - .collect(); - assert_eq!(types, [8, 12, 13, 14, 20, 23]); - } - - #[test] - fn kernel_table_is_closed_and_indexed_by_position() { - for (index, kernel) in KERNELS.into_iter().enumerate() { - assert_eq!(kernel.index(), index); - assert!(!kernel.entry().to_bytes().is_empty()); - } - let mut entries: Vec<_> = KERNELS.into_iter().map(|k| k.entry().to_owned()).collect(); - entries.sort(); - entries.dedup(); - assert_eq!(entries.len(), KERNELS.len()); - assert_eq!(KERNELS.into_iter().filter(|k| k.is_dequant()).count(), 6); - } - - #[test] - fn linear_launches_cover_every_item_in_256_blocks() { - assert_eq!(linear(1).unwrap(), ([1, 1, 1], [256, 1, 1])); - assert_eq!(linear(256).unwrap().0, [1, 1, 1]); - assert_eq!(linear(257).unwrap().0, [2, 1, 1]); - assert_eq!(linear(GDN_BATCH_MAX_TOKENS * C).unwrap().0[0], 81_920); - } - - #[test] - fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { - let a = ffi::BufferHandle::synthetic(0x1000); - let b = ffi::BufferHandle::synthetic(0x2000); - let overlapping = ffi::BufferHandle::synthetic(0x1800); - let mut bindings = Bindings::new(); - bindings.bind(Role::Qkv, a, 0x1000).unwrap(); - bindings.bind(Role::Z, b, 0x1000).unwrap(); - bindings.bind(Role::Qkv, a, 0x1000).unwrap(); - assert!(matches!( - bindings.bind(Role::Qkv, b, 0x1000), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Qkv, a, 0x800), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Gate, overlapping, 0x100), - Err(Error::OutputAliasesInput) - )); - assert!(bindings.get(Role::Gate).is_err()); - assert!(bindings.get(Role::Z).unwrap() == (b, 0x1000)); - } - - #[test] - fn unpinned_artifacts_fail_closed_and_pins_check_length_and_digest() { - static GOOD: &[u8] = b".version 8.0\n\0"; - assert!(matches!( - pinned(GOOD, 0, [0; 32], "x"), - Err(Error::InvalidDriverValue(_)) - )); - let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); - assert!(pinned(GOOD, GOOD.len() - 1, digest, "x").is_ok()); - assert!(pinned(GOOD, GOOD.len() - 2, digest, "x").is_err()); - let mut wrong = digest; - wrong[0] ^= 1; - assert!(pinned(GOOD, GOOD.len() - 1, wrong, "x").is_err()); - static NO_NUL: &[u8] = b".version 8.0\n"; - assert!(pinned(NO_NUL, NO_NUL.len(), digest, "x").is_err()); - } -} +#[path = "gdn_native_batch/tests.rs"] +mod tests; #[cfg(all( test, diff --git a/crates/cuda-driver/src/gdn_native_batch/tests.rs b/crates/cuda-driver/src/gdn_native_batch/tests.rs new file mode 100644 index 00000000..317d72fc --- /dev/null +++ b/crates/cuda-driver/src/gdn_native_batch/tests.rs @@ -0,0 +1,183 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +#[test] +fn stage_slots_follow_program_order_and_sizes_match_roles() { + for (index, stage) in STAGES.into_iter().enumerate() { + assert_eq!(stage.slot(), index); + } + assert_eq!(GdnBatchStage::NextState.bytes(7), 3_145_728); + assert_eq!(GdnBatchStage::NextHistory.bytes(7), 122_880); + assert_eq!(GdnBatchStage::Qkv.bytes(3), 3 * 40_960); + assert_eq!(GdnBatchStage::Ab.elements(5), 5 * 96); + assert_eq!(GdnBatchStage::Y16.bytes(2), 2 * 6144 * 2); + assert_eq!(GdnBatchStage::MixedH.bytes(2), 2 * 2560 * 2); + assert_eq!(GdnBatchStage::Bo.bytes(2), 2 * 2560 * 4); + assert!(GdnBatchStage::MixedH.is_half() && GdnBatchStage::Y16.is_half()); + assert!(!GdnBatchStage::Y.is_half()); +} + +#[test] +fn program_has_one_fixed_order_and_ends() { + let mut step = Step::Images; + let mut seen = Vec::new(); + while step != Step::Done { + seen.push(step); + step = step.next(); + } + assert_eq!( + seen, + [ + Step::Images, + Step::Qkv, + Step::Z, + Step::Ab, + Step::Gates, + Step::Conv, + Step::L2, + Step::Recurrence, + Step::OutNorm, + Step::Out + ] + ); + assert_eq!(Step::Done.next(), Step::Done); +} + +#[test] +fn earliest_status_in_program_order_is_the_refusal() { + let mut words = [0u32; SLOTS]; + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); + words[GdnBatchStage::Beta.slot()] = 1; + words[GdnBatchStage::NextState.slot()] = 1; + assert_eq!( + decode_statuses(&bytes(&words), SLOTS).unwrap(), + Some(GdnBatchStage::Beta) + ); + words[GdnBatchStage::Qkv.slot()] = 1; + assert_eq!( + decode_statuses(&bytes(&words), SLOTS).unwrap(), + Some(GdnBatchStage::Qkv) + ); +} + +#[test] +fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { + let mut words = [0u32; SLOTS]; + words[GdnBatchStage::Y.slot()] = 1; + assert!(matches!( + decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()), + Err(Error::InvalidDriverValue(_)) + )); + words[GdnBatchStage::Y.slot()] = 2; + assert!(matches!( + decode_statuses(&bytes(&words), SLOTS), + Err(Error::InvalidDriverValue(_)) + )); + assert!(matches!( + decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), + Err(Error::InvalidQwenShape) + )); + assert!(matches!( + decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), + Err(Error::InvalidQwenShape) + )); +} + +#[test] +fn native_formats_have_the_original_block_geometry() { + assert_eq!( + GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(), + 21_504_000 + ); + assert_eq!( + GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(), + 2 * 2 * 34 + ); + assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(1, 32).unwrap(), 18); + assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(1, 256).unwrap(), 136); + assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(1, 256).unwrap(), 144); + assert_eq!(GdnNativeFormat::Q5K.matrix_bytes(1, 256).unwrap(), 176); + for (rows, cols) in [(0, 256), (1, 0), (1, 255)] { + assert!(GdnNativeFormat::Q6K.matrix_bytes(rows, cols).is_err()); + } + let types: Vec = [ + GdnNativeFormat::Q8_0, + GdnNativeFormat::Q4K, + GdnNativeFormat::Q5K, + GdnNativeFormat::Q6K, + GdnNativeFormat::Iq4Nl, + GdnNativeFormat::Iq4Xs, + ] + .into_iter() + .map(GdnNativeFormat::ggml_type) + .collect(); + assert_eq!(types, [8, 12, 13, 14, 20, 23]); +} + +#[test] +fn kernel_table_is_closed_and_indexed_by_position() { + for (index, kernel) in KERNELS.into_iter().enumerate() { + assert_eq!(kernel.index(), index); + assert!(!kernel.entry().to_bytes().is_empty()); + } + let mut entries: Vec<_> = KERNELS.into_iter().map(|k| k.entry().to_owned()).collect(); + entries.sort(); + entries.dedup(); + assert_eq!(entries.len(), KERNELS.len()); + assert_eq!(KERNELS.into_iter().filter(|k| k.is_dequant()).count(), 6); +} + +#[test] +fn linear_launches_cover_every_item_in_256_blocks() { + assert_eq!(linear(1).unwrap(), ([1, 1, 1], [256, 1, 1])); + assert_eq!(linear(256).unwrap().0, [1, 1, 1]); + assert_eq!(linear(257).unwrap().0, [2, 1, 1]); + assert_eq!(linear(GDN_BATCH_MAX_TOKENS * C).unwrap().0[0], 81_920); +} + +#[test] +fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { + let a = ffi::BufferHandle::synthetic(0x1000); + let b = ffi::BufferHandle::synthetic(0x2000); + let overlapping = ffi::BufferHandle::synthetic(0x1800); + let mut bindings = Bindings::new(); + bindings.bind(Role::Qkv, a, 0x1000).unwrap(); + bindings.bind(Role::Z, b, 0x1000).unwrap(); + bindings.bind(Role::Qkv, a, 0x1000).unwrap(); + assert!(matches!( + bindings.bind(Role::Qkv, b, 0x1000), + Err(Error::InvalidQwenShape) + )); + assert!(matches!( + bindings.bind(Role::Qkv, a, 0x800), + Err(Error::InvalidQwenShape) + )); + assert!(matches!( + bindings.bind(Role::Gate, overlapping, 0x100), + Err(Error::OutputAliasesInput) + )); + assert!(bindings.get(Role::Gate).is_err()); + assert!(bindings.get(Role::Z).unwrap() == (b, 0x1000)); +} + +#[test] +fn unpinned_artifacts_fail_closed_and_pins_check_length_and_digest() { + static GOOD: &[u8] = b".version 8.0\n\0"; + assert!(matches!( + pinned(GOOD, 0, [0; 32], "x"), + Err(Error::InvalidDriverValue(_)) + )); + let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); + assert!(pinned(GOOD, GOOD.len() - 1, digest, "x").is_ok()); + assert!(pinned(GOOD, GOOD.len() - 2, digest, "x").is_err()); + let mut wrong = digest; + wrong[0] ^= 1; + assert!(pinned(GOOD, GOOD.len() - 1, wrong, "x").is_err()); + static NO_NUL: &[u8] = b".version 8.0\n"; + assert!(pinned(NO_NUL, NO_NUL.len(), digest, "x").is_err()); +} diff --git a/crates/cuda-driver/src/moe_prefill_batch.rs b/crates/cuda-driver/src/moe_prefill_batch.rs index ddf8ea06..46073b98 100644 --- a/crates/cuda-driver/src/moe_prefill_batch.rs +++ b/crates/cuda-driver/src/moe_prefill_batch.rs @@ -232,214 +232,8 @@ struct Drained { } #[cfg(test)] -mod tests { - use super::*; - - fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|word| word.to_le_bytes()).collect() - } - - #[test] - fn stage_slots_follow_program_order_and_sizes_match_roles() { - for (index, stage) in STAGES.into_iter().enumerate() { - assert_eq!(stage.slot(), index); - } - assert_eq!(MoeBatchStage::Logits.bytes(64), 64 * 512 * 4); - assert_eq!(MoeBatchStage::RouteWeights.bytes(3), 3 * 10 * 4); - assert_eq!(MoeBatchStage::ShH.bytes(2), 2 * 640 * 2); - assert_eq!(MoeBatchStage::MixedH.bytes(2), 2 * 2560 * 2); - assert_eq!(MoeBatchStage::Sg.bytes(5), 5 * 4); - assert_eq!(MoeBatchStage::Bo.bytes(2), 2 * 2560 * 4); - assert!(MoeBatchStage::MixedH.is_half() && MoeBatchStage::ShH.is_half()); - assert!(!MoeBatchStage::Shared.is_half()); - assert_eq!(MOE_BATCH_SCRATCH_BYTES, 3_276_800); - } - - #[test] - fn the_combine_only_program_starts_at_the_last_status_slot() { - // `begin_combine` starts with `checks == Bo.slot()`: the single scanned slot is the last one, every earlier - // slot stays zero, and a refusal there is attributed to `Bo`. - assert_eq!(MoeBatchStage::Bo.slot(), SLOTS - 1); - let mut statuses = [0u32; SLOTS]; - assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), None); - statuses[MoeBatchStage::Bo.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&statuses), SLOTS).unwrap(), - Some(MoeBatchStage::Bo) - ); - // A stray bit in a slot the combine-only program never scans would also be 1 and so reported as that - // stage; the zero kernel clears every slot first, so this cannot happen without a driver fault. - statuses[MoeBatchStage::Bo.slot()] = 0; - statuses[MoeBatchStage::Sg.slot()] = 2; - assert!(decode_statuses(&bytes(&statuses), SLOTS).is_err()); - } - - #[test] - fn program_has_one_fixed_order_and_combine_is_the_only_tail() { - let mut step = Step::Images; - let mut seen = Vec::new(); - while step != Step::Done { - seen.push(step); - step = step.next(); - } - assert_eq!( - seen, - [ - Step::Images, - Step::Router, - Step::Gate, - Step::Up, - Step::Swiglu, - Step::Down, - Step::Scalar, - Step::Combine - ] - ); - assert_eq!(Step::Done.next(), Step::Done); - } - - #[test] - fn earliest_status_in_program_order_is_the_refusal() { - let mut words = [0u32; SLOTS]; - assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); - words[MoeBatchStage::Shared.slot()] = 1; - words[MoeBatchStage::Bo.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(MoeBatchStage::Shared) - ); - words[MoeBatchStage::Logits.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(MoeBatchStage::Logits) - ); - } - - #[test] - fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { - let mut words = [0u32; SLOTS]; - words[MoeBatchStage::Sg.slot()] = 1; - assert!(matches!( - decode_statuses(&bytes(&words), MoeBatchStage::Sg.slot()), - Err(Error::InvalidDriverValue(_)) - )); - words[MoeBatchStage::Sg.slot()] = 2; - assert!(matches!( - decode_statuses(&bytes(&words), SLOTS), - Err(Error::InvalidDriverValue(_)) - )); - assert!(matches!( - decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), - Err(Error::InvalidQwenShape) - )); - } - - #[test] - fn kernel_table_is_closed_and_dequantizers_are_indexed_by_format() { - for (index, kernel) in MOE_KERNELS.into_iter().enumerate() { - assert_eq!(kernel.index(), index); - } - let mut entries: Vec<_> = MOE_KERNELS - .into_iter() - .map(|k| k.entry().to_owned()) - .collect(); - entries.sort(); - entries.dedup(); - assert_eq!(entries.len(), MOE_KERNELS.len()); - let formats = [ - GdnNativeFormat::Q8_0, - GdnNativeFormat::Q4K, - GdnNativeFormat::Q5K, - GdnNativeFormat::Q6K, - GdnNativeFormat::Iq4Nl, - GdnNativeFormat::Iq4Xs, - ]; - for (index, format) in formats.into_iter().enumerate() { - assert_eq!(format_index(format), index); - } - // The shared expert's real matrices: gate / up 640 x 2560, down 2560 x 640. - assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(FF, N).unwrap(), 921_600); - assert_eq!(GdnNativeFormat::Q5K.matrix_bytes(FF, N).unwrap(), 1_126_400); - assert_eq!(GdnNativeFormat::Q6K.matrix_bytes(FF, N).unwrap(), 1_344_000); - assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(FF, N).unwrap(), 870_400); - assert_eq!( - GdnNativeFormat::Q8_0.matrix_bytes(N, FF).unwrap(), - 1_740_800 - ); - assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(N, FF).unwrap(), 921_600); - } - - #[test] - fn combine_row_map_must_be_a_permutation_of_the_routed_rows() { - let identity: Vec = (0..30).collect(); - assert!(check_slot_map(&identity, 3).is_ok()); - let mut reversed = identity.clone(); - reversed.reverse(); - assert!(check_slot_map(&reversed, 3).is_ok()); - let mut duplicate = identity.clone(); - duplicate[5] = 4; - let mut high = identity.clone(); - high[0] = 30; - let mut negative = identity.clone(); - negative[0] = -1; - for bad in [duplicate, high, negative, identity[..29].to_vec()] { - assert!(matches!( - check_slot_map(&bad, 3), - Err(Error::InvalidQwenShape) - )); - } - assert_eq!(SLOT_BYTES, 2560); - } - - #[test] - fn route_launch_covers_eight_tokens_per_block() { - for (tokens, blocks) in [(1usize, 1u32), (8, 1), (9, 2), (64, 8)] { - assert_eq!(tokens.div_ceil(8) as u32, blocks); - } - assert_eq!(linear(1).unwrap(), ([1, 1, 1], [256, 1, 1])); - assert_eq!(linear(257).unwrap().0, [2, 1, 1]); - } - - #[test] - fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { - let a = ffi::BufferHandle::synthetic(0x1000); - let b = ffi::BufferHandle::synthetic(0x2000); - let overlapping = ffi::BufferHandle::synthetic(0x1800); - let mut bindings = Bindings::new(); - bindings.bind(Role::Logits, a, 0x1000).unwrap(); - bindings.bind(Role::Ids, b, 0x1000).unwrap(); - bindings.bind(Role::Logits, a, 0x1000).unwrap(); - assert!(matches!( - bindings.bind(Role::Logits, b, 0x1000), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Weights, overlapping, 0x100), - Err(Error::OutputAliasesInput) - )); - assert!(bindings.get(Role::Weights).is_err()); - assert!(bindings.get(Role::Ids).unwrap() == (b, 0x1000)); - } - - #[test] - fn unpinned_artifact_fails_closed_and_pins_check_length_and_digest() { - static GOOD: &[u8] = b".version 8.0\n\0"; - assert!(matches!( - pinned(GOOD, 0, [0; 32]), - Err(Error::InvalidDriverValue(_)) - )); - let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); - assert!(pinned(GOOD, GOOD.len() - 1, digest).is_ok()); - assert!(pinned(GOOD, GOOD.len() - 2, digest).is_err()); - let mut wrong = digest; - wrong[0] ^= 1; - assert!(pinned(GOOD, GOOD.len() - 1, wrong).is_err()); - } -} +#[path = "moe_prefill_batch/tests.rs"] +mod tests; #[cfg(all( test, diff --git a/crates/cuda-driver/src/moe_prefill_batch/tests.rs b/crates/cuda-driver/src/moe_prefill_batch/tests.rs new file mode 100644 index 00000000..0fb3e726 --- /dev/null +++ b/crates/cuda-driver/src/moe_prefill_batch/tests.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +#[test] +fn stage_slots_follow_program_order_and_sizes_match_roles() { + for (index, stage) in STAGES.into_iter().enumerate() { + assert_eq!(stage.slot(), index); + } + assert_eq!(MoeBatchStage::Logits.bytes(64), 64 * 512 * 4); + assert_eq!(MoeBatchStage::RouteWeights.bytes(3), 3 * 10 * 4); + assert_eq!(MoeBatchStage::ShH.bytes(2), 2 * 640 * 2); + assert_eq!(MoeBatchStage::MixedH.bytes(2), 2 * 2560 * 2); + assert_eq!(MoeBatchStage::Sg.bytes(5), 5 * 4); + assert_eq!(MoeBatchStage::Bo.bytes(2), 2 * 2560 * 4); + assert!(MoeBatchStage::MixedH.is_half() && MoeBatchStage::ShH.is_half()); + assert!(!MoeBatchStage::Shared.is_half()); + assert_eq!(MOE_BATCH_SCRATCH_BYTES, 3_276_800); +} + +#[test] +fn the_combine_only_program_starts_at_the_last_status_slot() { + // `begin_combine` starts with `checks == Bo.slot()`: the single scanned slot is the last one, every earlier + // slot stays zero, and a refusal there is attributed to `Bo`. + assert_eq!(MoeBatchStage::Bo.slot(), SLOTS - 1); + let mut statuses = [0u32; SLOTS]; + assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), None); + statuses[MoeBatchStage::Bo.slot()] = 1; + assert_eq!( + decode_statuses(&bytes(&statuses), SLOTS).unwrap(), + Some(MoeBatchStage::Bo) + ); + // A stray bit in a slot the combine-only program never scans would also be 1 and so reported as that + // stage; the zero kernel clears every slot first, so this cannot happen without a driver fault. + statuses[MoeBatchStage::Bo.slot()] = 0; + statuses[MoeBatchStage::Sg.slot()] = 2; + assert!(decode_statuses(&bytes(&statuses), SLOTS).is_err()); +} + +#[test] +fn program_has_one_fixed_order_and_combine_is_the_only_tail() { + let mut step = Step::Images; + let mut seen = Vec::new(); + while step != Step::Done { + seen.push(step); + step = step.next(); + } + assert_eq!( + seen, + [ + Step::Images, + Step::Router, + Step::Gate, + Step::Up, + Step::Swiglu, + Step::Down, + Step::Scalar, + Step::Combine + ] + ); + assert_eq!(Step::Done.next(), Step::Done); +} + +#[test] +fn earliest_status_in_program_order_is_the_refusal() { + let mut words = [0u32; SLOTS]; + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); + words[MoeBatchStage::Shared.slot()] = 1; + words[MoeBatchStage::Bo.slot()] = 1; + assert_eq!( + decode_statuses(&bytes(&words), SLOTS).unwrap(), + Some(MoeBatchStage::Shared) + ); + words[MoeBatchStage::Logits.slot()] = 1; + assert_eq!( + decode_statuses(&bytes(&words), SLOTS).unwrap(), + Some(MoeBatchStage::Logits) + ); +} + +#[test] +fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { + let mut words = [0u32; SLOTS]; + words[MoeBatchStage::Sg.slot()] = 1; + assert!(matches!( + decode_statuses(&bytes(&words), MoeBatchStage::Sg.slot()), + Err(Error::InvalidDriverValue(_)) + )); + words[MoeBatchStage::Sg.slot()] = 2; + assert!(matches!( + decode_statuses(&bytes(&words), SLOTS), + Err(Error::InvalidDriverValue(_)) + )); + assert!(matches!( + decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), + Err(Error::InvalidQwenShape) + )); + assert!(matches!( + decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), + Err(Error::InvalidQwenShape) + )); +} + +#[test] +fn kernel_table_is_closed_and_dequantizers_are_indexed_by_format() { + for (index, kernel) in MOE_KERNELS.into_iter().enumerate() { + assert_eq!(kernel.index(), index); + } + let mut entries: Vec<_> = MOE_KERNELS + .into_iter() + .map(|k| k.entry().to_owned()) + .collect(); + entries.sort(); + entries.dedup(); + assert_eq!(entries.len(), MOE_KERNELS.len()); + let formats = [ + GdnNativeFormat::Q8_0, + GdnNativeFormat::Q4K, + GdnNativeFormat::Q5K, + GdnNativeFormat::Q6K, + GdnNativeFormat::Iq4Nl, + GdnNativeFormat::Iq4Xs, + ]; + for (index, format) in formats.into_iter().enumerate() { + assert_eq!(format_index(format), index); + } + // The shared expert's real matrices: gate / up 640 x 2560, down 2560 x 640. + assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(FF, N).unwrap(), 921_600); + assert_eq!(GdnNativeFormat::Q5K.matrix_bytes(FF, N).unwrap(), 1_126_400); + assert_eq!(GdnNativeFormat::Q6K.matrix_bytes(FF, N).unwrap(), 1_344_000); + assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(FF, N).unwrap(), 870_400); + assert_eq!( + GdnNativeFormat::Q8_0.matrix_bytes(N, FF).unwrap(), + 1_740_800 + ); + assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(N, FF).unwrap(), 921_600); +} + +#[test] +fn combine_row_map_must_be_a_permutation_of_the_routed_rows() { + let identity: Vec = (0..30).collect(); + assert!(check_slot_map(&identity, 3).is_ok()); + let mut reversed = identity.clone(); + reversed.reverse(); + assert!(check_slot_map(&reversed, 3).is_ok()); + let mut duplicate = identity.clone(); + duplicate[5] = 4; + let mut high = identity.clone(); + high[0] = 30; + let mut negative = identity.clone(); + negative[0] = -1; + for bad in [duplicate, high, negative, identity[..29].to_vec()] { + assert!(matches!( + check_slot_map(&bad, 3), + Err(Error::InvalidQwenShape) + )); + } + assert_eq!(SLOT_BYTES, 2560); +} + +#[test] +fn route_launch_covers_eight_tokens_per_block() { + for (tokens, blocks) in [(1usize, 1u32), (8, 1), (9, 2), (64, 8)] { + assert_eq!(tokens.div_ceil(8) as u32, blocks); + } + assert_eq!(linear(1).unwrap(), ([1, 1, 1], [256, 1, 1])); + assert_eq!(linear(257).unwrap().0, [2, 1, 1]); +} + +#[test] +fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { + let a = ffi::BufferHandle::synthetic(0x1000); + let b = ffi::BufferHandle::synthetic(0x2000); + let overlapping = ffi::BufferHandle::synthetic(0x1800); + let mut bindings = Bindings::new(); + bindings.bind(Role::Logits, a, 0x1000).unwrap(); + bindings.bind(Role::Ids, b, 0x1000).unwrap(); + bindings.bind(Role::Logits, a, 0x1000).unwrap(); + assert!(matches!( + bindings.bind(Role::Logits, b, 0x1000), + Err(Error::InvalidQwenShape) + )); + assert!(matches!( + bindings.bind(Role::Weights, overlapping, 0x100), + Err(Error::OutputAliasesInput) + )); + assert!(bindings.get(Role::Weights).is_err()); + assert!(bindings.get(Role::Ids).unwrap() == (b, 0x1000)); +} + +#[test] +fn unpinned_artifact_fails_closed_and_pins_check_length_and_digest() { + static GOOD: &[u8] = b".version 8.0\n\0"; + assert!(matches!( + pinned(GOOD, 0, [0; 32]), + Err(Error::InvalidDriverValue(_)) + )); + let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); + assert!(pinned(GOOD, GOOD.len() - 1, digest).is_ok()); + assert!(pinned(GOOD, GOOD.len() - 2, digest).is_err()); + let mut wrong = digest; + wrong[0] ^= 1; + assert!(pinned(GOOD, GOOD.len() - 1, wrong).is_err()); +} diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi.rs b/crates/cuda-driver/src/mtp_original_int8_ffi.rs index 37a79e32..dff571b3 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi.rs @@ -17,233 +17,8 @@ pub(crate) struct Arguments { any(target_os = "linux", target_os = "windows"), target_pointer_width = "64" ))] -mod enabled { - use super::*; - type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; - type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; - type Unload = unsafe extern "C" fn(*mut c_void) -> i32; - type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; - type Device = unsafe extern "C" fn(*mut i32) -> i32; - type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; - type Launch = unsafe extern "C" fn( - *mut c_void, - u32, - u32, - u32, - u32, - u32, - u32, - u32, - *mut c_void, - *mut *mut c_void, - *mut *mut c_void, - ) -> i32; - struct Library(*mut c_void); - impl Drop for Library { - fn drop(&mut self) { - if !self.0.is_null() { - // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. - unsafe { - libc::dlclose(self.0); - } - } - } - } - fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } - } - macro_rules! sym { - ($l:ident,$n:literal,$t:ty) => {{ - // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. - let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; - if p.is_null() { - return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); - } - // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature - // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). - unsafe { std::mem::transmute::<*mut c_void, $t>(p) } - }}; - } - pub(crate) struct Module { - library: Option, - module: Option, - functions: Vec, - launch: Launch, - unload: Unload, - copy: Copy, - } - impl Module { - pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { - if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { - return Err(Error::UnsupportedQwenOperation); - } - // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); - if l.0.is_null() { - return Err(Error::LibraryUnavailable); - } - let load = sym!(l, c"cuModuleLoadData", Load); - let get = sym!(l, c"cuModuleGetFunction", Function); - let dev = sym!(l, c"cuCtxGetDevice", Device); - let attr = sym!(l, c"cuDeviceGetAttribute", Attr); - let mut device = 0; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuCtxGetDevice", unsafe { dev(&mut device) })?; - let mut major = 0; - let mut shared = 0; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; - if major < 8 || shared < 45584 { - return Err(Error::UnsupportedQwenOperation); - } - let mut owner = Self { - launch: sym!(l, c"cuLaunchKernel", Launch), - unload: sym!(l, c"cuModuleUnload", Unload), - copy: sym!(l, c"cuMemcpyAsync", Copy), - library: Some(l), - module: None, - functions: Vec::new(), - }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; - let result = (|| { - let mut m = std::ptr::null_mut(); - // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from - // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.module = Some(m as usize); - for n in entries { - let mut f = std::ptr::null_mut(); - // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static - // NUL-terminated literal; the function out-pointer is valid. - check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions.push(f as usize); - } - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub(crate) fn launch( - &self, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - stream: usize, - args: &mut Arguments, - ) -> Result<()> { - if grid.contains(&0) - || !matches!( - block, - [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1] - ) - || !matches!(shared, 0 | 45584) - || stream == 0 - { - return Err(Error::InvalidQwenShape); - } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; - args.pointers.clear(); - for v in &mut args.values { - args.pointers.push(match v { - Arg::U64(x) => (x as *mut u64).cast(), - Arg::I32(x) => (x as *mut i32).cast(), - Arg::I64(x) => (x as *mut i64).cast(), - Arg::F32(x) => (x as *mut f32).cast(), - }); - } - // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a - // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt - // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; - // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not - // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. - check("cuLaunchKernel", unsafe { - (self.launch)( - f as *mut c_void, - grid[0], - grid[1], - grid[2], - block[0], - block[1], - block[2], - shared, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) - }) - } - // Addresses are derived only by this producer from actual whole owners. - pub(crate) fn copy(&self, dst: u64, src: u64, n: usize, stream: usize) -> Result<()> { - if n == 0 || stream == 0 || dst == 0 || src == 0 { - return Err(Error::InvalidSize); - } - // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents - // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners - // must outlive the stream drain (graph resources / Context::synchronize on every close path). - check("cuMemcpyAsync", unsafe { - (self.copy)(dst, src, n, stream as *mut c_void) - }) - } - pub(crate) fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - if let Some(m) = self.module.take() { - // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the - // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. - let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); - if r.is_err() - && let Some(l) = self.library.take() - { - std::mem::forget(l); - } - r - } else { - Ok(()) - } - } - } - impl Drop for Module { - fn drop(&mut self) { - let _ = self.close_inner(); - } - } -} +#[path = "mtp_original_int8_ffi/enabled.rs"] +mod enabled; #[cfg(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), @@ -263,269 +38,8 @@ const HOST_BYTES: usize = 276_825_088; // Original payload + four256B cursor ali any(target_os = "linux", target_os = "windows"), target_pointer_width = "64" ))] -mod host_enabled { - use super::*; - use std::ffi::c_void; - type Alloc = unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> i32; - type Address = unsafe extern "C" fn(*mut u64, *mut c_void, u32) -> i32; - type Free = unsafe extern "C" fn(*mut c_void) -> i32; - struct Library(*mut c_void); - impl Drop for Library { - fn drop(&mut self) { - if !self.0.is_null() { - // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. - unsafe { - libc::dlclose(self.0); - } - } - } - } - fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } - } - macro_rules! sym { - ($l:ident,$s:literal,$t:ty) => {{ - // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. - let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; - if p.is_null() { - return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); - } - // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature - // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). - unsafe { std::mem::transmute::<*mut c_void, $t>(p) } - }}; - } - pub(crate) struct MappedOwner { - library: Option, - host: Option, - alias: u64, - free: Free, - bytes: usize, - } - impl MappedOwner { - pub(crate) fn new() -> Result { - Self::new_sized(HOST_BYTES) - } - pub(crate) fn new_sized(bytes: usize) -> Result { - Self::new_inner(bytes, None) - } - pub(crate) fn new_for_state(c: &crate::Context<'_>, bytes: usize) -> Result { - Self::new_inner(bytes, Some(c)) - } - fn new_inner(bytes: usize, context: Option<&crate::Context<'_>>) -> Result { - if !matches!(bytes, 20 | 96 | HOST_BYTES) { - return Err(Error::InvalidSize); - } - // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); - if library.0.is_null() { - return Err(Error::LibraryUnavailable); - } - let alloc = sym!(library, c"cuMemHostAlloc", Alloc); - let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); - let free = sym!(library, c"cuMemFreeHost", Free); - let mut ptr = std::ptr::null_mut(); - // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is - // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). - check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; - if ptr.is_null() { - return Err(Error::InvalidDriverValue("cuMemHostAlloc")); - } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - free, - bytes, - }; - // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); - if let Err(primary) = op { - if owner.close().is_err() { - if let Some(c) = context { - c.poison(); - c.retain_driver(); - } - } - return Err(primary); - } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { - if owner.close().is_err() { - if let Some(c) = context { - c.poison(); - c.retain_driver(); - } - } - return Err(Error::InvalidDriverValue("mapped-host-alignment")); - } - // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes - // the block fully initialized before the first CPU read. - unsafe { - std::ptr::write_bytes(ptr.cast::(), 0, bytes); - } // initialized final whole owner; never resized. - Ok(owner) - } - /// Literal qsa_state_zero on the caller's checked whole state spans. - /// Context is entered by the owning state; legacy default stream exactly. - pub(crate) fn zero_state(&self, destination: u64, bytes: usize) -> Result<()> { - if destination == 0 || bytes == 0 || self.host.is_none() { - return Err(Error::InvalidSize); - } - type Zero = unsafe extern "C" fn(u64, u8, usize, *mut c_void) -> i32; - let library = self.library.as_ref().ok_or(Error::ContextPoisoned)?; - let zero = sym!(library, c"cuMemsetD8Async", Zero); - // SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the legacy default - // stream and the caller drains (Context::synchronize) before the span is read or freed. - check("cuMemsetD8Async", unsafe { - zero(destination, 0, bytes, std::ptr::null_mut()) - }) - } - pub(crate) fn bytes(&self) -> usize { - self.bytes - } - pub(crate) fn address(&self, offset: usize, n: usize) -> Result { - self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) - } - fn range(&self, o: usize, n: usize) -> Result { - let p = self.host.ok_or(Error::ContextPoisoned)?; - if n == 0 || o.checked_add(n).is_none_or(|e| e > self.bytes) { - return Err(Error::InvalidSize); - } - p.checked_add(o).ok_or(Error::InvalidSize) - } - pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { - let p = self.range(o, b.len())?; - // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and - // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference - // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. - unsafe { - std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); - } - Ok(()) - } - /// CPU access only after the real producer stream drained. - pub(crate) fn read_into(&self, o: usize, b: &mut [u8]) -> Result<()> { - let p = self.range(o, b.len())?; - // SAFETY: range() proved [p, p+len) lies inside the live allocation and `b` is a distinct Rust slice. CPU reads happen only - // after the producing stream was drained (documented at each call site); GPU-written bytes are plain integers. - unsafe { - std::ptr::copy_nonoverlapping(p as *const u8, b.as_mut_ptr(), b.len()); - } - Ok(()) - } - pub(crate) fn close(&mut self) -> Result<()> { - if let Some(p) = self.host { - // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every - // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. - check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; - self.host = None; - self.alias = 0; - } - Ok(()) - } - } - impl Drop for MappedOwner { - fn drop(&mut self) { - if self.host.is_some() - && let Some(l) = self.library.take() - { - std::mem::forget(l); - } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ - } - } - // Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting - // function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. - #[cfg(test)] - mod tests { - use super::*; - use std::alloc::{Layout, alloc_zeroed, dealloc}; - use std::sync::Mutex; - static FREED: Mutex> = Mutex::new(Vec::new()); - extern "C" fn fake_free(p: *mut c_void) -> i32 { - FREED.lock().unwrap().push(p as usize); - 0 - } - fn frees(p: usize) -> usize { - FREED.lock().unwrap().iter().filter(|q| **q == p).count() - } - struct Block(*mut u8, Layout); - impl Block { - fn new(total: usize) -> Self { - let layout = Layout::from_size_align(total, 256).unwrap(); - // SAFETY: nonzero size and a valid layout; null is rejected below. - let p = unsafe { alloc_zeroed(layout) }; - assert!(!p.is_null()); - FREED.lock().unwrap().retain(|q| *q != p as usize); - Self(p, layout) - } - fn addr(&self) -> usize { - self.0 as usize - } - #[allow(dead_code)] - fn byte(&self, i: usize) -> u8 { - // SAFETY: tests only pass i < the block's total size. - unsafe { *self.0.add(i) } - } - } - impl Drop for Block { - fn drop(&mut self) { - // SAFETY: allocated in `new` with exactly this layout and freed once. - unsafe { dealloc(self.0, self.1) } - } - } - const BYTES: usize = 96; - fn owner(b: &Block) -> MappedOwner { - MappedOwner { - library: None, - host: Some(b.addr()), - alias: b.addr() as u64, - free: fake_free, - bytes: BYTES, - } - } - #[test] - fn mapped_audit_int8_write_read_into_stay_inside_and_close_frees_once() { - let b = Block::new(BYTES + 256); - let mut o = owner(&b); - o.write(BYTES - 4, &[1, 2, 3, 4]).unwrap(); - let mut out = [0u8; 4]; - o.read_into(BYTES - 4, &mut out).unwrap(); - assert_eq!(out, [1, 2, 3, 4]); - assert_eq!(o.write(BYTES - 3, &[1, 2, 3, 4]), Err(Error::InvalidSize)); - assert_eq!(o.read_into(BYTES - 3, &mut out), Err(Error::InvalidSize)); - assert_eq!(o.read_into(usize::MAX, &mut out), Err(Error::InvalidSize)); - assert_eq!(o.read_into(0, &mut []), Err(Error::InvalidSize)); - assert_eq!(b.byte(BYTES), 0); - assert_eq!(o.address(0, BYTES), Ok(b.addr() as u64)); - assert_eq!(o.address(1, BYTES), Err(Error::InvalidSize)); - assert_eq!(o.close(), Ok(())); - assert_eq!(o.close(), Ok(())); - assert_eq!(frees(b.addr()), 1); - assert_eq!(o.read_into(0, &mut out), Err(Error::ContextPoisoned)); - } - #[test] - fn mapped_audit_int8_drop_without_close_never_frees() { - let b = Block::new(BYTES); - drop(owner(&b)); - assert_eq!(frees(b.addr()), 0); - } - } -} +#[path = "mtp_original_int8_ffi/host_enabled.rs"] +mod host_enabled; #[cfg(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs new file mode 100644 index 00000000..67bb962e --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; +type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; +type Unload = unsafe extern "C" fn(*mut c_void) -> i32; +type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; +type Device = unsafe extern "C" fn(*mut i32) -> i32; +type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; +type Launch = unsafe extern "C" fn( + *mut c_void, + u32, + u32, + u32, + u32, + u32, + u32, + u32, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, +) -> i32; +struct Library(*mut c_void); +impl Drop for Library { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. + unsafe { + libc::dlclose(self.0); + } + } + } +} +fn check(op: &'static str, code: i32) -> Result<()> { + if code == 0 { + Ok(()) + } else { + Err(Error::Driver { + operation: op, + code, + }) + } +} +macro_rules! sym { + ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. + let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); + } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). + unsafe { std::mem::transmute::<*mut c_void, $t>(p) } + }}; +} +pub(crate) struct Module { + library: Option, + module: Option, + functions: Vec, + launch: Launch, + unload: Unload, + copy: Copy, +} +impl Module { + pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { + if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { + return Err(Error::UnsupportedQwenOperation); + } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. + let l = Library(unsafe { + libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) + }); + if l.0.is_null() { + return Err(Error::LibraryUnavailable); + } + let load = sym!(l, c"cuModuleLoadData", Load); + let get = sym!(l, c"cuModuleGetFunction", Function); + let dev = sym!(l, c"cuCtxGetDevice", Device); + let attr = sym!(l, c"cuDeviceGetAttribute", Attr); + let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuCtxGetDevice", unsafe { dev(&mut device) })?; + let mut major = 0; + let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuDeviceGetAttribute", unsafe { + attr(&mut major, 75, device) + })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuDeviceGetAttribute", unsafe { + attr(&mut shared, 8, device) + })?; + if major < 8 || shared < 45584 { + return Err(Error::UnsupportedQwenOperation); + } + let mut owner = Self { + launch: sym!(l, c"cuLaunchKernel", Launch), + unload: sym!(l, c"cuModuleUnload", Unload), + copy: sym!(l, c"cuMemcpyAsync", Copy), + library: Some(l), + module: None, + functions: Vec::new(), + }; + owner + .functions + .try_reserve_exact(entries.len()) + .map_err(|_| Error::HostAllocation)?; + let result = (|| { + let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. + check("cuModuleLoadData", unsafe { + load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) + })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + owner.module = Some(m as usize); + for n in entries { + let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. + check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + owner.functions.push(f as usize); + } + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub(crate) fn launch( + &self, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + stream: usize, + args: &mut Arguments, + ) -> Result<()> { + if grid.contains(&0) + || !matches!( + block, + [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1] + ) + || !matches!(shared, 0 | 45584) + || stream == 0 + { + return Err(Error::InvalidQwenShape); + } + let f = *self + .functions + .get(index) + .ok_or(Error::UnsupportedQwenOperation)?; + args.pointers.clear(); + for v in &mut args.values { + args.pointers.push(match v { + Arg::U64(x) => (x as *mut u64).cast(), + Arg::I32(x) => (x as *mut i32).cast(), + Arg::I64(x) => (x as *mut i64).cast(), + Arg::F32(x) => (x as *mut f32).cast(), + }); + } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. + check("cuLaunchKernel", unsafe { + (self.launch)( + f as *mut c_void, + grid[0], + grid[1], + grid[2], + block[0], + block[1], + block[2], + shared, + stream as *mut c_void, + args.pointers.as_mut_ptr(), + std::ptr::null_mut(), + ) + }) + } + // Addresses are derived only by this producer from actual whole owners. + pub(crate) fn copy(&self, dst: u64, src: u64, n: usize, stream: usize) -> Result<()> { + if n == 0 || stream == 0 || dst == 0 || src == 0 { + return Err(Error::InvalidSize); + } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). + check("cuMemcpyAsync", unsafe { + (self.copy)(dst, src, n, stream as *mut c_void) + }) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. + let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); + if r.is_err() + && let Some(l) = self.library.take() + { + std::mem::forget(l); + } + r + } else { + Ok(()) + } + } +} +impl Drop for Module { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs new file mode 100644 index 00000000..119df2be --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs @@ -0,0 +1,263 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use std::ffi::c_void; +type Alloc = unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> i32; +type Address = unsafe extern "C" fn(*mut u64, *mut c_void, u32) -> i32; +type Free = unsafe extern "C" fn(*mut c_void) -> i32; +struct Library(*mut c_void); +impl Drop for Library { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. + unsafe { + libc::dlclose(self.0); + } + } + } +} +fn check(op: &'static str, n: i32) -> Result<()> { + if n == 0 { + Ok(()) + } else { + Err(Error::Driver { + operation: op, + code: n, + }) + } +} +macro_rules! sym { + ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. + let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); + } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). + unsafe { std::mem::transmute::<*mut c_void, $t>(p) } + }}; +} +pub(crate) struct MappedOwner { + library: Option, + host: Option, + alias: u64, + free: Free, + bytes: usize, +} +impl MappedOwner { + pub(crate) fn new() -> Result { + Self::new_sized(HOST_BYTES) + } + pub(crate) fn new_sized(bytes: usize) -> Result { + Self::new_inner(bytes, None) + } + pub(crate) fn new_for_state(c: &crate::Context<'_>, bytes: usize) -> Result { + Self::new_inner(bytes, Some(c)) + } + fn new_inner(bytes: usize, context: Option<&crate::Context<'_>>) -> Result { + if !matches!(bytes, 20 | 96 | HOST_BYTES) { + return Err(Error::InvalidSize); + } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. + let library = Library(unsafe { + libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) + }); + if library.0.is_null() { + return Err(Error::LibraryUnavailable); + } + let alloc = sym!(library, c"cuMemHostAlloc", Alloc); + let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address); + let free = sym!(library, c"cuMemFreeHost", Free); + let mut ptr = std::ptr::null_mut(); + // SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is + // owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing). + check("cuMemHostAlloc", unsafe { alloc(&mut ptr, bytes, 3) })?; + if ptr.is_null() { + return Err(Error::InvalidDriverValue("cuMemHostAlloc")); + } + let mut owner = Self { + library: Some(library), + host: Some(ptr as usize), + alias: 0, + free, + bytes, + }; + // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. + let op = check("cuMemHostGetDevicePointer_v2", unsafe { + address(&mut owner.alias, ptr, 0) + }); + if let Err(primary) = op { + if owner.close().is_err() { + if let Some(c) = context { + c.poison(); + c.retain_driver(); + } + } + return Err(primary); + } + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) + { + if owner.close().is_err() { + if let Some(c) = context { + c.poison(); + c.retain_driver(); + } + } + return Err(Error::InvalidDriverValue("mapped-host-alignment")); + } + // SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes + // the block fully initialized before the first CPU read. + unsafe { + std::ptr::write_bytes(ptr.cast::(), 0, bytes); + } // initialized final whole owner; never resized. + Ok(owner) + } + /// Literal qsa_state_zero on the caller's checked whole state spans. + /// Context is entered by the owning state; legacy default stream exactly. + pub(crate) fn zero_state(&self, destination: u64, bytes: usize) -> Result<()> { + if destination == 0 || bytes == 0 || self.host.is_none() { + return Err(Error::InvalidSize); + } + type Zero = unsafe extern "C" fn(u64, u8, usize, *mut c_void) -> i32; + let library = self.library.as_ref().ok_or(Error::ContextPoisoned)?; + let zero = sym!(library, c"cuMemsetD8Async", Zero); + // SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the legacy default + // stream and the caller drains (Context::synchronize) before the span is read or freed. + check("cuMemsetD8Async", unsafe { + zero(destination, 0, bytes, std::ptr::null_mut()) + }) + } + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + pub(crate) fn address(&self, offset: usize, n: usize) -> Result { + self.range(offset, n)?; + self.alias + .checked_add(offset as u64) + .ok_or(Error::InvalidSize) + } + fn range(&self, o: usize, n: usize) -> Result { + let p = self.host.ok_or(Error::ContextPoisoned)?; + if n == 0 || o.checked_add(n).is_none_or(|e| e > self.bytes) { + return Err(Error::InvalidSize); + } + p.checked_add(o).ok_or(Error::InvalidSize) + } + pub(crate) fn write(&mut self, o: usize, b: &[u8]) -> Result<()> { + let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation (host is Some, offset+len <= bytes, checked_add) and + // `b` is a distinct Rust slice, so the ranges cannot overlap. The address is kept as usize on purpose: no Rust reference + // ever aliases memory the GPU may write. Caller obligation: no enqueued GPU work reads or writes this range. + unsafe { + std::ptr::copy_nonoverlapping(b.as_ptr(), p as *mut u8, b.len()); + } + Ok(()) + } + /// CPU access only after the real producer stream drained. + pub(crate) fn read_into(&self, o: usize, b: &mut [u8]) -> Result<()> { + let p = self.range(o, b.len())?; + // SAFETY: range() proved [p, p+len) lies inside the live allocation and `b` is a distinct Rust slice. CPU reads happen only + // after the producing stream was drained (documented at each call site); GPU-written bytes are plain integers. + unsafe { + std::ptr::copy_nonoverlapping(p as *const u8, b.as_mut_ptr(), b.len()); + } + Ok(()) + } + pub(crate) fn close(&mut self) -> Result<()> { + if let Some(p) = self.host { + // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every + // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. + check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; + self.host = None; + self.alias = 0; + } + Ok(()) + } +} +impl Drop for MappedOwner { + fn drop(&mut self) { + if self.host.is_some() + && let Some(l) = self.library.take() + { + std::mem::forget(l); + } /* unknown/unclosed DMA owner intentionally retained, never hostfree on uncertainty */ + } +} +// Model-free audit tests: a plain 256-aligned Rust block stands in for the cuMemHostAlloc block and a counting +// function for cuMemFreeHost, so the bounds / free-once / never-free-on-Drop invariants run without a GPU. +#[cfg(test)] +mod tests { + use super::*; + use std::alloc::{Layout, alloc_zeroed, dealloc}; + use std::sync::Mutex; + static FREED: Mutex> = Mutex::new(Vec::new()); + extern "C" fn fake_free(p: *mut c_void) -> i32 { + FREED.lock().unwrap().push(p as usize); + 0 + } + fn frees(p: usize) -> usize { + FREED.lock().unwrap().iter().filter(|q| **q == p).count() + } + struct Block(*mut u8, Layout); + impl Block { + fn new(total: usize) -> Self { + let layout = Layout::from_size_align(total, 256).unwrap(); + // SAFETY: nonzero size and a valid layout; null is rejected below. + let p = unsafe { alloc_zeroed(layout) }; + assert!(!p.is_null()); + FREED.lock().unwrap().retain(|q| *q != p as usize); + Self(p, layout) + } + fn addr(&self) -> usize { + self.0 as usize + } + #[allow(dead_code)] + fn byte(&self, i: usize) -> u8 { + // SAFETY: tests only pass i < the block's total size. + unsafe { *self.0.add(i) } + } + } + impl Drop for Block { + fn drop(&mut self) { + // SAFETY: allocated in `new` with exactly this layout and freed once. + unsafe { dealloc(self.0, self.1) } + } + } + const BYTES: usize = 96; + fn owner(b: &Block) -> MappedOwner { + MappedOwner { + library: None, + host: Some(b.addr()), + alias: b.addr() as u64, + free: fake_free, + bytes: BYTES, + } + } + #[test] + fn mapped_audit_int8_write_read_into_stay_inside_and_close_frees_once() { + let b = Block::new(BYTES + 256); + let mut o = owner(&b); + o.write(BYTES - 4, &[1, 2, 3, 4]).unwrap(); + let mut out = [0u8; 4]; + o.read_into(BYTES - 4, &mut out).unwrap(); + assert_eq!(out, [1, 2, 3, 4]); + assert_eq!(o.write(BYTES - 3, &[1, 2, 3, 4]), Err(Error::InvalidSize)); + assert_eq!(o.read_into(BYTES - 3, &mut out), Err(Error::InvalidSize)); + assert_eq!(o.read_into(usize::MAX, &mut out), Err(Error::InvalidSize)); + assert_eq!(o.read_into(0, &mut []), Err(Error::InvalidSize)); + assert_eq!(b.byte(BYTES), 0); + assert_eq!(o.address(0, BYTES), Ok(b.addr() as u64)); + assert_eq!(o.address(1, BYTES), Err(Error::InvalidSize)); + assert_eq!(o.close(), Ok(())); + assert_eq!(o.close(), Ok(())); + assert_eq!(frees(b.addr()), 1); + assert_eq!(o.read_into(0, &mut out), Err(Error::ContextPoisoned)); + } + #[test] + fn mapped_audit_int8_drop_without_close_never_frees() { + let b = Block::new(BYTES); + drop(owner(&b)); + assert_eq!(frees(b.addr()), 0); + } +} diff --git a/crates/cuda-driver/src/native_head.rs b/crates/cuda-driver/src/native_head.rs index 2c7dfe6a..fa673a7e 100644 --- a/crates/cuda-driver/src/native_head.rs +++ b/crates/cuda-driver/src/native_head.rs @@ -418,73 +418,7 @@ pub struct NativeHeadProjectionFlight<'a, 'ctx> { } #[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod alias_tests { - use super::*; - - fn payload(bytes: usize) -> Vec { - (0..bytes).map(|k| (k as u8).wrapping_mul(7).wrapping_add((k >> 8) as u8)).collect() - } - - /// Needs any CUDA device: `cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored mapped_table_alias`. - /// The alias `table_alias` returns is exactly a borrowed `DeviceBuffer` over a `cuMemHostAlloc` block's device pointer. - #[test] - #[ignore = "needs a CUDA device"] - fn mapped_table_alias_reads_the_host_bytes_and_costs_no_device_memory() { - let driver = crate::Driver::load().unwrap(); - let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); - let bytes = 1360 * 1024; - let expected = payload(bytes); - let guard = context.enter().unwrap(); - let mapped = MappedAllocation::new(bytes); - guard.finish().unwrap(); - let mut mapped = mapped.unwrap(); - mapped.write(0, &expected).unwrap(); - let handle = crate::ffi::BufferHandle::registered_bank_alias(mapped.address(0, bytes).unwrap(), bytes).unwrap(); - let alias = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; - assert_eq!(context.allocated_bytes(), 0, "an alias is not charged"); - let mut back = vec![0u8; bytes]; - alias.copy_to(&mut back).unwrap(); - assert!(back == expected, "the device reads the host copy through the alias"); - // dropping or releasing an alias frees nothing: a second alias of the same block still reads it - drop(alias); - let again = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; - let mut back = vec![0u8; bytes]; - again.copy_to(&mut back).unwrap(); - assert!(back == expected); - again.release().unwrap(); - assert_eq!(context.allocated_bytes(), 0); - let guard = context.enter().unwrap(); - let closed = mapped.close(); - guard.finish().unwrap(); - closed.unwrap(); - } - - /// Needs an sm_120 device (the sealed IQ PTX of the head/embedding): run on the 5090 server. - #[test] - #[ignore = "needs an sm_120 CUDA device (sealed PTX)"] - fn native_embed_table_alias_reads_the_same_bytes_and_costs_no_device_memory() { - let driver = crate::Driver::load().unwrap(); - let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); - // IQ4_XS (kind 23): 2560 columns are 10 blocks of 136 bytes = 1,360 bytes a row - let (kind, n, vocab) = (23u32, 2560usize, 1024usize); - let row = native_head_row_bytes(kind, n).unwrap(); - assert_eq!(row, 1360); - let expected = payload(row * vocab); - let embed = context.original_native_embed(kind, n, vocab, &expected).unwrap(); - let charged = context.allocated_bytes(); - let alias = embed.table_alias().unwrap(); - assert_eq!(alias.len(), expected.len()); - assert_eq!(context.allocated_bytes(), charged, "an alias is not charged"); - let mut back = vec![0u8; expected.len()]; - alias.copy_to(&mut back).unwrap(); - assert!(back == expected, "the alias reads the table's bytes"); - // it is a legal prompt-path table of this layout - crate::OriginalMtpEmbedding::native(&alias, kind as i32, row, vocab).unwrap(); - drop(alias); - assert_eq!(context.allocated_bytes(), charged); - embed.close().unwrap(); - } -} +mod alias_tests; mod native_asset_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/native_head/alias_tests.rs b/crates/cuda-driver/src/native_head/alias_tests.rs new file mode 100644 index 00000000..b75c1d28 --- /dev/null +++ b/crates/cuda-driver/src/native_head/alias_tests.rs @@ -0,0 +1,67 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn payload(bytes: usize) -> Vec { + (0..bytes).map(|k| (k as u8).wrapping_mul(7).wrapping_add((k >> 8) as u8)).collect() +} + +/// Needs any CUDA device: `cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored mapped_table_alias`. +/// The alias `table_alias` returns is exactly a borrowed `DeviceBuffer` over a `cuMemHostAlloc` block's device pointer. +#[test] +#[ignore = "needs a CUDA device"] +fn mapped_table_alias_reads_the_host_bytes_and_costs_no_device_memory() { + let driver = crate::Driver::load().unwrap(); + let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); + let bytes = 1360 * 1024; + let expected = payload(bytes); + let guard = context.enter().unwrap(); + let mapped = MappedAllocation::new(bytes); + guard.finish().unwrap(); + let mut mapped = mapped.unwrap(); + mapped.write(0, &expected).unwrap(); + let handle = crate::ffi::BufferHandle::registered_bank_alias(mapped.address(0, bytes).unwrap(), bytes).unwrap(); + let alias = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; + assert_eq!(context.allocated_bytes(), 0, "an alias is not charged"); + let mut back = vec![0u8; bytes]; + alias.copy_to(&mut back).unwrap(); + assert!(back == expected, "the device reads the host copy through the alias"); + // dropping or releasing an alias frees nothing: a second alias of the same block still reads it + drop(alias); + let again = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; + let mut back = vec![0u8; bytes]; + again.copy_to(&mut back).unwrap(); + assert!(back == expected); + again.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); + let guard = context.enter().unwrap(); + let closed = mapped.close(); + guard.finish().unwrap(); + closed.unwrap(); +} + +/// Needs an sm_120 device (the sealed IQ PTX of the head/embedding): run on the 5090 server. +#[test] +#[ignore = "needs an sm_120 CUDA device (sealed PTX)"] +fn native_embed_table_alias_reads_the_same_bytes_and_costs_no_device_memory() { + let driver = crate::Driver::load().unwrap(); + let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); + // IQ4_XS (kind 23): 2560 columns are 10 blocks of 136 bytes = 1,360 bytes a row + let (kind, n, vocab) = (23u32, 2560usize, 1024usize); + let row = native_head_row_bytes(kind, n).unwrap(); + assert_eq!(row, 1360); + let expected = payload(row * vocab); + let embed = context.original_native_embed(kind, n, vocab, &expected).unwrap(); + let charged = context.allocated_bytes(); + let alias = embed.table_alias().unwrap(); + assert_eq!(alias.len(), expected.len()); + assert_eq!(context.allocated_bytes(), charged, "an alias is not charged"); + let mut back = vec![0u8; expected.len()]; + alias.copy_to(&mut back).unwrap(); + assert!(back == expected, "the alias reads the table's bytes"); + // it is a legal prompt-path table of this layout + crate::OriginalMtpEmbedding::native(&alias, kind as i32, row, vocab).unwrap(); + drop(alias); + assert_eq!(context.allocated_bytes(), charged); + embed.close().unwrap(); +} diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs index df1dc12b..5f150ee6 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs @@ -5,438 +5,8 @@ use crate::{Error, Result}; any(target_os = "linux", target_os = "windows"), target_pointer_width = "64" ))] -mod platform { - use super::*; - use std::ffi::{CStr, c_void}; - type Handle = *mut c_void; - struct Library(Handle); - impl Drop for Library { - fn drop(&mut self) { - if !self.0.is_null() { - // SAFETY: `self.0` is the live, non-null dlopen handle; closed once when the table (or a failed `load`) drops. - unsafe { - libc::dlclose(self.0); - } - } - } - } - fn check(name: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: name, - code: n, - }) - } - } - type StreamCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32; - type StreamCall = unsafe extern "C" fn(Handle) -> i32; - type StreamPriority = unsafe extern "C" fn(Handle, *mut i32) -> i32; - type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32; - type EventCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32; - type EventCall = unsafe extern "C" fn(Handle) -> i32; - type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32; - type EventElapsed = unsafe extern "C" fn(*mut f32, Handle, Handle) -> i32; - type Begin = unsafe extern "C" fn(Handle, u32) -> i32; - type End = unsafe extern "C" fn(Handle, *mut Handle) -> i32; - type Nodes = unsafe extern "C" fn(Handle, *mut Handle, *mut usize) -> i32; - type Instantiate = unsafe extern "C" fn(*mut Handle, Handle, u64) -> i32; - type GraphCall = unsafe extern "C" fn(Handle) -> i32; - type GraphStream = unsafe extern "C" fn(Handle, Handle) -> i32; - type CopyH2d = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32; - type HostFn = unsafe extern "C" fn(*mut c_void); - /// `cuMemcpyBatchAsync_v2` (CUDA 12.8+/13): dsts, srcs, sizes, count, attrs, attrsIdxs, numAttrs, stream. - type CopyBatch = unsafe extern "C" fn(*mut u64, *mut u64, *mut usize, usize, *mut BatchAttributes, *mut usize, usize, Handle) -> i32; - /// `cuStreamWriteValue32_v2`: stream, device address, value, flags. - type WriteValue = unsafe extern "C" fn(Handle, u64, u32, u32) -> i32; - /// `CUmemcpyAttributes`: srcAccessOrder, srcLocHint {type, id}, dstLocHint {type, id}, flags. - #[repr(C)] - #[derive(Clone, Copy)] - struct BatchAttributes { - src_access_order: u32, - src_loc: [i32; 2], - dst_loc: [i32; 2], - flags: u32, - } - type LaunchHostFn = unsafe extern "C" fn(Handle, HostFn, *mut c_void) -> i32; - /// One `fetch_dma` flag raise: the mapped host word and the ring value it must reach. - struct Raise { - word: usize, - value: u32, - } - /// `cudaLaunchHostFunc` body of `Verifier::fetch_dma`: `raise_flag(flag, value)` (only rises). - unsafe extern "C" fn raise_after_copies(data: *mut c_void) { - // SAFETY: `data` is the Box leaked by `raise_u32_after` for exactly this one call. - let raise = unsafe { Box::from_raw(data.cast::()) }; - // SAFETY: the word is a 4-byte-aligned mapped host allocation the verifier bank keeps alive until the - // context is synchronized at its close, after every host function of its streams has run. - let word = unsafe { &*(raise.word as *const std::sync::atomic::AtomicU32) }; - word.fetch_max(raise.value, std::sync::atomic::Ordering::SeqCst); - } - /// The no-op host function of the callback-thread warm-up. - #[cfg(target_os = "linux")] - unsafe extern "C" fn noop_host_fn(_: *mut c_void) {} - /// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm; docs/upstream-port-plan.md row 0.6). - #[cfg(target_os = "linux")] - fn callback_warmup_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !matches!(std::env::var("LELEKA_CB_WARMUP").as_deref(), Ok("off" | "0" | "no"))) - } - pub(crate) struct Api { - _library: Library, - create: StreamCreate, - destroy: StreamCall, - sync: StreamCall, - query: StreamCall, - priority: StreamPriority, - wait: StreamWait, - event_create: EventCreate, - event_destroy: EventCall, - event_record: EventRecord, - event_query: EventCall, - event_sync: EventCall, - elapsed: EventElapsed, - begin: Begin, - end: End, - nodes: Nodes, - instantiate: Instantiate, - graph_destroy: GraphCall, - exec_destroy: GraphCall, - upload: GraphStream, - launch: GraphStream, - copy_h2d: CopyH2d, - host_fn: LaunchHostFn, - copy_batch: Option, - write_value: Option, - /// set when the driver refused the batch / stream-write call once (WSL, older drivers): the plain calls take over - batch_refused: std::sync::atomic::AtomicBool, - write_refused: std::sync::atomic::AtomicBool, - } - impl Api { - pub(crate) fn load() -> Result { - // SAFETY: fixed NUL-terminated library name and flags. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); - if l.0.is_null() { - return Err(Error::LibraryUnavailable); - } - fn symbol(l: &Library, n: &'static CStr) -> Result { - // SAFETY: live dlopen handle and a NUL-terminated static symbol name. - let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; - if p.is_null() { - Err(Error::MissingSymbol( - n.to_str().unwrap_or("Original schedule symbol"), - )) - } else { - Ok(p) - } - } - macro_rules! sym { - ($n:literal,$t:ty) => { - // SAFETY: non-null address of the named CUDA Driver symbol; every `$t` is that symbol's exact Linux64 C signature. - unsafe { std::mem::transmute::(symbol(&l, $n)?) } - }; - } - Ok(Self { - create: sym!(c"cuStreamCreate", StreamCreate), - destroy: sym!(c"cuStreamDestroy_v2", StreamCall), - sync: sym!(c"cuStreamSynchronize", StreamCall), - query: sym!(c"cuStreamQuery", StreamCall), - priority: sym!(c"cuStreamGetPriority", StreamPriority), - wait: sym!(c"cuStreamWaitEvent", StreamWait), - event_create: sym!(c"cuEventCreate", EventCreate), - event_destroy: sym!(c"cuEventDestroy_v2", EventCall), - event_record: sym!(c"cuEventRecord", EventRecord), - event_query: sym!(c"cuEventQuery", EventCall), - event_sync: sym!(c"cuEventSynchronize", EventCall), - elapsed: sym!(c"cuEventElapsedTime", EventElapsed), - begin: sym!(c"cuStreamBeginCapture_v2", Begin), - end: sym!(c"cuStreamEndCapture", End), - nodes: sym!(c"cuGraphGetNodes", Nodes), - instantiate: sym!(c"cuGraphInstantiateWithFlags", Instantiate), - graph_destroy: sym!(c"cuGraphDestroy", GraphCall), - exec_destroy: sym!(c"cuGraphExecDestroy", GraphCall), - upload: sym!(c"cuGraphUpload", GraphStream), - launch: sym!(c"cuGraphLaunch", GraphStream), - copy_h2d: sym!(c"cuMemcpyHtoDAsync_v2", CopyH2d), - host_fn: sym!(c"cuLaunchHostFunc", LaunchHostFn), - copy_batch: { - // SAFETY: optional symbol; a null address is mapped to `None` below. - let p = unsafe { libc::dlsym(l.0, c"cuMemcpyBatchAsync_v2".as_ptr()) }; - // SAFETY: non-null `cuMemcpyBatchAsync_v2` (CUDA 13 signature without `failIdx`); `CopyBatch` is that exact C signature. - (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) - }, - write_value: { - // SAFETY: optional symbol; a null address is mapped to `None` below. - let p = unsafe { libc::dlsym(l.0, c"cuStreamWriteValue32_v2".as_ptr()) }; - // SAFETY: non-null `cuStreamWriteValue32_v2`; `WriteValue` is its exact C signature. - (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) - }, - batch_refused: std::sync::atomic::AtomicBool::new(false), - write_refused: std::sync::atomic::AtomicBool::new(false), - _library: l, - }) - } - pub(crate) fn stream_create(&self, nonblocking: bool) -> Result { - let mut s = std::ptr::null_mut(); - // SAFETY: valid out pointer; the caller's Context is entered. - check("cuStreamCreate", unsafe { - (self.create)(&mut s, u32::from(nonblocking)) - })?; - if s.is_null() { - return Err(Error::InvalidDriverValue("cuStreamCreate")); - } - crate::compute_drain::register(s as usize); - self.warm_callback_thread(s); - Ok(s as usize) - } - /// Linux: the driver creates the thread that runs host functions lazily, at the first `cuLaunchHostFunc` of the process, and the - /// new thread inherits the CPU mask of the thread that made the call. The CPU expert pool later pins the host thread to one - /// core (`rust_platform::pin`); a callback thread created after that would share the core with the host's spin-wait (upstream - /// measured 985 us instead of 4 us per callback, `0e20d9ae`/`c08fd902`, `STRATA_ADAPT_CALLBACK_WARMUP`). One no-op host function and a - /// stream synchronize at the first stream's creation start the thread while the host thread is still unpinned. Windows CPU - /// sets are per thread and not inherited, so nothing is done there. A failure is ignored: the first real callback creates the thread. - #[cfg(target_os = "linux")] - fn warm_callback_thread(&self, s: Handle) { - static WARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !callback_warmup_enabled() || WARMED.swap(true, std::sync::atomic::Ordering::Relaxed) { - return; - } - // SAFETY: `s` is the stream just created through this Api in the entered Context; the host function ignores its argument. - let launched = unsafe { (self.host_fn)(s, noop_host_fn, std::ptr::null_mut()) }; - // SAFETY: C ABI call on the live handle; no host memory is passed. - let synced = if launched == 0 { unsafe { (self.sync)(s) } } else { launched }; - if synced == 0 { - eprintln!("leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)"); - } else { - eprintln!("leleka-serve: could not warm up the GPU host-callback thread (driver code {synced}); continuing"); - } - } - #[cfg(not(target_os = "linux"))] - fn warm_callback_thread(&self, _: Handle) {} - pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> { - crate::compute_drain::unregister(s); - // SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included). - check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) }) - } - pub(crate) fn stream_sync(&self, s: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) })) - } - pub(crate) fn stream_query(&self, s: usize) -> Result { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - let q = unsafe { (self.query)(s as Handle) }; - if q == 600 { - Ok(false) - } else { - check("cuStreamQuery", q).map(|()| true) - } - } - pub(crate) fn stream_priority(&self, s: usize) -> Result { - let mut p = 0; - // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuStreamGetPriority", unsafe { - (self.priority)(s as Handle, &mut p) - })?; - Ok(p) - } - pub(crate) fn stream_wait(&self, s: usize, e: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuStreamWaitEvent", unsafe { - (self.wait)(s as Handle, e as Handle, 0) - }) - } - pub(crate) fn event_create(&self, timing: bool) -> Result { - let mut e = std::ptr::null_mut(); - // SAFETY: valid out pointer; flags select timing / DISABLE_TIMING. - check("cuEventCreate", unsafe { - (self.event_create)(&mut e, if timing { 0 } else { 2 }) - })?; - if e.is_null() { - return Err(Error::InvalidDriverValue("cuEventCreate")); - } - Ok(e as usize) - } - pub(crate) fn event_destroy(&self, e: usize) -> Result<()> { - // SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its waiter streams) were synchronized. - check("cuEventDestroy_v2", unsafe { - (self.event_destroy)(e as Handle) - }) - } - pub(crate) fn event_record(&self, e: usize, s: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuEventRecord", unsafe { - (self.event_record)(e as Handle, s as Handle) - }) - } - pub(crate) fn event_query(&self, e: usize) -> Result { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - let q = unsafe { (self.event_query)(e as Handle) }; - if q == 600 { - Ok(false) - } else { - check("cuEventQuery", q).map(|()| true) - } - } - pub(crate) fn event_sync(&self, e: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { - (self.event_sync)(e as Handle) - })) - } - pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result { - let mut ms = 0.; - // SAFETY: valid out pointer; both events were created with timing enabled and recorded (checked by the caller). - check("cuEventElapsedTime", unsafe { - (self.elapsed)(&mut ms, a as Handle, b as Handle) - })?; - if !ms.is_finite() || ms < 0. { - return Err(Error::InvalidDriverValue("cuEventElapsedTime")); - } - Ok(ms) - } - pub(crate) fn begin(&self, s: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuStreamBeginCapture_v2", unsafe { - (self.begin)(s as Handle, 1) - }) - } // ThreadLocal - pub(crate) fn end(&self, s: usize) -> Result { - let mut g = std::ptr::null_mut(); - // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuStreamEndCapture", unsafe { - (self.end)(s as Handle, &mut g) - })?; - if g.is_null() { - return Err(Error::InvalidDriverValue("cuStreamEndCapture")); - } - Ok(g as usize) - } - pub(crate) fn nodes(&self, g: usize) -> Result { - let mut n = 0; - // SAFETY: live graph; a null node array with a valid count out pointer only queries the count. - check("cuGraphGetNodes", unsafe { - (self.nodes)(g as Handle, std::ptr::null_mut(), &mut n) - })?; - Ok(n) - } - pub(crate) fn instantiate(&self, g: usize) -> Result { - let mut e = std::ptr::null_mut(); - // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuGraphInstantiateWithFlags", unsafe { - (self.instantiate)(&mut e, g as Handle, 0) - })?; - if e.is_null() { - return Err(Error::InvalidDriverValue("cuGraphInstantiateWithFlags")); - } - Ok(e as usize) - } - pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuGraphDestroy", unsafe { - (self.graph_destroy)(g as Handle) - }) - } - pub(crate) fn exec_destroy(&self, e: usize) -> Result<()> { - // SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its stream was drained. - check("cuGraphExecDestroy", unsafe { - (self.exec_destroy)(e as Handle) - }) - } - pub(crate) fn upload(&self, e: usize, s: usize) -> Result<()> { - // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuGraphUpload", unsafe { - (self.upload)(e as Handle, s as Handle) - }) - } - pub(crate) fn launch(&self, e: usize, s: usize) -> Result<()> { - // SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by `OriginalGpuGraph` until drained. - check("cuGraphLaunch", unsafe { - (self.launch)(e as Handle, s as Handle) - }) - } - /// `cudaMemcpyAsync(H2D)` of `fetch_dma`. The caller keeps `src` (a registered bank) and `dst` alive - /// until the stream's fence. - pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> { - // SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and registered - // until this stream's next fence (documented contract of `enqueue_copy_h2d`). - check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) - }) - } - /// Every `(destination, source)` piece of a group in stream order: one `cuMemcpyBatchAsync` when `batch` and the - /// driver has it, else one `cuMemcpyHtoDAsync` per piece. The caller keeps every source (a registered bank) and - /// destination alive until the stream's fence. - pub(crate) fn copy_h2d_many(&self, pieces: &[(u64, &[u8])], s: usize, batch: bool) -> Result<()> { - if let (true, Some(f), false) = (batch, self.copy_batch, self.batch_refused.load(std::sync::atomic::Ordering::Relaxed)) { - let mut dsts: Vec = pieces.iter().map(|p| p.0).collect(); - let mut srcs: Vec = pieces.iter().map(|p| p.1.as_ptr() as u64).collect(); - let mut sizes: Vec = pieces.iter().map(|p| p.1.len()).collect(); - // srcAccessOrder STREAM (1): the registered bank stays valid until the stream's fence - let mut attr = BatchAttributes { src_access_order: 1, src_loc: [0, 0], dst_loc: [0, 0], flags: 0 }; - let mut index = 0usize; - // SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it (CUDA copies the - // descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller until the stream fence (srcAccessOrder STREAM). - let code = unsafe { - f(dsts.as_mut_ptr(), srcs.as_mut_ptr(), sizes.as_mut_ptr(), pieces.len(), &mut attr, &mut index, 1, s as Handle) - }; - if code == 0 { - return Ok(()); - } - // refused (not supported here, or an argument it does not take): never again; the plain calls below - // enqueue every piece (a piece the refused call may have queued is copied again with the same bytes) - self.batch_refused.store(true, std::sync::atomic::Ordering::Relaxed); - } - for (dst, src) in pieces { - self.copy_h2d(*dst, src, s)?; - } - Ok(()) - } - pub(crate) fn can_write_u32(&self) -> bool { - self.write_value.is_some() - } - /// `cuStreamWriteValue32` of a device-visible mapped host word after every earlier operation of the stream - /// (no host callback thread). `MissingSymbol` when the driver lacks the call. - pub(crate) fn write_u32_after(&self, s: usize, device_address: u64, value: u32) -> Result<()> { - let f = self.write_value.ok_or(Error::MissingSymbol("cuStreamWriteValue32_v2"))?; - // SAFETY: `device_address` is the device alias of a live 4-byte mapped host word the caller keeps allocated past this stream's fence. - check("cuStreamWriteValue32_v2", unsafe { f(s as Handle, device_address, value, 0) }) - } - /// Flag B after the copies: a stream write of the device alias when the driver takes it, else (or after one - /// refusal) the host callback raising the mapped host word. - pub(crate) fn raise_flag_after(&self, s: usize, host_word: usize, device_address: u64, value: u32) -> Result<()> { - use std::sync::atomic::Ordering::Relaxed; - if let (Some(f), false, true) = (self.write_value, self.write_refused.load(Relaxed), device_address != 0 && device_address % 4 == 0) { - // SAFETY: as `write_u32_after`; the alias is non-null and 4-byte aligned (checked in the condition). - if unsafe { f(s as Handle, device_address, value, 0) } == 0 { - return Ok(()); - } - self.write_refused.store(true, Relaxed); - } - self.raise_u32_after(s, host_word, value) - } - /// `cudaLaunchHostFunc(raise_flag)` of `fetch_dma`: `word` rises to at least `value` once every earlier - /// operation of the stream completed. `word` must be a live 4-byte-aligned mapped host word. - pub(crate) fn raise_u32_after(&self, s: usize, word: usize, value: u32) -> Result<()> { - if word == 0 || word % 4 != 0 { - return Err(Error::InvalidSize); - } - let data = Box::into_raw(Box::new(Raise { word, value })); - // SAFETY: `data` is a leaked `Box` owned by the callback from here on (reclaimed there, or below if the launch is refused); - // `word` is a live 4-byte-aligned mapped host word whose owner synchronizes the Context before freeing it. - let launched = check("cuLaunchHostFunc", unsafe { - (self.host_fn)(s as Handle, raise_after_copies, data.cast()) - }); - if launched.is_err() { - // SAFETY: the driver refused the launch, so the callback will never take this Box. - drop(unsafe { Box::from_raw(data) }); - } - launched - } - } -} +#[path = "original_gpu_schedule_ffi/platform.rs"] +mod platform; #[cfg(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs new file mode 100644 index 00000000..8068b053 --- /dev/null +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs @@ -0,0 +1,88 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use std::ffi::{CStr, c_void}; +type Handle = *mut c_void; +struct Library(Handle); +type StreamCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32; +type StreamCall = unsafe extern "C" fn(Handle) -> i32; +type StreamPriority = unsafe extern "C" fn(Handle, *mut i32) -> i32; +type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32; +type EventCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32; +type EventCall = unsafe extern "C" fn(Handle) -> i32; +type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32; +type EventElapsed = unsafe extern "C" fn(*mut f32, Handle, Handle) -> i32; +type Begin = unsafe extern "C" fn(Handle, u32) -> i32; +type End = unsafe extern "C" fn(Handle, *mut Handle) -> i32; +type Nodes = unsafe extern "C" fn(Handle, *mut Handle, *mut usize) -> i32; +type Instantiate = unsafe extern "C" fn(*mut Handle, Handle, u64) -> i32; +type GraphCall = unsafe extern "C" fn(Handle) -> i32; +type GraphStream = unsafe extern "C" fn(Handle, Handle) -> i32; +type CopyH2d = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32; +type HostFn = unsafe extern "C" fn(*mut c_void); +/// `cuMemcpyBatchAsync_v2` (CUDA 12.8+/13): dsts, srcs, sizes, count, attrs, attrsIdxs, numAttrs, stream. +type CopyBatch = unsafe extern "C" fn(*mut u64, *mut u64, *mut usize, usize, *mut BatchAttributes, *mut usize, usize, Handle) -> i32; +/// `cuStreamWriteValue32_v2`: stream, device address, value, flags. +type WriteValue = unsafe extern "C" fn(Handle, u64, u32, u32) -> i32; +/// `CUmemcpyAttributes`: srcAccessOrder, srcLocHint {type, id}, dstLocHint {type, id}, flags. +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchAttributes { + src_access_order: u32, + src_loc: [i32; 2], + dst_loc: [i32; 2], + flags: u32, +} +type LaunchHostFn = unsafe extern "C" fn(Handle, HostFn, *mut c_void) -> i32; +/// One `fetch_dma` flag raise: the mapped host word and the ring value it must reach. +struct Raise { + word: usize, + value: u32, +} +pub(crate) struct Api { + _library: Library, + create: StreamCreate, + destroy: StreamCall, + sync: StreamCall, + query: StreamCall, + priority: StreamPriority, + wait: StreamWait, + event_create: EventCreate, + event_destroy: EventCall, + event_record: EventRecord, + event_query: EventCall, + event_sync: EventCall, + elapsed: EventElapsed, + begin: Begin, + end: End, + nodes: Nodes, + instantiate: Instantiate, + graph_destroy: GraphCall, + exec_destroy: GraphCall, + upload: GraphStream, + launch: GraphStream, + copy_h2d: CopyH2d, + host_fn: LaunchHostFn, + copy_batch: Option, + write_value: Option, + /// set when the driver refused the batch / stream-write call once (WSL, older drivers): the plain calls take over + batch_refused: std::sync::atomic::AtomicBool, + write_refused: std::sync::atomic::AtomicBool, +} + +#[path = "platform/impl_drop_for_library.rs"] +mod impl_drop_for_library; +#[allow(unused_imports)] +use impl_drop_for_library::check; +#[allow(unused_imports)] +use impl_drop_for_library::raise_after_copies; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +use impl_drop_for_library::noop_host_fn; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +use impl_drop_for_library::callback_warmup_enabled; +#[path = "platform/impl_api.rs"] +mod impl_api; +#[path = "platform/impl_api_2.rs"] +mod impl_api_2; diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs new file mode 100644 index 00000000..bf27ce28 --- /dev/null +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs @@ -0,0 +1,250 @@ +//! Moved out of the parent module by STRA-338: impl Api. + +#[allow(unused_imports)] +use super::*; + +impl Api { + pub(crate) fn load() -> Result { + // SAFETY: fixed NUL-terminated library name and flags. + let l = Library(unsafe { + libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) + }); + if l.0.is_null() { + return Err(Error::LibraryUnavailable); + } + fn symbol(l: &Library, n: &'static CStr) -> Result { + // SAFETY: live dlopen handle and a NUL-terminated static symbol name. + let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; + if p.is_null() { + Err(Error::MissingSymbol( + n.to_str().unwrap_or("Original schedule symbol"), + )) + } else { + Ok(p) + } + } + macro_rules! sym { + ($n:literal,$t:ty) => { + // SAFETY: non-null address of the named CUDA Driver symbol; every `$t` is that symbol's exact Linux64 C signature. + unsafe { std::mem::transmute::(symbol(&l, $n)?) } + }; + } + Ok(Self { + create: sym!(c"cuStreamCreate", StreamCreate), + destroy: sym!(c"cuStreamDestroy_v2", StreamCall), + sync: sym!(c"cuStreamSynchronize", StreamCall), + query: sym!(c"cuStreamQuery", StreamCall), + priority: sym!(c"cuStreamGetPriority", StreamPriority), + wait: sym!(c"cuStreamWaitEvent", StreamWait), + event_create: sym!(c"cuEventCreate", EventCreate), + event_destroy: sym!(c"cuEventDestroy_v2", EventCall), + event_record: sym!(c"cuEventRecord", EventRecord), + event_query: sym!(c"cuEventQuery", EventCall), + event_sync: sym!(c"cuEventSynchronize", EventCall), + elapsed: sym!(c"cuEventElapsedTime", EventElapsed), + begin: sym!(c"cuStreamBeginCapture_v2", Begin), + end: sym!(c"cuStreamEndCapture", End), + nodes: sym!(c"cuGraphGetNodes", Nodes), + instantiate: sym!(c"cuGraphInstantiateWithFlags", Instantiate), + graph_destroy: sym!(c"cuGraphDestroy", GraphCall), + exec_destroy: sym!(c"cuGraphExecDestroy", GraphCall), + upload: sym!(c"cuGraphUpload", GraphStream), + launch: sym!(c"cuGraphLaunch", GraphStream), + copy_h2d: sym!(c"cuMemcpyHtoDAsync_v2", CopyH2d), + host_fn: sym!(c"cuLaunchHostFunc", LaunchHostFn), + copy_batch: { + // SAFETY: optional symbol; a null address is mapped to `None` below. + let p = unsafe { libc::dlsym(l.0, c"cuMemcpyBatchAsync_v2".as_ptr()) }; + // SAFETY: non-null `cuMemcpyBatchAsync_v2` (CUDA 13 signature without `failIdx`); `CopyBatch` is that exact C signature. + (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) + }, + write_value: { + // SAFETY: optional symbol; a null address is mapped to `None` below. + let p = unsafe { libc::dlsym(l.0, c"cuStreamWriteValue32_v2".as_ptr()) }; + // SAFETY: non-null `cuStreamWriteValue32_v2`; `WriteValue` is its exact C signature. + (!p.is_null()).then(|| unsafe { std::mem::transmute::(p) }) + }, + batch_refused: std::sync::atomic::AtomicBool::new(false), + write_refused: std::sync::atomic::AtomicBool::new(false), + _library: l, + }) + } + pub(crate) fn stream_create(&self, nonblocking: bool) -> Result { + let mut s = std::ptr::null_mut(); + // SAFETY: valid out pointer; the caller's Context is entered. + check("cuStreamCreate", unsafe { + (self.create)(&mut s, u32::from(nonblocking)) + })?; + if s.is_null() { + return Err(Error::InvalidDriverValue("cuStreamCreate")); + } + crate::compute_drain::register(s as usize); + self.warm_callback_thread(s); + Ok(s as usize) + } + /// Linux: the driver creates the thread that runs host functions lazily, at the first `cuLaunchHostFunc` of the process, and the + /// new thread inherits the CPU mask of the thread that made the call. The CPU expert pool later pins the host thread to one + /// core (`rust_platform::pin`); a callback thread created after that would share the core with the host's spin-wait (upstream + /// measured 985 us instead of 4 us per callback, `0e20d9ae`/`c08fd902`, `STRATA_ADAPT_CALLBACK_WARMUP`). One no-op host function and a + /// stream synchronize at the first stream's creation start the thread while the host thread is still unpinned. Windows CPU + /// sets are per thread and not inherited, so nothing is done there. A failure is ignored: the first real callback creates the thread. + #[cfg(target_os = "linux")] + pub(super) fn warm_callback_thread(&self, s: Handle) { + static WARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !callback_warmup_enabled() || WARMED.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + // SAFETY: `s` is the stream just created through this Api in the entered Context; the host function ignores its argument. + let launched = unsafe { (self.host_fn)(s, noop_host_fn, std::ptr::null_mut()) }; + // SAFETY: C ABI call on the live handle; no host memory is passed. + let synced = if launched == 0 { unsafe { (self.sync)(s) } } else { launched }; + if synced == 0 { + eprintln!("leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)"); + } else { + eprintln!("leleka-serve: could not warm up the GPU host-callback thread (driver code {synced}); continuing"); + } + } + #[cfg(not(target_os = "linux"))] + pub(super) fn warm_callback_thread(&self, _: Handle) {} + pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> { + crate::compute_drain::unregister(s); + // SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included). + check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) }) + } + pub(crate) fn stream_sync(&self, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) })) + } + pub(crate) fn stream_query(&self, s: usize) -> Result { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + let q = unsafe { (self.query)(s as Handle) }; + if q == 600 { + Ok(false) + } else { + check("cuStreamQuery", q).map(|()| true) + } + } + pub(crate) fn stream_priority(&self, s: usize) -> Result { + let mut p = 0; + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. + check("cuStreamGetPriority", unsafe { + (self.priority)(s as Handle, &mut p) + })?; + Ok(p) + } + pub(crate) fn stream_wait(&self, s: usize, e: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + check("cuStreamWaitEvent", unsafe { + (self.wait)(s as Handle, e as Handle, 0) + }) + } + pub(crate) fn event_create(&self, timing: bool) -> Result { + let mut e = std::ptr::null_mut(); + // SAFETY: valid out pointer; flags select timing / DISABLE_TIMING. + check("cuEventCreate", unsafe { + (self.event_create)(&mut e, if timing { 0 } else { 2 }) + })?; + if e.is_null() { + return Err(Error::InvalidDriverValue("cuEventCreate")); + } + Ok(e as usize) + } + pub(crate) fn event_destroy(&self, e: usize) -> Result<()> { + // SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its waiter streams) were synchronized. + check("cuEventDestroy_v2", unsafe { + (self.event_destroy)(e as Handle) + }) + } + pub(crate) fn event_record(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + check("cuEventRecord", unsafe { + (self.event_record)(e as Handle, s as Handle) + }) + } + pub(crate) fn event_query(&self, e: usize) -> Result { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + let q = unsafe { (self.event_query)(e as Handle) }; + if q == 600 { + Ok(false) + } else { + check("cuEventQuery", q).map(|()| true) + } + } + pub(crate) fn event_sync(&self, e: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { + (self.event_sync)(e as Handle) + })) + } + pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result { + let mut ms = 0.; + // SAFETY: valid out pointer; both events were created with timing enabled and recorded (checked by the caller). + check("cuEventElapsedTime", unsafe { + (self.elapsed)(&mut ms, a as Handle, b as Handle) + })?; + if !ms.is_finite() || ms < 0. { + return Err(Error::InvalidDriverValue("cuEventElapsedTime")); + } + Ok(ms) + } + pub(crate) fn begin(&self, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + check("cuStreamBeginCapture_v2", unsafe { + (self.begin)(s as Handle, 1) + }) + } // ThreadLocal + pub(crate) fn end(&self, s: usize) -> Result { + let mut g = std::ptr::null_mut(); + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. + check("cuStreamEndCapture", unsafe { + (self.end)(s as Handle, &mut g) + })?; + if g.is_null() { + return Err(Error::InvalidDriverValue("cuStreamEndCapture")); + } + Ok(g as usize) + } + pub(crate) fn nodes(&self, g: usize) -> Result { + let mut n = 0; + // SAFETY: live graph; a null node array with a valid count out pointer only queries the count. + check("cuGraphGetNodes", unsafe { + (self.nodes)(g as Handle, std::ptr::null_mut(), &mut n) + })?; + Ok(n) + } + pub(crate) fn instantiate(&self, g: usize) -> Result { + let mut e = std::ptr::null_mut(); + // SAFETY: C ABI call on a live handle; the out pointer is a valid local. + check("cuGraphInstantiateWithFlags", unsafe { + (self.instantiate)(&mut e, g as Handle, 0) + })?; + if e.is_null() { + return Err(Error::InvalidDriverValue("cuGraphInstantiateWithFlags")); + } + Ok(e as usize) + } + pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + check("cuGraphDestroy", unsafe { + (self.graph_destroy)(g as Handle) + }) + } + pub(crate) fn exec_destroy(&self, e: usize) -> Result<()> { + // SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its stream was drained. + check("cuGraphExecDestroy", unsafe { + (self.exec_destroy)(e as Handle) + }) + } + pub(crate) fn upload(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. + check("cuGraphUpload", unsafe { + (self.upload)(e as Handle, s as Handle) + }) + } + pub(crate) fn launch(&self, e: usize, s: usize) -> Result<()> { + // SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by `OriginalGpuGraph` until drained. + check("cuGraphLaunch", unsafe { + (self.launch)(e as Handle, s as Handle) + }) + } +} diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs new file mode 100644 index 00000000..4ce69e1c --- /dev/null +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs @@ -0,0 +1,85 @@ +//! Moved out of the parent module by STRA-338: impl Api (2). + +#[allow(unused_imports)] +use super::*; + +impl Api { + /// `cudaMemcpyAsync(H2D)` of `fetch_dma`. The caller keeps `src` (a registered bank) and `dst` alive + /// until the stream's fence. + pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> { + // SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and registered + // until this stream's next fence (documented contract of `enqueue_copy_h2d`). + check("cuMemcpyHtoDAsync_v2", unsafe { + (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) + }) + } + /// Every `(destination, source)` piece of a group in stream order: one `cuMemcpyBatchAsync` when `batch` and the + /// driver has it, else one `cuMemcpyHtoDAsync` per piece. The caller keeps every source (a registered bank) and + /// destination alive until the stream's fence. + pub(crate) fn copy_h2d_many(&self, pieces: &[(u64, &[u8])], s: usize, batch: bool) -> Result<()> { + if let (true, Some(f), false) = (batch, self.copy_batch, self.batch_refused.load(std::sync::atomic::Ordering::Relaxed)) { + let mut dsts: Vec = pieces.iter().map(|p| p.0).collect(); + let mut srcs: Vec = pieces.iter().map(|p| p.1.as_ptr() as u64).collect(); + let mut sizes: Vec = pieces.iter().map(|p| p.1.len()).collect(); + // srcAccessOrder STREAM (1): the registered bank stays valid until the stream's fence + let mut attr = BatchAttributes { src_access_order: 1, src_loc: [0, 0], dst_loc: [0, 0], flags: 0 }; + let mut index = 0usize; + // SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it (CUDA copies the + // descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller until the stream fence (srcAccessOrder STREAM). + let code = unsafe { + f(dsts.as_mut_ptr(), srcs.as_mut_ptr(), sizes.as_mut_ptr(), pieces.len(), &mut attr, &mut index, 1, s as Handle) + }; + if code == 0 { + return Ok(()); + } + // refused (not supported here, or an argument it does not take): never again; the plain calls below + // enqueue every piece (a piece the refused call may have queued is copied again with the same bytes) + self.batch_refused.store(true, std::sync::atomic::Ordering::Relaxed); + } + for (dst, src) in pieces { + self.copy_h2d(*dst, src, s)?; + } + Ok(()) + } + pub(crate) fn can_write_u32(&self) -> bool { + self.write_value.is_some() + } + /// `cuStreamWriteValue32` of a device-visible mapped host word after every earlier operation of the stream + /// (no host callback thread). `MissingSymbol` when the driver lacks the call. + pub(crate) fn write_u32_after(&self, s: usize, device_address: u64, value: u32) -> Result<()> { + let f = self.write_value.ok_or(Error::MissingSymbol("cuStreamWriteValue32_v2"))?; + // SAFETY: `device_address` is the device alias of a live 4-byte mapped host word the caller keeps allocated past this stream's fence. + check("cuStreamWriteValue32_v2", unsafe { f(s as Handle, device_address, value, 0) }) + } + /// Flag B after the copies: a stream write of the device alias when the driver takes it, else (or after one + /// refusal) the host callback raising the mapped host word. + pub(crate) fn raise_flag_after(&self, s: usize, host_word: usize, device_address: u64, value: u32) -> Result<()> { + use std::sync::atomic::Ordering::Relaxed; + if let (Some(f), false, true) = (self.write_value, self.write_refused.load(Relaxed), device_address != 0 && device_address % 4 == 0) { + // SAFETY: as `write_u32_after`; the alias is non-null and 4-byte aligned (checked in the condition). + if unsafe { f(s as Handle, device_address, value, 0) } == 0 { + return Ok(()); + } + self.write_refused.store(true, Relaxed); + } + self.raise_u32_after(s, host_word, value) + } + /// `cudaLaunchHostFunc(raise_flag)` of `fetch_dma`: `word` rises to at least `value` once every earlier + /// operation of the stream completed. `word` must be a live 4-byte-aligned mapped host word. + pub(crate) fn raise_u32_after(&self, s: usize, word: usize, value: u32) -> Result<()> { + if word == 0 || word % 4 != 0 { + return Err(Error::InvalidSize); + } + let data = Box::into_raw(Box::new(Raise { word, value })); + // SAFETY: `data` is a leaked `Box` owned by the callback from here on (reclaimed there, or below if the launch is refused); + // `word` is a live 4-byte-aligned mapped host word whose owner synchronizes the Context before freeing it. + let launched = check("cuLaunchHostFunc", unsafe { + (self.host_fn)(s as Handle, raise_after_copies, data.cast()) + }); + if launched.is_err() { + // SAFETY: the driver refused the launch, so the callback will never take this Box. + drop(unsafe { Box::from_raw(data) }); + } + launched + } +} diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs new file mode 100644 index 00000000..0355569a --- /dev/null +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs @@ -0,0 +1,43 @@ +//! Moved out of the parent module by STRA-338: impl Drop_for_Library, fn check, fn raise_after_copies, fn noop_host_fn, fn callback_warmup_enabled. + +#[allow(unused_imports)] +use super::*; + +impl Drop for Library { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: `self.0` is the live, non-null dlopen handle; closed once when the table (or a failed `load`) drops. + unsafe { + libc::dlclose(self.0); + } + } + } +} +pub(super) fn check(name: &'static str, n: i32) -> Result<()> { + if n == 0 { + Ok(()) + } else { + Err(Error::Driver { + operation: name, + code: n, + }) + } +} +/// `cudaLaunchHostFunc` body of `Verifier::fetch_dma`: `raise_flag(flag, value)` (only rises). +pub(super) unsafe extern "C" fn raise_after_copies(data: *mut c_void) { + // SAFETY: `data` is the Box leaked by `raise_u32_after` for exactly this one call. + let raise = unsafe { Box::from_raw(data.cast::()) }; + // SAFETY: the word is a 4-byte-aligned mapped host allocation the verifier bank keeps alive until the + // context is synchronized at its close, after every host function of its streams has run. + let word = unsafe { &*(raise.word as *const std::sync::atomic::AtomicU32) }; + word.fetch_max(raise.value, std::sync::atomic::Ordering::SeqCst); +} +/// The no-op host function of the callback-thread warm-up. +#[cfg(target_os = "linux")] +pub(super) unsafe extern "C" fn noop_host_fn(_: *mut c_void) {} +/// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm; docs/upstream-port-plan.md row 0.6). +#[cfg(target_os = "linux")] +pub(super) fn callback_warmup_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !matches!(std::env::var("LELEKA_CB_WARMUP").as_deref(), Ok("off" | "0" | "no"))) +} diff --git a/crates/cuda-driver/src/ple_batch_ffi.rs b/crates/cuda-driver/src/ple_batch_ffi.rs index d97c6c1c..1f5b429f 100644 --- a/crates/cuda-driver/src/ple_batch_ffi.rs +++ b/crates/cuda-driver/src/ple_batch_ffi.rs @@ -28,581 +28,7 @@ pub(crate) enum InputType { any(target_os = "linux", target_os = "windows"), 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_int; - type Destroy = unsafe extern "C" fn(*mut c_void) -> c_int; - type SetStream = unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int; - type SetWorkspace = unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> c_int; - type SetMath = unsafe extern "C" fn(*mut c_void, c_int) -> c_int; - type Gemm = unsafe extern "C" fn( - *mut c_void, - c_int, - c_int, - c_int, - c_int, - c_int, - *const c_void, - *const c_void, - c_int, - c_int, - *const c_void, - c_int, - c_int, - *const c_void, - *mut c_void, - c_int, - c_int, - c_int, - c_int, - ) -> c_int; - type StreamCreate = unsafe extern "C" fn(*mut *mut c_void, c_uint) -> c_int; - type ModuleLoad = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; - type ModuleFunction = - 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; - use crate::launch_ex::{FuncSetAttribute, LaunchAttribute, LaunchConfig, LaunchEx}; - struct Library(*mut c_void); - impl Library { - fn open(name: &'static CStr) -> Result { - // SAFETY: fixed private library name, owned dlopen reference. - let ptr = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; - if ptr.is_null() { - Err(Error::LibraryUnavailable) - } else { - Ok(Self(ptr)) - } - } - } - impl Drop for Library { - fn drop(&mut self) { - // SAFETY: actual owned dlopen handle. - unsafe { - libc::dlclose(self.0); - } - } - } - macro_rules! symbol { - ($l:ident,$name:literal,$ty:ty) => {{ - // SAFETY: private fixed symbol/signature; not a caller resolver. - let p = unsafe { libc::dlsym($l.0, $name.as_ptr()) }; - if p.is_null() { - return Err(Error::MissingSymbol( - $name.to_str().expect("static ASCII ABI"), - )); - } - // SAFETY: exact Linux64 ABI paired with the static name above. - unsafe { std::mem::transmute::<*mut c_void, $ty>(p) } - }}; - } - fn check(op: &'static str, code: c_int) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } - } - pub(crate) struct Blas { - _driver: Option, - _vendor: Option, - handle: Option, - stream: Option, - destroy: Destroy, - stream_destroy: Destroy, - sync: Destroy, - gemm: Gemm, - } - impl Blas { - pub(crate) fn load(workspace: BufferHandle, bytes: usize) -> Result { - if bytes != 32 * 1024 * 1024 { - return Err(Error::InvalidSize); - } - workspace.validate_projection_extent(bytes, 256)?; - let driver = Library::open(c"libcuda.so.1")?; - let vendor = Library::open(c"libcublas.so.12")?; - let create = symbol!(vendor, c"cublasCreate_v2", Create); - let set_stream = symbol!(vendor, c"cublasSetStream_v2", SetStream); - let set_workspace = symbol!(vendor, c"cublasSetWorkspace_v2", SetWorkspace); - let set_math = symbol!(vendor, c"cublasSetMathMode", SetMath); - let stream_create = symbol!(driver, c"cuStreamCreate", StreamCreate); - let mut owner = Self { - destroy: symbol!(vendor, c"cublasDestroy_v2", Destroy), - stream_destroy: symbol!(driver, c"cuStreamDestroy_v2", Destroy), - sync: symbol!(driver, c"cuStreamSynchronize", Destroy), - gemm: symbol!(vendor, c"cublasGemmEx", Gemm), - handle: None, - stream: None, - _driver: Some(driver), - _vendor: Some(vendor), - }; - let result = (|| { - let mut stream = std::ptr::null_mut(); - // SAFETY: current owner Context; actual private NON_BLOCKING stream. - check("cuStreamCreate", unsafe { stream_create(&mut stream, 1) })?; - if stream.is_null() { - return Err(Error::InvalidDriverValue("cuStreamCreate")); - } - owner.stream = Some(stream as usize); - crate::compute_drain::register(stream as usize); - let mut h = std::ptr::null_mut(); - // SAFETY: current owner Context, valid writable output. - check("cublasCreate_v2", unsafe { create(&mut h) })?; - if h.is_null() { - return Err(Error::InvalidDriverValue("cublasCreate_v2")); - } - owner.handle = Some(h as usize); - // SAFETY: actual owned handle/stream and admitted whole workspace. - check("cublasSetStream_v2", unsafe { set_stream(h, stream) })?; - check("cublasSetWorkspace_v2", unsafe { - set_workspace(h, workspace.qwen_address() as *mut c_void, bytes) - })?; - check("cublasSetMathMode", unsafe { set_math(h, 0) })?; // CUBLAS_DEFAULT_MATH - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub(crate) fn stream(&self) -> usize { - self.stream.expect("private live stream") - } - #[allow(clippy::too_many_arguments)] - fn gemm( - &self, - kind: InputType, - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - t: i32, - n: i32, - k: i32, - alpha: &f32, - beta: &f32, - ) -> Result<()> { - if !(1..=8192).contains(&t) - || !matches!( - (n, k), - (10240, 2560) - | (2560, 2560) - | (320, 10240) - | (10240, 320) - | (4, 10240) - | (6144, 2560) - | (2560, 6144) - | (48, 2560) - | (12288, 2560) - | (512, 2560) - | (128, 2560) - // Literal Original shared expert and shared-router - // shapes; private typed producers authenticate owners. - | (640, 2560) - | (2560, 640) - | (1, 2560) - ) - || *alpha != 1.0 - || (*beta != 0.0 && *beta != 1.0) - { - return Err(Error::InvalidQwenShape); - } - x.validate_projection_extent(t as usize * k as usize * 2, 2)?; - w.validate_projection_extent(n as usize * k as usize * 2, 2)?; - y.validate_projection_extent(t as usize * n as usize * 4, 4)?; - let dtype = match kind { - InputType::Bf16 => 14, - InputType::F16 => 2, - }; // CUDA_R_16BF/F - // SAFETY: only closed producers call this private ABI after whole - // owner Context/shape/alias checks. Actual owners and alpha/beta - // command storage remain live through the same stream drain. - check("cublasGemmEx", unsafe { - (self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1, - 0, - n, - t, - k, - (alpha as *const f32).cast(), - w.qwen_address() as *const c_void, - dtype, - k, - x.qwen_address() as *const c_void, - dtype, - k, - (beta as *const f32).cast(), - y.qwen_address() as *mut c_void, - 0, - n, - 68, - -1, - ) - }) // OP_T/OP_N/F32/COMPUTE32F/DEFAULT - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn gemm_bf16( - &self, - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - t: i32, - n: i32, - k: i32, - alpha: &f32, - beta: &f32, - ) -> Result<()> { - self.gemm(InputType::Bf16, x, w, y, t, n, k, alpha, beta) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn gemm_f16( - &self, - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - t: i32, - n: i32, - k: i32, - alpha: &f32, - beta: &f32, - ) -> Result<()> { - self.gemm(InputType::F16, x, w, y, t, n, k, alpha, beta) - } - // Only the original interleaved Alpha/Beta whole bank, N48/K2560/ldy96. - // Caller authenticates the actual whole bank and derives no public span. - #[allow(clippy::too_many_arguments)] - pub(crate) fn gemm_bf16_interleaved_ab( - &self, - x: BufferHandle, - w: BufferHandle, - ab: BufferHandle, - t: i32, - beta_role: bool, - alpha: &f32, - beta: &f32, - ) -> Result<()> { - if !(1..=8192).contains(&t) || *alpha != 1.0 || (*beta != 0.0 && *beta != 1.0) { - return Err(Error::InvalidQwenShape); - } - x.validate_projection_extent(t as usize * 2560 * 2, 2)?; - w.validate_projection_extent(48 * 2560 * 2, 2)?; - let whole = t as usize * 96 * 4; - ab.validate_projection_extent(whole, 4)?; - let offset = if beta_role { 48 * 4 } else { 0 }; - let bytes = ((t as usize - 1) * 96 + 48) * 4; - let y = ab.checked_subspan(whole, offset, bytes)?; - // SAFETY: fixed exact originalABstride; actual owners retained by - // the GDN producer until same-stream drain. No arbitrary ldy API. - check("cublasGemmEx", unsafe { - (self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1, - 0, - 48, - t, - 2560, - (alpha as *const f32).cast(), - w.qwen_address() as *const c_void, - 14, - 2560, - x.qwen_address() as *const c_void, - 14, - 2560, - (beta as *const f32).cast(), - y.qwen_address() as *mut c_void, - 0, - 96, - 68, - -1, - ) - }) - } - /// Closed Original Option-B layouts. WHOLE owner checks are made by - /// NativeGdnGemm before these private admitted addresses reach cuBLAS. - /// F16 admits QKV/Z/Out and Original shared expert; BF16 admits - /// interleaved Alpha/Beta and the Original router/shared scalar. - #[allow(clippy::too_many_arguments)] - pub(crate) fn gemm_gdn( - &self, bf16: bool, x: BufferHandle, w: BufferHandle, y: BufferHandle, - t: i32, n: i32, k: i32, ldy: i32, y_offset: usize, beta: &f32, - ) -> Result<()> { - if !(1..=8192).contains(&t) { return Err(Error::InvalidQwenShape); } - if bf16 { - let interleaved=(n,k,ldy)==(48,2560,96)&&matches!(y_offset,0|48); - let moe=matches!((n,k),(512,2560)|(1,2560))&&ldy==n&&y_offset==0; - if (!interleaved&&!moe)||(*beta!=0.0&&*beta!=1.0) {return Err(Error::InvalidQwenShape);} - } else if !matches!((n,k),(10240,2560)|(6144,2560)|(2560,6144)|(640,2560)|(2560,640)) - || ldy!=n || y_offset!=0 || *beta!=0.0 { return Err(Error::InvalidQwenShape); } - x.validate_projection_extent(t as usize*k as usize*2,2)?; - w.validate_projection_extent(n as usize*k as usize*2,2)?; - let whole=t as usize*ldy as usize*4; - y.validate_projection_extent(whole,4)?; - let consumed=((t as usize-1)*ldy as usize+n as usize)*4; - let output=y.checked_subspan(whole,y_offset*4,consumed)?; - let dtype=if bf16 {14} else {2}; - let alpha=1.0f32; - // SAFETY: fixed shapes/stride/offset from authentic WHOLE loans. - // The exclusive actual workspace and producer-owned arguments, - // buffers and weights are retained through its same-stream drain. - // Default cuBLAS HOST scalar mode consumes alpha/beta in this call. - check("cublasGemmEx",unsafe{(self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1,0,n,t,k,(&alpha as *const f32).cast(), - w.qwen_address() as *const c_void,dtype,k, - x.qwen_address() as *const c_void,dtype,k, - (beta as *const f32).cast(),output.qwen_address() as *mut c_void, - 0,ldy,68,-1, - )}) - } - pub(crate) fn synchronize(&self) -> Result<()> { - // SAFETY: actual private stream remains owned through this call. - crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { - (self.sync)(self.stream() as *mut c_void) - })) - } - pub(crate) fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - let mut result = Ok(()); - if let Some(h) = self.handle.take() { - // SAFETY: actual handle after drain or constructor partial admission. - result = check("cublasDestroy_v2", unsafe { - (self.destroy)(h as *mut c_void) - }); - } - if let Some(s) = self.stream.take() { - crate::compute_drain::unregister(s); - // SAFETY: actual created stream, no undisclosed outstanding commands. - result = combine( - result, - check("cuStreamDestroy_v2", unsafe { - (self.stream_destroy)(s as *mut c_void) - }), - ); - } - if result.is_err() { - // Unknown vendor cleanup retains its callable libraries. - if let Some(driver) = self._driver.take() { - std::mem::forget(driver); - } - if let Some(vendor) = self._vendor.take() { - std::mem::forget(vendor); - } - } - result - } - } - impl Drop for Blas { - fn drop(&mut self) { - let _ = self.close_inner(); - } - } - - pub(crate) struct KernelModule { - _library: Option, - module: Option, - functions: Vec, - launch: Launch, - unload: Destroy, - } - impl KernelModule { - pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { - if ptx.last() != Some(&0) || entries.is_empty() || entries.len() > 32 { - return Err(Error::InvalidQwenShape); - } - let library = Library::open(c"libcuda.so.1")?; - let load = symbol!(library, c"cuModuleLoadData", ModuleLoad); - let function = symbol!(library, c"cuModuleGetFunction", ModuleFunction); - let mut owner = Self { - launch: symbol!(library, c"cuLaunchKernel", Launch), - unload: symbol!(library, c"cuModuleUnload", Destroy), - _library: Some(library), - module: None, - functions: Vec::new(), - }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; - let result = (|| { - let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.module = Some(m as usize); - for entry in entries { - let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. - check("cuModuleGetFunction", unsafe { - function(&mut f, m, entry.as_ptr()) - })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions.push(f as usize); - } - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub(crate) fn launch( - &self, - index: usize, - grid: u32, - block: u32, - stream: usize, - args: &mut KernelArguments, - ) -> Result<()> { - if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 { - return Err(Error::InvalidQwenShape); - } - let function = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; - args.pointers.clear(); - args.pointers - .try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; - args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; - args.addresses.resize(args.values.len(), 0); - for (index, arg) in args.values.iter_mut().enumerate() { - args.pointers.push(match arg { - BatchArg::Address(x) => { - // CUDA consumes an actual uint64_t parameter, never - // the unspecified Rust representation of BufferHandle. - args.addresses[index] = x.qwen_address(); - (&mut args.addresses[index] as *mut u64).cast() - }, - BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), - BatchArg::I32(x) => (x as *mut i32).cast(), - BatchArg::I64(x) => (x as *mut i64).cast(), - BatchArg::U32(x) => (x as *mut u32).cast(), - BatchArg::F32(x) => (x as *mut f32).cast(), - }); - } - // SAFETY: owned boxed command fields and exact producer-declared - // ABI persist until drain; Driver copies the parameter pointer array - // during this call. No pointer/entry escapes to public callers. - check("cuLaunchKernel", unsafe { - (self.launch)( - function as *mut c_void, - grid, - 1, - 1, - block, - 1, - 1, - 0, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) - }) - } - /// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1, 1]`, - /// `smem` bytes of dynamic shared memory (opted in first with `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)`). - /// Row 2.5 (`qsa_cluster.cu`). Capturable into a graph like any launch. - pub(crate) fn launch_cluster( - &self, - index: usize, - grid: [u32; 2], - block: u32, - cluster_x: u32, - smem: u32, - stream: usize, - args: &mut KernelArguments, - ) -> Result<()> { - if grid[0] == 0 || grid[1] == 0 || block == 0 || block > 1024 || cluster_x == 0 || grid[0] % cluster_x != 0 || stream == 0 { - return Err(Error::InvalidQwenShape); - } - let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; - let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?; - let launch_ex = symbol!(library, c"cuLaunchKernelEx", LaunchEx); - let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute); - args.pointers.clear(); - args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; - args.addresses.resize(args.values.len(), 0); - for (index, arg) in args.values.iter_mut().enumerate() { - args.pointers.push(match arg { - BatchArg::Address(x) => { - args.addresses[index] = x.qwen_address(); - (&mut args.addresses[index] as *mut u64).cast() - } - BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), - BatchArg::I32(x) => (x as *mut i32).cast(), - BatchArg::I64(x) => (x as *mut i64).cast(), - BatchArg::U32(x) => (x as *mut u32).cast(), - BatchArg::F32(x) => (x as *mut f32).cast(), - }); - } - check("cuFuncSetAttribute", unsafe { - set_attribute(function as *mut c_void, crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED, smem as c_int) - })?; - let mut attribute = LaunchAttribute::cluster_x(cluster_x); - let config = LaunchConfig { - grid: [grid[0], grid[1], 1], - block: [block, 1, 1], - smem, - stream: stream as *mut c_void, - attrs: &mut attribute, - num_attrs: 1, - }; - // SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during the call); - // the config and the attribute live across the call; the function belongs to this module. - check("cuLaunchKernelEx", unsafe { - launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut()) - }) - } - pub(crate) fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - if let Some(m) = self.module.take() { - // SAFETY: actual module after real queue drain. - let result = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); - if result.is_err() - && let Some(library) = self._library.take() - { - std::mem::forget(library); - } - result - } else { - Ok(()) - } - } - } - impl Drop for KernelModule { - fn drop(&mut self) { - let _ = self.close_inner(); - } - } -} +mod enabled; #[cfg(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled.rs new file mode 100644 index 00000000..7079fef5 --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled.rs @@ -0,0 +1,89 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use libc::{c_int, c_uint, c_void}; +type Create = unsafe extern "C" fn(*mut *mut c_void) -> c_int; +type Destroy = unsafe extern "C" fn(*mut c_void) -> c_int; +type SetStream = unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int; +type SetWorkspace = unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> c_int; +type SetMath = unsafe extern "C" fn(*mut c_void, c_int) -> c_int; +type Gemm = unsafe extern "C" fn( + *mut c_void, + c_int, + c_int, + c_int, + c_int, + c_int, + *const c_void, + *const c_void, + c_int, + c_int, + *const c_void, + c_int, + c_int, + *const c_void, + *mut c_void, + c_int, + c_int, + c_int, + c_int, +) -> c_int; +type StreamCreate = unsafe extern "C" fn(*mut *mut c_void, c_uint) -> c_int; +type ModuleLoad = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; +type ModuleFunction = + 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; +use crate::launch_ex::{FuncSetAttribute, LaunchAttribute, LaunchConfig, LaunchEx}; +struct Library(*mut c_void); +macro_rules! symbol { + ($l:ident,$name:literal,$ty:ty) => {{ + // SAFETY: private fixed symbol/signature; not a caller resolver. + let p = unsafe { libc::dlsym($l.0, $name.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol( + $name.to_str().expect("static ASCII ABI"), + )); + } + // SAFETY: exact Linux64 ABI paired with the static name above. + unsafe { std::mem::transmute::<*mut c_void, $ty>(p) } + }}; +} +pub(crate) struct Blas { + _driver: Option, + _vendor: Option, + handle: Option, + stream: Option, + destroy: Destroy, + stream_destroy: Destroy, + sync: Destroy, + gemm: Gemm, +} + +pub(crate) struct KernelModule { + _library: Option, + module: Option, + functions: Vec, + launch: Launch, + unload: Destroy, +} + +#[path = "enabled/impl_library.rs"] +mod impl_library; +#[allow(unused_imports)] +use impl_library::check; +#[path = "enabled/impl_blas.rs"] +mod impl_blas; +#[path = "enabled/impl_blas_2.rs"] +mod impl_blas_2; diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs new file mode 100644 index 00000000..dd5dbc7f --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs @@ -0,0 +1,256 @@ +//! Moved out of the parent module by STRA-338: impl Blas. + +#[allow(unused_imports)] +use super::*; + +impl Blas { + pub(crate) fn load(workspace: BufferHandle, bytes: usize) -> Result { + if bytes != 32 * 1024 * 1024 { + return Err(Error::InvalidSize); + } + workspace.validate_projection_extent(bytes, 256)?; + let driver = Library::open(c"libcuda.so.1")?; + let vendor = Library::open(c"libcublas.so.12")?; + let create = symbol!(vendor, c"cublasCreate_v2", Create); + let set_stream = symbol!(vendor, c"cublasSetStream_v2", SetStream); + let set_workspace = symbol!(vendor, c"cublasSetWorkspace_v2", SetWorkspace); + let set_math = symbol!(vendor, c"cublasSetMathMode", SetMath); + let stream_create = symbol!(driver, c"cuStreamCreate", StreamCreate); + let mut owner = Self { + destroy: symbol!(vendor, c"cublasDestroy_v2", Destroy), + stream_destroy: symbol!(driver, c"cuStreamDestroy_v2", Destroy), + sync: symbol!(driver, c"cuStreamSynchronize", Destroy), + gemm: symbol!(vendor, c"cublasGemmEx", Gemm), + handle: None, + stream: None, + _driver: Some(driver), + _vendor: Some(vendor), + }; + let result = (|| { + let mut stream = std::ptr::null_mut(); + // SAFETY: current owner Context; actual private NON_BLOCKING stream. + check("cuStreamCreate", unsafe { stream_create(&mut stream, 1) })?; + if stream.is_null() { + return Err(Error::InvalidDriverValue("cuStreamCreate")); + } + owner.stream = Some(stream as usize); + crate::compute_drain::register(stream as usize); + let mut h = std::ptr::null_mut(); + // SAFETY: current owner Context, valid writable output. + check("cublasCreate_v2", unsafe { create(&mut h) })?; + if h.is_null() { + return Err(Error::InvalidDriverValue("cublasCreate_v2")); + } + owner.handle = Some(h as usize); + // SAFETY: actual owned handle/stream and admitted whole workspace. + check("cublasSetStream_v2", unsafe { set_stream(h, stream) })?; + check("cublasSetWorkspace_v2", unsafe { + set_workspace(h, workspace.qwen_address() as *mut c_void, bytes) + })?; + check("cublasSetMathMode", unsafe { set_math(h, 0) })?; // CUBLAS_DEFAULT_MATH + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub(crate) fn stream(&self) -> usize { + self.stream.expect("private live stream") + } + #[allow(clippy::too_many_arguments)] + pub(super) fn gemm( + &self, + kind: InputType, + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + t: i32, + n: i32, + k: i32, + alpha: &f32, + beta: &f32, + ) -> Result<()> { + if !(1..=8192).contains(&t) + || !matches!( + (n, k), + (10240, 2560) + | (2560, 2560) + | (320, 10240) + | (10240, 320) + | (4, 10240) + | (6144, 2560) + | (2560, 6144) + | (48, 2560) + | (12288, 2560) + | (512, 2560) + | (128, 2560) + // Literal Original shared expert and shared-router + // shapes; private typed producers authenticate owners. + | (640, 2560) + | (2560, 640) + | (1, 2560) + ) + || *alpha != 1.0 + || (*beta != 0.0 && *beta != 1.0) + { + return Err(Error::InvalidQwenShape); + } + x.validate_projection_extent(t as usize * k as usize * 2, 2)?; + w.validate_projection_extent(n as usize * k as usize * 2, 2)?; + y.validate_projection_extent(t as usize * n as usize * 4, 4)?; + let dtype = match kind { + InputType::Bf16 => 14, + InputType::F16 => 2, + }; // CUDA_R_16BF/F + // SAFETY: only closed producers call this private ABI after whole + // owner Context/shape/alias checks. Actual owners and alpha/beta + // command storage remain live through the same stream drain. + check("cublasGemmEx", unsafe { + (self.gemm)( + self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, + 1, + 0, + n, + t, + k, + (alpha as *const f32).cast(), + w.qwen_address() as *const c_void, + dtype, + k, + x.qwen_address() as *const c_void, + dtype, + k, + (beta as *const f32).cast(), + y.qwen_address() as *mut c_void, + 0, + n, + 68, + -1, + ) + }) // OP_T/OP_N/F32/COMPUTE32F/DEFAULT + } + #[allow(clippy::too_many_arguments)] + pub(crate) fn gemm_bf16( + &self, + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + t: i32, + n: i32, + k: i32, + alpha: &f32, + beta: &f32, + ) -> Result<()> { + self.gemm(InputType::Bf16, x, w, y, t, n, k, alpha, beta) + } + #[allow(clippy::too_many_arguments)] + pub(crate) fn gemm_f16( + &self, + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + t: i32, + n: i32, + k: i32, + alpha: &f32, + beta: &f32, + ) -> Result<()> { + self.gemm(InputType::F16, x, w, y, t, n, k, alpha, beta) + } + // Only the original interleaved Alpha/Beta whole bank, N48/K2560/ldy96. + // Caller authenticates the actual whole bank and derives no public span. + #[allow(clippy::too_many_arguments)] + pub(crate) fn gemm_bf16_interleaved_ab( + &self, + x: BufferHandle, + w: BufferHandle, + ab: BufferHandle, + t: i32, + beta_role: bool, + alpha: &f32, + beta: &f32, + ) -> Result<()> { + if !(1..=8192).contains(&t) || *alpha != 1.0 || (*beta != 0.0 && *beta != 1.0) { + return Err(Error::InvalidQwenShape); + } + x.validate_projection_extent(t as usize * 2560 * 2, 2)?; + w.validate_projection_extent(48 * 2560 * 2, 2)?; + let whole = t as usize * 96 * 4; + ab.validate_projection_extent(whole, 4)?; + let offset = if beta_role { 48 * 4 } else { 0 }; + let bytes = ((t as usize - 1) * 96 + 48) * 4; + let y = ab.checked_subspan(whole, offset, bytes)?; + // SAFETY: fixed exact originalABstride; actual owners retained by + // the GDN producer until same-stream drain. No arbitrary ldy API. + check("cublasGemmEx", unsafe { + (self.gemm)( + self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, + 1, + 0, + 48, + t, + 2560, + (alpha as *const f32).cast(), + w.qwen_address() as *const c_void, + 14, + 2560, + x.qwen_address() as *const c_void, + 14, + 2560, + (beta as *const f32).cast(), + y.qwen_address() as *mut c_void, + 0, + 96, + 68, + -1, + ) + }) + } + /// Closed Original Option-B layouts. WHOLE owner checks are made by + /// NativeGdnGemm before these private admitted addresses reach cuBLAS. + /// F16 admits QKV/Z/Out and Original shared expert; BF16 admits + /// interleaved Alpha/Beta and the Original router/shared scalar. + #[allow(clippy::too_many_arguments)] + pub(crate) fn gemm_gdn( + &self, bf16: bool, x: BufferHandle, w: BufferHandle, y: BufferHandle, + t: i32, n: i32, k: i32, ldy: i32, y_offset: usize, beta: &f32, + ) -> Result<()> { + if !(1..=8192).contains(&t) { return Err(Error::InvalidQwenShape); } + if bf16 { + let interleaved=(n,k,ldy)==(48,2560,96)&&matches!(y_offset,0|48); + let moe=matches!((n,k),(512,2560)|(1,2560))&&ldy==n&&y_offset==0; + if (!interleaved&&!moe)||(*beta!=0.0&&*beta!=1.0) {return Err(Error::InvalidQwenShape);} + } else if !matches!((n,k),(10240,2560)|(6144,2560)|(2560,6144)|(640,2560)|(2560,640)) + || ldy!=n || y_offset!=0 || *beta!=0.0 { return Err(Error::InvalidQwenShape); } + x.validate_projection_extent(t as usize*k as usize*2,2)?; + w.validate_projection_extent(n as usize*k as usize*2,2)?; + let whole=t as usize*ldy as usize*4; + y.validate_projection_extent(whole,4)?; + let consumed=((t as usize-1)*ldy as usize+n as usize)*4; + let output=y.checked_subspan(whole,y_offset*4,consumed)?; + let dtype=if bf16 {14} else {2}; + let alpha=1.0f32; + // SAFETY: fixed shapes/stride/offset from authentic WHOLE loans. + // The exclusive actual workspace and producer-owned arguments, + // buffers and weights are retained through its same-stream drain. + // Default cuBLAS HOST scalar mode consumes alpha/beta in this call. + check("cublasGemmEx",unsafe{(self.gemm)( + self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, + 1,0,n,t,k,(&alpha as *const f32).cast(), + w.qwen_address() as *const c_void,dtype,k, + x.qwen_address() as *const c_void,dtype,k, + (beta as *const f32).cast(),output.qwen_address() as *mut c_void, + 0,ldy,68,-1, + )}) + } + pub(crate) fn synchronize(&self) -> Result<()> { + // SAFETY: actual private stream remains owned through this call. + crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { + (self.sync)(self.stream() as *mut c_void) + })) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs new file mode 100644 index 00000000..9b0c8ab6 --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs @@ -0,0 +1,222 @@ +//! Moved out of the parent module by STRA-338: impl Blas (2), impl Drop_for_Blas, impl KernelModule, impl Drop_for_KernelModule. + +#[allow(unused_imports)] +use super::*; + +impl Blas { + pub(super) fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + if let Some(h) = self.handle.take() { + // SAFETY: actual handle after drain or constructor partial admission. + result = check("cublasDestroy_v2", unsafe { + (self.destroy)(h as *mut c_void) + }); + } + if let Some(s) = self.stream.take() { + crate::compute_drain::unregister(s); + // SAFETY: actual created stream, no undisclosed outstanding commands. + result = combine( + result, + check("cuStreamDestroy_v2", unsafe { + (self.stream_destroy)(s as *mut c_void) + }), + ); + } + if result.is_err() { + // Unknown vendor cleanup retains its callable libraries. + if let Some(driver) = self._driver.take() { + std::mem::forget(driver); + } + if let Some(vendor) = self._vendor.take() { + std::mem::forget(vendor); + } + } + result + } +} +impl Drop for Blas { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +impl KernelModule { + pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { + if ptx.last() != Some(&0) || entries.is_empty() || entries.len() > 32 { + return Err(Error::InvalidQwenShape); + } + let library = Library::open(c"libcuda.so.1")?; + let load = symbol!(library, c"cuModuleLoadData", ModuleLoad); + let function = symbol!(library, c"cuModuleGetFunction", ModuleFunction); + let mut owner = Self { + launch: symbol!(library, c"cuLaunchKernel", Launch), + unload: symbol!(library, c"cuModuleUnload", Destroy), + _library: Some(library), + module: None, + functions: Vec::new(), + }; + owner + .functions + .try_reserve_exact(entries.len()) + .map_err(|_| Error::HostAllocation)?; + let result = (|| { + let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. + check("cuModuleLoadData", unsafe { + load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) + })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + owner.module = Some(m as usize); + for entry in entries { + let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. + check("cuModuleGetFunction", unsafe { + function(&mut f, m, entry.as_ptr()) + })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + owner.functions.push(f as usize); + } + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub(crate) fn launch( + &self, + index: usize, + grid: u32, + block: u32, + stream: usize, + args: &mut KernelArguments, + ) -> Result<()> { + if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 { + return Err(Error::InvalidQwenShape); + } + let function = *self + .functions + .get(index) + .ok_or(Error::UnsupportedQwenOperation)?; + args.pointers.clear(); + args.pointers + .try_reserve_exact(args.values.len()) + .map_err(|_| Error::HostAllocation)?; + args.addresses.clear(); + args.addresses.try_reserve_exact(args.values.len()) + .map_err(|_| Error::HostAllocation)?; + args.addresses.resize(args.values.len(), 0); + for (index, arg) in args.values.iter_mut().enumerate() { + args.pointers.push(match arg { + BatchArg::Address(x) => { + // CUDA consumes an actual uint64_t parameter, never + // the unspecified Rust representation of BufferHandle. + args.addresses[index] = x.qwen_address(); + (&mut args.addresses[index] as *mut u64).cast() + }, + BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), + BatchArg::I32(x) => (x as *mut i32).cast(), + BatchArg::I64(x) => (x as *mut i64).cast(), + BatchArg::U32(x) => (x as *mut u32).cast(), + BatchArg::F32(x) => (x as *mut f32).cast(), + }); + } + // SAFETY: owned boxed command fields and exact producer-declared + // ABI persist until drain; Driver copies the parameter pointer array + // during this call. No pointer/entry escapes to public callers. + check("cuLaunchKernel", unsafe { + (self.launch)( + function as *mut c_void, + grid, + 1, + 1, + block, + 1, + 1, + 0, + stream as *mut c_void, + args.pointers.as_mut_ptr(), + std::ptr::null_mut(), + ) + }) + } + /// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1, 1]`, + /// `smem` bytes of dynamic shared memory (opted in first with `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)`). + /// Row 2.5 (`qsa_cluster.cu`). Capturable into a graph like any launch. + pub(crate) fn launch_cluster( + &self, + index: usize, + grid: [u32; 2], + block: u32, + cluster_x: u32, + smem: u32, + stream: usize, + args: &mut KernelArguments, + ) -> Result<()> { + if grid[0] == 0 || grid[1] == 0 || block == 0 || block > 1024 || cluster_x == 0 || grid[0] % cluster_x != 0 || stream == 0 { + return Err(Error::InvalidQwenShape); + } + let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?; + let launch_ex = symbol!(library, c"cuLaunchKernelEx", LaunchEx); + let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute); + args.pointers.clear(); + args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; + args.addresses.clear(); + args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; + args.addresses.resize(args.values.len(), 0); + for (index, arg) in args.values.iter_mut().enumerate() { + args.pointers.push(match arg { + BatchArg::Address(x) => { + args.addresses[index] = x.qwen_address(); + (&mut args.addresses[index] as *mut u64).cast() + } + BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), + BatchArg::I32(x) => (x as *mut i32).cast(), + BatchArg::I64(x) => (x as *mut i64).cast(), + BatchArg::U32(x) => (x as *mut u32).cast(), + BatchArg::F32(x) => (x as *mut f32).cast(), + }); + } + check("cuFuncSetAttribute", unsafe { + set_attribute(function as *mut c_void, crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED, smem as c_int) + })?; + let mut attribute = LaunchAttribute::cluster_x(cluster_x); + let config = LaunchConfig { + grid: [grid[0], grid[1], 1], + block: [block, 1, 1], + smem, + stream: stream as *mut c_void, + attrs: &mut attribute, + num_attrs: 1, + }; + // SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during the call); + // the config and the attribute live across the call; the function belongs to this module. + check("cuLaunchKernelEx", unsafe { + launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut()) + }) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + if let Some(m) = self.module.take() { + // SAFETY: actual module after real queue drain. + let result = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); + if result.is_err() + && let Some(library) = self._library.take() + { + std::mem::forget(library); + } + result + } else { + Ok(()) + } + } +} +impl Drop for KernelModule { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs new file mode 100644 index 00000000..7a35e119 --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs @@ -0,0 +1,34 @@ +//! Moved out of the parent module by STRA-338: impl Library, impl Drop_for_Library, fn check. + +#[allow(unused_imports)] +use super::*; + +impl Library { + pub(super) fn open(name: &'static CStr) -> Result { + // SAFETY: fixed private library name, owned dlopen reference. + let ptr = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if ptr.is_null() { + Err(Error::LibraryUnavailable) + } else { + Ok(Self(ptr)) + } + } +} +impl Drop for Library { + fn drop(&mut self) { + // SAFETY: actual owned dlopen handle. + unsafe { + libc::dlclose(self.0); + } + } +} +pub(super) fn check(op: &'static str, code: c_int) -> Result<()> { + if code == 0 { + Ok(()) + } else { + Err(Error::Driver { + operation: op, + code, + }) + } +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve.rs b/crates/engine-qwen35-cuda/src/backend_original_serve.rs index ade30efd..12acde87 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve.rs @@ -123,825 +123,12 @@ pub(super) struct ConfigFacts { pub(super) use runner::{run, Run}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(super) mod runner { - use super::super::{ - emit_event, emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, clock_seed, unavailable, - ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GenerationEvent, - GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, Reply, Shared, - Tokenizer, Usage, Utf8Pending, GENERATION_TIMEOUT, QUEUE, - }; - use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; - - type GpuProbe = Box Option + Send + Sync>; - - /// The telemetry sampler's view of the GPU: NVML when `libnvidia-ml` loads, otherwise polling `nvidia-smi` (WSL2, containers - /// without the management library), otherwise nothing (the document then has no `gpu` block). - fn gpu_probe(ordinal: u32) -> Option { - match leleka_cuda_driver::nvml::Nvml::open(ordinal) { - Some(nvml) => Some(Box::new(move || { - nvml.sample().map(|s| leleka_memory::telemetry::GpuSample { - index: s.index, - util_pct: s.util_pct, - mem_util_pct: s.mem_util_pct, - vram_used_mib: s.vram_used_mib, - vram_total_mib: s.vram_total_mib, - power_w: s.power_w, - sm_clock_mhz: s.sm_clock_mhz, - temp_c: s.temp_c, - name: s.name, - mem_clock_mhz: s.mem_clock_mhz, - pcie_tx_kb_s: s.pcie_tx_kb_s, - pcie_rx_kb_s: s.pcie_rx_kb_s, - throttle_reasons: s.throttle_reasons, - }) - })), - None => leleka_memory::smi::probe(ordinal), - } - } - use crate::qwen_forward::{ - contract::Error as ForwardError, - original_serve_engine::ServeStop, - original_serve_request::{Admission, ServeDevice, ServeError, ServeRequest}, - original_serve_stack::{OriginalServeStack, StackConfig}, - original_serve_verifier::ServeFailure, - }; - use leleka_backend_api::GenerationRequest; - use {crate::idle_sweep::IdleSweep, leleka_obs::time::{Clock, SystemClock}}; - use std::{ - path::PathBuf, - rc::Rc, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::{self, Receiver}, - }, - thread, - time::Duration, - }; - - /// Everything the Original owner loop needs from `serve_load` once the context exists. - pub(in super::super) struct Run<'a, 'd> { - pub(in super::super) context_tokens: u32, - pub(in super::super) rx: &'a Receiver, - pub(in super::super) shared: &'a Shared, - pub(in super::super) binding: ModelBinding, - pub(in super::super) context: Rc>, - pub(in super::super) tokenizer: Tokenizer, - pub(in super::super) eos: u32, - pub(in super::super) loaded: LoadedModel, - pub(in super::super) reply: &'a Reply, - pub(in super::super) options: &'a OriginalServeOptions, - /// The model files, for the start-up report only (size and mtime are read; the content never is). - pub(in super::super) model_files: Vec, - pub(in super::super) clock: SystemClock, - pub(in super::super) gpu_ordinal: u32, // for the telemetry sampler (NVML indexes the same physical order) - } - - /// Host memory a reconfigure needs beside the soft floor: the reopened stack's pinned K/V (3.1 GiB at 262,144 cells), rings and pools. - const RECONFIGURE_HEADROOM_BYTES: u64 = 4 << 30; - - /// The serve stack's configuration for these settings (everything except the weights, which stay loaded). - fn stack_config(options: &OriginalServeOptions, context_tokens: u32) -> Result { - let mut config = StackConfig::new(i64::from(context_tokens)); - if let Some(capacity) = options.prefill_capacity { - config.capacity = capacity; - } - if let Some(workers) = options.cpu_workers { - config.cpu_workers = workers; - } - config.rt_directory = options.mtp_rt_directory.clone(); - if let Some(format) = options.kv_format { - config.kv_format = format; - } - if let Some(cells) = options.kv_resident { - config.kv_resident = cells; - } - config.conversation = options.conversation(); - if let Some(prefix) = options.prefix_cache.as_ref() { - use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig, TailMode}; - let mut prefix_config = PrefixConfig { - tail: match prefix.tail { - PrefixTail::Off => TailMode::Off, - PrefixTail::Prompt => TailMode::Prompt, - PrefixTail::Reply => TailMode::Reply, - }, - budget: match prefix.budget_bytes { - None => PrefixBudget::Auto, - Some(0) => PrefixBudget::Off, - Some(bytes) => PrefixBudget::Bytes(bytes), - }, - block_tokens: prefix.block_tokens, - ..PrefixConfig::auto() - }; - if let Some(seconds) = prefix.retention_s { - prefix_config.policy.retention_ms = seconds.saturating_mul(1000); - } - config.prefix = Some(prefix_config); - } - // The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it). - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .map_err(|_| load_failure(LoadPhase::OriginalStack, invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting")))?; - Ok(config) - } - - /// The effective tuning of a stack configuration as plain values for the start-up report (`serve_meta`); reads nothing else. - fn meta_facts(config: &StackConfig, options: &OriginalServeOptions, context_tokens: u32) -> crate::serve_meta::ConfigFacts { - use crate::qwen_forward::original_serve_stack::{PrefixBudget, TailMode}; - let prefix = config.prefix.as_ref().filter(|p| !matches!(p.budget, PrefixBudget::Off)); - let slots = config.expert_tier.effective_slots(); - crate::serve_meta::ConfigFacts { - context_tokens, - chunk: config.capacity, - prefix_block: prefix.map(|p| p.resolved_block(config.capacity)), - prefix_tail: match prefix.map(|p| p.tail) { - None => "none", - Some(TailMode::Off) => "off", - Some(TailMode::Prompt) => "prompt", - Some(TailMode::Reply) => "reply", - }, - cpu_workers: config.cpu_workers, - kv: config.kv_format.name().to_owned(), - kv_resident_cells: config.kv_resident, - expert_tier: match slots { - 0 => "off".to_owned(), - n if n < 0 => "auto".to_owned(), - n => n.to_string(), - }, - expert_per_layer: config.expert_tier.per_layer, - expert_profile: config.expert_tier.profile.is_some(), - pcie_frac: config.expert_tier.pcie_frac, - spec_min_p: options.spec_min_p, - } - } - - /// The operator-facing error for a stack that could not start: the class of the owner's refusal and its - /// fixed text (an unbound producer, an unsealed asset, a budget). - fn open_error(failure: &ServeFailure) -> BackendError { - let message = format!("Original serve stack could not start: {}", failure.describe()); - let code = match failure.error { - ForwardError::InputAllocation => ErrorCode::ResourceExhausted, - ForwardError::Unsupported(_) => ErrorCode::UnsupportedModel, - ForwardError::IdentityMismatch | ForwardError::InvalidDimension => ErrorCode::InvalidRequest, - _ => ErrorCode::BackendUnavailable, - }; - BackendError { code, message, retryable: false } - } - - /// Number of checkpoint heads a pool summary carries. - const PREFIX_SUMMARY_HEADS: usize = 512; - - /// Hand the prefix cache's summary to the threads that answer status queries (the stack stays on this thread). - fn publish_prefix_summary(stack: &OriginalServeStack<'_, '_>, _shared: &Shared) { - if let Some(summary) = stack.prefix_summary(PREFIX_SUMMARY_HEADS) { - if let Ok(json) = serde_json::to_string(&summary) { - if let Ok(mut cell) = PREFIX_SUMMARY.lock() { - *cell = Some(json); - } - } - } - } - - fn admission_error(admission: Admission) -> BackendError { - match admission { - Admission::Context => exhausted("prompt and output exceed configured context"), - _ => invalid("unsupported generation request"), - } - } - - /// The expert tier's counters after the previous request, to turn the stack-lifetime figures into a request's share. - static PREVIOUS_TIER: std::sync::Mutex> = std::sync::Mutex::new(None); - - /// The engine's one structured line per finished request (`engine.log`), keyed by the id the API gave the request, so - /// `leleka logs --request ID` can join it with the API's record: tokens, the speculative loop (tokens committed per - /// verified round), the expert tier's share served from VRAM / over PCIe / by the CPU for this request alone. - fn log_request_end( - request_id: &str, - usage: &Usage, - prefill_ms: f64, - decode_ms: f64, - produced: u64, - rounds: u64, - tier: Option, - ) { - let shares = tier.map(|now| { - let mut previous = PREVIOUS_TIER.lock().unwrap_or_else(|p| p.into_inner()); - let shares = leleka_memory::telemetry::tier_shares(previous.as_ref(), &now); - *previous = Some(now); - shares - }); - leleka_obs::emit_always( - leleka_obs::Level::Info, - "engine", - "request", - &leleka_memory::telemetry::request_line_fields(&leleka_memory::telemetry::RequestLine { - request_id, - input_tokens: usage.input_tokens, - reused_tokens: usage.reused_input_tokens, - output_tokens: usage.output_tokens, - prefill_ms, - decode_ms, - produced, - rounds, - shares, - }), - ); - } - - /// `LELEKA_CAPTURE_DIR`: keep the prompt ids and the generated ids of every completed request for offline replay - /// (`original_serve_replay_smoke`). PRIVATE data (the prompt is the user's conversation): never in Git. One - /// `req-NNNNNN.json` per request plus `prompts.ids` / `generated.ids`, one comma-separated line per request. - fn capture_request(dir: &std::path::Path, prompt: &[u32], generated: &[i32], request: &GenerationRequest, rounds: u64, reused: u64) { - use std::io::Write; - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - let index = NEXT.fetch_add(1, Ordering::Relaxed); - let join = |ids: &mut dyn Iterator| ids.map(|t| t.to_string()).collect::>().join(","); - let prompt_line = join(&mut prompt.iter().map(|&t| i64::from(t))); - let generated_line = join(&mut generated.iter().map(|&t| i64::from(t))); - let s = &request.sampling; - fn opt(v: Option) -> String { - v.map_or_else(|| "null".to_owned(), |v| v.to_string()) - } - let json = format!( - "{{\"index\":{index},\"max_new\":{},\"temperature_milli\":{},\"top_p_micro\":{},\"top_k\":{},\"min_p_micro\":{},\"repetition_penalty_micro\":{},\"frequency_penalty_micro\":{},\"presence_penalty_micro\":{},\"penalty_last_n\":{},\"seed\":{},\"prompt_tokens\":{},\"reused\":{reused},\"rounds\":{rounds},\"produced\":{},\"prompt_ids\":[{prompt_line}],\"generated_ids\":[{generated_line}]}} -", - request.max_output_tokens, request.temperature_milli, opt(s.top_p_micro), opt(s.top_k), opt(s.min_p_micro), opt(s.repetition_penalty_micro), - opt(s.frequency_penalty_micro), opt(s.presence_penalty_micro), opt(s.penalty_last_n), opt(s.seed), prompt.len(), generated.len() - ); - if std::fs::create_dir_all(dir).is_err() { - return; - } - let _ = std::fs::write(dir.join(format!("req-{index:06}.json")), json); - for (name, line) in [("prompts.ids", &prompt_line), ("generated.ids", &generated_line)] { - if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(name)) { - let _ = writeln!(file, "{line}"); - } - } - } - - #[cfg(test)] - mod capture_tests { - use super::*; - - #[test] - fn a_captured_request_is_json_with_the_ids_and_one_line_per_request_in_the_id_files() { - let dir = std::env::temp_dir().join(format!("leleka-capture-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let request = GenerationRequest { - request_id: "r".into(), - prompt: String::new(), - max_output_tokens: 64, - temperature_milli: 0, - sampling: Default::default(), - }; - capture_request(&dir, &[1, 2, 3], &[7, 8], &request, 2, 1); - capture_request(&dir, &[1, 2, 3, 7, 8, 9], &[5], &request, 1, 4); - let names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); - let first = names.iter().filter(|n| n.starts_with("req-")).min().cloned().unwrap(); - let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join(&first)).unwrap()).unwrap(); - assert_eq!(doc["prompt_ids"], serde_json::json!([1, 2, 3])); - assert_eq!(doc["generated_ids"], serde_json::json!([7, 8])); - assert_eq!(doc["max_new"], 64); - assert!(doc["top_k"].is_null()); - let prompts = std::fs::read_to_string(dir.join("prompts.ids")).unwrap(); - assert_eq!(prompts.lines().count(), 2); - assert!(prompts.lines().any(|l| l == "1,2,3,7,8,9")); - let _ = std::fs::remove_dir_all(&dir); - } - } - - /// One request over the stack; the caller owns the stream/terminal bookkeeping. - #[allow(clippy::too_many_arguments)] - pub(in super::super) fn generate( - stack: &mut impl ServeDevice, - tokenizer: &Tokenizer, - sink: &GenerationSink, - cancel: &AtomicBool, - shared: &Shared, - eos: u32, - prompt: &[u32], - request: &GenerationRequest, - spec_min_p: f32, - clock: &impl Clock, - ) -> Result<(FinishReason, Usage), GenerationFailure> { - let sampler = request_sampler(request, clock_seed()).map_err(|_| invalid("unsupported generation request"))?; - let serve_request = ServeRequest::new( - prompt.iter().map(|&t| t as i32).collect(), - request.max_output_tokens as usize, - sampler.as_ref(), - clock_seed(), - spec_min_p, - crate::qwen_forward::original_serve_request::original_stop_tokens(eos), - ); - let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(eos); - let cancelled = || cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed(); - let start = clock.now(); - let mut utf8 = Utf8Pending::default(); - let mut count: u64 = 0; - let mut captured: Option = None; - let mut timed_out = false; - let mut generated_ids: Vec = Vec::new(); - leleka_memory::telemetry::request_started_at(prompt.len() as u64, start); - let result = { - let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> { - generated_ids.extend_from_slice(tokens); - leleka_memory::telemetry::tokens_delivered_at(tokens.len() as u64, clock.now()); - let mut deliver = |token: i32| -> Result<(), GenerationFailure> { - count += 1; - if stop_tokens.contains(&token) { - // the authoritative EOS (<|im_end|> or <|endoftext|>) counts as an output token and carries no text - return Ok(()); - } - let bytes = tokenizer - .decode_bytes(&[token as u32]) - .map_err(|_| unavailable("native token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text })?; - } - Ok(()) - }; - for &token in tokens { - if let Err(failure) = deliver(token) { - captured = Some(failure); - return Err(ForwardError::InputRead); - } - } - Ok(()) - }; - let mut cancel_probe = || { - if clock.since(start) > GENERATION_TIMEOUT { - timed_out = true; - return true; - } - cancelled() - }; - stack.serve(&serve_request, &mut emit, &mut cancel_probe) - }; - if let Some(failure) = captured.take() { - leleka_memory::telemetry::request_aborted(); - return Err(failure); - } - if timed_out { - leleka_memory::telemetry::request_aborted(); - return Err(unavailable("generation deadline exceeded").into()); - } - let outcome = match result { - Ok(outcome) => outcome, - Err(ServeError::Cancelled) => { - leleka_memory::telemetry::request_aborted(); - return Err(GenerationFailure::Cancelled); - } - Err(ServeError::Refused(admission)) => { - leleka_memory::telemetry::request_aborted(); - return Err(admission_error(admission).into()); - } - Err(ServeError::Failed(error)) => { - leleka_memory::telemetry::request_aborted(); - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve request failed: class={error:?}"); - return Err(unavailable("Original serve request failed").into()); - } - Err(ServeError::Broken(error)) => { - leleka_memory::telemetry::request_aborted(); - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack lost an owner: class={error:?}"); - return Err(unavailable("Original serve stack lost a physical owner").into()); - } - }; - if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() { - capture_request(std::path::Path::new(directory), prompt, &generated_ids, request, outcome.rounds as u64, stack.reused_tokens() as u64); - } - let reason = match outcome.stop { - ServeStop::Eos => FinishReason::Stop, - ServeStop::Length | ServeStop::Context => FinishReason::Length, - }; - if matches!(reason, FinishReason::Length) { - utf8.finish_length(|text| emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text }))?; - } else { - utf8.finish()?; - } - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count, - reused_input_tokens: stack.reused_tokens() as u64, - }; - let (prompt_ms, decode_ms) = stack.last_timing(); - leleka_memory::telemetry::request_finished(usage.input_tokens, usage.reused_input_tokens, usage.output_tokens, prompt_ms, decode_ms); - let tier_stats = stack.expert_tier_stats(); - let tier = tier_stats.map(|s| leleka_memory::telemetry::TierCounters { - groups: s.groups, - vram_entries: s.vram_entries, - pcie_entries: s.pcie_entries, - cpu_entries: s.cpu_entries, - adaptations: s.adaptations, - swaps: s.swaps, - }); - leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier); - emit_event(sink, &cancelled, clock, GenerationEvent::Usage(usage.clone()))?; - log_request_end(&request.request_id, &usage, prompt_ms, decode_ms, outcome.produced as u64, outcome.rounds as u64, tier); - if leleka_obs::settings().legacy { - // the exact lines scripts/e2e/analyze_session.py parses - leleka_obs::legacy_line(&format!( - "leleka-serve request outcome=completed produced={} rounds={} reused={}", - outcome.produced, - outcome.rounds, - stack.reused_tokens() - )); - if let Some(stats) = tier_stats { - leleka_obs::legacy_line(&format!("leleka-serve {}", stats.describe())); - } - } - if cancelled() { - return Err(GenerationFailure::Cancelled); - } - Ok((reason, usage)) - } - - /// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply - /// target, as `serve_load` does after its loop. - pub(in super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { - let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock, gpu_ordinal } = args; - // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy - let mut options = options.clone(); - let mut context_tokens = context_tokens; - options.validate()?; - let config = stack_config(&options, context_tokens)?; - let mut workers = config.cpu_workers; - // STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only; reads nothing the stack uses) - crate::serve_meta::emit(&crate::serve_meta::startup_lines( - &crate::serve_meta::BuildInfo::current(), - &crate::serve_meta::ProfileInfo::from_settings(crate::settings::process()), - &crate::serve_meta::ModelInfo::recorded(&loaded.descriptor.artifact_digest, &model_files), - &meta_facts(&config, &options, context_tokens), - )); - let stack = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve open: {}", failure.describe()); - load_failure(LoadPhase::OriginalStack, open_error(&failure)) - })?; - crate::serve_meta::emit(&[crate::serve_meta::cache_line(&match stack.prefix_summary(0) { - Some(summary) => crate::serve_meta::CacheFacts { - prefix_on: true, - prefix_entries: summary.nodes, - prefix_blocks: summary.blocks, - prefix_used_bytes: summary.used_bytes, - prefix_budget_bytes: summary.budget_bytes, - }, - None => crate::serve_meta::CacheFacts { prefix_on: false, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 0 }, - })]); - publish_prefix_summary(&stack, shared); - crate::load_clock::lap("serve_stack_open_total"); - // The first release (right after the expert bank was copied) cannot see what the stack open reads next: the dense tensors of shard 0 and the - // MTP pack go through the page cache (4-5 GiB measured at idle on the 5090), and the resident copies are in the engine's own memory. Give - // those pages back too, so that no model byte is held twice (clean pages only, POSIX_FADV_DONTNEED, never drop_caches; best effort). - #[cfg(target_os = "linux")] - if options.expert_source == crate::backend::ExpertSource::Resident { - let mut files: Vec = model_files.clone(); - if let Some(dir) = options.mtp_rt_directory.as_ref() { - files.extend(["experts.bin", "dense.bin"].map(|name| dir.join(name))); - } - let paths: Vec<&std::path::Path> = files.iter().map(PathBuf::as_path).collect(); - crate::memory_governor::drop_file_cache(&paths); - } - leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None)); - // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request - leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); - let _telemetry = leleka_memory::telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1)); - let mut stack = Some(stack); - if shared.shutdown.load(Ordering::Acquire) { - if let Some(stack) = stack.take() { - let _ = stack.close(); - } - return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled"))); - } - shared.ready.store(true, Ordering::Release); - crate::load_clock::lap("ready_published"); - if reply.send(Ok(loaded.clone())).is_err() { - shared.ready.store(false, Ordering::Release); - if let Some(stack) = stack.take() { - let _ = stack.close(); - } - drop(stack); - let _ = Rc::try_unwrap(context).map(|c| c.close()); - return Ok(()); - } - let mut unload_reply = None; - let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock); - while !shared.shutdown.load(Ordering::Acquire) { - match rx.recv_timeout(Duration::from_millis(100)) { - Err(mpsc::RecvTimeoutError::Timeout) => { - // sessions idle past the retention time give their host memory back - if sweep.due(&clock) - && let Some(owner) = stack.as_mut() - { - let expired = owner.prefix_expire_idle(); - if expired > 0 { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default()); - publish_prefix_summary(owner, shared); - } - } - continue; - } - Err(_) => break, - Ok(Command::Load(_, _, reply)) => { - let _ = reply.send(Err(exhausted("unload the existing model before another load"))); - } - Ok(Command::Reconfigure(text, reply)) => { - let outcome = (|| -> Result { - let tuning = crate::serve_tuning::Tuning::parse(&text).map_err(super::super::invalid_dynamic)?; - let mut next_options = options.clone(); - let mut next_context = context_tokens; - let changed = tuning.apply(&mut next_options, &mut next_context).map_err(super::super::invalid_dynamic)?; - if changed.is_empty() || stack.is_none() { - return Ok(crate::serve_tuning::describe(&options, context_tokens, workers, None).to_string()); - } - use std::io::Write; - // The old stack is closed before the new one opens, so the new one's pinned host memory (K/V, rings, pools) must fit in - // what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run 2026-10-25). - if let Some(governor) = leleka_memory::Governor::global() { - let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); - if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { - return Err(BackendError { - code: ErrorCode::ResourceExhausted, - message: format!( - "reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed", - available >> 20, - need >> 20, - RECONFIGURE_HEADROOM_BYTES >> 20 - ), - retryable: false, - }); - } - } - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); - let started = clock.now(); - shared.ready.store(false, Ordering::Release); - if let Some(old) = stack.take() { - if old.close().is_err() { - shared.shutdown.store(true, Ordering::Release); - return Err(unavailable("Original serve stack cleanup failed during reconfigure")); - } - } - let open = |options: &OriginalServeOptions, tokens: u32| -> Result<(OriginalServeStack<'_, '_>, i32), BackendError> { - let config = stack_config(options, tokens)?; - let workers = config.cpu_workers; - let opened = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| open_error(&failure))?; - Ok((opened, workers)) - }; - match open(&next_options, next_context) { - Ok((opened, w)) => { - publish_prefix_summary(&opened, shared); - stack = Some(opened); - options = next_options; - context_tokens = next_context; - workers = w; - } - Err(failure) => { - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure failed: {}; reopening with the previous settings", failure.message); - match open(&options, context_tokens) { - Ok((again, w)) => { - publish_prefix_summary(&again, shared); - stack = Some(again); - workers = w; - shared.ready.store(true, Ordering::Release); - } - Err(_) => { - shared.shutdown.store(true, Ordering::Release); - // No stack is left and none can be built here: end the process a moment after the reply goes out so that the - // supervisor starts a fresh engine instead of keeping a half-dead one. - let _ = writeln!(std::io::stderr().lock(), "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine"); - thread::spawn(|| { - thread::sleep(Duration::from_secs(2)); - std::process::exit(70); - }); - return Err(unavailable("reconfigure failed and the previous settings could not be restored")); - } - } - return Err(BackendError { - code: ErrorCode::InvalidRequest, - message: format!("reconfigure refused: {}; the previous settings are back", failure.message), - retryable: false, - }); - } - } - shared.ready.store(true, Ordering::Release); - leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); - let effective = crate::serve_tuning::describe(&options, context_tokens, workers, None); - leleka_memory::telemetry::set_settings(effective.clone()); - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure done in {:.1} s", clock.since(started).as_secs_f64()); - Ok(effective.to_string()) - })(); - let _ = reply.send(outcome); - } - Ok(Command::Unload(candidate, reply)) => { - if candidate != loaded { - let _ = reply.send(Err(invalid("unknown loaded model handle"))); - } else { - unload_reply = Some(reply); - break; - } - } - Ok(Command::Generate(candidate, request, cancel, reply)) => { - let _guard = ActiveGuard(shared); - if candidate != loaded { - let _ = reply.send(Err(invalid("unknown loaded model handle"))); - continue; - } - if !shared.ready.load(Ordering::Acquire) { - let _ = reply.send(Err(unavailable("native model is not ready"))); - continue; - } - let prompt = match prepare_prompt(&tokenizer, &request, context_tokens) { - Ok(prompt) => prompt, - Err(error) => { - let _ = reply.send(Err(error)); - continue; - } - }; - if !context_fits(prompt.len(), request.max_output_tokens as usize, context_tokens) { - let _ = reply.send(Err(exhausted("prompt and output exceed configured context"))); - continue; - } - // memory admission: refuse before the first byte of work when the host is under pressure (the front end - // answers 503 `memory_pressure` with Retry-After; the text is the contract: `: retry_after=: `) - if let Some(governor) = leleka_memory::Governor::global() { - let shape = leleka_memory::RequestShape { - prompt_tokens: prompt.len() as u64, - max_new_tokens: u64::from(request.max_output_tokens), - max_context: u64::from(context_tokens), - }; - if let leleka_memory::Admission::Refuse(refusal) = governor.admit(&shape) { - let _ = reply.send(Err(BackendError { - code: ErrorCode::ResourceExhausted, - message: format!("{}: retry_after={}: {}", refusal.code, refusal.retry_after_secs, refusal.message), - retryable: refusal.status == 503, - })); - continue; - } - } - let (sink, stream) = GenerationSink::bounded_channel(QUEUE) - .map_err(|_| unavailable("generation queue unavailable"))?; - if reply.send(Ok(stream)).is_err() { - continue; - } - let Some(owner) = stack.as_mut() else { - let _ = emit_terminal( - &sink, - GenerationTerminal::Failed { - code: ErrorCode::BackendUnavailable, - message: "Original serve stack is not available".into(), - retryable: false, - }, - &clock, - ); - continue; - }; - let result = generate(owner, &tokenizer, &sink, &cancel, shared, eos, &prompt, &request, options.spec_min_p, &clock); - let terminal = match result { - Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage }, - Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled, - Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed { - code: error.code, - message: error.message, - retryable: false, - }, - }; - let _ = emit_terminal(&sink, terminal, &clock); - publish_prefix_summary(owner, shared); - if let Some(lost) = owner.health() { - // a lost physical owner cannot be repaired in place: stop serving, keep the process - // alive for an orderly unload - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack health: class={lost:?}"); - shared.ready.store(false, Ordering::Release); - } - } - } - } - shared.ready.store(false, Ordering::Release); - let stack_closed = match stack.take() { - Some(stack) => stack.close().map_err(|_| unavailable("Original serve stack cleanup failed")), - None => Ok(()), - }; - // the stack's borrow of the context ends with it - drop(stack); - let closed = Rc::try_unwrap(context) - .map_err(|_| unavailable("native context still borrowed"))? - .close() - .map_err(|_| unavailable("native context cleanup failed")); - let closed = closed.and(stack_closed); - if closed.is_err() { - shared.shutdown.store(true, Ordering::Release); - } - if let Some(reply) = unload_reply { - let _ = reply.send(closed); - } - Ok(()) - } -} +#[path = "backend_original_serve/runner.rs"] +pub(super) mod runner; #[cfg(test)] -mod tests { - use super::*; - - fn facts() -> ConfigFacts { - ConfigFacts { kar_inherited: true, kar_staged: false, mtp: true, kar_expert: false, gguf_ple: false, experimental: false, context_tokens: 32768 } - } - - #[test] - fn modes_parse_and_print_symmetrically() { - for mode in [OriginalServeMode::Auto, OriginalServeMode::Original, OriginalServeMode::Preview] { - assert_eq!(OriginalServeMode::parse(mode.as_str()), Some(mode)); - } - assert_eq!(OriginalServeMode::parse("AUTO"), None); - assert_eq!(OriginalServeMode::parse(""), None); - } - - #[test] - fn auto_takes_the_original_path_only_when_everything_is_sealed_and_fed() { - assert_eq!(choose(OriginalServeMode::Auto, &facts(), &[]).unwrap(), OriginalServeChoice::Original); - let OriginalServeChoice::Preview { reason } = choose(OriginalServeMode::Auto, &facts(), &["router", "head"]).unwrap() else { - panic!("an unsealed build must stay on the preview path"); - }; - assert!(reason.contains("router") && reason.contains("head"), "{reason}"); - // the experimental GGUF-PLE opt-in lets the Original path start without an archive, and only that - let gguf = ConfigFacts { kar_inherited: false, gguf_ple: true, ..facts() }; - assert_eq!(choose(OriginalServeMode::Auto, &gguf, &[]).unwrap(), OriginalServeChoice::Original); - assert_eq!(choose(OriginalServeMode::Original, &gguf, &[]).unwrap(), OriginalServeChoice::Original); - assert!(matches!( - choose(OriginalServeMode::Auto, &ConfigFacts { kar_staged: true, ..gguf }, &[]).unwrap(), - OriginalServeChoice::Preview { .. } - )); - assert!(matches!( - choose(OriginalServeMode::Auto, &ConfigFacts { mtp: false, ..gguf }, &[]).unwrap(), - OriginalServeChoice::Preview { .. } - )); - for broken in [ - ConfigFacts { kar_inherited: false, ..facts() }, - ConfigFacts { kar_staged: true, ..facts() }, - ConfigFacts { mtp: false, ..facts() }, - ConfigFacts { kar_expert: true, ..facts() }, - ConfigFacts { experimental: true, ..facts() }, - ConfigFacts { context_tokens: 0, ..facts() }, - ConfigFacts { context_tokens: 262_145, ..facts() }, - ] { - assert!(matches!(choose(OriginalServeMode::Auto, &broken, &[]).unwrap(), OriginalServeChoice::Preview { .. }), "{broken:?}"); - } - } - - #[test] - fn explicit_original_never_falls_back_and_names_what_is_missing() { - assert_eq!(choose(OriginalServeMode::Original, &facts(), &[]).unwrap(), OriginalServeChoice::Original); - let missing = choose(OriginalServeMode::Original, &facts(), &["ple_layer1", "hc_read"]).unwrap_err(); - assert!(missing.message.contains("ple_layer1") && missing.message.contains("hc_read"), "{}", missing.message); - let expert = choose(OriginalServeMode::Original, &ConfigFacts { kar_expert: true, ..facts() }, &[]).unwrap_err(); - assert!(expert.message.contains("KAR expert source"), "{}", expert.message); - let kar = choose(OriginalServeMode::Original, &ConfigFacts { kar_inherited: false, ..facts() }, &[]).unwrap_err(); - assert!(kar.message.contains("KAR archive"), "{}", kar.message); - let mtp = choose(OriginalServeMode::Original, &ConfigFacts { mtp: false, ..facts() }, &[]).unwrap_err(); - assert!(mtp.message.contains("MTP"), "{}", mtp.message); - } - - #[test] - fn preview_is_never_overridden() { - assert!(matches!(choose(OriginalServeMode::Preview, &facts(), &[]).unwrap(), OriginalServeChoice::Preview { .. })); - } - - #[test] - fn options_validation_bounds_the_chunk_and_the_floor() { - assert!(OriginalServeOptions::default().validate().is_ok()); - for capacity in [256usize, 2048, 8192] { - assert!(OriginalServeOptions { prefill_capacity: Some(capacity), ..Default::default() }.validate().is_ok()); - } - for capacity in [0usize, 100, 16384] { - assert!(OriginalServeOptions { prefill_capacity: Some(capacity), ..Default::default() }.validate().is_err()); - } - for floor in [-0.1f32, 1.1, f32::NAN] { - assert!(OriginalServeOptions { spec_min_p: floor, ..Default::default() }.validate().is_err()); - } - assert!(OriginalServeOptions { mtp_rt_directory: Some(PathBuf::new()), ..Default::default() }.validate().is_err()); - } - - #[test] - fn the_conversation_cache_is_on_by_default_and_maps_the_original_flags() { - let defaults = OriginalServeOptions::default(); - assert_eq!(defaults.conversation().map(|c| c.prompt_cache), Some(6), "--prompt-cache 6 by default"); - assert!(OriginalServeOptions { prompt_cache: 0, ..Default::default() }.conversation().is_none(), "--prompt-cache 0 turns it off"); - let on = OriginalServeOptions { prompt_cache: 6, prompt_cache_every: 0, turn_token: None, ..Default::default() }; - assert!(on.validate().is_ok()); - let config = on.conversation().expect("--prompt-cache 6 turns the cache on"); - assert_eq!((config.prompt_cache, config.prompt_cache_every, config.prompt_cache_root, config.turn_token), (6, 0, 2048, None)); - assert!(OriginalServeOptions { prompt_cache: 65, ..Default::default() }.validate().is_err()); - assert!(OriginalServeOptions { turn_token: Some(248_320), ..Default::default() }.validate().is_err()); - } - - #[test] - fn the_request_fits_only_with_the_eight_cell_slack() { - assert!(context_fits(100, 20, 128)); - assert!(!context_fits(100, 21, 128)); - assert!(!context_fits(usize::MAX, 1, 128)); - assert!(!context_fits(1, usize::MAX, 128)); - } -} +#[path = "backend_original_serve/tests.rs"] +mod tests; #[path = "backend_original_serve/impl_originalservemode.rs"] mod impl_originalservemode; diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs new file mode 100644 index 00000000..36f3074f --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs @@ -0,0 +1,115 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::super::{ + emit_event, emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, clock_seed, unavailable, + ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GenerationEvent, + GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, Reply, Shared, + Tokenizer, Usage, Utf8Pending, GENERATION_TIMEOUT, QUEUE, +}; +use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; + +type GpuProbe = Box Option + Send + Sync>; +use crate::qwen_forward::{ + contract::Error as ForwardError, + original_serve_engine::ServeStop, + original_serve_request::{Admission, ServeDevice, ServeError, ServeRequest}, + original_serve_stack::{OriginalServeStack, StackConfig}, + original_serve_verifier::ServeFailure, +}; +use leleka_backend_api::GenerationRequest; +use {crate::idle_sweep::IdleSweep, leleka_obs::time::{Clock, SystemClock}}; +use std::{ + path::PathBuf, + rc::Rc, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::{self, Receiver}, + }, + thread, + time::Duration, +}; + +/// Everything the Original owner loop needs from `serve_load` once the context exists. +pub(in super::super) struct Run<'a, 'd> { + pub(in super::super) context_tokens: u32, + pub(in super::super) rx: &'a Receiver, + pub(in super::super) shared: &'a Shared, + pub(in super::super) binding: ModelBinding, + pub(in super::super) context: Rc>, + pub(in super::super) tokenizer: Tokenizer, + pub(in super::super) eos: u32, + pub(in super::super) loaded: LoadedModel, + pub(in super::super) reply: &'a Reply, + pub(in super::super) options: &'a OriginalServeOptions, + /// The model files, for the start-up report only (size and mtime are read; the content never is). + pub(in super::super) model_files: Vec, + pub(in super::super) clock: SystemClock, + pub(in super::super) gpu_ordinal: u32, // for the telemetry sampler (NVML indexes the same physical order) +} + +/// Host memory a reconfigure needs beside the soft floor: the reopened stack's pinned K/V (3.1 GiB at 262,144 cells), rings and pools. +const RECONFIGURE_HEADROOM_BYTES: u64 = 4 << 30; + +/// Number of checkpoint heads a pool summary carries. +const PREFIX_SUMMARY_HEADS: usize = 512; + +/// The expert tier's counters after the previous request, to turn the stack-lifetime figures into a request's share. +static PREVIOUS_TIER: std::sync::Mutex> = std::sync::Mutex::new(None); + +#[cfg(test)] +mod capture_tests { + use super::*; + + #[test] + fn a_captured_request_is_json_with_the_ids_and_one_line_per_request_in_the_id_files() { + let dir = std::env::temp_dir().join(format!("leleka-capture-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let request = GenerationRequest { + request_id: "r".into(), + prompt: String::new(), + max_output_tokens: 64, + temperature_milli: 0, + sampling: Default::default(), + }; + capture_request(&dir, &[1, 2, 3], &[7, 8], &request, 2, 1); + capture_request(&dir, &[1, 2, 3, 7, 8, 9], &[5], &request, 1, 4); + let names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + let first = names.iter().filter(|n| n.starts_with("req-")).min().cloned().unwrap(); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join(&first)).unwrap()).unwrap(); + assert_eq!(doc["prompt_ids"], serde_json::json!([1, 2, 3])); + assert_eq!(doc["generated_ids"], serde_json::json!([7, 8])); + assert_eq!(doc["max_new"], 64); + assert!(doc["top_k"].is_null()); + let prompts = std::fs::read_to_string(dir.join("prompts.ids")).unwrap(); + assert_eq!(prompts.lines().count(), 2); + assert!(prompts.lines().any(|l| l == "1,2,3,7,8,9")); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[path = "runner/gpu_probe_fn.rs"] +mod gpu_probe_fn; +#[allow(unused_imports)] +use gpu_probe_fn::gpu_probe; +#[allow(unused_imports)] +use gpu_probe_fn::stack_config; +#[allow(unused_imports)] +use gpu_probe_fn::meta_facts; +#[allow(unused_imports)] +use gpu_probe_fn::open_error; +#[allow(unused_imports)] +use gpu_probe_fn::publish_prefix_summary; +#[allow(unused_imports)] +use gpu_probe_fn::admission_error; +#[allow(unused_imports)] +use gpu_probe_fn::log_request_end; +#[allow(unused_imports)] +use gpu_probe_fn::capture_request; +#[path = "runner/generate_fn.rs"] +mod generate_fn; +#[allow(unused_imports)] +pub(in super::super) use generate_fn::generate; +#[path = "runner/run_fn.rs"] +mod run_fn; +#[allow(unused_imports)] +pub(in super::super) use run_fn::run; diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs new file mode 100644 index 00000000..19100148 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs @@ -0,0 +1,152 @@ +//! Moved out of the parent module by STRA-338: fn generate. + +#[allow(unused_imports)] +use super::*; + + +/// One request over the stack; the caller owns the stream/terminal bookkeeping. +#[allow(clippy::too_many_arguments)] +pub(in super::super::super) fn generate( + stack: &mut impl ServeDevice, + tokenizer: &Tokenizer, + sink: &GenerationSink, + cancel: &AtomicBool, + shared: &Shared, + eos: u32, + prompt: &[u32], + request: &GenerationRequest, + spec_min_p: f32, + clock: &impl Clock, +) -> Result<(FinishReason, Usage), GenerationFailure> { + let sampler = request_sampler(request, clock_seed()).map_err(|_| invalid("unsupported generation request"))?; + let serve_request = ServeRequest::new( + prompt.iter().map(|&t| t as i32).collect(), + request.max_output_tokens as usize, + sampler.as_ref(), + clock_seed(), + spec_min_p, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ); + let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(eos); + let cancelled = || cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed(); + let start = clock.now(); + let mut utf8 = Utf8Pending::default(); + let mut count: u64 = 0; + let mut captured: Option = None; + let mut timed_out = false; + let mut generated_ids: Vec = Vec::new(); + leleka_memory::telemetry::request_started_at(prompt.len() as u64, start); + let result = { + let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> { + generated_ids.extend_from_slice(tokens); + leleka_memory::telemetry::tokens_delivered_at(tokens.len() as u64, clock.now()); + let mut deliver = |token: i32| -> Result<(), GenerationFailure> { + count += 1; + if stop_tokens.contains(&token) { + // the authoritative EOS (<|im_end|> or <|endoftext|>) counts as an output token and carries no text + return Ok(()); + } + let bytes = tokenizer + .decode_bytes(&[token as u32]) + .map_err(|_| unavailable("native token decoding failed"))?; + if let Some(text) = utf8.push(&bytes)? { + emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text })?; + } + Ok(()) + }; + for &token in tokens { + if let Err(failure) = deliver(token) { + captured = Some(failure); + return Err(ForwardError::InputRead); + } + } + Ok(()) + }; + let mut cancel_probe = || { + if clock.since(start) > GENERATION_TIMEOUT { + timed_out = true; + return true; + } + cancelled() + }; + stack.serve(&serve_request, &mut emit, &mut cancel_probe) + }; + if let Some(failure) = captured.take() { + leleka_memory::telemetry::request_aborted(); + return Err(failure); + } + if timed_out { + leleka_memory::telemetry::request_aborted(); + return Err(unavailable("generation deadline exceeded").into()); + } + let outcome = match result { + Ok(outcome) => outcome, + Err(ServeError::Cancelled) => { + leleka_memory::telemetry::request_aborted(); + return Err(GenerationFailure::Cancelled); + } + Err(ServeError::Refused(admission)) => { + leleka_memory::telemetry::request_aborted(); + return Err(admission_error(admission).into()); + } + Err(ServeError::Failed(error)) => { + leleka_memory::telemetry::request_aborted(); + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve request failed: class={error:?}"); + return Err(unavailable("Original serve request failed").into()); + } + Err(ServeError::Broken(error)) => { + leleka_memory::telemetry::request_aborted(); + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack lost an owner: class={error:?}"); + return Err(unavailable("Original serve stack lost a physical owner").into()); + } + }; + if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() { + capture_request(std::path::Path::new(directory), prompt, &generated_ids, request, outcome.rounds as u64, stack.reused_tokens() as u64); + } + let reason = match outcome.stop { + ServeStop::Eos => FinishReason::Stop, + ServeStop::Length | ServeStop::Context => FinishReason::Length, + }; + if matches!(reason, FinishReason::Length) { + utf8.finish_length(|text| emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text }))?; + } else { + utf8.finish()?; + } + let usage = Usage { + input_tokens: prompt.len() as u64, + output_tokens: count, + reused_input_tokens: stack.reused_tokens() as u64, + }; + let (prompt_ms, decode_ms) = stack.last_timing(); + leleka_memory::telemetry::request_finished(usage.input_tokens, usage.reused_input_tokens, usage.output_tokens, prompt_ms, decode_ms); + let tier_stats = stack.expert_tier_stats(); + let tier = tier_stats.map(|s| leleka_memory::telemetry::TierCounters { + groups: s.groups, + vram_entries: s.vram_entries, + pcie_entries: s.pcie_entries, + cpu_entries: s.cpu_entries, + adaptations: s.adaptations, + swaps: s.swaps, + }); + leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier); + emit_event(sink, &cancelled, clock, GenerationEvent::Usage(usage.clone()))?; + log_request_end(&request.request_id, &usage, prompt_ms, decode_ms, outcome.produced as u64, outcome.rounds as u64, tier); + if leleka_obs::settings().legacy { + // the exact lines scripts/e2e/analyze_session.py parses + leleka_obs::legacy_line(&format!( + "leleka-serve request outcome=completed produced={} rounds={} reused={}", + outcome.produced, + outcome.rounds, + stack.reused_tokens() + )); + if let Some(stats) = tier_stats { + leleka_obs::legacy_line(&format!("leleka-serve {}", stats.describe())); + } + } + if cancelled() { + return Err(GenerationFailure::Cancelled); + } + Ok((reason, usage)) +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs new file mode 100644 index 00000000..3ef63824 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs @@ -0,0 +1,202 @@ +//! Moved out of the parent module by STRA-338: fn gpu_probe, fn stack_config, fn meta_facts, fn open_error, fn publish_prefix_summary, fn admission_error .... + +#[allow(unused_imports)] +use super::*; + + +/// The telemetry sampler's view of the GPU: NVML when `libnvidia-ml` loads, otherwise polling `nvidia-smi` (WSL2, containers +/// without the management library), otherwise nothing (the document then has no `gpu` block). +pub(super) fn gpu_probe(ordinal: u32) -> Option { + match leleka_cuda_driver::nvml::Nvml::open(ordinal) { + Some(nvml) => Some(Box::new(move || { + nvml.sample().map(|s| leleka_memory::telemetry::GpuSample { + index: s.index, + util_pct: s.util_pct, + mem_util_pct: s.mem_util_pct, + vram_used_mib: s.vram_used_mib, + vram_total_mib: s.vram_total_mib, + power_w: s.power_w, + sm_clock_mhz: s.sm_clock_mhz, + temp_c: s.temp_c, + name: s.name, + mem_clock_mhz: s.mem_clock_mhz, + pcie_tx_kb_s: s.pcie_tx_kb_s, + pcie_rx_kb_s: s.pcie_rx_kb_s, + throttle_reasons: s.throttle_reasons, + }) + })), + None => leleka_memory::smi::probe(ordinal), + } +} + +/// The serve stack's configuration for these settings (everything except the weights, which stay loaded). +pub(super) fn stack_config(options: &OriginalServeOptions, context_tokens: u32) -> Result { + let mut config = StackConfig::new(i64::from(context_tokens)); + if let Some(capacity) = options.prefill_capacity { + config.capacity = capacity; + } + if let Some(workers) = options.cpu_workers { + config.cpu_workers = workers; + } + config.rt_directory = options.mtp_rt_directory.clone(); + if let Some(format) = options.kv_format { + config.kv_format = format; + } + if let Some(cells) = options.kv_resident { + config.kv_resident = cells; + } + config.conversation = options.conversation(); + if let Some(prefix) = options.prefix_cache.as_ref() { + use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig, TailMode}; + let mut prefix_config = PrefixConfig { + tail: match prefix.tail { + PrefixTail::Off => TailMode::Off, + PrefixTail::Prompt => TailMode::Prompt, + PrefixTail::Reply => TailMode::Reply, + }, + budget: match prefix.budget_bytes { + None => PrefixBudget::Auto, + Some(0) => PrefixBudget::Off, + Some(bytes) => PrefixBudget::Bytes(bytes), + }, + block_tokens: prefix.block_tokens, + ..PrefixConfig::auto() + }; + if let Some(seconds) = prefix.retention_s { + prefix_config.policy.retention_ms = seconds.saturating_mul(1000); + } + config.prefix = Some(prefix_config); + } + // The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it). + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .map_err(|_| load_failure(LoadPhase::OriginalStack, invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting")))?; + Ok(config) +} + +/// The effective tuning of a stack configuration as plain values for the start-up report (`serve_meta`); reads nothing else. +pub(super) fn meta_facts(config: &StackConfig, options: &OriginalServeOptions, context_tokens: u32) -> crate::serve_meta::ConfigFacts { + use crate::qwen_forward::original_serve_stack::{PrefixBudget, TailMode}; + let prefix = config.prefix.as_ref().filter(|p| !matches!(p.budget, PrefixBudget::Off)); + let slots = config.expert_tier.effective_slots(); + crate::serve_meta::ConfigFacts { + context_tokens, + chunk: config.capacity, + prefix_block: prefix.map(|p| p.resolved_block(config.capacity)), + prefix_tail: match prefix.map(|p| p.tail) { + None => "none", + Some(TailMode::Off) => "off", + Some(TailMode::Prompt) => "prompt", + Some(TailMode::Reply) => "reply", + }, + cpu_workers: config.cpu_workers, + kv: config.kv_format.name().to_owned(), + kv_resident_cells: config.kv_resident, + expert_tier: match slots { + 0 => "off".to_owned(), + n if n < 0 => "auto".to_owned(), + n => n.to_string(), + }, + expert_per_layer: config.expert_tier.per_layer, + expert_profile: config.expert_tier.profile.is_some(), + pcie_frac: config.expert_tier.pcie_frac, + spec_min_p: options.spec_min_p, + } +} + +/// The operator-facing error for a stack that could not start: the class of the owner's refusal and its +/// fixed text (an unbound producer, an unsealed asset, a budget). +pub(super) fn open_error(failure: &ServeFailure) -> BackendError { + let message = format!("Original serve stack could not start: {}", failure.describe()); + let code = match failure.error { + ForwardError::InputAllocation => ErrorCode::ResourceExhausted, + ForwardError::Unsupported(_) => ErrorCode::UnsupportedModel, + ForwardError::IdentityMismatch | ForwardError::InvalidDimension => ErrorCode::InvalidRequest, + _ => ErrorCode::BackendUnavailable, + }; + BackendError { code, message, retryable: false } +} + +/// Hand the prefix cache's summary to the threads that answer status queries (the stack stays on this thread). +pub(super) fn publish_prefix_summary(stack: &OriginalServeStack<'_, '_>, _shared: &Shared) { + if let Some(summary) = stack.prefix_summary(PREFIX_SUMMARY_HEADS) { + if let Ok(json) = serde_json::to_string(&summary) { + if let Ok(mut cell) = PREFIX_SUMMARY.lock() { + *cell = Some(json); + } + } + } +} + +pub(super) fn admission_error(admission: Admission) -> BackendError { + match admission { + Admission::Context => exhausted("prompt and output exceed configured context"), + _ => invalid("unsupported generation request"), + } +} + +/// The engine's one structured line per finished request (`engine.log`), keyed by the id the API gave the request, so +/// `leleka logs --request ID` can join it with the API's record: tokens, the speculative loop (tokens committed per +/// verified round), the expert tier's share served from VRAM / over PCIe / by the CPU for this request alone. +pub(super) fn log_request_end( + request_id: &str, + usage: &Usage, + prefill_ms: f64, + decode_ms: f64, + produced: u64, + rounds: u64, + tier: Option, +) { + let shares = tier.map(|now| { + let mut previous = PREVIOUS_TIER.lock().unwrap_or_else(|p| p.into_inner()); + let shares = leleka_memory::telemetry::tier_shares(previous.as_ref(), &now); + *previous = Some(now); + shares + }); + leleka_obs::emit_always( + leleka_obs::Level::Info, + "engine", + "request", + &leleka_memory::telemetry::request_line_fields(&leleka_memory::telemetry::RequestLine { + request_id, + input_tokens: usage.input_tokens, + reused_tokens: usage.reused_input_tokens, + output_tokens: usage.output_tokens, + prefill_ms, + decode_ms, + produced, + rounds, + shares, + }), + ); +} + +/// `LELEKA_CAPTURE_DIR`: keep the prompt ids and the generated ids of every completed request for offline replay +/// (`original_serve_replay_smoke`). PRIVATE data (the prompt is the user's conversation): never in Git. One +/// `req-NNNNNN.json` per request plus `prompts.ids` / `generated.ids`, one comma-separated line per request. +pub(super) fn capture_request(dir: &std::path::Path, prompt: &[u32], generated: &[i32], request: &GenerationRequest, rounds: u64, reused: u64) { + use std::io::Write; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let index = NEXT.fetch_add(1, Ordering::Relaxed); + let join = |ids: &mut dyn Iterator| ids.map(|t| t.to_string()).collect::>().join(","); + let prompt_line = join(&mut prompt.iter().map(|&t| i64::from(t))); + let generated_line = join(&mut generated.iter().map(|&t| i64::from(t))); + let s = &request.sampling; + fn opt(v: Option) -> String { + v.map_or_else(|| "null".to_owned(), |v| v.to_string()) + } + let json = format!( + "{{\"index\":{index},\"max_new\":{},\"temperature_milli\":{},\"top_p_micro\":{},\"top_k\":{},\"min_p_micro\":{},\"repetition_penalty_micro\":{},\"frequency_penalty_micro\":{},\"presence_penalty_micro\":{},\"penalty_last_n\":{},\"seed\":{},\"prompt_tokens\":{},\"reused\":{reused},\"rounds\":{rounds},\"produced\":{},\"prompt_ids\":[{prompt_line}],\"generated_ids\":[{generated_line}]}} +", + request.max_output_tokens, request.temperature_milli, opt(s.top_p_micro), opt(s.top_k), opt(s.min_p_micro), opt(s.repetition_penalty_micro), + opt(s.frequency_penalty_micro), opt(s.presence_penalty_micro), opt(s.penalty_last_n), opt(s.seed), prompt.len(), generated.len() + ); + if std::fs::create_dir_all(dir).is_err() { + return; + } + let _ = std::fs::write(dir.join(format!("req-{index:06}.json")), json); + for (name, line) in [("prompts.ids", &prompt_line), ("generated.ids", &generated_line)] { + if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(name)) { + let _ = writeln!(file, "{line}"); + } + } +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs new file mode 100644 index 00000000..68999926 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs @@ -0,0 +1,288 @@ +//! Moved out of the parent module by STRA-338: fn run. + +#[allow(unused_imports)] +use super::*; + + +/// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply +/// target, as `serve_load` does after its loop. +pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { + let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock, gpu_ordinal } = args; + // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy + let mut options = options.clone(); + let mut context_tokens = context_tokens; + options.validate()?; + let config = stack_config(&options, context_tokens)?; + let mut workers = config.cpu_workers; + // STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only; reads nothing the stack uses) + crate::serve_meta::emit(&crate::serve_meta::startup_lines( + &crate::serve_meta::BuildInfo::current(), + &crate::serve_meta::ProfileInfo::from_settings(crate::settings::process()), + &crate::serve_meta::ModelInfo::recorded(&loaded.descriptor.artifact_digest, &model_files), + &meta_facts(&config, &options, context_tokens), + )); + let stack = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve open: {}", failure.describe()); + load_failure(LoadPhase::OriginalStack, open_error(&failure)) + })?; + crate::serve_meta::emit(&[crate::serve_meta::cache_line(&match stack.prefix_summary(0) { + Some(summary) => crate::serve_meta::CacheFacts { + prefix_on: true, + prefix_entries: summary.nodes, + prefix_blocks: summary.blocks, + prefix_used_bytes: summary.used_bytes, + prefix_budget_bytes: summary.budget_bytes, + }, + None => crate::serve_meta::CacheFacts { prefix_on: false, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 0 }, + })]); + publish_prefix_summary(&stack, shared); + crate::load_clock::lap("serve_stack_open_total"); + // The first release (right after the expert bank was copied) cannot see what the stack open reads next: the dense tensors of shard 0 and the + // MTP pack go through the page cache (4-5 GiB measured at idle on the 5090), and the resident copies are in the engine's own memory. Give + // those pages back too, so that no model byte is held twice (clean pages only, POSIX_FADV_DONTNEED, never drop_caches; best effort). + #[cfg(target_os = "linux")] + if options.expert_source == crate::backend::ExpertSource::Resident { + let mut files: Vec = model_files.clone(); + if let Some(dir) = options.mtp_rt_directory.as_ref() { + files.extend(["experts.bin", "dense.bin"].map(|name| dir.join(name))); + } + let paths: Vec<&std::path::Path> = files.iter().map(PathBuf::as_path).collect(); + crate::memory_governor::drop_file_cache(&paths); + } + leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None)); + // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request + leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); + let _telemetry = leleka_memory::telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1)); + let mut stack = Some(stack); + if shared.shutdown.load(Ordering::Acquire) { + if let Some(stack) = stack.take() { + let _ = stack.close(); + } + return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled"))); + } + shared.ready.store(true, Ordering::Release); + crate::load_clock::lap("ready_published"); + if reply.send(Ok(loaded.clone())).is_err() { + shared.ready.store(false, Ordering::Release); + if let Some(stack) = stack.take() { + let _ = stack.close(); + } + drop(stack); + let _ = Rc::try_unwrap(context).map(|c| c.close()); + return Ok(()); + } + let mut unload_reply = None; + let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock); + while !shared.shutdown.load(Ordering::Acquire) { + match rx.recv_timeout(Duration::from_millis(100)) { + Err(mpsc::RecvTimeoutError::Timeout) => { + // sessions idle past the retention time give their host memory back + if sweep.due(&clock) + && let Some(owner) = stack.as_mut() + { + let expired = owner.prefix_expire_idle(); + if expired > 0 { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default()); + publish_prefix_summary(owner, shared); + } + } + continue; + } + Err(_) => break, + Ok(Command::Load(_, _, reply)) => { + let _ = reply.send(Err(exhausted("unload the existing model before another load"))); + } + Ok(Command::Reconfigure(text, reply)) => { + let outcome = (|| -> Result { + let tuning = crate::serve_tuning::Tuning::parse(&text).map_err(super::super::super::invalid_dynamic)?; + let mut next_options = options.clone(); + let mut next_context = context_tokens; + let changed = tuning.apply(&mut next_options, &mut next_context).map_err(super::super::super::invalid_dynamic)?; + if changed.is_empty() || stack.is_none() { + return Ok(crate::serve_tuning::describe(&options, context_tokens, workers, None).to_string()); + } + use std::io::Write; + // The old stack is closed before the new one opens, so the new one's pinned host memory (K/V, rings, pools) must fit in + // what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run 2026-10-25). + if let Some(governor) = leleka_memory::Governor::global() { + let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); + if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { + return Err(BackendError { + code: ErrorCode::ResourceExhausted, + message: format!( + "reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed", + available >> 20, + need >> 20, + RECONFIGURE_HEADROOM_BYTES >> 20 + ), + retryable: false, + }); + } + } + let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); + let started = clock.now(); + shared.ready.store(false, Ordering::Release); + if let Some(old) = stack.take() { + if old.close().is_err() { + shared.shutdown.store(true, Ordering::Release); + return Err(unavailable("Original serve stack cleanup failed during reconfigure")); + } + } + let open = |options: &OriginalServeOptions, tokens: u32| -> Result<(OriginalServeStack<'_, '_>, i32), BackendError> { + let config = stack_config(options, tokens)?; + let workers = config.cpu_workers; + let opened = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| open_error(&failure))?; + Ok((opened, workers)) + }; + match open(&next_options, next_context) { + Ok((opened, w)) => { + publish_prefix_summary(&opened, shared); + stack = Some(opened); + options = next_options; + context_tokens = next_context; + workers = w; + } + Err(failure) => { + let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure failed: {}; reopening with the previous settings", failure.message); + match open(&options, context_tokens) { + Ok((again, w)) => { + publish_prefix_summary(&again, shared); + stack = Some(again); + workers = w; + shared.ready.store(true, Ordering::Release); + } + Err(_) => { + shared.shutdown.store(true, Ordering::Release); + // No stack is left and none can be built here: end the process a moment after the reply goes out so that the + // supervisor starts a fresh engine instead of keeping a half-dead one. + let _ = writeln!(std::io::stderr().lock(), "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine"); + thread::spawn(|| { + thread::sleep(Duration::from_secs(2)); + std::process::exit(70); + }); + return Err(unavailable("reconfigure failed and the previous settings could not be restored")); + } + } + return Err(BackendError { + code: ErrorCode::InvalidRequest, + message: format!("reconfigure refused: {}; the previous settings are back", failure.message), + retryable: false, + }); + } + } + shared.ready.store(true, Ordering::Release); + leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); + let effective = crate::serve_tuning::describe(&options, context_tokens, workers, None); + leleka_memory::telemetry::set_settings(effective.clone()); + let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure done in {:.1} s", clock.since(started).as_secs_f64()); + Ok(effective.to_string()) + })(); + let _ = reply.send(outcome); + } + Ok(Command::Unload(candidate, reply)) => { + if candidate != loaded { + let _ = reply.send(Err(invalid("unknown loaded model handle"))); + } else { + unload_reply = Some(reply); + break; + } + } + Ok(Command::Generate(candidate, request, cancel, reply)) => { + let _guard = ActiveGuard(shared); + if candidate != loaded { + let _ = reply.send(Err(invalid("unknown loaded model handle"))); + continue; + } + if !shared.ready.load(Ordering::Acquire) { + let _ = reply.send(Err(unavailable("native model is not ready"))); + continue; + } + let prompt = match prepare_prompt(&tokenizer, &request, context_tokens) { + Ok(prompt) => prompt, + Err(error) => { + let _ = reply.send(Err(error)); + continue; + } + }; + if !context_fits(prompt.len(), request.max_output_tokens as usize, context_tokens) { + let _ = reply.send(Err(exhausted("prompt and output exceed configured context"))); + continue; + } + // memory admission: refuse before the first byte of work when the host is under pressure (the front end + // answers 503 `memory_pressure` with Retry-After; the text is the contract: `: retry_after=: `) + if let Some(governor) = leleka_memory::Governor::global() { + let shape = leleka_memory::RequestShape { + prompt_tokens: prompt.len() as u64, + max_new_tokens: u64::from(request.max_output_tokens), + max_context: u64::from(context_tokens), + }; + if let leleka_memory::Admission::Refuse(refusal) = governor.admit(&shape) { + let _ = reply.send(Err(BackendError { + code: ErrorCode::ResourceExhausted, + message: format!("{}: retry_after={}: {}", refusal.code, refusal.retry_after_secs, refusal.message), + retryable: refusal.status == 503, + })); + continue; + } + } + let (sink, stream) = GenerationSink::bounded_channel(QUEUE) + .map_err(|_| unavailable("generation queue unavailable"))?; + if reply.send(Ok(stream)).is_err() { + continue; + } + let Some(owner) = stack.as_mut() else { + let _ = emit_terminal( + &sink, + GenerationTerminal::Failed { + code: ErrorCode::BackendUnavailable, + message: "Original serve stack is not available".into(), + retryable: false, + }, + &clock, + ); + continue; + }; + let result = generate(owner, &tokenizer, &sink, &cancel, shared, eos, &prompt, &request, options.spec_min_p, &clock); + let terminal = match result { + Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage }, + Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled, + Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed { + code: error.code, + message: error.message, + retryable: false, + }, + }; + let _ = emit_terminal(&sink, terminal, &clock); + publish_prefix_summary(owner, shared); + if let Some(lost) = owner.health() { + // a lost physical owner cannot be repaired in place: stop serving, keep the process + // alive for an orderly unload + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack health: class={lost:?}"); + shared.ready.store(false, Ordering::Release); + } + } + } + } + shared.ready.store(false, Ordering::Release); + let stack_closed = match stack.take() { + Some(stack) => stack.close().map_err(|_| unavailable("Original serve stack cleanup failed")), + None => Ok(()), + }; + // the stack's borrow of the context ends with it + drop(stack); + let closed = Rc::try_unwrap(context) + .map_err(|_| unavailable("native context still borrowed"))? + .close() + .map_err(|_| unavailable("native context cleanup failed")); + let closed = closed.and(stack_closed); + if closed.is_err() { + shared.shutdown.store(true, Ordering::Release); + } + if let Some(reply) = unload_reply { + let _ = reply.send(closed); + } + Ok(()) +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs new file mode 100644 index 00000000..be353281 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs @@ -0,0 +1,102 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn facts() -> ConfigFacts { + ConfigFacts { kar_inherited: true, kar_staged: false, mtp: true, kar_expert: false, gguf_ple: false, experimental: false, context_tokens: 32768 } +} + +#[test] +fn modes_parse_and_print_symmetrically() { + for mode in [OriginalServeMode::Auto, OriginalServeMode::Original, OriginalServeMode::Preview] { + assert_eq!(OriginalServeMode::parse(mode.as_str()), Some(mode)); + } + assert_eq!(OriginalServeMode::parse("AUTO"), None); + assert_eq!(OriginalServeMode::parse(""), None); +} + +#[test] +fn auto_takes_the_original_path_only_when_everything_is_sealed_and_fed() { + assert_eq!(choose(OriginalServeMode::Auto, &facts(), &[]).unwrap(), OriginalServeChoice::Original); + let OriginalServeChoice::Preview { reason } = choose(OriginalServeMode::Auto, &facts(), &["router", "head"]).unwrap() else { + panic!("an unsealed build must stay on the preview path"); + }; + assert!(reason.contains("router") && reason.contains("head"), "{reason}"); + // the experimental GGUF-PLE opt-in lets the Original path start without an archive, and only that + let gguf = ConfigFacts { kar_inherited: false, gguf_ple: true, ..facts() }; + assert_eq!(choose(OriginalServeMode::Auto, &gguf, &[]).unwrap(), OriginalServeChoice::Original); + assert_eq!(choose(OriginalServeMode::Original, &gguf, &[]).unwrap(), OriginalServeChoice::Original); + assert!(matches!( + choose(OriginalServeMode::Auto, &ConfigFacts { kar_staged: true, ..gguf }, &[]).unwrap(), + OriginalServeChoice::Preview { .. } + )); + assert!(matches!( + choose(OriginalServeMode::Auto, &ConfigFacts { mtp: false, ..gguf }, &[]).unwrap(), + OriginalServeChoice::Preview { .. } + )); + for broken in [ + ConfigFacts { kar_inherited: false, ..facts() }, + ConfigFacts { kar_staged: true, ..facts() }, + ConfigFacts { mtp: false, ..facts() }, + ConfigFacts { kar_expert: true, ..facts() }, + ConfigFacts { experimental: true, ..facts() }, + ConfigFacts { context_tokens: 0, ..facts() }, + ConfigFacts { context_tokens: 262_145, ..facts() }, + ] { + assert!(matches!(choose(OriginalServeMode::Auto, &broken, &[]).unwrap(), OriginalServeChoice::Preview { .. }), "{broken:?}"); + } +} + +#[test] +fn explicit_original_never_falls_back_and_names_what_is_missing() { + assert_eq!(choose(OriginalServeMode::Original, &facts(), &[]).unwrap(), OriginalServeChoice::Original); + let missing = choose(OriginalServeMode::Original, &facts(), &["ple_layer1", "hc_read"]).unwrap_err(); + assert!(missing.message.contains("ple_layer1") && missing.message.contains("hc_read"), "{}", missing.message); + let expert = choose(OriginalServeMode::Original, &ConfigFacts { kar_expert: true, ..facts() }, &[]).unwrap_err(); + assert!(expert.message.contains("KAR expert source"), "{}", expert.message); + let kar = choose(OriginalServeMode::Original, &ConfigFacts { kar_inherited: false, ..facts() }, &[]).unwrap_err(); + assert!(kar.message.contains("KAR archive"), "{}", kar.message); + let mtp = choose(OriginalServeMode::Original, &ConfigFacts { mtp: false, ..facts() }, &[]).unwrap_err(); + assert!(mtp.message.contains("MTP"), "{}", mtp.message); +} + +#[test] +fn preview_is_never_overridden() { + assert!(matches!(choose(OriginalServeMode::Preview, &facts(), &[]).unwrap(), OriginalServeChoice::Preview { .. })); +} + +#[test] +fn options_validation_bounds_the_chunk_and_the_floor() { + assert!(OriginalServeOptions::default().validate().is_ok()); + for capacity in [256usize, 2048, 8192] { + assert!(OriginalServeOptions { prefill_capacity: Some(capacity), ..Default::default() }.validate().is_ok()); + } + for capacity in [0usize, 100, 16384] { + assert!(OriginalServeOptions { prefill_capacity: Some(capacity), ..Default::default() }.validate().is_err()); + } + for floor in [-0.1f32, 1.1, f32::NAN] { + assert!(OriginalServeOptions { spec_min_p: floor, ..Default::default() }.validate().is_err()); + } + assert!(OriginalServeOptions { mtp_rt_directory: Some(PathBuf::new()), ..Default::default() }.validate().is_err()); +} + +#[test] +fn the_conversation_cache_is_on_by_default_and_maps_the_original_flags() { + let defaults = OriginalServeOptions::default(); + assert_eq!(defaults.conversation().map(|c| c.prompt_cache), Some(6), "--prompt-cache 6 by default"); + assert!(OriginalServeOptions { prompt_cache: 0, ..Default::default() }.conversation().is_none(), "--prompt-cache 0 turns it off"); + let on = OriginalServeOptions { prompt_cache: 6, prompt_cache_every: 0, turn_token: None, ..Default::default() }; + assert!(on.validate().is_ok()); + let config = on.conversation().expect("--prompt-cache 6 turns the cache on"); + assert_eq!((config.prompt_cache, config.prompt_cache_every, config.prompt_cache_root, config.turn_token), (6, 0, 2048, None)); + assert!(OriginalServeOptions { prompt_cache: 65, ..Default::default() }.validate().is_err()); + assert!(OriginalServeOptions { turn_token: Some(248_320), ..Default::default() }.validate().is_err()); +} + +#[test] +fn the_request_fits_only_with_the_eight_cell_slack() { + assert!(context_fits(100, 20, 128)); + assert!(!context_fits(100, 21, 128)); + assert!(!context_fits(usize::MAX, 1, 128)); + assert!(!context_fits(1, usize::MAX, 128)); +} diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs index ddd94d3f..53d7ca2d 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs @@ -35,128 +35,7 @@ struct SparseArchive { /// same weaker one as Linux's `open_read_only_file`: the pinned length, one regular file, a share mode that keeps /// every writer out while the process holds the file, and the full SHA-256 plus every payload CRC at load. #[cfg(target_os = "windows")] -mod win_archive { - use super::{InputBindingError, InputResult}; - use std::{ - fs::File, - os::windows::fs::{FileExt, OpenOptionsExt}, - path::Path, - }; - - const FILE_SHARE_READ: u32 = 1; - const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; - - pub(super) fn io_error(error: std::io::Error) -> InputBindingError { - // Only a closed kind and the numeric OS code reach the diagnostic, never a path. - eprintln!("leleka-kar kind={:?} os_error={:?}", error.kind(), error.raw_os_error()); - InputBindingError::Read - } - - /// A regular file opened for reading; other readers are allowed, writers are not, reparse points are not followed. - pub(super) fn open_regular(path: &Path) -> InputResult { - let file = std::fs::OpenOptions::new() - .read(true) - .share_mode(FILE_SHARE_READ) - .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) - .open(path) - .map_err(io_error)?; - let meta = file.metadata().map_err(io_error)?; - if !meta.is_file() { - return Err(InputBindingError::Range); - } - Ok(file) - } - - pub(super) fn open_read_only_archive(path: &Path, expected_bytes: u64) -> InputResult { - let file = open_regular(path)?; - check_len(&file, expected_bytes)?; - Ok(file) - } - - fn check_len(file: &File, expected_bytes: u64) -> InputResult<()> { - let meta = file.metadata().map_err(io_error)?; - if !meta.is_file() || meta.len() != expected_bytes { - return Err(InputBindingError::Range); - } - Ok(()) - } - - /// An independent handle on the admitted archive (reads are positional, so the shared pointer is irrelevant). - pub(super) fn reopen_read_only_archive(source: &File, expected_bytes: u64) -> InputResult { - let file = source.try_clone().map_err(io_error)?; - check_len(&file, expected_bytes)?; - Ok(file) - } - - pub(super) fn read_exact_at(file: &File, mut buffer: &mut [u8], mut offset: u64) -> std::io::Result<()> { - while !buffer.is_empty() { - let count = file.seek_read(buffer, offset)?; - if count == 0 { - return Err(std::io::ErrorKind::UnexpectedEof.into()); - } - buffer = &mut buffer[count..]; - offset += count as u64; - } - Ok(()) - } - - pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> { - use sha2::{Digest, Sha256}; - let length = file.metadata().map_err(io_error)?.len(); - if length == 0 || length > 1024 * 1024 { - return Err(InputBindingError::Range); - } - let mut digest = Sha256::new(); - let mut buffer = [0u8; 64 * 1024]; - let mut offset = 0u64; - while offset < length { - let count = usize::try_from((length - offset).min(buffer.len() as u64)) - .map_err(|_| InputBindingError::Range)?; - read_exact_at(file, &mut buffer[..count], offset).map_err(io_error)?; - digest.update(&buffer[..count]); - offset += count as u64; - } - if file.metadata().map_err(io_error)?.len() != length || digest.finalize().as_slice() != expected_digest { - return Err(InputBindingError::Metadata); - } - Ok(()) - } - - #[cfg(test)] - mod tests { - use super::*; - - #[test] - fn a_regular_file_of_the_wrong_length_is_refused_and_reads_are_positional() { - let dir = std::env::temp_dir().join(format!("leleka-kar-win-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("a.bin"); - std::fs::write(&path, b"abc").unwrap(); - assert!(open_read_only_archive(&path, 3).is_ok()); - assert!(matches!(open_read_only_archive(&path, 4), Err(InputBindingError::Range))); - let file = open_regular(&path).unwrap(); - let mut buffer = [0u8; 2]; - read_exact_at(&file, &mut buffer, 1).unwrap(); - assert_eq!(&buffer, b"bc"); - assert!(read_exact_at(&file, &mut buffer, 2).is_err()); - drop(file); - std::fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn the_share_mode_keeps_writers_out_while_the_archive_is_open() { - let dir = std::env::temp_dir().join(format!("leleka-kar-win-share-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("b.bin"); - std::fs::write(&path, b"abc").unwrap(); - let file = open_regular(&path).unwrap(); - assert!(std::fs::OpenOptions::new().write(true).open(&path).is_err()); - drop(file); - assert!(std::fs::OpenOptions::new().write(true).open(&path).is_ok()); - std::fs::remove_dir_all(&dir).unwrap(); - } - } -} +mod win_archive; #[cfg(all(test, target_os = "linux"))] #[path = "qwen4exp_inherited_kar_gpu.rs"] @@ -236,739 +115,10 @@ const PART1_F32_DIGEST: [u8; 32] = [ ]; #[cfg(test)] -mod pinned_profile_tests { - use super::*; - - #[test] - #[cfg(not(target_os = "windows"))] // asserts the Linux errno 28 (ENOSPC) mapping to StorageFull - fn load_diagnostics_redact_causes_and_preserve_typed_failures() { - struct BrokenSink; - impl std::io::Write for BrokenSink { - fn write(&mut self, _: &[u8]) -> std::io::Result { - Err(std::io::ErrorKind::BrokenPipe.into()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - for (cause, expected, typed) in [ - ( - KarError::Io(std::io::Error::other("SECRET_PATH_CAPTURE")), - "leleka-kar phase=Verify class=Io kind=Other errno=None\n", - InputBindingError::Read, - ), - ( - KarError::Io(std::io::Error::from_raw_os_error(28)), - "leleka-kar phase=Verify class=Io kind=StorageFull errno=Some(28)\n", - InputBindingError::Read, - ), - ( - KarError::Integrity("KAR full archive SHA-256 mismatch"), - "leleka-kar phase=Verify class=ArchiveSha\n", - InputBindingError::Metadata, - ), - ( - KarError::Profile("SECRET_PATH_CAPTURE"), - "leleka-kar phase=Verify class=Profile\n", - InputBindingError::Metadata, - ), - ] { - let mut bytes = Vec::new(); - kar_diagnostic(&mut bytes, LoadPhase::Verify, &cause); - assert_eq!(String::from_utf8(bytes).unwrap(), expected); - kar_diagnostic(&mut BrokenSink, LoadPhase::Verify, &cause); - assert_eq!(error(cause), typed); - } - let mut bytes = Vec::new(); - assert_eq!( - input_diagnostic( - &mut bytes, - LoadPhase::ReaderDetached, - InputBindingError::Metadata - ), - InputBindingError::Metadata - ); - assert_eq!(bytes, b"leleka-kar phase=ReaderDetached class=Metadata\n"); - assert_eq!( - input_diagnostic( - &mut BrokenSink, - LoadPhase::ReaderDetached, - InputBindingError::Metadata - ), - InputBindingError::Metadata - ); - } - - #[test] - fn pins_match_independent_conversion_receipts() { - fn hex(bytes: &[u8; 32]) -> String { - bytes.iter().map(|byte| format!("{byte:02x}")).collect() - } - let spec = pinned_profile_spec().unwrap(); - assert_eq!(spec.archive_bytes, 55_295_529_472); - assert_eq!(spec.virtual_f32_bytes, 707_775_598_080); - assert_eq!( - hex(&spec.archive_sha256), - "536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5" - ); - assert_eq!( - hex(&spec.provenance_sha256), - "3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5" - ); - assert_eq!( - hex(&spec.virtual_f32_sha256), - "c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479" - ); - assert_eq!( - hex(&spec.native_shard_sha256[0]), - "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3" - ); - assert_eq!( - hex(&spec.native_shard_sha256[1]), - "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" - ); - assert_eq!( - hex(&spec.parts[0].derived_f32_sha256), - "94f83e0c081fd92a824cb74a0d67c6fc2261af101dee251a411a6bb5f0664681" - ); - assert_eq!( - hex(&spec.parts[1].derived_f32_sha256), - "06623754d1373dd50f21ec99380fb3e7823eb3c9993700ee071965242dc7eb15" - ); - assert_eq!( - pinned_profile().unwrap().native_shard_sha256(), - &NATIVE_DIGESTS - ); - } - - #[test] - fn partitions_cover_exact_rows_and_contiguous_virtual_bytes() { - let spec = pinned_profile_spec().unwrap(); - assert_eq!(spec.parts.len(), 2); - assert_eq!( - spec.parts[0].name, - "per_layer_token_embd.weight#strata-part-001-of-002" - ); - assert_eq!( - spec.parts[1].name, - "per_layer_token_embd.weight#strata-part-002-of-002" - ); - let mut next_row = 0; - let mut next_byte = 502_974_615_040; - for part in &spec.parts { - assert_eq!(part.row_base, next_row); - assert_eq!(part.derived_f32_offset, next_byte); - next_row += part.row_count; - next_byte += part.row_count * 160 * 4; - } - assert_eq!(spec.parts[0].row_count, 200_000_000); - assert_eq!(spec.parts[1].row_count, 120_001_536); - assert_eq!(next_row, PLE_ROWS); - assert_eq!(next_byte, spec.virtual_f32_bytes); - } -} +mod pinned_profile_tests; #[cfg(any(target_os = "linux", all(test, target_os = "macos")))] -mod private_copy { - use super::{InputBindingError, InputResult, LoadPhase, input_failure}; - #[cfg(target_os = "linux")] - use std::io::Seek; - #[cfg(target_os = "macos")] - use std::{fs::Permissions, os::unix::fs::PermissionsExt}; - #[cfg(any(target_os = "macos", test))] - use std::{ - fs::{self, DirBuilder}, - os::unix::fs::DirBuilderExt, - path::PathBuf, - sync::atomic::{AtomicU64, Ordering}, - }; - use std::{ - fs::{File, Metadata, OpenOptions}, - io::{Read, Write}, - os::unix::fs::{MetadataExt, OpenOptionsExt}, - path::Path, - }; - - // Linux UAPI values, with macOS values only for the tiny offline unit tests. - #[cfg(target_os = "linux")] - const SOURCE_FLAGS: i32 = 0x20000 | 0x800; // O_NOFOLLOW | O_NONBLOCK - #[cfg(target_os = "macos")] - const SOURCE_FLAGS: i32 = 0x100 | 0x4; // O_NOFOLLOW | O_NONBLOCK - const COPY_BUFFER: usize = 8 * 1024 * 1024; - #[cfg(any(target_os = "macos", test))] - static SEQUENCE: AtomicU64 = AtomicU64::new(1); - type Inode = (u64, u64); - - fn inode(meta: &Metadata) -> Inode { - (meta.dev(), meta.ino()) - } - #[derive(Clone, Copy, Debug)] - enum IoPhase { - SourceOpen, - SourceMetadata, - Provenance, - RootMetadata, - RootCanonical, - Create, - DirectoryMetadata, - WriterOpen, - WriterMetadata, - DetachedMetadata, - CopyRead, - CopyWrite, - CopyEof, - Sync, - Seal, - OpenReader, - Unlink, - } - - // ErrorDisplay can contain an operator path or arbitrary source text. - // Only a closed phase/kind and numeric OS code reach this diagnostic. - fn diagnostic(sink: &mut W, phase: IoPhase, error: &std::io::Error) { - let _ = writeln!( - sink, - "leleka-kar phase={phase:?} kind={:?} errno={:?}", - error.kind(), - error.raw_os_error() - ); - } - fn report_io(phase: IoPhase, error: &std::io::Error) { - diagnostic(&mut std::io::stderr().lock(), phase, error); - } - fn phase_error(phase: IoPhase, error: std::io::Error) -> InputBindingError { - report_io(phase, &error); - InputBindingError::Read - } - pub(super) fn provenance_error(error: std::io::Error) -> InputBindingError { - phase_error(IoPhase::Provenance, error) - } - - pub(super) fn open_regular(path: &Path, bytes: Option) -> InputResult { - let file = OpenOptions::new() - .read(true) - .custom_flags(SOURCE_FLAGS) - .open(path) - .map_err(|e| phase_error(IoPhase::SourceOpen, e))?; - let meta = file - .metadata() - .map_err(|e| phase_error(IoPhase::SourceMetadata, e))?; - if !meta.is_file() || bytes.is_some_and(|size| meta.len() != size) { - return Err(InputBindingError::Range); - } - Ok(file) - } - - #[cfg(target_os = "macos")] - fn protected_root(path: &Path) -> InputResult<(PathBuf, u32)> { - let meta = fs::symlink_metadata(path).map_err(|e| phase_error(IoPhase::RootMetadata, e))?; - if !meta.is_dir() || meta.permissions().mode() & 0o7777 != 0o700 { - return Err(input_failure( - LoadPhase::RootMode, - InputBindingError::Metadata, - )); - } - let canonical = path - .canonicalize() - .map_err(|e| phase_error(IoPhase::RootCanonical, e))?; - if inode(&meta) - != inode(&fs::metadata(&canonical).map_err(|e| phase_error(IoPhase::RootMetadata, e))?) - { - return Err(input_failure( - LoadPhase::RootIdentity, - InputBindingError::Metadata, - )); - } - Ok((canonical, meta.uid())) - } - - #[cfg(target_os = "macos")] - struct OwnedCopy { - directory: PathBuf, - path: PathBuf, - directory_inode: Inode, - file_inode: Option, - } - #[cfg(target_os = "macos")] - impl OwnedCopy { - fn create(root: &Path, uid: u32) -> InputResult { - for _ in 0..128 { - let serial = SEQUENCE.fetch_add(1, Ordering::Relaxed); - let directory = root.join(format!(".leleka-kar-{}-{serial}", std::process::id())); - match DirBuilder::new().mode(0o700).create(&directory) { - Ok(()) => return Self::created(directory, uid), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(phase_error(IoPhase::Create, e)), - } - } - Err(InputBindingError::Busy) - } - - fn created(directory: PathBuf, uid: u32) -> InputResult { - let meta = fs::symlink_metadata(&directory) - .map_err(|e| phase_error(IoPhase::DirectoryMetadata, e))?; - let own = Self { - path: directory.join("archive.kar"), - directory, - directory_inode: inode(&meta), - file_inode: None, - }; - if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o7777 != 0o700 { - return Err(input_failure( - LoadPhase::DirectoryIdentity, - InputBindingError::Metadata, - )); - } - Ok(own) - } - - fn writer(&mut self, uid: u32) -> InputResult { - let file = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .custom_flags(SOURCE_FLAGS) - .open(&self.path) - .map_err(|e| phase_error(IoPhase::WriterOpen, e))?; - let meta = file - .metadata() - .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; - self.file_inode = Some(inode(&meta)); - if !meta.is_file() - || meta.uid() != uid - || meta.mode() & 0o7777 != 0o600 - || meta.nlink() != 1 - { - return Err(input_failure( - LoadPhase::WriterIdentity, - InputBindingError::Metadata, - )); - } - Ok(file) - } - - fn detach(&mut self) -> InputResult<()> { - if !self.owns_directory() || !self.owns_file() { - return Err(input_failure( - LoadPhase::DetachIdentity, - InputBindingError::Metadata, - )); - } - fs::remove_file(&self.path).map_err(|e| phase_error(IoPhase::Unlink, e))?; - self.file_inode = None; - fs::remove_dir(&self.directory).map_err(|e| phase_error(IoPhase::Unlink, e))?; - Ok(()) - } - fn owns_directory(&self) -> bool { - fs::symlink_metadata(&self.directory) - .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) - } - fn owns_file(&self) -> bool { - fs::symlink_metadata(&self.path) - .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) - } - } - #[cfg(target_os = "macos")] - impl Drop for OwnedCopy { - fn drop(&mut self) { - if self.owns_directory() { - if self.owns_file() { - let _ = fs::remove_file(&self.path); - } - let _ = fs::remove_dir(&self.directory); - } - } - } - - #[cfg(target_os = "linux")] - pub(super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64) -> InputResult { - use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; - // Safe OwnedFd -> File conversion transfers ownership exactly once. - // No pathname, filesystem quota, permission change or privileged call - // is needed. Unsupported/failed sealing refuses admission outright. - let fd = memfd_create( - "leleka-kar", - MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, - ) - .map_err(|e| phase_error(IoPhase::Create, e.into()))?; - let mut writer = File::from(fd); - copy_exact(source, &mut writer, bytes)?; - writer - .sync_all() - .map_err(|e| phase_error(IoPhase::Sync, e))?; - let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL; - fcntl_add_seals(&writer, required).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; - let actual = fcntl_get_seals(&writer).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; - if !actual.contains(required) { - return Err(input_failure( - LoadPhase::ReaderIdentity, - InputBindingError::Metadata, - )); - } - let meta = writer - .metadata() - .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; - if !meta.is_file() || meta.len() != bytes { - return Err(input_failure( - LoadPhase::ReaderLength, - InputBindingError::Range, - )); - } - if meta.nlink() != 0 { - return Err(input_failure( - LoadPhase::ReaderDetached, - InputBindingError::Metadata, - )); - } - // A cloned descriptor retains the same sealed inode. Its access mode - // cannot bypass the kernel seals. Close the copy writer before return. - let mut reader = writer - .try_clone() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; - drop(writer); - reader - .rewind() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; - Ok(reader) - } - - #[cfg(target_os = "macos")] - pub(super) fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult { - let (root, uid) = protected_root(owner_root)?; - let mut own = OwnedCopy::create(&root, uid)?; - let mut writer = own.writer(uid)?; - copy_exact(source, &mut writer, bytes)?; - writer - .sync_all() - .map_err(|e| phase_error(IoPhase::Sync, e))?; - writer - .set_permissions(Permissions::from_mode(0o400)) - .map_err(|e| phase_error(IoPhase::Seal, e))?; - let reader = checked_reader(&own, bytes)?; - drop(writer); - own.detach()?; - if reader - .metadata() - .map_err(|e| phase_error(IoPhase::DetachedMetadata, e))? - .nlink() - != 0 - { - return Err(input_failure( - LoadPhase::ReaderDetached, - InputBindingError::Metadata, - )); - } - Ok(reader) - } - - #[cfg(target_os = "macos")] - fn checked_reader(own: &OwnedCopy, bytes: u64) -> InputResult { - let reader = OpenOptions::new() - .read(true) - .custom_flags(SOURCE_FLAGS) - .open(&own.path) - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; - let meta = reader - .metadata() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; - // Preserve open_regular's exact file/length refusal separately from - // the existing inode/mode/link checks below. - if !meta.is_file() || meta.len() != bytes { - return Err(input_failure( - LoadPhase::ReaderLength, - InputBindingError::Range, - )); - } - if Some(inode(&meta)) != own.file_inode - || meta.mode() & 0o7777 != 0o400 - || meta.nlink() != 1 - { - return Err(input_failure( - LoadPhase::ReaderIdentity, - InputBindingError::Metadata, - )); - } - Ok(reader) - } - - fn copy_exact( - source: &mut R, - destination: &mut W, - bytes: u64, - ) -> InputResult<()> { - copy_exact_reporting(source, destination, bytes, report_io) - } - - fn copy_exact_reporting( - source: &mut R, - destination: &mut W, - bytes: u64, - mut report: F, - ) -> InputResult<()> { - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(COPY_BUFFER) - .map_err(|_| input_failure(LoadPhase::CopyAllocation, InputBindingError::Allocation))?; - buffer.resize(COPY_BUFFER, 0); - let mut remaining = bytes; - while remaining != 0 { - let count = remaining.min(COPY_BUFFER as u64) as usize; - source.read_exact(&mut buffer[..count]).map_err(|e| { - report(IoPhase::CopyRead, &e); - InputBindingError::Read - })?; - destination.write_all(&buffer[..count]).map_err(|e| { - report(IoPhase::CopyWrite, &e); - InputBindingError::Read - })?; - remaining -= count as u64; - } - if source.read(&mut buffer[..1]).map_err(|e| { - report(IoPhase::CopyEof, &e); - InputBindingError::Read - })? != 0 - { - return Err(input_failure( - LoadPhase::CopyTrailingBytes, - InputBindingError::Range, - )); - } - Ok(()) - } - - #[cfg(test)] - mod private_loader_tests { - use super::*; - use std::io::{Cursor, Seek, SeekFrom}; - use std::os::unix::fs::symlink; - - #[test] - fn short_write_diagnostics_preserve_error_and_redact_source() { - struct ShortWriter { - bytes: Vec, - failure: Option, - } - impl Write for ShortWriter { - fn write(&mut self, bytes: &[u8]) -> std::io::Result { - if self.bytes.is_empty() { - let count = bytes.len().min(3); - self.bytes.extend_from_slice(&bytes[..count]); - Ok(count) - } else { - Err(self.failure.take().expect("one injected write failure")) - } - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - struct BrokenSink; - impl Write for BrokenSink { - fn write(&mut self, _: &[u8]) -> std::io::Result { - Err(std::io::ErrorKind::BrokenPipe.into()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - for (error, expected) in [ - ( - std::io::Error::other("SECRET_OPERATOR_PATH_AND_CAPTURE"), - "leleka-kar phase=CopyWrite kind=Other errno=None\n", - ), - ( - std::io::Error::from_raw_os_error(28), - "leleka-kar phase=CopyWrite kind=StorageFull errno=Some(28)\n", - ), - ] { - let mut writer = ShortWriter { - bytes: Vec::new(), - failure: Some(error), - }; - let mut captured = Vec::new(); - let result = copy_exact_reporting( - &mut Cursor::new(b"abcdef"), - &mut writer, - 6, - |phase, error| diagnostic(&mut captured, phase, error), - ); - assert!(matches!(result, Err(InputBindingError::Read))); - assert_eq!(writer.bytes, b"abc"); - assert_eq!(captured, expected.as_bytes()); - assert!(!captured.windows(6).any(|w| w == b"SECRET")); - } - let mut writer = ShortWriter { - bytes: Vec::new(), - failure: Some(std::io::Error::other("PRIVATE_ERROR_DETAIL")), - }; - let result = copy_exact_reporting( - &mut Cursor::new(b"abcdef"), - &mut writer, - 6, - |phase, error| diagnostic(&mut BrokenSink, phase, error), - ); - assert!(matches!(result, Err(InputBindingError::Read))); - assert_eq!(writer.bytes, b"abc"); - } - - struct Fixture(PathBuf); - impl Fixture { - fn new() -> Self { - let parent = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-loader"); - fs::create_dir_all(&parent).unwrap(); - loop { - let id = SEQUENCE.fetch_add(1, Ordering::Relaxed); - let root = parent.join(format!("test-{}-{id}", std::process::id())); - match DirBuilder::new().mode(0o700).create(&root) { - Ok(()) => return Self(root), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => panic!("fixture creation failed: {e}"), - } - } - } - fn source(&self, bytes: &[u8]) -> File { - let path = self.0.join("source.kar"); - fs::write(&path, bytes).unwrap(); - open_regular(&path, Some(bytes.len() as u64)).unwrap() - } - fn children(&self) -> Vec { - fs::read_dir(&self.0) - .unwrap() - .map(|x| x.unwrap().path()) - .collect() - } - } - impl Drop for Fixture { - fn drop(&mut self) { - fs::remove_dir_all(&self.0).unwrap(); - } - } - - #[test] - #[cfg(target_os = "macos")] - fn copy_is_unnamed_readonly_and_independent_of_source() { - let fixture = Fixture::new(); - let source_path = fixture.0.join("source.kar"); - let mut source = fixture.source(b"frozen"); - let source_inode = inode(&source.metadata().unwrap()); - let mut copy = freeze(&mut source, &fixture.0, 6).unwrap(); - assert_ne!(inode(©.metadata().unwrap()), source_inode); - assert_eq!(copy.metadata().unwrap().nlink(), 0); - assert_eq!(copy.metadata().unwrap().mode() & 0o7777, 0o400); - assert_eq!(fixture.children(), vec![source_path.clone()]); - assert!((©).write_all(b"overwrite").is_err()); - fs::write(source_path, b"edited").unwrap(); - let mut content = Vec::new(); - copy.read_to_end(&mut content).unwrap(); - assert_eq!(content, b"frozen"); - } - - #[test] - #[cfg(target_os = "linux")] - fn linux_memfd_snapshot_is_independent_and_irrevocably_sealed() { - use rustix::fs::{SealFlags, fcntl_add_seals, fcntl_get_seals}; - let fixture = Fixture::new(); - let source_path = fixture.0.join("source.kar"); - let mut source = fixture.source(b"frozen"); - let source_inode = inode(&source.metadata().unwrap()); - // A nonexistent staging root proves Linux does not depend on it. - let mut copy = freeze(&mut source, &fixture.0.join("absent"), 6).unwrap(); - assert_ne!(inode(©.metadata().unwrap()), source_inode); - assert_eq!(copy.metadata().unwrap().len(), 6); - assert_eq!(copy.metadata().unwrap().nlink(), 0); - assert_eq!(fixture.children(), vec![source_path.clone()]); - fs::write(&source_path, b"edited").unwrap(); - let mut content = Vec::new(); - copy.read_to_end(&mut content).unwrap(); - assert_eq!(content, b"frozen"); - copy.rewind().unwrap(); - assert!((©).write_all(b"changed").is_err()); - assert!(copy.set_len(7).is_err()); - assert!(copy.set_len(5).is_err()); - let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL; - assert!(fcntl_get_seals(©).unwrap().contains(required)); - // Linux seals are only additive; SEAL prevents even an empty - // alteration request, and the full required set remains intact. - assert!(fcntl_add_seals(©, SealFlags::empty()).is_err()); - assert!(fcntl_get_seals(©).unwrap().contains(required)); - content.clear(); - copy.read_to_end(&mut content).unwrap(); - assert_eq!(content, b"frozen"); - } - - #[test] - fn truncated_or_extra_copy_never_leaves_private_partial() { - for expected in [2, 4] { - let fixture = Fixture::new(); - let mut source = fixture.source(b"abc"); - assert!(freeze(&mut source, &fixture.0, expected).is_err()); - assert_eq!(fixture.children(), vec![fixture.0.join("source.kar")]); - let mut unchanged = Vec::new(); - source.seek(SeekFrom::Start(0)).unwrap(); - source.read_to_end(&mut unchanged).unwrap(); - assert_eq!(unchanged, b"abc"); - } - } - - #[test] - fn exact_copy_checks_eof_and_write_failure() { - assert!(copy_exact(&mut Cursor::new(b"ab"), &mut Vec::new(), 3).is_err()); - assert!(copy_exact(&mut Cursor::new(b"abcd"), &mut Vec::new(), 3).is_err()); - assert!(copy_exact(&mut Cursor::new(b"abc"), &mut &mut [0u8; 1][..], 3).is_err()); - } - - #[test] - fn symlink_nonregular_and_wrong_length_are_refused() { - let fixture = Fixture::new(); - drop(fixture.source(b"abc")); - let link = fixture.0.join("link.kar"); - symlink(fixture.0.join("source.kar"), &link).unwrap(); - assert!(open_regular(&link, Some(3)).is_err()); - assert!(open_regular(&fixture.0, None).is_err()); - assert!(open_regular(&fixture.0.join("source.kar"), Some(2)).is_err()); - let root_link = fixture.0.join("root-link"); - symlink(&fixture.0, &root_link).unwrap(); - #[cfg(target_os = "macos")] - { - assert!(protected_root(&root_link).is_err()); - fs::set_permissions(&fixture.0, Permissions::from_mode(0o755)).unwrap(); - assert!(protected_root(&fixture.0).is_err()); - } - } - - #[test] - #[cfg(target_os = "macos")] - fn failed_directory_cleanup_refuses_and_preserves_other_content() { - let fixture = Fixture::new(); - let uid = fs::metadata(&fixture.0).unwrap().uid(); - let mut own = OwnedCopy::create(&fixture.0, uid).unwrap(); - let writer = own.writer(uid).unwrap(); - drop(writer); - let sentinel = own.directory.join("unowned-sentinel"); - fs::write(&sentinel, b"preserve").unwrap(); - assert_eq!(own.detach(), Err(InputBindingError::Read)); - drop(own); - assert_eq!(fs::read(sentinel).unwrap(), b"preserve"); - } - - #[test] - #[cfg(target_os = "macos")] - fn cleanup_does_not_delete_replaced_file_inode() { - let fixture = Fixture::new(); - let uid = fs::metadata(&fixture.0).unwrap().uid(); - let mut own = OwnedCopy::create(&fixture.0, uid).unwrap(); - let writer = own.writer(uid).unwrap(); - let path = own.path.clone(); - fs::remove_file(&path).unwrap(); - fs::write(&path, b"replacement").unwrap(); - assert_eq!(own.detach(), Err(InputBindingError::Metadata)); - drop(own); - assert_eq!(fs::read(path).unwrap(), b"replacement"); - drop(writer); - } - } -} +mod private_copy; mod impl_inheritedkararchive; #[cfg(target_os = "linux")] diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs new file mode 100644 index 00000000..7c896648 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs @@ -0,0 +1,131 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +#[test] +#[cfg(not(target_os = "windows"))] // asserts the Linux errno 28 (ENOSPC) mapping to StorageFull +fn load_diagnostics_redact_causes_and_preserve_typed_failures() { + struct BrokenSink; + impl std::io::Write for BrokenSink { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + for (cause, expected, typed) in [ + ( + KarError::Io(std::io::Error::other("SECRET_PATH_CAPTURE")), + "leleka-kar phase=Verify class=Io kind=Other errno=None\n", + InputBindingError::Read, + ), + ( + KarError::Io(std::io::Error::from_raw_os_error(28)), + "leleka-kar phase=Verify class=Io kind=StorageFull errno=Some(28)\n", + InputBindingError::Read, + ), + ( + KarError::Integrity("KAR full archive SHA-256 mismatch"), + "leleka-kar phase=Verify class=ArchiveSha\n", + InputBindingError::Metadata, + ), + ( + KarError::Profile("SECRET_PATH_CAPTURE"), + "leleka-kar phase=Verify class=Profile\n", + InputBindingError::Metadata, + ), + ] { + let mut bytes = Vec::new(); + kar_diagnostic(&mut bytes, LoadPhase::Verify, &cause); + assert_eq!(String::from_utf8(bytes).unwrap(), expected); + kar_diagnostic(&mut BrokenSink, LoadPhase::Verify, &cause); + assert_eq!(error(cause), typed); + } + let mut bytes = Vec::new(); + assert_eq!( + input_diagnostic( + &mut bytes, + LoadPhase::ReaderDetached, + InputBindingError::Metadata + ), + InputBindingError::Metadata + ); + assert_eq!(bytes, b"leleka-kar phase=ReaderDetached class=Metadata\n"); + assert_eq!( + input_diagnostic( + &mut BrokenSink, + LoadPhase::ReaderDetached, + InputBindingError::Metadata + ), + InputBindingError::Metadata + ); +} + +#[test] +fn pins_match_independent_conversion_receipts() { + fn hex(bytes: &[u8; 32]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + let spec = pinned_profile_spec().unwrap(); + assert_eq!(spec.archive_bytes, 55_295_529_472); + assert_eq!(spec.virtual_f32_bytes, 707_775_598_080); + assert_eq!( + hex(&spec.archive_sha256), + "536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5" + ); + assert_eq!( + hex(&spec.provenance_sha256), + "3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5" + ); + assert_eq!( + hex(&spec.virtual_f32_sha256), + "c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479" + ); + assert_eq!( + hex(&spec.native_shard_sha256[0]), + "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3" + ); + assert_eq!( + hex(&spec.native_shard_sha256[1]), + "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" + ); + assert_eq!( + hex(&spec.parts[0].derived_f32_sha256), + "94f83e0c081fd92a824cb74a0d67c6fc2261af101dee251a411a6bb5f0664681" + ); + assert_eq!( + hex(&spec.parts[1].derived_f32_sha256), + "06623754d1373dd50f21ec99380fb3e7823eb3c9993700ee071965242dc7eb15" + ); + assert_eq!( + pinned_profile().unwrap().native_shard_sha256(), + &NATIVE_DIGESTS + ); +} + +#[test] +fn partitions_cover_exact_rows_and_contiguous_virtual_bytes() { + let spec = pinned_profile_spec().unwrap(); + assert_eq!(spec.parts.len(), 2); + assert_eq!( + spec.parts[0].name, + "per_layer_token_embd.weight#strata-part-001-of-002" + ); + assert_eq!( + spec.parts[1].name, + "per_layer_token_embd.weight#strata-part-002-of-002" + ); + let mut next_row = 0; + let mut next_byte = 502_974_615_040; + for part in &spec.parts { + assert_eq!(part.row_base, next_row); + assert_eq!(part.derived_f32_offset, next_byte); + next_row += part.row_count; + next_byte += part.row_count * 160 * 4; + } + assert_eq!(spec.parts[0].row_count, 200_000_000); + assert_eq!(spec.parts[1].row_count, 120_001_536); + assert_eq!(next_row, PLE_ROWS); + assert_eq!(next_byte, spec.virtual_f32_bytes); +} diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs new file mode 100644 index 00000000..3f267b91 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs @@ -0,0 +1,322 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::{InputBindingError, InputResult, LoadPhase, input_failure}; +#[cfg(target_os = "linux")] +use std::io::Seek; +#[cfg(target_os = "macos")] +use std::{fs::Permissions, os::unix::fs::PermissionsExt}; +#[cfg(any(target_os = "macos", test))] +use std::{ + fs::{self, DirBuilder}, + os::unix::fs::DirBuilderExt, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; +use std::{ + fs::{File, Metadata, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::Path, +}; + +// Linux UAPI values, with macOS values only for the tiny offline unit tests. +#[cfg(target_os = "linux")] +const SOURCE_FLAGS: i32 = 0x20000 | 0x800; // O_NOFOLLOW | O_NONBLOCK +#[cfg(target_os = "macos")] +const SOURCE_FLAGS: i32 = 0x100 | 0x4; // O_NOFOLLOW | O_NONBLOCK +const COPY_BUFFER: usize = 8 * 1024 * 1024; +#[cfg(any(target_os = "macos", test))] +static SEQUENCE: AtomicU64 = AtomicU64::new(1); +type Inode = (u64, u64); +#[derive(Clone, Copy, Debug)] +enum IoPhase { + SourceOpen, + SourceMetadata, + Provenance, + RootMetadata, + RootCanonical, + Create, + DirectoryMetadata, + WriterOpen, + WriterMetadata, + DetachedMetadata, + CopyRead, + CopyWrite, + CopyEof, + Sync, + Seal, + OpenReader, + Unlink, +} + +#[cfg(target_os = "macos")] +struct OwnedCopy { + directory: PathBuf, + path: PathBuf, + directory_inode: Inode, + file_inode: Option, +} + +#[cfg(test)] +mod private_loader_tests { + use super::*; + use std::io::{Cursor, Seek, SeekFrom}; + use std::os::unix::fs::symlink; + + #[test] + fn short_write_diagnostics_preserve_error_and_redact_source() { + struct ShortWriter { + bytes: Vec, + failure: Option, + } + impl Write for ShortWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.bytes.is_empty() { + let count = bytes.len().min(3); + self.bytes.extend_from_slice(&bytes[..count]); + Ok(count) + } else { + Err(self.failure.take().expect("one injected write failure")) + } + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + struct BrokenSink; + impl Write for BrokenSink { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + for (error, expected) in [ + ( + std::io::Error::other("SECRET_OPERATOR_PATH_AND_CAPTURE"), + "leleka-kar phase=CopyWrite kind=Other errno=None\n", + ), + ( + std::io::Error::from_raw_os_error(28), + "leleka-kar phase=CopyWrite kind=StorageFull errno=Some(28)\n", + ), + ] { + let mut writer = ShortWriter { + bytes: Vec::new(), + failure: Some(error), + }; + let mut captured = Vec::new(); + let result = copy_exact_reporting( + &mut Cursor::new(b"abcdef"), + &mut writer, + 6, + |phase, error| diagnostic(&mut captured, phase, error), + ); + assert!(matches!(result, Err(InputBindingError::Read))); + assert_eq!(writer.bytes, b"abc"); + assert_eq!(captured, expected.as_bytes()); + assert!(!captured.windows(6).any(|w| w == b"SECRET")); + } + let mut writer = ShortWriter { + bytes: Vec::new(), + failure: Some(std::io::Error::other("PRIVATE_ERROR_DETAIL")), + }; + let result = copy_exact_reporting( + &mut Cursor::new(b"abcdef"), + &mut writer, + 6, + |phase, error| diagnostic(&mut BrokenSink, phase, error), + ); + assert!(matches!(result, Err(InputBindingError::Read))); + assert_eq!(writer.bytes, b"abc"); + } + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + let parent = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-loader"); + fs::create_dir_all(&parent).unwrap(); + loop { + let id = SEQUENCE.fetch_add(1, Ordering::Relaxed); + let root = parent.join(format!("test-{}-{id}", std::process::id())); + match DirBuilder::new().mode(0o700).create(&root) { + Ok(()) => return Self(root), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("fixture creation failed: {e}"), + } + } + } + fn source(&self, bytes: &[u8]) -> File { + let path = self.0.join("source.kar"); + fs::write(&path, bytes).unwrap(); + open_regular(&path, Some(bytes.len() as u64)).unwrap() + } + fn children(&self) -> Vec { + fs::read_dir(&self.0) + .unwrap() + .map(|x| x.unwrap().path()) + .collect() + } + } + impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + #[cfg(target_os = "macos")] + fn copy_is_unnamed_readonly_and_independent_of_source() { + let fixture = Fixture::new(); + let source_path = fixture.0.join("source.kar"); + let mut source = fixture.source(b"frozen"); + let source_inode = inode(&source.metadata().unwrap()); + let mut copy = freeze(&mut source, &fixture.0, 6).unwrap(); + assert_ne!(inode(©.metadata().unwrap()), source_inode); + assert_eq!(copy.metadata().unwrap().nlink(), 0); + assert_eq!(copy.metadata().unwrap().mode() & 0o7777, 0o400); + assert_eq!(fixture.children(), vec![source_path.clone()]); + assert!((©).write_all(b"overwrite").is_err()); + fs::write(source_path, b"edited").unwrap(); + let mut content = Vec::new(); + copy.read_to_end(&mut content).unwrap(); + assert_eq!(content, b"frozen"); + } + + #[test] + #[cfg(target_os = "linux")] + fn linux_memfd_snapshot_is_independent_and_irrevocably_sealed() { + use rustix::fs::{SealFlags, fcntl_add_seals, fcntl_get_seals}; + let fixture = Fixture::new(); + let source_path = fixture.0.join("source.kar"); + let mut source = fixture.source(b"frozen"); + let source_inode = inode(&source.metadata().unwrap()); + // A nonexistent staging root proves Linux does not depend on it. + let mut copy = freeze(&mut source, &fixture.0.join("absent"), 6).unwrap(); + assert_ne!(inode(©.metadata().unwrap()), source_inode); + assert_eq!(copy.metadata().unwrap().len(), 6); + assert_eq!(copy.metadata().unwrap().nlink(), 0); + assert_eq!(fixture.children(), vec![source_path.clone()]); + fs::write(&source_path, b"edited").unwrap(); + let mut content = Vec::new(); + copy.read_to_end(&mut content).unwrap(); + assert_eq!(content, b"frozen"); + copy.rewind().unwrap(); + assert!((©).write_all(b"changed").is_err()); + assert!(copy.set_len(7).is_err()); + assert!(copy.set_len(5).is_err()); + let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL; + assert!(fcntl_get_seals(©).unwrap().contains(required)); + // Linux seals are only additive; SEAL prevents even an empty + // alteration request, and the full required set remains intact. + assert!(fcntl_add_seals(©, SealFlags::empty()).is_err()); + assert!(fcntl_get_seals(©).unwrap().contains(required)); + content.clear(); + copy.read_to_end(&mut content).unwrap(); + assert_eq!(content, b"frozen"); + } + + #[test] + fn truncated_or_extra_copy_never_leaves_private_partial() { + for expected in [2, 4] { + let fixture = Fixture::new(); + let mut source = fixture.source(b"abc"); + assert!(freeze(&mut source, &fixture.0, expected).is_err()); + assert_eq!(fixture.children(), vec![fixture.0.join("source.kar")]); + let mut unchanged = Vec::new(); + source.seek(SeekFrom::Start(0)).unwrap(); + source.read_to_end(&mut unchanged).unwrap(); + assert_eq!(unchanged, b"abc"); + } + } + + #[test] + fn exact_copy_checks_eof_and_write_failure() { + assert!(copy_exact(&mut Cursor::new(b"ab"), &mut Vec::new(), 3).is_err()); + assert!(copy_exact(&mut Cursor::new(b"abcd"), &mut Vec::new(), 3).is_err()); + assert!(copy_exact(&mut Cursor::new(b"abc"), &mut &mut [0u8; 1][..], 3).is_err()); + } + + #[test] + fn symlink_nonregular_and_wrong_length_are_refused() { + let fixture = Fixture::new(); + drop(fixture.source(b"abc")); + let link = fixture.0.join("link.kar"); + symlink(fixture.0.join("source.kar"), &link).unwrap(); + assert!(open_regular(&link, Some(3)).is_err()); + assert!(open_regular(&fixture.0, None).is_err()); + assert!(open_regular(&fixture.0.join("source.kar"), Some(2)).is_err()); + let root_link = fixture.0.join("root-link"); + symlink(&fixture.0, &root_link).unwrap(); + #[cfg(target_os = "macos")] + { + assert!(protected_root(&root_link).is_err()); + fs::set_permissions(&fixture.0, Permissions::from_mode(0o755)).unwrap(); + assert!(protected_root(&fixture.0).is_err()); + } + } + + #[test] + #[cfg(target_os = "macos")] + fn failed_directory_cleanup_refuses_and_preserves_other_content() { + let fixture = Fixture::new(); + let uid = fs::metadata(&fixture.0).unwrap().uid(); + let mut own = OwnedCopy::create(&fixture.0, uid).unwrap(); + let writer = own.writer(uid).unwrap(); + drop(writer); + let sentinel = own.directory.join("unowned-sentinel"); + fs::write(&sentinel, b"preserve").unwrap(); + assert_eq!(own.detach(), Err(InputBindingError::Read)); + drop(own); + assert_eq!(fs::read(sentinel).unwrap(), b"preserve"); + } + + #[test] + #[cfg(target_os = "macos")] + fn cleanup_does_not_delete_replaced_file_inode() { + let fixture = Fixture::new(); + let uid = fs::metadata(&fixture.0).unwrap().uid(); + let mut own = OwnedCopy::create(&fixture.0, uid).unwrap(); + let writer = own.writer(uid).unwrap(); + let path = own.path.clone(); + fs::remove_file(&path).unwrap(); + fs::write(&path, b"replacement").unwrap(); + assert_eq!(own.detach(), Err(InputBindingError::Metadata)); + drop(own); + assert_eq!(fs::read(path).unwrap(), b"replacement"); + drop(writer); + } +} + +mod inode_fn; +#[allow(unused_imports)] +use inode_fn::inode; +#[allow(unused_imports)] +use inode_fn::diagnostic; +#[allow(unused_imports)] +use inode_fn::report_io; +#[allow(unused_imports)] +use inode_fn::phase_error; +#[allow(unused_imports)] +pub(super) use inode_fn::provenance_error; +#[allow(unused_imports)] +pub(super) use inode_fn::open_regular; +#[cfg(target_os = "macos")] +#[allow(unused_imports)] +use inode_fn::protected_root; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +pub(super) use inode_fn::freeze; +#[cfg(target_os = "macos")] +#[allow(unused_imports)] +pub(super) use inode_fn::freeze; +mod checked_reader_fn; +#[cfg(target_os = "macos")] +#[allow(unused_imports)] +use checked_reader_fn::checked_reader; +#[allow(unused_imports)] +use checked_reader_fn::copy_exact; +#[allow(unused_imports)] +use checked_reader_fn::copy_exact_reporting; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs new file mode 100644 index 00000000..aa7b9187 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs @@ -0,0 +1,80 @@ +//! Moved out of the parent module by STRA-338: fn checked_reader, fn copy_exact, fn copy_exact_reporting. + +#[allow(unused_imports)] +use super::*; + + +#[cfg(target_os = "macos")] +pub(super) fn checked_reader(own: &OwnedCopy, bytes: u64) -> InputResult { + let reader = OpenOptions::new() + .read(true) + .custom_flags(SOURCE_FLAGS) + .open(&own.path) + .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + let meta = reader + .metadata() + .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + // Preserve open_regular's exact file/length refusal separately from + // the existing inode/mode/link checks below. + if !meta.is_file() || meta.len() != bytes { + return Err(input_failure( + LoadPhase::ReaderLength, + InputBindingError::Range, + )); + } + if Some(inode(&meta)) != own.file_inode + || meta.mode() & 0o7777 != 0o400 + || meta.nlink() != 1 + { + return Err(input_failure( + LoadPhase::ReaderIdentity, + InputBindingError::Metadata, + )); + } + Ok(reader) +} + +pub(super) fn copy_exact( + source: &mut R, + destination: &mut W, + bytes: u64, +) -> InputResult<()> { + copy_exact_reporting(source, destination, bytes, report_io) +} + +pub(super) fn copy_exact_reporting( + source: &mut R, + destination: &mut W, + bytes: u64, + mut report: F, +) -> InputResult<()> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(COPY_BUFFER) + .map_err(|_| input_failure(LoadPhase::CopyAllocation, InputBindingError::Allocation))?; + buffer.resize(COPY_BUFFER, 0); + let mut remaining = bytes; + while remaining != 0 { + let count = remaining.min(COPY_BUFFER as u64) as usize; + source.read_exact(&mut buffer[..count]).map_err(|e| { + report(IoPhase::CopyRead, &e); + InputBindingError::Read + })?; + destination.write_all(&buffer[..count]).map_err(|e| { + report(IoPhase::CopyWrite, &e); + InputBindingError::Read + })?; + remaining -= count as u64; + } + if source.read(&mut buffer[..1]).map_err(|e| { + report(IoPhase::CopyEof, &e); + InputBindingError::Read + })? != 0 + { + return Err(input_failure( + LoadPhase::CopyTrailingBytes, + InputBindingError::Range, + )); + } + Ok(()) +} diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode_fn.rs new file mode 100644 index 00000000..6d925edd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode_fn.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: fn inode, fn diagnostic, fn report_io, fn phase_error, fn provenance_error, fn open_regular .... + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn inode(meta: &Metadata) -> Inode { + (meta.dev(), meta.ino()) +} + +// ErrorDisplay can contain an operator path or arbitrary source text. +// Only a closed phase/kind and numeric OS code reach this diagnostic. +pub(super) fn diagnostic(sink: &mut W, phase: IoPhase, error: &std::io::Error) { + let _ = writeln!( + sink, + "leleka-kar phase={phase:?} kind={:?} errno={:?}", + error.kind(), + error.raw_os_error() + ); +} +pub(super) fn report_io(phase: IoPhase, error: &std::io::Error) { + diagnostic(&mut std::io::stderr().lock(), phase, error); +} +pub(super) fn phase_error(phase: IoPhase, error: std::io::Error) -> InputBindingError { + report_io(phase, &error); + InputBindingError::Read +} +pub(in super::super) fn provenance_error(error: std::io::Error) -> InputBindingError { + phase_error(IoPhase::Provenance, error) +} + +pub(in super::super) fn open_regular(path: &Path, bytes: Option) -> InputResult { + let file = OpenOptions::new() + .read(true) + .custom_flags(SOURCE_FLAGS) + .open(path) + .map_err(|e| phase_error(IoPhase::SourceOpen, e))?; + let meta = file + .metadata() + .map_err(|e| phase_error(IoPhase::SourceMetadata, e))?; + if !meta.is_file() || bytes.is_some_and(|size| meta.len() != size) { + return Err(InputBindingError::Range); + } + Ok(file) +} + +#[cfg(target_os = "macos")] +pub(super) fn protected_root(path: &Path) -> InputResult<(PathBuf, u32)> { + let meta = fs::symlink_metadata(path).map_err(|e| phase_error(IoPhase::RootMetadata, e))?; + if !meta.is_dir() || meta.permissions().mode() & 0o7777 != 0o700 { + return Err(input_failure( + LoadPhase::RootMode, + InputBindingError::Metadata, + )); + } + let canonical = path + .canonicalize() + .map_err(|e| phase_error(IoPhase::RootCanonical, e))?; + if inode(&meta) + != inode(&fs::metadata(&canonical).map_err(|e| phase_error(IoPhase::RootMetadata, e))?) + { + return Err(input_failure( + LoadPhase::RootIdentity, + InputBindingError::Metadata, + )); + } + Ok((canonical, meta.uid())) +} +#[cfg(target_os = "macos")] +impl OwnedCopy { + pub(super) fn create(root: &Path, uid: u32) -> InputResult { + for _ in 0..128 { + let serial = SEQUENCE.fetch_add(1, Ordering::Relaxed); + let directory = root.join(format!(".leleka-kar-{}-{serial}", std::process::id())); + match DirBuilder::new().mode(0o700).create(&directory) { + Ok(()) => return Self::created(directory, uid), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(phase_error(IoPhase::Create, e)), + } + } + Err(InputBindingError::Busy) + } + + pub(super) fn created(directory: PathBuf, uid: u32) -> InputResult { + let meta = fs::symlink_metadata(&directory) + .map_err(|e| phase_error(IoPhase::DirectoryMetadata, e))?; + let own = Self { + path: directory.join("archive.kar"), + directory, + directory_inode: inode(&meta), + file_inode: None, + }; + if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o7777 != 0o700 { + return Err(input_failure( + LoadPhase::DirectoryIdentity, + InputBindingError::Metadata, + )); + } + Ok(own) + } + + pub(super) fn writer(&mut self, uid: u32) -> InputResult { + let file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(SOURCE_FLAGS) + .open(&self.path) + .map_err(|e| phase_error(IoPhase::WriterOpen, e))?; + let meta = file + .metadata() + .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; + self.file_inode = Some(inode(&meta)); + if !meta.is_file() + || meta.uid() != uid + || meta.mode() & 0o7777 != 0o600 + || meta.nlink() != 1 + { + return Err(input_failure( + LoadPhase::WriterIdentity, + InputBindingError::Metadata, + )); + } + Ok(file) + } + + pub(super) fn detach(&mut self) -> InputResult<()> { + if !self.owns_directory() || !self.owns_file() { + return Err(input_failure( + LoadPhase::DetachIdentity, + InputBindingError::Metadata, + )); + } + fs::remove_file(&self.path).map_err(|e| phase_error(IoPhase::Unlink, e))?; + self.file_inode = None; + fs::remove_dir(&self.directory).map_err(|e| phase_error(IoPhase::Unlink, e))?; + Ok(()) + } + pub(super) fn owns_directory(&self) -> bool { + fs::symlink_metadata(&self.directory) + .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) + } + pub(super) fn owns_file(&self) -> bool { + fs::symlink_metadata(&self.path) + .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) + } +} +#[cfg(target_os = "macos")] +impl Drop for OwnedCopy { + fn drop(&mut self) { + if self.owns_directory() { + if self.owns_file() { + let _ = fs::remove_file(&self.path); + } + let _ = fs::remove_dir(&self.directory); + } + } +} + +#[cfg(target_os = "linux")] +pub(in super::super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64) -> InputResult { + use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create}; + // Safe OwnedFd -> File conversion transfers ownership exactly once. + // No pathname, filesystem quota, permission change or privileged call + // is needed. Unsupported/failed sealing refuses admission outright. + let fd = memfd_create( + "leleka-kar", + MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, + ) + .map_err(|e| phase_error(IoPhase::Create, e.into()))?; + let mut writer = File::from(fd); + copy_exact(source, &mut writer, bytes)?; + writer + .sync_all() + .map_err(|e| phase_error(IoPhase::Sync, e))?; + let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL; + fcntl_add_seals(&writer, required).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; + let actual = fcntl_get_seals(&writer).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; + if !actual.contains(required) { + return Err(input_failure( + LoadPhase::ReaderIdentity, + InputBindingError::Metadata, + )); + } + let meta = writer + .metadata() + .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; + if !meta.is_file() || meta.len() != bytes { + return Err(input_failure( + LoadPhase::ReaderLength, + InputBindingError::Range, + )); + } + if meta.nlink() != 0 { + return Err(input_failure( + LoadPhase::ReaderDetached, + InputBindingError::Metadata, + )); + } + // A cloned descriptor retains the same sealed inode. Its access mode + // cannot bypass the kernel seals. Close the copy writer before return. + let mut reader = writer + .try_clone() + .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + drop(writer); + reader + .rewind() + .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + Ok(reader) +} + +#[cfg(target_os = "macos")] +pub(in super::super) fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult { + let (root, uid) = protected_root(owner_root)?; + let mut own = OwnedCopy::create(&root, uid)?; + let mut writer = own.writer(uid)?; + copy_exact(source, &mut writer, bytes)?; + writer + .sync_all() + .map_err(|e| phase_error(IoPhase::Sync, e))?; + writer + .set_permissions(Permissions::from_mode(0o400)) + .map_err(|e| phase_error(IoPhase::Seal, e))?; + let reader = checked_reader(&own, bytes)?; + drop(writer); + own.detach()?; + if reader + .metadata() + .map_err(|e| phase_error(IoPhase::DetachedMetadata, e))? + .nlink() + != 0 + { + return Err(input_failure( + LoadPhase::ReaderDetached, + InputBindingError::Metadata, + )); + } + Ok(reader) +} diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs new file mode 100644 index 00000000..aee07cf6 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs @@ -0,0 +1,122 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::{InputBindingError, InputResult}; +use std::{ + fs::File, + os::windows::fs::{FileExt, OpenOptionsExt}, + path::Path, +}; + +const FILE_SHARE_READ: u32 = 1; +const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + +pub(super) fn io_error(error: std::io::Error) -> InputBindingError { + // Only a closed kind and the numeric OS code reach the diagnostic, never a path. + eprintln!("leleka-kar kind={:?} os_error={:?}", error.kind(), error.raw_os_error()); + InputBindingError::Read +} + +/// A regular file opened for reading; other readers are allowed, writers are not, reparse points are not followed. +pub(super) fn open_regular(path: &Path) -> InputResult { + let file = std::fs::OpenOptions::new() + .read(true) + .share_mode(FILE_SHARE_READ) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) + .map_err(io_error)?; + let meta = file.metadata().map_err(io_error)?; + if !meta.is_file() { + return Err(InputBindingError::Range); + } + Ok(file) +} + +pub(super) fn open_read_only_archive(path: &Path, expected_bytes: u64) -> InputResult { + let file = open_regular(path)?; + check_len(&file, expected_bytes)?; + Ok(file) +} + +fn check_len(file: &File, expected_bytes: u64) -> InputResult<()> { + let meta = file.metadata().map_err(io_error)?; + if !meta.is_file() || meta.len() != expected_bytes { + return Err(InputBindingError::Range); + } + Ok(()) +} + +/// An independent handle on the admitted archive (reads are positional, so the shared pointer is irrelevant). +pub(super) fn reopen_read_only_archive(source: &File, expected_bytes: u64) -> InputResult { + let file = source.try_clone().map_err(io_error)?; + check_len(&file, expected_bytes)?; + Ok(file) +} + +pub(super) fn read_exact_at(file: &File, mut buffer: &mut [u8], mut offset: u64) -> std::io::Result<()> { + while !buffer.is_empty() { + let count = file.seek_read(buffer, offset)?; + if count == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + buffer = &mut buffer[count..]; + offset += count as u64; + } + Ok(()) +} + +pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> { + use sha2::{Digest, Sha256}; + let length = file.metadata().map_err(io_error)?.len(); + if length == 0 || length > 1024 * 1024 { + return Err(InputBindingError::Range); + } + let mut digest = Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + let mut offset = 0u64; + while offset < length { + let count = usize::try_from((length - offset).min(buffer.len() as u64)) + .map_err(|_| InputBindingError::Range)?; + read_exact_at(file, &mut buffer[..count], offset).map_err(io_error)?; + digest.update(&buffer[..count]); + offset += count as u64; + } + if file.metadata().map_err(io_error)?.len() != length || digest.finalize().as_slice() != expected_digest { + return Err(InputBindingError::Metadata); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_regular_file_of_the_wrong_length_is_refused_and_reads_are_positional() { + let dir = std::env::temp_dir().join(format!("leleka-kar-win-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.bin"); + std::fs::write(&path, b"abc").unwrap(); + assert!(open_read_only_archive(&path, 3).is_ok()); + assert!(matches!(open_read_only_archive(&path, 4), Err(InputBindingError::Range))); + let file = open_regular(&path).unwrap(); + let mut buffer = [0u8; 2]; + read_exact_at(&file, &mut buffer, 1).unwrap(); + assert_eq!(&buffer, b"bc"); + assert!(read_exact_at(&file, &mut buffer, 2).is_err()); + drop(file); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn the_share_mode_keeps_writers_out_while_the_archive_is_open() { + let dir = std::env::temp_dir().join(format!("leleka-kar-win-share-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("b.bin"); + std::fs::write(&path, b"abc").unwrap(); + let file = open_regular(&path).unwrap(); + assert!(std::fs::OpenOptions::new().write(true).open(&path).is_err()); + drop(file); + assert!(std::fs::OpenOptions::new().write(true).open(&path).is_ok()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs index 9c3648bb..c1c674b3 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs @@ -606,485 +606,12 @@ pub(crate) struct MtpWeights { /// writer out for as long as the handle lives, its length is checked and its SHA-256 is verified in place; that /// handle is the owner (the Linux form verifies a private frozen copy instead). `owner_root` is not used. #[cfg(target_os = "windows")] -mod backing { - use super::*; - use sha2::{Digest, Sha256}; - use std::os::windows::fs::{FileExt, OpenOptionsExt}; - const SCRATCH: usize = 8 * 1024 * 1024; - const FILE_SHARE_READ: u32 = 1; - const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; - - pub(super) fn read_exact_at(file: &File, mut buffer: &mut [u8], mut offset: u64) -> std::io::Result<()> { - while !buffer.is_empty() { - let count = file.seek_read(buffer, offset)?; - if count == 0 { - return Err(std::io::ErrorKind::UnexpectedEof.into()); - } - buffer = &mut buffer[count..]; - offset += count as u64; - } - Ok(()) - } - fn regular(path: &Path, bytes: u64) -> InputResult { - let file = std::fs::OpenOptions::new() - .read(true) - .share_mode(FILE_SHARE_READ) - .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) - .open(path) - .map_err(|_| InputBindingError::Read)?; - let m = file.metadata().map_err(|_| InputBindingError::Read)?; - if !m.is_file() || m.len() != bytes { - return Err(InputBindingError::Metadata); - } - Ok(file) - } - pub(super) fn freeze_file( - source: &Path, - _owner_root: &Path, - pin: (&str, u64, &str), - ) -> InputResult { - let directory = std::fs::symlink_metadata(source).map_err(|_| InputBindingError::Read)?; - if !directory.is_dir() || directory.file_type().is_symlink() { - return Err(InputBindingError::Metadata); - } - let file = regular(&source.join(pin.0), pin.1)?; - verify(&file, pin.1, pin.2)?; - Ok(file) - } - fn verify(file: &File, bytes: u64, pin: &str) -> InputResult<()> { - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(SCRATCH) - .map_err(|_| InputBindingError::Allocation)?; - buffer.resize(SCRATCH, 0); - let mut hasher = Sha256::new(); - let mut offset = 0u64; - while offset != bytes { - let n = (bytes - offset).min(SCRATCH as u64) as usize; - read_exact_at(file, &mut buffer[..n], offset).map_err(|_| InputBindingError::Read)?; - hasher.update(&buffer[..n]); - offset += n as u64; - } - let actual: [u8; 32] = hasher.finalize().into(); - let mut expected = [0u8; 32]; - if pin.len() != 64 { - return Err(InputBindingError::Metadata); - } - for (i, byte) in expected.iter_mut().enumerate() { - *byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16) - .map_err(|_| InputBindingError::Metadata)?; - } - if actual != expected { - return Err(InputBindingError::Metadata); - } - Ok(()) - } - - #[cfg(test)] - mod tests { - use super::*; - #[test] - fn a_file_of_the_wrong_length_or_digest_is_refused_and_writers_are_kept_out() { - let dir = std::env::temp_dir().join(format!("leleka-mtp-win-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("w.bin"), b"abc").unwrap(); - // sha256("abc") - let good = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - let file = freeze_file(&dir, &dir, ("w.bin", 3, good)).unwrap(); - assert!(std::fs::OpenOptions::new().write(true).open(dir.join("w.bin")).is_err()); - drop(file); - assert!(matches!(freeze_file(&dir, &dir, ("w.bin", 4, good)), Err(InputBindingError::Metadata))); - assert!(matches!( - freeze_file(&dir, &dir, ("w.bin", 3, &good.replace("ba78", "ba79"))), - Err(InputBindingError::Metadata) - )); - std::fs::remove_dir_all(&dir).unwrap(); - } - } -} +#[path = "qwen4exp_mtp/backing.rs"] +mod backing; #[cfg(any(target_os = "linux", all(test, target_os = "macos")))] -mod backing { - use super::*; - use sha2::{Digest, Sha256}; - use std::io::Read; - use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; - use std::{ - fs::{self, DirBuilder, OpenOptions, Permissions}, - io::Write, - path::PathBuf, - sync::atomic::{AtomicU64, Ordering}, - }; - const SCRATCH: usize = 8 * 1024 * 1024; - #[cfg(target_os = "linux")] - const FLAGS: i32 = 0x20000 | 0x800; // O_NOFOLLOW | O_NONBLOCK - #[cfg(target_os = "macos")] - const FLAGS: i32 = 0x100 | 0x4; - static SERIAL: AtomicU64 = AtomicU64::new(0); - type Inode = (u64, u64); - fn inode(m: &fs::Metadata) -> Inode { - (m.dev(), m.ino()) - } - fn regular(path: &Path, bytes: u64) -> InputResult { - let file = OpenOptions::new() - .read(true) - .custom_flags(FLAGS) - .open(path) - .map_err(|_| InputBindingError::Read)?; - let m = file.metadata().map_err(|_| InputBindingError::Read)?; - if !m.is_file() || m.len() != bytes { - return Err(InputBindingError::Metadata); - } - Ok(file) - } - fn root(path: &Path) -> InputResult<(PathBuf, u32)> { - let m = fs::symlink_metadata(path).map_err(|_| InputBindingError::Read)?; - if !m.is_dir() || m.file_type().is_symlink() || m.mode() & 0o7777 != 0o700 { - return Err(InputBindingError::Metadata); - } - let canonical = path.canonicalize().map_err(|_| InputBindingError::Read)?; - if inode(&m) != inode(&fs::metadata(&canonical).map_err(|_| InputBindingError::Read)?) { - return Err(InputBindingError::Metadata); - } - Ok((canonical, m.uid())) - } - struct OwnedCopy { - directory: PathBuf, - path: PathBuf, - directory_inode: Inode, - file_inode: Option, - } - impl OwnedCopy { - fn create(root: &Path, uid: u32) -> InputResult { - for _ in 0..128 { - let serial = SERIAL.fetch_add(1, Ordering::Relaxed); - let directory = root.join(format!(".leleka-mtp-{}-{serial}", std::process::id())); - match DirBuilder::new().mode(0o700).create(&directory) { - Ok(()) => { - let m = fs::symlink_metadata(&directory) - .map_err(|_| InputBindingError::Read)?; - let own = Self { - path: directory.join("weights"), - directory, - directory_inode: inode(&m), - file_inode: None, - }; - if !m.is_dir() || m.uid() != uid || m.mode() & 0o7777 != 0o700 { - return Err(InputBindingError::Metadata); - } - return Ok(own); - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(_) => return Err(InputBindingError::Read), - } - } - Err(InputBindingError::Busy) - } - fn writer(&mut self, uid: u32) -> InputResult { - let f = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .custom_flags(FLAGS) - .open(&self.path) - .map_err(|_| InputBindingError::Read)?; - let m = f.metadata().map_err(|_| InputBindingError::Read)?; - self.file_inode = Some(inode(&m)); - if !m.is_file() || m.uid() != uid || m.nlink() != 1 || m.mode() & 0o7777 != 0o600 { - return Err(InputBindingError::Metadata); - } - Ok(f) - } - fn owns_directory(&self) -> bool { - fs::symlink_metadata(&self.directory) - .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) - } - fn owns_file(&self) -> bool { - fs::symlink_metadata(&self.path) - .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) - } - fn detach(&mut self) -> InputResult<()> { - if !self.owns_directory() || !self.owns_file() { - return Err(InputBindingError::Metadata); - } - fs::remove_file(&self.path).map_err(|_| InputBindingError::Read)?; - self.file_inode = None; - fs::remove_dir(&self.directory).map_err(|_| InputBindingError::Read) - } - } - impl Drop for OwnedCopy { - fn drop(&mut self) { - if self.owns_directory() { - if self.owns_file() { - let _ = fs::remove_file(&self.path); - } - let _ = fs::remove_dir(&self.directory); - } - } - } - fn copy_exact( - source: &mut R, - destination: &mut W, - bytes: u64, - ) -> InputResult<()> { - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(SCRATCH) - .map_err(|_| InputBindingError::Allocation)?; - buffer.resize(SCRATCH, 0); - let mut remaining = bytes; - while remaining != 0 { - let n = remaining.min(SCRATCH as u64) as usize; - source - .read_exact(&mut buffer[..n]) - .map_err(|_| InputBindingError::Read)?; - destination - .write_all(&buffer[..n]) - .map_err(|_| InputBindingError::Read)?; - remaining -= n as u64; - } - if source - .read(&mut buffer[..1]) - .map_err(|_| InputBindingError::Read)? - != 0 - { - return Err(InputBindingError::Range); - } - Ok(()) - } - fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult { - let (root, uid) = root(owner_root)?; - let mut own = OwnedCopy::create(&root, uid)?; - let mut writer = own.writer(uid)?; - copy_exact(source, &mut writer, bytes)?; - writer.sync_all().map_err(|_| InputBindingError::Read)?; - writer - .set_permissions(Permissions::from_mode(0o400)) - .map_err(|_| InputBindingError::Read)?; - let reader = regular(&own.path, bytes)?; - let m = reader.metadata().map_err(|_| InputBindingError::Read)?; - if Some(inode(&m)) != own.file_inode || m.mode() & 0o7777 != 0o400 || m.nlink() != 1 { - return Err(InputBindingError::Metadata); - } - drop(writer); - own.detach()?; - if reader - .metadata() - .map_err(|_| InputBindingError::Read)? - .nlink() - != 0 - { - return Err(InputBindingError::Metadata); - } - Ok(reader) - } - pub(super) fn freeze_file( - source: &Path, - owner_root: &Path, - pin: (&str, u64, &str), - ) -> InputResult { - let directory = fs::symlink_metadata(source).map_err(|_| InputBindingError::Read)?; - if !directory.is_dir() || directory.file_type().is_symlink() { - return Err(InputBindingError::Metadata); - } - let mut original = regular(&source.join(pin.0), pin.1)?; - let mut frozen = freeze(&mut original, owner_root, pin.1)?; - verify(&mut frozen, pin.1, pin.2)?; - Ok(frozen) - } - fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> { - use std::io::{Seek, SeekFrom}; - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(SCRATCH) - .map_err(|_| InputBindingError::Allocation)?; - buffer.resize(SCRATCH, 0); - file.seek(SeekFrom::Start(0)) - .map_err(|_| InputBindingError::Read)?; - let mut hasher = Sha256::new(); - let mut remaining = bytes; - while remaining != 0 { - let n = remaining.min(SCRATCH as u64) as usize; - file.read_exact(&mut buffer[..n]) - .map_err(|_| InputBindingError::Read)?; - hasher.update(&buffer[..n]); - remaining -= n as u64; - } - if file - .read(&mut buffer[..1]) - .map_err(|_| InputBindingError::Read)? - != 0 - { - return Err(InputBindingError::Range); - } - let actual: [u8; 32] = hasher.finalize().into(); - let mut expected = [0u8; 32]; - if pin.len() != 64 { - return Err(InputBindingError::Metadata); - } - for (i, byte) in expected.iter_mut().enumerate() { - *byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16) - .map_err(|_| InputBindingError::Metadata)?; - } - if actual != expected { - return Err(InputBindingError::Metadata); - } - file.seek(SeekFrom::Start(0)) - .map_err(|_| InputBindingError::Read)?; - Ok(()) - } - - #[cfg(test)] - mod tests { - use super::*; - use std::io::{Cursor, Seek, SeekFrom}; - struct Fixture(PathBuf); - impl Fixture { - fn new() -> Self { - let parent = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra169-mtp-binder"); - fs::create_dir_all(&parent).unwrap(); - loop { - let root = parent.join(format!( - "tiny-{}-{}", - std::process::id(), - SERIAL.fetch_add(1, Ordering::Relaxed) - )); - match DirBuilder::new().mode(0o700).create(&root) { - Ok(()) => return Self(root), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => panic!("fixture: {e}"), - } - } - } - fn source(&self) -> File { - fs::write(self.0.join("source"), b"abc").unwrap(); - regular(&self.0.join("source"), 3).unwrap() - } - } - impl Drop for Fixture { - fn drop(&mut self) { - fs::remove_dir_all(&self.0).unwrap(); - } - } - #[test] - fn frozen_same_fd_hash_owner_and_source_independence() { - let f = Fixture::new(); - let mut source = f.source(); - let original = inode(&source.metadata().unwrap()); - let mut frozen = freeze(&mut source, &f.0, 3).unwrap(); - assert_ne!(inode(&frozen.metadata().unwrap()), original); - assert_eq!(frozen.metadata().unwrap().nlink(), 0); - assert_eq!(frozen.metadata().unwrap().mode() & 0o7777, 0o400); - assert!((&frozen).write_all(b"replace").is_err()); - fs::write(f.0.join("source"), b"new").unwrap(); - assert_eq!(read_exact_range(&frozen, 0, 3).unwrap(), b"abc"); - verify( - &mut frozen, - 3, - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", - ) - .unwrap(); - assert_eq!( - verify(&mut frozen, 3, &"0".repeat(64)), - Err(InputBindingError::Metadata) - ); - assert_eq!(fs::read_dir(&f.0).unwrap().count(), 1); - } - #[test] - fn copy_short_extra_write_failures_leave_no_owners() { - let f = Fixture::new(); - for bytes in [2, 4] { - let mut source = f.source(); - assert!(freeze(&mut source, &f.0, bytes).is_err()); - assert_eq!(fs::read_dir(&f.0).unwrap().count(), 1); - } - assert!(copy_exact(&mut Cursor::new(b"abc"), &mut &mut [0u8; 1][..], 3).is_err()); - } - #[test] - fn symlink_length_root_permission_and_hash_fail_closed() { - use std::os::unix::fs::symlink; - let f = Fixture::new(); - drop(f.source()); - symlink(f.0.join("source"), f.0.join("link")).unwrap(); - assert!(regular(&f.0.join("link"), 3).is_err()); - assert!(regular(&f.0, 3).is_err()); - assert!(regular(&f.0.join("source"), 4).is_err()); - symlink(&f.0, f.0.join("root-link")).unwrap(); - assert!(root(&f.0.join("root-link")).is_err()); - assert!(freeze_file(&f.0, &f.0, ("source", 3, &"0".repeat(64))).is_err()); - assert_eq!(fs::read_dir(&f.0).unwrap().count(), 3); - fs::set_permissions(&f.0, Permissions::from_mode(0o755)).unwrap(); - assert!(root(&f.0).is_err()); - } - #[test] - fn failed_cleanup_or_replaced_inode_never_deletes_unowned_file() { - let f = Fixture::new(); - let uid = fs::metadata(&f.0).unwrap().uid(); - let mut own = OwnedCopy::create(&f.0, uid).unwrap(); - drop(own.writer(uid).unwrap()); - let sentinel = own.directory.join("sentinel"); - fs::write(&sentinel, b"keep").unwrap(); - assert_eq!(own.detach(), Err(InputBindingError::Read)); - drop(own); - assert_eq!(fs::read(&sentinel).unwrap(), b"keep"); - let mut own = OwnedCopy::create(&f.0, uid).unwrap(); - let mut writer = own.writer(uid).unwrap(); - writer.write_all(b"old").unwrap(); - writer.seek(SeekFrom::Start(0)).unwrap(); - let replaced = own.path.clone(); - fs::remove_file(&replaced).unwrap(); - fs::write(&replaced, b"keep").unwrap(); - assert_eq!(own.detach(), Err(InputBindingError::Metadata)); - drop(writer); - drop(own); - assert_eq!(fs::read(replaced).unwrap(), b"keep"); - } - #[test] - fn real_plane_reader_selects_expert_gate_up_down_and_last_rows() { - // An unverified synthetic plane file tests layout only; it never - // becomes MtpWeights or a serving capability. - let f = Fixture::new(); - let file = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .open(f.0.join("planes")) - .unwrap(); - file.set_len(2 * EXPERT_BLOB).unwrap(); - use std::os::unix::fs::FileExt; - let cases = [ - (MtpExpertMatrix::Gate, 0, 0u64, 1_228_800u64, 40, 11u8), - (MtpExpertMatrix::Up, 0, 640, 1_228_880, 40, 22), - (MtpExpertMatrix::Gate, 639, 817_920, 1_331_040, 40, 33), - (MtpExpertMatrix::Up, 639, 818_560, 1_331_120, 40, 44), - (MtpExpertMatrix::Down, 2559, 1_228_640, 1_382_380, 10, 55), - ]; - for expert in 0..2u32 { - let base = u64::from(expert) * EXPERT_BLOB; - for &(_, _, code, scale, blocks, value) in &cases { - file.write_all_at(&vec![value + expert as u8; blocks * 16], base + code) - .unwrap(); - file.write_all_at(&[0, 0x3c].repeat(blocks), base + scale) - .unwrap(); - } - } - for expert in 0..2 { - for &(matrix, row, _, _, blocks, value) in &cases { - let result = read_expert_rows(&file, expert, matrix, row, 1).unwrap(); - let mut one = vec![0, 0x3c]; - one.extend(vec![value + expert as u8; 16]); - assert_eq!(result.bytes(), one.repeat(blocks)); - assert_eq!(result.kind(), MtpKind::Q2_0); - assert_eq!(result.rows(), 1); - } - } - assert!(read_expert_rows(&file, 512, MtpExpertMatrix::Gate, 0, 1).is_err()); - assert!(read_expert_rows(&file, 0, MtpExpertMatrix::Gate, 640, 1).is_err()); - assert!(read_expert_rows(&file, 0, MtpExpertMatrix::Down, 2560, 1).is_err()); - } - } -} +#[path = "qwen4exp_mtp/backing.rs"] +mod backing; #[cfg(test)] #[path = "qwen4exp_mtp/tests.rs"] diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs new file mode 100644 index 00000000..e203c33e --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs @@ -0,0 +1,381 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::{ + fs::{self, DirBuilder, OpenOptions, Permissions}, + io::Write, + path::PathBuf, + sync::atomic::{AtomicU64, Ordering}, +}; +const SCRATCH: usize = 8 * 1024 * 1024; +#[cfg(target_os = "linux")] +const FLAGS: i32 = 0x20000 | 0x800; // O_NOFOLLOW | O_NONBLOCK +#[cfg(target_os = "macos")] +const FLAGS: i32 = 0x100 | 0x4; +static SERIAL: AtomicU64 = AtomicU64::new(0); +type Inode = (u64, u64); +fn inode(m: &fs::Metadata) -> Inode { + (m.dev(), m.ino()) +} +fn regular(path: &Path, bytes: u64) -> InputResult { + let file = OpenOptions::new() + .read(true) + .custom_flags(FLAGS) + .open(path) + .map_err(|_| InputBindingError::Read)?; + let m = file.metadata().map_err(|_| InputBindingError::Read)?; + if !m.is_file() || m.len() != bytes { + return Err(InputBindingError::Metadata); + } + Ok(file) +} +fn root(path: &Path) -> InputResult<(PathBuf, u32)> { + let m = fs::symlink_metadata(path).map_err(|_| InputBindingError::Read)?; + if !m.is_dir() || m.file_type().is_symlink() || m.mode() & 0o7777 != 0o700 { + return Err(InputBindingError::Metadata); + } + let canonical = path.canonicalize().map_err(|_| InputBindingError::Read)?; + if inode(&m) != inode(&fs::metadata(&canonical).map_err(|_| InputBindingError::Read)?) { + return Err(InputBindingError::Metadata); + } + Ok((canonical, m.uid())) +} +struct OwnedCopy { + directory: PathBuf, + path: PathBuf, + directory_inode: Inode, + file_inode: Option, +} +impl OwnedCopy { + fn create(root: &Path, uid: u32) -> InputResult { + for _ in 0..128 { + let serial = SERIAL.fetch_add(1, Ordering::Relaxed); + let directory = root.join(format!(".leleka-mtp-{}-{serial}", std::process::id())); + match DirBuilder::new().mode(0o700).create(&directory) { + Ok(()) => { + let m = fs::symlink_metadata(&directory) + .map_err(|_| InputBindingError::Read)?; + let own = Self { + path: directory.join("weights"), + directory, + directory_inode: inode(&m), + file_inode: None, + }; + if !m.is_dir() || m.uid() != uid || m.mode() & 0o7777 != 0o700 { + return Err(InputBindingError::Metadata); + } + return Ok(own); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(_) => return Err(InputBindingError::Read), + } + } + Err(InputBindingError::Busy) + } + fn writer(&mut self, uid: u32) -> InputResult { + let f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(FLAGS) + .open(&self.path) + .map_err(|_| InputBindingError::Read)?; + let m = f.metadata().map_err(|_| InputBindingError::Read)?; + self.file_inode = Some(inode(&m)); + if !m.is_file() || m.uid() != uid || m.nlink() != 1 || m.mode() & 0o7777 != 0o600 { + return Err(InputBindingError::Metadata); + } + Ok(f) + } + fn owns_directory(&self) -> bool { + fs::symlink_metadata(&self.directory) + .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) + } + fn owns_file(&self) -> bool { + fs::symlink_metadata(&self.path) + .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) + } + fn detach(&mut self) -> InputResult<()> { + if !self.owns_directory() || !self.owns_file() { + return Err(InputBindingError::Metadata); + } + fs::remove_file(&self.path).map_err(|_| InputBindingError::Read)?; + self.file_inode = None; + fs::remove_dir(&self.directory).map_err(|_| InputBindingError::Read) + } +} +impl Drop for OwnedCopy { + fn drop(&mut self) { + if self.owns_directory() { + if self.owns_file() { + let _ = fs::remove_file(&self.path); + } + let _ = fs::remove_dir(&self.directory); + } + } +} +fn copy_exact( + source: &mut R, + destination: &mut W, + bytes: u64, +) -> InputResult<()> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(SCRATCH) + .map_err(|_| InputBindingError::Allocation)?; + buffer.resize(SCRATCH, 0); + let mut remaining = bytes; + while remaining != 0 { + let n = remaining.min(SCRATCH as u64) as usize; + source + .read_exact(&mut buffer[..n]) + .map_err(|_| InputBindingError::Read)?; + destination + .write_all(&buffer[..n]) + .map_err(|_| InputBindingError::Read)?; + remaining -= n as u64; + } + if source + .read(&mut buffer[..1]) + .map_err(|_| InputBindingError::Read)? + != 0 + { + return Err(InputBindingError::Range); + } + Ok(()) +} +fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult { + let (root, uid) = root(owner_root)?; + let mut own = OwnedCopy::create(&root, uid)?; + let mut writer = own.writer(uid)?; + copy_exact(source, &mut writer, bytes)?; + writer.sync_all().map_err(|_| InputBindingError::Read)?; + writer + .set_permissions(Permissions::from_mode(0o400)) + .map_err(|_| InputBindingError::Read)?; + let reader = regular(&own.path, bytes)?; + let m = reader.metadata().map_err(|_| InputBindingError::Read)?; + if Some(inode(&m)) != own.file_inode || m.mode() & 0o7777 != 0o400 || m.nlink() != 1 { + return Err(InputBindingError::Metadata); + } + drop(writer); + own.detach()?; + if reader + .metadata() + .map_err(|_| InputBindingError::Read)? + .nlink() + != 0 + { + return Err(InputBindingError::Metadata); + } + Ok(reader) +} +pub(super) fn freeze_file( + source: &Path, + owner_root: &Path, + pin: (&str, u64, &str), +) -> InputResult { + let directory = fs::symlink_metadata(source).map_err(|_| InputBindingError::Read)?; + if !directory.is_dir() || directory.file_type().is_symlink() { + return Err(InputBindingError::Metadata); + } + let mut original = regular(&source.join(pin.0), pin.1)?; + let mut frozen = freeze(&mut original, owner_root, pin.1)?; + verify(&mut frozen, pin.1, pin.2)?; + Ok(frozen) +} +fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> { + use std::io::{Seek, SeekFrom}; + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(SCRATCH) + .map_err(|_| InputBindingError::Allocation)?; + buffer.resize(SCRATCH, 0); + file.seek(SeekFrom::Start(0)) + .map_err(|_| InputBindingError::Read)?; + let mut hasher = Sha256::new(); + let mut remaining = bytes; + while remaining != 0 { + let n = remaining.min(SCRATCH as u64) as usize; + file.read_exact(&mut buffer[..n]) + .map_err(|_| InputBindingError::Read)?; + hasher.update(&buffer[..n]); + remaining -= n as u64; + } + if file + .read(&mut buffer[..1]) + .map_err(|_| InputBindingError::Read)? + != 0 + { + return Err(InputBindingError::Range); + } + let actual: [u8; 32] = hasher.finalize().into(); + let mut expected = [0u8; 32]; + if pin.len() != 64 { + return Err(InputBindingError::Metadata); + } + for (i, byte) in expected.iter_mut().enumerate() { + *byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16) + .map_err(|_| InputBindingError::Metadata)?; + } + if actual != expected { + return Err(InputBindingError::Metadata); + } + file.seek(SeekFrom::Start(0)) + .map_err(|_| InputBindingError::Read)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Cursor, Seek, SeekFrom}; + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + let parent = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra169-mtp-binder"); + fs::create_dir_all(&parent).unwrap(); + loop { + let root = parent.join(format!( + "tiny-{}-{}", + std::process::id(), + SERIAL.fetch_add(1, Ordering::Relaxed) + )); + match DirBuilder::new().mode(0o700).create(&root) { + Ok(()) => return Self(root), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("fixture: {e}"), + } + } + } + fn source(&self) -> File { + fs::write(self.0.join("source"), b"abc").unwrap(); + regular(&self.0.join("source"), 3).unwrap() + } + } + impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + #[test] + fn frozen_same_fd_hash_owner_and_source_independence() { + let f = Fixture::new(); + let mut source = f.source(); + let original = inode(&source.metadata().unwrap()); + let mut frozen = freeze(&mut source, &f.0, 3).unwrap(); + assert_ne!(inode(&frozen.metadata().unwrap()), original); + assert_eq!(frozen.metadata().unwrap().nlink(), 0); + assert_eq!(frozen.metadata().unwrap().mode() & 0o7777, 0o400); + assert!((&frozen).write_all(b"replace").is_err()); + fs::write(f.0.join("source"), b"new").unwrap(); + assert_eq!(read_exact_range(&frozen, 0, 3).unwrap(), b"abc"); + verify( + &mut frozen, + 3, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ) + .unwrap(); + assert_eq!( + verify(&mut frozen, 3, &"0".repeat(64)), + Err(InputBindingError::Metadata) + ); + assert_eq!(fs::read_dir(&f.0).unwrap().count(), 1); + } + #[test] + fn copy_short_extra_write_failures_leave_no_owners() { + let f = Fixture::new(); + for bytes in [2, 4] { + let mut source = f.source(); + assert!(freeze(&mut source, &f.0, bytes).is_err()); + assert_eq!(fs::read_dir(&f.0).unwrap().count(), 1); + } + assert!(copy_exact(&mut Cursor::new(b"abc"), &mut &mut [0u8; 1][..], 3).is_err()); + } + #[test] + fn symlink_length_root_permission_and_hash_fail_closed() { + use std::os::unix::fs::symlink; + let f = Fixture::new(); + drop(f.source()); + symlink(f.0.join("source"), f.0.join("link")).unwrap(); + assert!(regular(&f.0.join("link"), 3).is_err()); + assert!(regular(&f.0, 3).is_err()); + assert!(regular(&f.0.join("source"), 4).is_err()); + symlink(&f.0, f.0.join("root-link")).unwrap(); + assert!(root(&f.0.join("root-link")).is_err()); + assert!(freeze_file(&f.0, &f.0, ("source", 3, &"0".repeat(64))).is_err()); + assert_eq!(fs::read_dir(&f.0).unwrap().count(), 3); + fs::set_permissions(&f.0, Permissions::from_mode(0o755)).unwrap(); + assert!(root(&f.0).is_err()); + } + #[test] + fn failed_cleanup_or_replaced_inode_never_deletes_unowned_file() { + let f = Fixture::new(); + let uid = fs::metadata(&f.0).unwrap().uid(); + let mut own = OwnedCopy::create(&f.0, uid).unwrap(); + drop(own.writer(uid).unwrap()); + let sentinel = own.directory.join("sentinel"); + fs::write(&sentinel, b"keep").unwrap(); + assert_eq!(own.detach(), Err(InputBindingError::Read)); + drop(own); + assert_eq!(fs::read(&sentinel).unwrap(), b"keep"); + let mut own = OwnedCopy::create(&f.0, uid).unwrap(); + let mut writer = own.writer(uid).unwrap(); + writer.write_all(b"old").unwrap(); + writer.seek(SeekFrom::Start(0)).unwrap(); + let replaced = own.path.clone(); + fs::remove_file(&replaced).unwrap(); + fs::write(&replaced, b"keep").unwrap(); + assert_eq!(own.detach(), Err(InputBindingError::Metadata)); + drop(writer); + drop(own); + assert_eq!(fs::read(replaced).unwrap(), b"keep"); + } + #[test] + fn real_plane_reader_selects_expert_gate_up_down_and_last_rows() { + // An unverified synthetic plane file tests layout only; it never + // becomes MtpWeights or a serving capability. + let f = Fixture::new(); + let file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(f.0.join("planes")) + .unwrap(); + file.set_len(2 * EXPERT_BLOB).unwrap(); + use std::os::unix::fs::FileExt; + let cases = [ + (MtpExpertMatrix::Gate, 0, 0u64, 1_228_800u64, 40, 11u8), + (MtpExpertMatrix::Up, 0, 640, 1_228_880, 40, 22), + (MtpExpertMatrix::Gate, 639, 817_920, 1_331_040, 40, 33), + (MtpExpertMatrix::Up, 639, 818_560, 1_331_120, 40, 44), + (MtpExpertMatrix::Down, 2559, 1_228_640, 1_382_380, 10, 55), + ]; + for expert in 0..2u32 { + let base = u64::from(expert) * EXPERT_BLOB; + for &(_, _, code, scale, blocks, value) in &cases { + file.write_all_at(&vec![value + expert as u8; blocks * 16], base + code) + .unwrap(); + file.write_all_at(&[0, 0x3c].repeat(blocks), base + scale) + .unwrap(); + } + } + for expert in 0..2 { + for &(matrix, row, _, _, blocks, value) in &cases { + let result = read_expert_rows(&file, expert, matrix, row, 1).unwrap(); + let mut one = vec![0, 0x3c]; + one.extend(vec![value + expert as u8; 16]); + assert_eq!(result.bytes(), one.repeat(blocks)); + assert_eq!(result.kind(), MtpKind::Q2_0); + assert_eq!(result.rows(), 1); + } + } + assert!(read_expert_rows(&file, 512, MtpExpertMatrix::Gate, 0, 1).is_err()); + assert!(read_expert_rows(&file, 0, MtpExpertMatrix::Gate, 640, 1).is_err()); + assert!(read_expert_rows(&file, 0, MtpExpertMatrix::Down, 2560, 1).is_err()); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs index b0a23d8a..de5083d5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs @@ -88,161 +88,7 @@ pub(super) struct InjectedResidual { pub(crate) struct GrStage; #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn gr_preflight_keeps_all_inputs_unchanged_on_shape_or_numeric_refusal() { - let mut values = vec![-0.0_f32; 4 * 2560]; - let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); - assert_eq!(validate_streams(&values), Ok(())); - assert_eq!( - validate_streams(&values[..values.len() - 1]), - Err(Error::InvalidDimension) - ); - assert_eq!( - values.iter().map(|v| v.to_bits()).collect::>(), - before - ); - for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - values[10239] = invalid; - let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); - assert_eq!(validate_streams(&values), Err(Error::NonFinite)); - assert_eq!( - values.iter().map(|v| v.to_bits()).collect::>(), - before - ); - } - } - - #[test] - fn gr_layer_identity_cannot_substitute_a_different_verified_extent() { - let layer = LayerId::new(47, Dimension::new(48).unwrap()).unwrap(); - assert_eq!(validate_layer(layer, 48), Ok(())); - assert_eq!(validate_layer(layer, 49), Err(Error::IdentityMismatch)); - assert_eq!(validate_layer(layer, 47), Err(Error::InvalidLayer)); - assert_eq!(validate_layer(layer, 0), Err(Error::InvalidDimension)); - } - - fn identity() -> TokenLayer { - use super::super::contract::{Position, TokenId}; - TokenLayer::new( - TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(), - Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(), - LayerId::new(0, Dimension::new(48).unwrap()).unwrap(), - ) - } - - #[test] - fn gr_candidate_quiet_nan_refuses_late_failure_without_stream_publication() { - let caller = vec![-0.0_f32; 4 * 2560]; - let before: Vec<_> = caller.iter().map(|v| v.to_bits()).collect(); - let mut candidate = vec![1.0_f32; 4 * 2560]; - candidate[10239] = f32::from_bits(0x7fc0_0000); - assert!(matches!( - InjectedResidual::from_candidates( - identity(), - BindingIdentity::test_identity(), - GrRole::Attention(0), - candidate.into_boxed_slice() - ), - Err(Error::NonFinite) - )); - assert_eq!( - caller.iter().map(|v| v.to_bits()).collect::>(), - before - ); - let accepted = InjectedResidual::from_candidates( - identity(), - BindingIdentity::test_identity(), - GrRole::Attention(0), - caller.into_boxed_slice(), - ) - .unwrap(); - assert_eq!( - accepted - .streams() - .iter() - .map(|v| v.to_bits()) - .collect::>(), - before - ); - assert_eq!(accepted.identity(), identity()); - } - - #[test] - fn gr_injected_capability_refuses_cross_model_or_wrong_stage_before_read() { - let binding = BindingIdentity::test_identity(); - let other = BindingIdentity::test_identity(); - let residual = InjectedResidual::from_candidates( - identity(), - binding.clone(), - GrRole::Attention(0), - vec![-0.0; 10240].into_boxed_slice(), - ) - .unwrap(); - assert_eq!( - residual.validate_origin(&binding, GrRole::Attention(0)), - Ok(()) - ); - for wrong in [GrRole::Ffn(0), GrRole::Attention(1), GrRole::Final] { - assert_eq!( - residual.validate_origin(&binding, wrong), - Err(Error::IdentityMismatch) - ); - } - assert_eq!( - residual.validate_origin(&other, GrRole::Attention(0)), - Err(Error::IdentityMismatch) - ); - for role in [GrRole::Attention(1), GrRole::Ffn(1), GrRole::Final] { - assert!(matches!( - InjectedResidual::from_candidates( - identity(), - binding.clone(), - role, - vec![0.0; 10240].into_boxed_slice() - ), - Err(Error::IdentityMismatch) - )); - } - assert!(residual.streams().iter().all(|v| v.to_bits() == 0x80000000)); - } - - #[test] - fn gr_candidate_norm_overflow_oracle_distinguishes_masked_finite_zero() { - // Offline malformed-domain facts, not a per-request CPU norm/reference. - let large = f32::from_bits(0x7f7f_ffff); - let square = large.mul_add(large, 0.0); - assert!(square.is_infinite()); - let masked_native = (1.0 / (square / 2560.0).sqrt()) * large; - assert_eq!(masked_native.to_bits(), 0); - assert_eq!(validate_streams(&vec![masked_native; 4 * 2560]), Ok(())); - assert_eq!( - validate_streams(&vec![f32::from_bits(0x7fc0_0000); 4 * 2560]), - Err(Error::NonFinite) - ); - assert!((1.0_f32 / 0.0_f32.sqrt()).is_infinite()); - } - - #[test] - fn gr_candidate_postop_overflow_oracles_require_signal_not_masked_success() { - // exp(100)>F32_MAX while sigmoid(-100) can hide that overflow as +0. - let exponential = 100.0_f32.exp(); - assert!(exponential.is_infinite()); - assert_eq!((1.0_f32 / (1.0 + exponential)).to_bits(), 0); - let product = f32::from_bits(0x7e96_7699); // 1e38, individually finite. - assert!(product.is_finite()); - let sum = product + product + product + product; - assert!(sum.is_infinite()); - for output in [f32::from_bits(0x7fc0_0000), sum, exponential] { - assert_eq!( - validate_streams(&vec![output; 4 * 2560]), - Err(Error::NonFinite) - ); - } - } -} +mod tests; #[cfg(test)] #[path = "gr_residual_reuse_gpu.rs"] @@ -264,735 +110,7 @@ pub(in crate::qwen_forward) use attention_chunk::DetachedGrRead; mod retained_handoff; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod output_workspace_gpu { - use super::*; - use leleka_cuda_driver::Driver; - - fn fresh_read( - context: &Context<'_>, - residual: &DeviceBuffer<'_>, - weights: &[DeviceBuffer<'_>; 4], - ) -> Result>> { - // Exact compiled289 per-read allocation boundary FIRST, same queued - // kernels and fixed finite guard, never candidate-derived arithmetic. - let mut owned = Vec::new(); - let operation: Result>> = (|| { - for bytes in GR_OUTPUT_BYTES.into_iter().chain([16]) { - owned.push(context.allocate(bytes).map_err(driver_error)?); - } - let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() - else { - return Err(Error::InvalidDimension); - }; - let mask = context - .gr_read_chain_queued( - residual, - &weights[0], - &weights[1], - &weights[2], - 1e-6, - xn, - down, - activated, - gates, - products, - mixed, - ) - .map_err(driver_error)?; - if mask != 0 { - return Err(Error::NonFinite); - } - context - .gr_inject_projection_bf16_f32(&weights[3], xn, injection) - .map_err(driver_error)?; - owned - .iter() - .map(|buffer| { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - Ok(bytes) - }) - .collect::>>() - })(); - let mut cleanup = Ok(()); - for buffer in owned.into_iter().rev() { - let result = buffer.release().map_err(driver_error); - if cleanup.is_ok() { - cleanup = result; - } - } - let value = operation?; - cleanup?; - Ok(value) - } - - fn fresh_inject( - context: &Context<'_>, - residual: &DeviceBuffer<'_>, - block: &[f32], - coefficients: &[f32; 4], - ) -> Result> { - // Original cached injection allocation/upload/kernel/readback FIRST. - let mut owned = Vec::new(); - let operation: Result> = (|| { - owned.push(upload_f32(context, block)?); - owned.push(upload_f32(context, coefficients)?); - owned.push(context.allocate(40960).map_err(driver_error)?); - let [block, coefficients, candidate] = owned.as_mut_slice() else { - return Err(Error::InvalidDimension); - }; - context - .gr_inject_residual_f32(residual, block, coefficients, candidate) - .map_err(driver_error)?; - download_f32(candidate, 10240) - })(); - let mut cleanup = Ok(()); - for buffer in owned.into_iter().rev() { - let result = buffer.release().map_err(driver_error); - if cleanup.is_ok() { - cleanup = result; - } - } - let value = operation?; - cleanup?; - Ok(value) - } - - fn block(pattern: usize) -> Vec { - (0..2560) - .map(|i| { - if pattern == 0 { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - ((i % (13 + pattern)) as f32 - 6.0) / 128.0 - } - }) - .collect() - } - - fn coefficients(expected: &[Vec]) -> Result<[f32; 4]> { - let bytes = expected.get(6).ok_or(Error::InvalidDimension)?; - if bytes.len() != 16 { - return Err(Error::InvalidDimension); - } - Ok(std::array::from_fn(|i| { - f32::from_le_bytes( - bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed four bytes"), - ) - })) - } - - fn streams(pattern: usize) -> Vec { - (0..10240) - .map(|i| { - if pattern == 0 { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - ((i % (19 + pattern)) as f32 - 9.0) / 64.0 - } - }) - .collect() - } - - fn check_handoff<'ctx>( - scratch: &mut GrScratch<'ctx>, - context: &'ctx Context<'ctx>, - binding: &BindingIdentity, - weights: &[DeviceBuffer<'_>; 4], - pattern: usize, - ) -> Result<(usize, usize)> { - let input = streams(pattern); - let block = block(pattern); - let coefficients = [0.5, -0.25, 0.0, 1.0]; - scratch.write(binding, context, &input)?; - // Original fresh allocation/kernel/readback plus canonical host H2D - // FIRST. The following fresh FFN trace cannot come from the candidate. - let reference = fresh_inject(context, scratch.buffer(context)?, &block, &coefficients)?; - scratch.write(binding, context, &reference)?; - let reference_ffn = fresh_read(context, scratch.buffer(context)?, weights)?; - for buffer in scratch - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; - } - scratch - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .copy_from(&f32::NAN.to_le_bytes().repeat(4)) - .map_err(driver_error)?; - for buffer in scratch - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; - } - let actual = retained_handoff::inject_replace_residual( - scratch, - context, - &input, - &block, - &coefficients, - )?; - let resident = download_f32(scratch.buffer(context)?, 10240)?; - let previous = download_f32( - &scratch - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; - let mut differences = 0; - for (left, right) in [ - (&actual[..], &reference[..]), - (&resident[..], &reference[..]), - (&previous[..], &input[..]), - ] { - differences += left - .iter() - .zip(right) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - } - // No host residual upload: the actual swapped producer feeds FFN. - let ffn = read_cached_cuda( - context, - 1e-6, - true, - scratch, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - )?; - let outputs = scratch - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow(); - for (buffer, expected) in outputs.iter().zip(&reference_ffn) { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - } - let injected: Vec = ffn - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injected - .chunks_exact(4) - .zip(reference_ffn[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - if ffn - .mixed - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - != reference_ffn[5] - { - differences += 1; - } - Ok((3 * 10240 + GR_OUTPUT_DEVICE_BYTES / 4 + 4, differences)) - } - - #[test] - #[ignore = "Root-only changed persistent GR outputs, no model/old-suite replay"] - fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GR_OUTPUT_WORKSPACE").as_deref(), - Ok("yes") - ); - let driver = Driver::load().expect("actual driver"); - let device = driver.device(0).expect("device"); - let context = device - .create_context(160 * 1024 * 1024) - .expect("bounded context"); - let foreign = device - .create_context(160 * 1024 * 1024) - .expect("foreign context"); - let binding = BindingIdentity::test_identity(); // CPU owner tag, NOT actual ModelBinding. - let failed = Rc::new(Cell::new(false)); - let mut scratch = None; - let mut matrices = Vec::new(); - let operation: Result<(usize, usize, usize)> = (|| { - scratch = Some(RefCell::new(GrScratch::new_identity( - binding.clone(), - &context, - failed.clone(), - )?)); - matrices.push(upload_f32(&context, &vec![1.0; 10240])?); - for (count, seed) in [(3276800, 0), (3276800, 1), (40960, 2)] { - let values: Vec = (0..count) - .map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }) - .collect(); - matrices.push(upload_bf16(&context, &values)?); - } - let cell = scratch.as_ref().ok_or(Error::CudaExecution)?; - let charged = context.allocated_bytes(); - let mut differences = 0; - let mut words = 0; - let mut guards = 0; - for pattern in [0, 1, 1, 2] { - let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - lease.write(&binding, &context, &streams(pattern))?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; - let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; - let block = block(pattern); - let expected_injected = fresh_inject( - &context, - lease.buffer(&context)?, - &block, - &coefficients(&expected)?, - )?; - // Poison every retained byte BEFORE candidate, proving all - // six fixed outputs overwrite rather than reuse old results. - for buffer in lease - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; - } - lease - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .copy_from(&f32::NAN.to_le_bytes().repeat(4)) - .map_err(driver_error)?; - for buffer in lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; - } - let actual = read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - )?; - let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); - for (buffer, expected) in outputs.iter().zip(&expected) { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - words += bytes.len() / 4; - } - let mixed: Vec = actual.mixed.iter().flat_map(|v| v.to_le_bytes()).collect(); - if mixed != expected[5] { - differences += 1; - } - let injected: Vec = actual - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injected - .chunks_exact(4) - .zip(expected[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - words += 4; - let injected = inject_cached_cuda( - &context, - &lease, - &block, - &actual.inject.ok_or(Error::InvalidDimension)?, - )?; - differences += injected - .iter() - .zip(expected_injected.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - words += injected.len(); - if cell.try_borrow_mut().is_ok() || context.allocated_bytes() != charged { - differences += 1; - } - guards += 1; - drop(outputs); - // No finish/publication: dropping the genuine lease is abort. - drop(lease); - } - let mut lease = cell.borrow_mut(); - let before = context.allocated_bytes(); - for (owner, ctx) in [ - (&BindingIdentity::test_identity(), &context), - (&binding, &foreign), - ] { - if lease.write(owner, ctx, &streams(1)) != Err(Error::IdentityMismatch) { - differences += 1; - } - guards += 1; - } - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; - let held = lease - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - ) - .err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let mut gamma = vec![1.0f32; 10240]; - gamma[10239] = f32::NAN; - matrices[0] - .copy_from( - &gamma - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>(), - ) - .map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - ) - .err() - != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - guards += 1; - matrices[0] - .copy_from(&1.0f32.to_le_bytes().repeat(10240)) - .map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; - lease.write(&binding, &context, &streams(3))?; - let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; - let block = block(3); - let expected_injected = fresh_inject( - &context, - lease.buffer(&context)?, - &block, - &coefficients(&expected)?, - )?; - let recovered = read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - )?; - let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); - for (buffer, expected) in outputs.iter().zip(&expected) { - let mut bytes = vec![0; buffer.len()]; - buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - words += bytes.len() / 4; - } - let injection: Vec = recovered - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injection - .chunks_exact(4) - .zip(expected[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - words += 4; - drop(outputs); - let actual_injected = inject_cached_cuda( - &context, - &lease, - &block, - &recovered.inject.ok_or(Error::InvalidDimension)?, - )?; - differences += actual_injected - .iter() - .zip(expected_injected.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - words += actual_injected.len(); - if context.allocated_bytes() != before { - differences += 1; - } - guards += 1; - let held = lease - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); - if read_cached_cuda( - &context, - 1e-6, - true, - &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], - ) - .err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let held = lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); - if inject_cached_cuda(&context, &lease, &block, &coefficients(&expected)?).err() - != Some(Error::IdentityMismatch) - { - differences += 1; - } - guards += 1; - drop(held); - let before_refusal = download_f32( - &lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; - if inject_cached_cuda(&context, &lease, &block[..2559], &coefficients(&expected)?).err() - != Some(Error::InvalidDimension) - { - differences += 1; - } - guards += 1; - let mut invalid = block.clone(); - invalid[2559] = f32::NAN; - if inject_cached_cuda(&context, &lease, &invalid, &coefficients(&expected)?).err() - != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - guards += 1; - let after_refusal = download_f32( - &lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; - differences += before_refusal - .iter() - .zip(after_refusal.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - for pattern in [0, 1, 1, 2] { - let (checked, different) = - check_handoff(&mut lease, &context, &binding, weights, pattern)?; - words += checked; - differences += different; - if context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { - differences += 1; - } - guards += 1; - } - let sentinel = download_f32(lease.buffer(&context)?, 10240)?; - let input = streams(1); - let block = self::block(1); - let coefficients = [0.5, -0.25, 0.0, 1.0]; - for (ctx, current, expected) in [ - (&foreign, &block[..], Error::IdentityMismatch), - (&context, &block[..2559], Error::InvalidDimension), - ] { - if retained_handoff::inject_replace_residual( - &mut lease, - ctx, - &input, - current, - &coefficients, - ) - .err() - != Some(expected) - { - differences += 1; - } - guards += 1; - } - let mut invalid = block.clone(); - invalid[2559] = f32::NAN; - if retained_handoff::inject_replace_residual( - &mut lease, - &context, - &input, - &invalid, - &coefficients, - ) - .err() - != Some(Error::NonFinite) - { - differences += 1; - } - guards += 1; - let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += sentinel - .iter() - .zip(&after) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - words += 10240; - // Valid finite inputs producing a genuinely nonfinite output must - // refuse BEFORE the residual swap; the current input remains. - let overflow = vec![f32::MAX; 2560]; - if retained_handoff::inject_replace_residual( - &mut lease, &context, &input, &overflow, &[20.0; 4], - ) - .err() - != Some(Error::NonFinite) - || failed.get() - { - differences += 1; - } - let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += input - .iter() - .zip(&after) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - words += 10240; - guards += 1; - // Abort exposes no readiness capability. Next actual call fully - // overwrites the failed candidate and all FFN read outputs. - drop(lease); - let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let (checked, different) = check_handoff(&mut lease, &context, &binding, weights, 3)?; - words += checked; - differences += different; - if context.allocated_bytes() != before || failed.get() { - differences += 1; - } - guards += 1; - drop(lease); - Ok((words, differences, guards)) - })(); - let mut cleanup = Ok(()); - for buffer in matrices.into_iter().rev() { - let result = buffer.release().map_err(driver_error); - if cleanup.is_ok() { - cleanup = result; - } - } - if let Some(scratch) = scratch.take() { - let result = scratch.into_inner().close(); - if cleanup.is_ok() { - cleanup = result; - } - } - drop(scratch); - let allocated = context.allocated_bytes(); - let foreign_allocated = foreign.allocated_bytes(); - let closed = context.close().map_err(driver_error); - let foreign_closed = foreign.close().map_err(driver_error); - let (words, differences, guards) = operation.expect("completed changed boundary"); - cleanup.expect("attempted all resource cleanup"); - closed.expect("context closed"); - foreign_closed.expect("foreign context closed"); - assert_eq!(allocated, 0); - assert_eq!(foreign_allocated, 0); - assert_eq!(words, 564520); - assert_eq!(differences, 0); - assert_eq!(guards, 22); - eprintln!( - "GR_OUTPUT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true full_overwrite=true" - ); - } -} +mod output_workspace_gpu; mod diagnose_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs new file mode 100644 index 00000000..6102ef27 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs @@ -0,0 +1,493 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use leleka_cuda_driver::Driver; + +#[test] +#[ignore = "Root-only changed persistent GR outputs, no model/old-suite replay"] +fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { + assert_eq!( + std::env::var("LELEKA_STRA169_RUN_GR_OUTPUT_WORKSPACE").as_deref(), + Ok("yes") + ); + let driver = Driver::load().expect("actual driver"); + let device = driver.device(0).expect("device"); + let context = device + .create_context(160 * 1024 * 1024) + .expect("bounded context"); + let foreign = device + .create_context(160 * 1024 * 1024) + .expect("foreign context"); + let binding = BindingIdentity::test_identity(); // CPU owner tag, NOT actual ModelBinding. + let failed = Rc::new(Cell::new(false)); + let mut scratch = None; + let mut matrices = Vec::new(); + let operation: Result<(usize, usize, usize)> = (|| { + scratch = Some(RefCell::new(GrScratch::new_identity( + binding.clone(), + &context, + failed.clone(), + )?)); + matrices.push(upload_f32(&context, &vec![1.0; 10240])?); + for (count, seed) in [(3276800, 0), (3276800, 1), (40960, 2)] { + let values: Vec = (0..count) + .map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }) + .collect(); + matrices.push(upload_bf16(&context, &values)?); + } + let cell = scratch.as_ref().ok_or(Error::CudaExecution)?; + let charged = context.allocated_bytes(); + let mut differences = 0; + let mut words = 0; + let mut guards = 0; + for pattern in [0, 1, 1, 2] { + let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + lease.write(&binding, &context, &streams(pattern))?; + let weights: &[DeviceBuffer<'_>; 4] = matrices + .as_slice() + .try_into() + .map_err(|_| Error::InvalidDimension)?; + let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; + let block = block(pattern); + let expected_injected = fresh_inject( + &context, + lease.buffer(&context)?, + &block, + &coefficients(&expected)?, + )?; + // Poison every retained byte BEFORE candidate, proving all + // six fixed outputs overwrite rather than reuse old results. + for buffer in lease + .outputs + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .iter_mut() + { + buffer + .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) + .map_err(driver_error)?; + } + lease + .read_inject + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .copy_from(&f32::NAN.to_le_bytes().repeat(4)) + .map_err(driver_error)?; + for buffer in lease + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .iter_mut() + { + buffer + .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) + .map_err(driver_error)?; + } + let actual = read_cached_cuda( + &context, + 1e-6, + true, + &lease, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + )?; + let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); + for (buffer, expected) in outputs.iter().zip(&expected) { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + differences += bytes + .chunks_exact(4) + .zip(expected.chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + words += bytes.len() / 4; + } + let mixed: Vec = actual.mixed.iter().flat_map(|v| v.to_le_bytes()).collect(); + if mixed != expected[5] { + differences += 1; + } + let injected: Vec = actual + .inject + .ok_or(Error::InvalidDimension)? + .into_iter() + .flat_map(f32::to_le_bytes) + .collect(); + differences += injected + .chunks_exact(4) + .zip(expected[6].chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + words += 4; + let injected = inject_cached_cuda( + &context, + &lease, + &block, + &actual.inject.ok_or(Error::InvalidDimension)?, + )?; + differences += injected + .iter() + .zip(expected_injected.iter()) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + words += injected.len(); + if cell.try_borrow_mut().is_ok() || context.allocated_bytes() != charged { + differences += 1; + } + guards += 1; + drop(outputs); + // No finish/publication: dropping the genuine lease is abort. + drop(lease); + } + let mut lease = cell.borrow_mut(); + let before = context.allocated_bytes(); + for (owner, ctx) in [ + (&BindingIdentity::test_identity(), &context), + (&binding, &foreign), + ] { + if lease.write(owner, ctx, &streams(1)) != Err(Error::IdentityMismatch) { + differences += 1; + } + guards += 1; + } + let weights: &[DeviceBuffer<'_>; 4] = matrices + .as_slice() + .try_into() + .map_err(|_| Error::InvalidDimension)?; + let held = lease + .outputs + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut(); + if read_cached_cuda( + &context, + 1e-6, + true, + &lease, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + ) + .err() + != Some(Error::IdentityMismatch) + { + differences += 1; + } + guards += 1; + drop(held); + let mut gamma = vec![1.0f32; 10240]; + gamma[10239] = f32::NAN; + matrices[0] + .copy_from( + &gamma + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>(), + ) + .map_err(driver_error)?; + let weights: &[DeviceBuffer<'_>; 4] = matrices + .as_slice() + .try_into() + .map_err(|_| Error::InvalidDimension)?; + if read_cached_cuda( + &context, + 1e-6, + true, + &lease, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + ) + .err() + != Some(Error::NonFinite) + || failed.get() + { + differences += 1; + } + guards += 1; + matrices[0] + .copy_from(&1.0f32.to_le_bytes().repeat(10240)) + .map_err(driver_error)?; + let weights: &[DeviceBuffer<'_>; 4] = matrices + .as_slice() + .try_into() + .map_err(|_| Error::InvalidDimension)?; + lease.write(&binding, &context, &streams(3))?; + let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; + let block = block(3); + let expected_injected = fresh_inject( + &context, + lease.buffer(&context)?, + &block, + &coefficients(&expected)?, + )?; + let recovered = read_cached_cuda( + &context, + 1e-6, + true, + &lease, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + )?; + let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); + for (buffer, expected) in outputs.iter().zip(&expected) { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + differences += bytes + .chunks_exact(4) + .zip(expected.chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + words += bytes.len() / 4; + } + let injection: Vec = recovered + .inject + .ok_or(Error::InvalidDimension)? + .into_iter() + .flat_map(f32::to_le_bytes) + .collect(); + differences += injection + .chunks_exact(4) + .zip(expected[6].chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + words += 4; + drop(outputs); + let actual_injected = inject_cached_cuda( + &context, + &lease, + &block, + &recovered.inject.ok_or(Error::InvalidDimension)?, + )?; + differences += actual_injected + .iter() + .zip(expected_injected.iter()) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + words += actual_injected.len(); + if context.allocated_bytes() != before { + differences += 1; + } + guards += 1; + let held = lease + .read_inject + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut(); + if read_cached_cuda( + &context, + 1e-6, + true, + &lease, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + ) + .err() + != Some(Error::IdentityMismatch) + { + differences += 1; + } + guards += 1; + drop(held); + let held = lease + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut(); + if inject_cached_cuda(&context, &lease, &block, &coefficients(&expected)?).err() + != Some(Error::IdentityMismatch) + { + differences += 1; + } + guards += 1; + drop(held); + let before_refusal = download_f32( + &lease + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow()[2], + 10240, + )?; + if inject_cached_cuda(&context, &lease, &block[..2559], &coefficients(&expected)?).err() + != Some(Error::InvalidDimension) + { + differences += 1; + } + guards += 1; + let mut invalid = block.clone(); + invalid[2559] = f32::NAN; + if inject_cached_cuda(&context, &lease, &invalid, &coefficients(&expected)?).err() + != Some(Error::NonFinite) + || failed.get() + { + differences += 1; + } + guards += 1; + let after_refusal = download_f32( + &lease + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow()[2], + 10240, + )?; + differences += before_refusal + .iter() + .zip(after_refusal.iter()) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + for pattern in [0, 1, 1, 2] { + let (checked, different) = + check_handoff(&mut lease, &context, &binding, weights, pattern)?; + words += checked; + differences += different; + if context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { + differences += 1; + } + guards += 1; + } + let sentinel = download_f32(lease.buffer(&context)?, 10240)?; + let input = streams(1); + let block = self::block(1); + let coefficients = [0.5, -0.25, 0.0, 1.0]; + for (ctx, current, expected) in [ + (&foreign, &block[..], Error::IdentityMismatch), + (&context, &block[..2559], Error::InvalidDimension), + ] { + if retained_handoff::inject_replace_residual( + &mut lease, + ctx, + &input, + current, + &coefficients, + ) + .err() + != Some(expected) + { + differences += 1; + } + guards += 1; + } + let mut invalid = block.clone(); + invalid[2559] = f32::NAN; + if retained_handoff::inject_replace_residual( + &mut lease, + &context, + &input, + &invalid, + &coefficients, + ) + .err() + != Some(Error::NonFinite) + { + differences += 1; + } + guards += 1; + let after = download_f32(lease.buffer(&context)?, 10240)?; + differences += sentinel + .iter() + .zip(&after) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + words += 10240; + // Valid finite inputs producing a genuinely nonfinite output must + // refuse BEFORE the residual swap; the current input remains. + let overflow = vec![f32::MAX; 2560]; + if retained_handoff::inject_replace_residual( + &mut lease, &context, &input, &overflow, &[20.0; 4], + ) + .err() + != Some(Error::NonFinite) + || failed.get() + { + differences += 1; + } + let after = download_f32(lease.buffer(&context)?, 10240)?; + differences += input + .iter() + .zip(&after) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + words += 10240; + guards += 1; + // Abort exposes no readiness capability. Next actual call fully + // overwrites the failed candidate and all FFN read outputs. + drop(lease); + let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let (checked, different) = check_handoff(&mut lease, &context, &binding, weights, 3)?; + words += checked; + differences += different; + if context.allocated_bytes() != before || failed.get() { + differences += 1; + } + guards += 1; + drop(lease); + Ok((words, differences, guards)) + })(); + let mut cleanup = Ok(()); + for buffer in matrices.into_iter().rev() { + let result = buffer.release().map_err(driver_error); + if cleanup.is_ok() { + cleanup = result; + } + } + if let Some(scratch) = scratch.take() { + let result = scratch.into_inner().close(); + if cleanup.is_ok() { + cleanup = result; + } + } + drop(scratch); + let allocated = context.allocated_bytes(); + let foreign_allocated = foreign.allocated_bytes(); + let closed = context.close().map_err(driver_error); + let foreign_closed = foreign.close().map_err(driver_error); + let (words, differences, guards) = operation.expect("completed changed boundary"); + cleanup.expect("attempted all resource cleanup"); + closed.expect("context closed"); + foreign_closed.expect("foreign context closed"); + assert_eq!(allocated, 0); + assert_eq!(foreign_allocated, 0); + assert_eq!(words, 564520); + assert_eq!(differences, 0); + assert_eq!(guards, 22); + eprintln!( + "GR_OUTPUT_WORKSPACE PASS exact_words={words} guards={guards} allocated0=true original_first=true full_overwrite=true" + ); +} + +mod fresh_read_fn; +#[allow(unused_imports)] +use fresh_read_fn::fresh_read; +#[allow(unused_imports)] +use fresh_read_fn::fresh_inject; +#[allow(unused_imports)] +use fresh_read_fn::block; +#[allow(unused_imports)] +use fresh_read_fn::coefficients; +#[allow(unused_imports)] +use fresh_read_fn::streams; +mod check_handoff_fn; +#[allow(unused_imports)] +use check_handoff_fn::check_handoff; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs new file mode 100644 index 00000000..520a24f3 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs @@ -0,0 +1,128 @@ +//! Moved out of the parent module by STRA-338: fn check_handoff. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn check_handoff<'ctx>( + scratch: &mut GrScratch<'ctx>, + context: &'ctx Context<'ctx>, + binding: &BindingIdentity, + weights: &[DeviceBuffer<'_>; 4], + pattern: usize, +) -> Result<(usize, usize)> { + let input = streams(pattern); + let block = block(pattern); + let coefficients = [0.5, -0.25, 0.0, 1.0]; + scratch.write(binding, context, &input)?; + // Original fresh allocation/kernel/readback plus canonical host H2D + // FIRST. The following fresh FFN trace cannot come from the candidate. + let reference = fresh_inject(context, scratch.buffer(context)?, &block, &coefficients)?; + scratch.write(binding, context, &reference)?; + let reference_ffn = fresh_read(context, scratch.buffer(context)?, weights)?; + for buffer in scratch + .outputs + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .iter_mut() + { + buffer + .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) + .map_err(driver_error)?; + } + scratch + .read_inject + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .copy_from(&f32::NAN.to_le_bytes().repeat(4)) + .map_err(driver_error)?; + for buffer in scratch + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow_mut() + .iter_mut() + { + buffer + .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) + .map_err(driver_error)?; + } + let actual = retained_handoff::inject_replace_residual( + scratch, + context, + &input, + &block, + &coefficients, + )?; + let resident = download_f32(scratch.buffer(context)?, 10240)?; + let previous = download_f32( + &scratch + .injection + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow()[2], + 10240, + )?; + let mut differences = 0; + for (left, right) in [ + (&actual[..], &reference[..]), + (&resident[..], &reference[..]), + (&previous[..], &input[..]), + ] { + differences += left + .iter() + .zip(right) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + } + // No host residual upload: the actual swapped producer feeds FFN. + let ffn = read_cached_cuda( + context, + 1e-6, + true, + scratch, + [ + Some(&weights[0]), + Some(&weights[1]), + Some(&weights[2]), + Some(&weights[3]), + ], + )?; + let outputs = scratch + .outputs + .as_ref() + .ok_or(Error::CudaExecution)? + .borrow(); + for (buffer, expected) in outputs.iter().zip(&reference_ffn) { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + differences += bytes + .chunks_exact(4) + .zip(expected.chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + } + let injected: Vec = ffn + .inject + .ok_or(Error::InvalidDimension)? + .into_iter() + .flat_map(f32::to_le_bytes) + .collect(); + differences += injected + .chunks_exact(4) + .zip(reference_ffn[6].chunks_exact(4)) + .filter(|(a, b)| a != b) + .count(); + if ffn + .mixed + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>() + != reference_ffn[5] + { + differences += 1; + } + Ok((3 * 10240 + GR_OUTPUT_DEVICE_BYTES / 4 + 4, differences)) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs new file mode 100644 index 00000000..5ea7dbbc --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs @@ -0,0 +1,133 @@ +//! Moved out of the parent module by STRA-338: fn fresh_read, fn fresh_inject, fn block, fn coefficients, fn streams. + +#[allow(unused_imports)] +use super::*; + + +pub(super) fn fresh_read( + context: &Context<'_>, + residual: &DeviceBuffer<'_>, + weights: &[DeviceBuffer<'_>; 4], +) -> Result>> { + // Exact compiled289 per-read allocation boundary FIRST, same queued + // kernels and fixed finite guard, never candidate-derived arithmetic. + let mut owned = Vec::new(); + let operation: Result>> = (|| { + for bytes in GR_OUTPUT_BYTES.into_iter().chain([16]) { + owned.push(context.allocate(bytes).map_err(driver_error)?); + } + let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() + else { + return Err(Error::InvalidDimension); + }; + let mask = context + .gr_read_chain_queued( + residual, + &weights[0], + &weights[1], + &weights[2], + 1e-6, + xn, + down, + activated, + gates, + products, + mixed, + ) + .map_err(driver_error)?; + if mask != 0 { + return Err(Error::NonFinite); + } + context + .gr_inject_projection_bf16_f32(&weights[3], xn, injection) + .map_err(driver_error)?; + owned + .iter() + .map(|buffer| { + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes).map_err(driver_error)?; + Ok(bytes) + }) + .collect::>>() + })(); + let mut cleanup = Ok(()); + for buffer in owned.into_iter().rev() { + let result = buffer.release().map_err(driver_error); + if cleanup.is_ok() { + cleanup = result; + } + } + let value = operation?; + cleanup?; + Ok(value) +} + +pub(super) fn fresh_inject( + context: &Context<'_>, + residual: &DeviceBuffer<'_>, + block: &[f32], + coefficients: &[f32; 4], +) -> Result> { + // Original cached injection allocation/upload/kernel/readback FIRST. + let mut owned = Vec::new(); + let operation: Result> = (|| { + owned.push(upload_f32(context, block)?); + owned.push(upload_f32(context, coefficients)?); + owned.push(context.allocate(40960).map_err(driver_error)?); + let [block, coefficients, candidate] = owned.as_mut_slice() else { + return Err(Error::InvalidDimension); + }; + context + .gr_inject_residual_f32(residual, block, coefficients, candidate) + .map_err(driver_error)?; + download_f32(candidate, 10240) + })(); + let mut cleanup = Ok(()); + for buffer in owned.into_iter().rev() { + let result = buffer.release().map_err(driver_error); + if cleanup.is_ok() { + cleanup = result; + } + } + let value = operation?; + cleanup?; + Ok(value) +} + +pub(super) fn block(pattern: usize) -> Vec { + (0..2560) + .map(|i| { + if pattern == 0 { + if i % 2 == 0 { -0.0 } else { 0.0 } + } else { + ((i % (13 + pattern)) as f32 - 6.0) / 128.0 + } + }) + .collect() +} + +pub(super) fn coefficients(expected: &[Vec]) -> Result<[f32; 4]> { + let bytes = expected.get(6).ok_or(Error::InvalidDimension)?; + if bytes.len() != 16 { + return Err(Error::InvalidDimension); + } + Ok(std::array::from_fn(|i| { + f32::from_le_bytes( + bytes[i * 4..i * 4 + 4] + .try_into() + .expect("fixed four bytes"), + ) + })) +} + +pub(super) fn streams(pattern: usize) -> Vec { + (0..10240) + .map(|i| { + if pattern == 0 { + if i % 2 == 0 { -0.0 } else { 0.0 } + } else { + ((i % (19 + pattern)) as f32 - 9.0) / 64.0 + } + }) + .collect() +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs new file mode 100644 index 00000000..6b9b5f25 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs @@ -0,0 +1,155 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +#[test] +fn gr_preflight_keeps_all_inputs_unchanged_on_shape_or_numeric_refusal() { + let mut values = vec![-0.0_f32; 4 * 2560]; + let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); + assert_eq!(validate_streams(&values), Ok(())); + assert_eq!( + validate_streams(&values[..values.len() - 1]), + Err(Error::InvalidDimension) + ); + assert_eq!( + values.iter().map(|v| v.to_bits()).collect::>(), + before + ); + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + values[10239] = invalid; + let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); + assert_eq!(validate_streams(&values), Err(Error::NonFinite)); + assert_eq!( + values.iter().map(|v| v.to_bits()).collect::>(), + before + ); + } +} + +#[test] +fn gr_layer_identity_cannot_substitute_a_different_verified_extent() { + let layer = LayerId::new(47, Dimension::new(48).unwrap()).unwrap(); + assert_eq!(validate_layer(layer, 48), Ok(())); + assert_eq!(validate_layer(layer, 49), Err(Error::IdentityMismatch)); + assert_eq!(validate_layer(layer, 47), Err(Error::InvalidLayer)); + assert_eq!(validate_layer(layer, 0), Err(Error::InvalidDimension)); +} + +fn identity() -> TokenLayer { + use super::super::contract::{Position, TokenId}; + TokenLayer::new( + TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(), + Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(), + LayerId::new(0, Dimension::new(48).unwrap()).unwrap(), + ) +} + +#[test] +fn gr_candidate_quiet_nan_refuses_late_failure_without_stream_publication() { + let caller = vec![-0.0_f32; 4 * 2560]; + let before: Vec<_> = caller.iter().map(|v| v.to_bits()).collect(); + let mut candidate = vec![1.0_f32; 4 * 2560]; + candidate[10239] = f32::from_bits(0x7fc0_0000); + assert!(matches!( + InjectedResidual::from_candidates( + identity(), + BindingIdentity::test_identity(), + GrRole::Attention(0), + candidate.into_boxed_slice() + ), + Err(Error::NonFinite) + )); + assert_eq!( + caller.iter().map(|v| v.to_bits()).collect::>(), + before + ); + let accepted = InjectedResidual::from_candidates( + identity(), + BindingIdentity::test_identity(), + GrRole::Attention(0), + caller.into_boxed_slice(), + ) + .unwrap(); + assert_eq!( + accepted + .streams() + .iter() + .map(|v| v.to_bits()) + .collect::>(), + before + ); + assert_eq!(accepted.identity(), identity()); +} + +#[test] +fn gr_injected_capability_refuses_cross_model_or_wrong_stage_before_read() { + let binding = BindingIdentity::test_identity(); + let other = BindingIdentity::test_identity(); + let residual = InjectedResidual::from_candidates( + identity(), + binding.clone(), + GrRole::Attention(0), + vec![-0.0; 10240].into_boxed_slice(), + ) + .unwrap(); + assert_eq!( + residual.validate_origin(&binding, GrRole::Attention(0)), + Ok(()) + ); + for wrong in [GrRole::Ffn(0), GrRole::Attention(1), GrRole::Final] { + assert_eq!( + residual.validate_origin(&binding, wrong), + Err(Error::IdentityMismatch) + ); + } + assert_eq!( + residual.validate_origin(&other, GrRole::Attention(0)), + Err(Error::IdentityMismatch) + ); + for role in [GrRole::Attention(1), GrRole::Ffn(1), GrRole::Final] { + assert!(matches!( + InjectedResidual::from_candidates( + identity(), + binding.clone(), + role, + vec![0.0; 10240].into_boxed_slice() + ), + Err(Error::IdentityMismatch) + )); + } + assert!(residual.streams().iter().all(|v| v.to_bits() == 0x80000000)); +} + +#[test] +fn gr_candidate_norm_overflow_oracle_distinguishes_masked_finite_zero() { + // Offline malformed-domain facts, not a per-request CPU norm/reference. + let large = f32::from_bits(0x7f7f_ffff); + let square = large.mul_add(large, 0.0); + assert!(square.is_infinite()); + let masked_native = (1.0 / (square / 2560.0).sqrt()) * large; + assert_eq!(masked_native.to_bits(), 0); + assert_eq!(validate_streams(&vec![masked_native; 4 * 2560]), Ok(())); + assert_eq!( + validate_streams(&vec![f32::from_bits(0x7fc0_0000); 4 * 2560]), + Err(Error::NonFinite) + ); + assert!((1.0_f32 / 0.0_f32.sqrt()).is_infinite()); +} + +#[test] +fn gr_candidate_postop_overflow_oracles_require_signal_not_masked_success() { + // exp(100)>F32_MAX while sigmoid(-100) can hide that overflow as +0. + let exponential = 100.0_f32.exp(); + assert!(exponential.is_infinite()); + assert_eq!((1.0_f32 / (1.0 + exponential)).to_bits(), 0); + let product = f32::from_bits(0x7e96_7699); // 1e38, individually finite. + assert!(product.is_finite()); + let sum = product + product + product + product; + assert!(sum.is_infinite()); + for output in [f32::from_bits(0x7fc0_0000), sum, exponential] { + assert_eq!( + validate_streams(&vec![output; 4 * 2560]), + Err(Error::NonFinite) + ); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs index 9b356cda..1bd8d1ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs @@ -112,606 +112,13 @@ pub(crate) struct KarPleCache<'ctx> { /// through the same `VerifiedKarPleArtifact::verify` + pinned profile as /// production, but does not touch the sealed-fd admission. #[cfg(all(test, any(target_os = "linux", target_os = "windows")))] -mod row_parity_probe { - use super::*; - use crate::model_binding::qwen4exp_kar_ple::pinned_profile; - use leleka_cuda_driver::Driver; - use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; - use std::io::Write; - - fn fnv(values: &[f32]) -> u64 { - let mut hash = 0xcbf29ce484222325u64; - for v in values { - for b in v.to_le_bytes() { - hash ^= u64::from(b); - hash = hash.wrapping_mul(0x100000001b3); - } - } - hash - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] - fn dump_decoded_rows_for_original_comparison() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); - let mut rows: Vec = std::fs::read_to_string(rows_path) - .expect("rows file readable") - .split_whitespace() - .map(|t| t.parse().expect("row number")) - .collect(); - let wanted = rows.len(); - while rows.len() % 16 != 0 { - rows.push(*rows.last().unwrap()); - } - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device0"); - let context = device.create_context(2usize << 30).expect("context"); - let mut cache = KarPleCache::new(&context, &binding).expect("cache"); - let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") - .ok() - .map(|p| std::fs::File::create(p).expect("dump file")); - let mut done = 0; - for chunk in rows.chunks_exact(16) { - let batch: [u64; 16] = chunk.try_into().unwrap(); - let values = cache.gather(&binding, &batch).expect("gather"); - for (i, row) in batch.iter().enumerate() { - if done + i < wanted { - println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); - } - } - if let Some(dump) = dump.as_mut() { - for v in values.iter() { - dump.write_all(&v.to_le_bytes()).unwrap(); - } - } - done += 16; - } - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] - fn batch_read_equals_the_sixteen_row_reads() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share - let mut state = 0x9e3779b97f4a7c15u64; - let mut rows: Vec = (0..40_000) - .map(|_| { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state % PLE_ROWS - }) - .collect(); - rows[0] = 0; - rows[1] = PLE_ROWS - 1; - while rows.len() % 16 != 0 { - rows.push(7); - } - let batch = binding.read_rows_batch(&rows).expect("batch read"); - assert_eq!(batch.len(), rows.len()); - for (i, chunk) in rows.chunks_exact(16).enumerate() { - let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); - for (j, packet) in sixteen.iter().enumerate() { - assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); - assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); - } - } - println!("batch read equals the 16-row reads for {} rows", rows.len()); - } -} +mod row_parity_probe; #[cfg(test)] -mod slot_tests { - use super::*; - - /// What `KarPleCache::commit` does to the map, over the pure parts. - fn apply( - entries: &mut Residents, - lookup: &Lookup, - miss_slot: &[u32], - victims: &[Option], - stamp: u64, - ) { - for victim in victims.iter().flatten() { - entries.remove(victim); - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert(*row, miss_slot[i], stamp); - } - } - /// The staging buffers of the scatter: one per miss count, each exactly the update block the kernel's layout names - /// (`misses * 56` bytes: slot u32, packet payload 50, partition u16), so the persistent buffers are admitted like the former - /// per-call allocation of `updates.len()` bytes. - #[test] - fn the_scatter_staging_buffers_match_the_update_records() { - assert_eq!(UPDATE_RECORD_BYTES, 4 + 50 + 2); - assert_eq!(MAX_MISSES, 16); - assert_eq!(scratch_bytes(), UPDATE_RECORD_BYTES * (1..=16).sum::()); - let sizes: Vec = (1..=MAX_MISSES).map(|k| k * UPDATE_RECORD_BYTES).collect(); - assert_eq!(sizes[0], 56); - assert_eq!(sizes[15], 16 * 56); - // `gather` builds `updates` as 56 bytes per miss, so `scratch[misses - 1]` is the buffer of exactly that length - for misses in 1..=16usize { - assert_eq!(sizes[misses - 1], misses * (4 + 50 + 2)); - } - } - - fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { - rows.chunks(16) - .map(|c| std::array::from_fn(|i| c[i % c.len()])) - .collect() - } - /// Every row maps to one slot and no slot serves two rows. - fn consistent(entries: &Residents) { - let mut seen = std::collections::HashSet::new(); - for entry in entries.map.values() { - assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); - } - } - - #[test] - fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { - let mut entries = Residents::default(); - let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); - let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); - assert_eq!(lookup.miss_rows.len(), 14); - let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); - assert_eq!(next, 14); - assert!(victims.iter().all(Option::is_none)); - let mut slots = lookup.slots.clone(); - for (at, miss) in &lookup.pending { - slots[*at as usize] = miss_slot[*miss as usize]; - } - assert!(slots.iter().all(|s| *s < 14)); - assert_eq!(slots[0], slots[2]); - assert_eq!(slots[1], slots[4]); - apply(&mut entries, &lookup, &miss_slot, &victims, 1); - consistent(&entries); - assert_eq!(entries.len(), 14); - } - - #[test] - fn hits_keep_their_slots_and_refresh_their_age() { - let mut entries = Residents::default(); - let first = chunk(&[1, 2, 3, 4]); - let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries.map[r].slot)).collect(); - let second = chunk(&[3, 4, 5, 6]); - let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); - assert_eq!(lookup.miss_rows, vec![5, 6]); - assert_eq!(entries.map[&3].age, 2); - assert_eq!(entries.map[&1].age, 1); - for (row, slot) in before { - assert_eq!(entries.map[&row].slot, slot); - } - } - - #[test] - fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { - let mut entries = Residents::default(); - let capacity = 12u32; - let mut next = 0u32; - // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) - let rows1: Vec = (100..112).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - next = n; - assert_eq!(next, capacity); - let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); - assert!(lookup.miss_rows.is_empty()); - // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) - let rows3 = [100u64, 101, 500, 501, 502, 503]; - let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); - assert_eq!(n, capacity); - let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); - assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); - let distinct: std::collections::HashSet<_> = slot.iter().collect(); - assert_eq!(distinct.len(), 4); - // the evicted rows' slots are the ones handed out - for (i, v) in evicted.iter().enumerate() { - assert_eq!(entries.map[v].slot, slot[i]); - } - apply(&mut entries, &lookup, &slot, &victims, 3); - consistent(&entries); - assert_eq!(entries.len(), capacity as usize); - for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { - assert!(entries.contains_key(&r), "row {r}"); - } - } - - /// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row - /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. - #[test] - fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { - let mut entries = Residents::default(); - let first: Vec = (1..=32).map(|r| r * 1000).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let given: std::collections::HashMap = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect(); - let slot_of = |row: u64| given[&row]; - let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; - let flat = |lookup: &Lookup| lookup.slots.clone(); - // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset - let mut swapped = first.clone(); - swapped.rotate_left(16); - let mut reversed = first.clone(); - reversed.reverse(); - let mut shifted = first.clone(); - shifted.rotate_left(1); - for (name, rows) in [ - ("swapped", swapped), - ("reversed", reversed), - ("shifted", shifted), - ("one row repeated", vec![first[5]; 16]), - ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), - ] { - let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); - assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); - assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); - } - // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats - let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; - let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); - for (at, &row) in mixed.iter().enumerate() { - let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; - // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves - assert_eq!(lookup.slots[at], want, "mixed position {at}"); - } - // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each - let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); - assert_eq!((named(0), named(1)), (4, 4)); - } - - #[test] - fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { - let mut entries = Residents::default(); - let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); - let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable - let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); - assert_eq!(lookup.miss_rows.len(), 4); - assert_eq!( - assign_slots(&entries, next, 8, 2, 4).err(), - Some(Error::InvalidDimension) - ); - } -} +mod slot_tests; #[cfg(test)] -mod lru_tests { - use super::*; - use std::collections::HashMap; - - struct Rng(u64); - impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - /// Half the draws from a hot set, the rest from the whole universe. - fn row(&mut self, hot: u64, universe: u64) -> u64 { - if self.next() % 2 == 0 { - self.next() % hot - } else { - self.next() % universe - } - } - } - - /// The previous implementation, kept as the reference: a plain map scanned in full for every victim. - struct Scan { - map: HashMap, - next_slot: u32, - age: u64, - capacity: u32, - } - impl Scan { - fn new(capacity: u32) -> Self { - Self { - map: HashMap::new(), - next_slot: 0, - age: 0, - capacity, - } - } - /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. - fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { - let mut misses = Vec::<(u64, u32, Option)>::new(); - let mut selected = [0u32; 16]; - let mut next_slot = self.next_slot; - for (i, row) in rows.iter().enumerate() { - if let Some(&(slot, _)) = self.map.get(row) { - selected[i] = slot; - continue; - } - if let Some(m) = misses.iter().find(|m| m.0 == *row) { - selected[i] = m.1; - continue; - } - let (slot, victim) = if next_slot < self.capacity { - next_slot += 1; - (next_slot - 1, None) - } else { - let (victim, (slot, _)) = self - .map - .iter() - .filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r))) - .min_by_key(|(_, e)| e.1) - .unwrap(); - (*slot, Some(*victim)) - }; - selected[i] = slot; - misses.push((*row, slot, victim)); - } - for m in &misses { - if let Some(v) = m.2 { - self.map.remove(&v); - } - self.map.insert(m.0, (m.1, 0)); - } - for (i, row) in rows.iter().enumerate() { - self.map.get_mut(row).unwrap().1 = self.age + i as u64 + 1; - } - self.next_slot = next_slot; - self.age += 16; - (selected, misses) - } - } - - /// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right - /// exactly when its slot holds its own number. - struct Device(Vec); - - fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { - std::array::from_fn(|_| rng.row(hot, universe)) - } - - /// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims - /// and ends in the same state as the full scan, and every gathered row is its own row. - #[test] - fn gather_equals_the_full_scan_on_random_sequences() { - for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { - let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); - let mut old = Scan::new(capacity); - let mut new = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut device = Device(vec![u64::MAX; capacity as usize]); - let mut evictions = 0usize; - for step in 0..6000 { - let rows = token(&mut rng, hot, universe); - let (old_selected, old_misses) = old.gather(&rows); - let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap(); - assert_eq!(plan.selected, old_selected, "step {step}"); - let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect(); - assert_eq!(planned, old_misses, "step {step}"); - evictions += planned.iter().filter(|m| m.2.is_some()).count(); - for m in &plan.misses { - device.0[m.slot as usize] = m.row; - } - publish_gather(&mut new, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - for (i, row) in rows.iter().enumerate() { - assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); - } - } - assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); - let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect(); - let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect(); - a.sort(); - b.sort(); - assert_eq!(a, b, "capacity {capacity}: final state"); - assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); - } - } - - /// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot - /// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim). - #[test] - fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { - let capacity = 300u32; - let mut rng = Rng(0x2545f4914f6cdd1d); - let mut entries = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut device = Device(vec![u64::MAX; capacity as usize]); - let mut chunk_evictions = 0usize; - for step in 0..1500 { - if step % 3 == 0 { - let n = 1 + (rng.next() % 6) as usize; - let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); - let stamp = age + 1; - let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); - let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); - // a victim is no younger than any row left in the cache that the chunk did not touch - let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); - if let Some(limit) = youngest_victim { - let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); - for (r, e) in &entries.map { - if e.age < stamp && !victims_set.contains(r) { - assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); - } - } - } - chunk_evictions += victims.iter().flatten().count(); - let mut slots = lookup.slots.clone(); - for (at, miss) in &lookup.pending { - slots[*at as usize] = miss_slot[*miss as usize]; - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - device.0[miss_slot[i] as usize] = *row; - } - for v in victims.iter().flatten() { - entries.remove(v); - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert(*row, miss_slot[i], stamp); - } - next_slot = next; - age = stamp; - for (at, row) in rows.iter().flatten().enumerate() { - assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}"); - } - } else { - let rows = token(&mut rng, 150, 2500); - let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); - for m in &plan.misses { - device.0[m.slot as usize] = m.row; - } - publish_gather(&mut entries, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - for (i, row) in rows.iter().enumerate() { - assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}"); - } - } - let mut seen = std::collections::HashSet::new(); - for e in entries.map.values() { - assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot); - } - assert!(entries.len() <= capacity as usize); - // one live queue item per row - let live = entries - .order - .iter() - .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) - .count(); - assert_eq!(live, entries.len(), "step {step}"); - } - assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); - } - - /// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read. - #[test] - fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() { - let capacity = 200_000u32; - let mut entries = Residents::default(); - let (mut next_slot, mut age) = (0u32, 0u64); - let mut row = 0u64; - let mut batches = 0; - let mut examined_after_full = 0usize; - let mut misses_after_full = 0usize; - while batches < capacity as usize / 16 + 2000 { - let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64); - row += 16; - let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); - let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); - publish_gather(&mut entries, &plan.misses, &rows, age); - next_slot = plan.next_slot; - age += 16; - if next_slot == capacity { - examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; - misses_after_full += plan.misses.len(); - } - batches += 1; - } - assert!(misses_after_full >= 16 * 1900, "{misses_after_full}"); - // each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss - assert!( - examined_after_full <= misses_after_full * 40, - "{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})", - misses_after_full * capacity as usize - ); - // and a hot row touched over and over leaves the queue bounded - for i in 0..50_000u64 { - entries.touch(&(row - 1 - (i % 4)), age + i + 1); - } - assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len()); - } - - /// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk. - #[test] - fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() { - let capacity = 100_000u32; - let mut entries = Residents::default(); - for r in 0..capacity as u64 { - entries.insert(r, r as u32, 1 + r / 10); - } - let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); - let (victims, _) = entries.oldest(50_000, 1_000_000, |_| false).unwrap(); - assert_eq!(victims.len(), 50_000); - assert!(victims.iter().enumerate().all(|(i, (r, _))| *r == i as u64)); - let examined = entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; - assert_eq!(examined, 50_000); - } - - /// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan. - #[test] - fn oldest_returns_what_exists_when_the_queue_runs_short() { - let mut entries = Residents::default(); - for r in 0..10u64 { - entries.insert(r, r as u32, r + 1); - } - let (victims, _) = entries.oldest(8, 6, |r| r == 2).unwrap(); - let rows: Vec = victims.iter().map(|v| v.0).collect(); - assert_eq!(rows, vec![0, 1, 3, 4]); - // a queue out of order (cannot happen by construction) is settled by the full scan, still oldest first - let mut entries = Residents::default(); - entries.insert(100, 0, 50); - entries.insert(101, 1, 10); - entries.insert(102, 2, 12); - let (victims, examined) = entries.oldest(2, 20, |_| false).unwrap(); - assert_eq!(victims, vec![(101, 1), (102, 2)]); - assert!(examined >= entries.len()); - } - - /// Cost of the old scan against the queue on a full cache of 1,048,576 rows (the production size): - /// `cargo test --release -p leleka-engine-qwen35-cuda scan_against_queue -- --ignored --nocapture`. - #[test] - #[ignore = "timing probe; prints the per-miss cost of the old scan and of the queue"] - fn scan_against_queue_on_a_full_cache() { - let capacity = SLOTS; - let mut entries = Residents::default(); - let mut old = Scan::new(capacity); - for r in 0..capacity as u64 { - entries.insert(r * 7 + 3, r as u32, 1 + r); - old.map.insert(r * 7 + 3, (r as u32, 1 + r)); - } - let rows: [u64; 16] = std::array::from_fn(|i| 1_000_000_007 + i as u64 * 2); - let t = std::time::Instant::now(); - let n = 20; - for _ in 0..n { - std::hint::black_box( - old.map - .iter() - .filter(|(r, _)| !rows.contains(r)) - .min_by_key(|(_, e)| e.1) - .map(|(r, _)| *r), - ); - } - let scan = t.elapsed() / n; - let t = std::time::Instant::now(); - for _ in 0..1000 { - std::hint::black_box(entries.oldest(1, u64::MAX, |r| rows.contains(&r)).unwrap()); - } - let queue = t.elapsed() / 1000; - println!("per missed row: old scan {scan:?}, recency queue {queue:?} (full cache of {capacity} rows)"); - } -} +mod lru_tests; mod scratch_bytes_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs new file mode 100644 index 00000000..fe643617 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs @@ -0,0 +1,311 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use std::collections::HashMap; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + /// Half the draws from a hot set, the rest from the whole universe. + fn row(&mut self, hot: u64, universe: u64) -> u64 { + if self.next() % 2 == 0 { + self.next() % hot + } else { + self.next() % universe + } + } +} + +/// The previous implementation, kept as the reference: a plain map scanned in full for every victim. +struct Scan { + map: HashMap, + next_slot: u32, + age: u64, + capacity: u32, +} +impl Scan { + fn new(capacity: u32) -> Self { + Self { + map: HashMap::new(), + next_slot: 0, + age: 0, + capacity, + } + } + /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. + fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { + let mut misses = Vec::<(u64, u32, Option)>::new(); + let mut selected = [0u32; 16]; + let mut next_slot = self.next_slot; + for (i, row) in rows.iter().enumerate() { + if let Some(&(slot, _)) = self.map.get(row) { + selected[i] = slot; + continue; + } + if let Some(m) = misses.iter().find(|m| m.0 == *row) { + selected[i] = m.1; + continue; + } + let (slot, victim) = if next_slot < self.capacity { + next_slot += 1; + (next_slot - 1, None) + } else { + let (victim, (slot, _)) = self + .map + .iter() + .filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r))) + .min_by_key(|(_, e)| e.1) + .unwrap(); + (*slot, Some(*victim)) + }; + selected[i] = slot; + misses.push((*row, slot, victim)); + } + for m in &misses { + if let Some(v) = m.2 { + self.map.remove(&v); + } + self.map.insert(m.0, (m.1, 0)); + } + for (i, row) in rows.iter().enumerate() { + self.map.get_mut(row).unwrap().1 = self.age + i as u64 + 1; + } + self.next_slot = next_slot; + self.age += 16; + (selected, misses) + } +} + +/// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right +/// exactly when its slot holds its own number. +struct Device(Vec); + +fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { + std::array::from_fn(|_| rng.row(hot, universe)) +} + +/// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims +/// and ends in the same state as the full scan, and every gathered row is its own row. +#[test] +fn gather_equals_the_full_scan_on_random_sequences() { + for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { + let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); + let mut old = Scan::new(capacity); + let mut new = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut evictions = 0usize; + for step in 0..6000 { + let rows = token(&mut rng, hot, universe); + let (old_selected, old_misses) = old.gather(&rows); + let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap(); + assert_eq!(plan.selected, old_selected, "step {step}"); + let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect(); + assert_eq!(planned, old_misses, "step {step}"); + evictions += planned.iter().filter(|m| m.2.is_some()).count(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut new, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); + } + } + assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); + let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect(); + let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect(); + a.sort(); + b.sort(); + assert_eq!(a, b, "capacity {capacity}: final state"); + assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); + } +} + +/// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot +/// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim). +#[test] +fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { + let capacity = 300u32; + let mut rng = Rng(0x2545f4914f6cdd1d); + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut chunk_evictions = 0usize; + for step in 0..1500 { + if step % 3 == 0 { + let n = 1 + (rng.next() % 6) as usize; + let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); + let stamp = age + 1; + let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); + let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); + // a victim is no younger than any row left in the cache that the chunk did not touch + let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); + if let Some(limit) = youngest_victim { + let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); + for (r, e) in &entries.map { + if e.age < stamp && !victims_set.contains(r) { + assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); + } + } + } + chunk_evictions += victims.iter().flatten().count(); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + device.0[miss_slot[i] as usize] = *row; + } + for v in victims.iter().flatten() { + entries.remove(v); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert(*row, miss_slot[i], stamp); + } + next_slot = next; + age = stamp; + for (at, row) in rows.iter().flatten().enumerate() { + assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}"); + } + } else { + let rows = token(&mut rng, 150, 2500); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}"); + } + } + let mut seen = std::collections::HashSet::new(); + for e in entries.map.values() { + assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot); + } + assert!(entries.len() <= capacity as usize); + // one live queue item per row + let live = entries + .order + .iter() + .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) + .count(); + assert_eq!(live, entries.len(), "step {step}"); + } + assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); +} + +/// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read. +#[test] +fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() { + let capacity = 200_000u32; + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut row = 0u64; + let mut batches = 0; + let mut examined_after_full = 0usize; + let mut misses_after_full = 0usize; + while batches < capacity as usize / 16 + 2000 { + let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64); + row += 16; + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + if next_slot == capacity { + examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + misses_after_full += plan.misses.len(); + } + batches += 1; + } + assert!(misses_after_full >= 16 * 1900, "{misses_after_full}"); + // each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss + assert!( + examined_after_full <= misses_after_full * 40, + "{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})", + misses_after_full * capacity as usize + ); + // and a hot row touched over and over leaves the queue bounded + for i in 0..50_000u64 { + entries.touch(&(row - 1 - (i % 4)), age + i + 1); + } + assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len()); +} + +/// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk. +#[test] +fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() { + let capacity = 100_000u32; + let mut entries = Residents::default(); + for r in 0..capacity as u64 { + entries.insert(r, r as u32, 1 + r / 10); + } + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let (victims, _) = entries.oldest(50_000, 1_000_000, |_| false).unwrap(); + assert_eq!(victims.len(), 50_000); + assert!(victims.iter().enumerate().all(|(i, (r, _))| *r == i as u64)); + let examined = entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + assert_eq!(examined, 50_000); +} + +/// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan. +#[test] +fn oldest_returns_what_exists_when_the_queue_runs_short() { + let mut entries = Residents::default(); + for r in 0..10u64 { + entries.insert(r, r as u32, r + 1); + } + let (victims, _) = entries.oldest(8, 6, |r| r == 2).unwrap(); + let rows: Vec = victims.iter().map(|v| v.0).collect(); + assert_eq!(rows, vec![0, 1, 3, 4]); + // a queue out of order (cannot happen by construction) is settled by the full scan, still oldest first + let mut entries = Residents::default(); + entries.insert(100, 0, 50); + entries.insert(101, 1, 10); + entries.insert(102, 2, 12); + let (victims, examined) = entries.oldest(2, 20, |_| false).unwrap(); + assert_eq!(victims, vec![(101, 1), (102, 2)]); + assert!(examined >= entries.len()); +} + +/// Cost of the old scan against the queue on a full cache of 1,048,576 rows (the production size): +/// `cargo test --release -p leleka-engine-qwen35-cuda scan_against_queue -- --ignored --nocapture`. +#[test] +#[ignore = "timing probe; prints the per-miss cost of the old scan and of the queue"] +fn scan_against_queue_on_a_full_cache() { + let capacity = SLOTS; + let mut entries = Residents::default(); + let mut old = Scan::new(capacity); + for r in 0..capacity as u64 { + entries.insert(r * 7 + 3, r as u32, 1 + r); + old.map.insert(r * 7 + 3, (r as u32, 1 + r)); + } + let rows: [u64; 16] = std::array::from_fn(|i| 1_000_000_007 + i as u64 * 2); + let t = std::time::Instant::now(); + let n = 20; + for _ in 0..n { + std::hint::black_box( + old.map + .iter() + .filter(|(r, _)| !rows.contains(r)) + .min_by_key(|(_, e)| e.1) + .map(|(r, _)| *r), + ); + } + let scan = t.elapsed() / n; + let t = std::time::Instant::now(); + for _ in 0..1000 { + std::hint::black_box(entries.oldest(1, u64::MAX, |r| rows.contains(&r)).unwrap()); + } + let queue = t.elapsed() / 1000; + println!("per missed row: old scan {scan:?}, recency queue {queue:?} (full cache of {capacity} rows)"); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs new file mode 100644 index 00000000..da7b4f8a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs @@ -0,0 +1,102 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use crate::model_binding::qwen4exp_kar_ple::pinned_profile; +use leleka_cuda_driver::Driver; +use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; +use std::io::Write; + +fn fnv(values: &[f32]) -> u64 { + let mut hash = 0xcbf29ce484222325u64; + for v in values { + for b in v.to_le_bytes() { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100000001b3); + } + } + hash +} + +#[test] +#[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] +fn dump_decoded_rows_for_original_comparison() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); + let mut rows: Vec = std::fs::read_to_string(rows_path) + .expect("rows file readable") + .split_whitespace() + .map(|t| t.parse().expect("row number")) + .collect(); + let wanted = rows.len(); + while rows.len() % 16 != 0 { + rows.push(*rows.last().unwrap()); + } + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device0"); + let context = device.create_context(2usize << 30).expect("context"); + let mut cache = KarPleCache::new(&context, &binding).expect("cache"); + let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") + .ok() + .map(|p| std::fs::File::create(p).expect("dump file")); + let mut done = 0; + for chunk in rows.chunks_exact(16) { + let batch: [u64; 16] = chunk.try_into().unwrap(); + let values = cache.gather(&binding, &batch).expect("gather"); + for (i, row) in batch.iter().enumerate() { + if done + i < wanted { + println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); + } + } + if let Some(dump) = dump.as_mut() { + for v in values.iter() { + dump.write_all(&v.to_le_bytes()).unwrap(); + } + } + done += 16; + } +} + +#[test] +#[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] +fn batch_read_equals_the_sixteen_row_reads() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share + let mut state = 0x9e3779b97f4a7c15u64; + let mut rows: Vec = (0..40_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % PLE_ROWS + }) + .collect(); + rows[0] = 0; + rows[1] = PLE_ROWS - 1; + while rows.len() % 16 != 0 { + rows.push(7); + } + let batch = binding.read_rows_batch(&rows).expect("batch read"); + assert_eq!(batch.len(), rows.len()); + for (i, chunk) in rows.chunks_exact(16).enumerate() { + let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); + for (j, packet) in sixteen.iter().enumerate() { + assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); + assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); + } + } + println!("batch read equals the 16-row reads for {} rows", rows.len()); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs new file mode 100644 index 00000000..16852964 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs @@ -0,0 +1,183 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +/// What `KarPleCache::commit` does to the map, over the pure parts. +fn apply( + entries: &mut Residents, + lookup: &Lookup, + miss_slot: &[u32], + victims: &[Option], + stamp: u64, +) { + for victim in victims.iter().flatten() { + entries.remove(victim); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert(*row, miss_slot[i], stamp); + } +} +/// The staging buffers of the scatter: one per miss count, each exactly the update block the kernel's layout names +/// (`misses * 56` bytes: slot u32, packet payload 50, partition u16), so the persistent buffers are admitted like the former +/// per-call allocation of `updates.len()` bytes. +#[test] +fn the_scatter_staging_buffers_match_the_update_records() { + assert_eq!(UPDATE_RECORD_BYTES, 4 + 50 + 2); + assert_eq!(MAX_MISSES, 16); + assert_eq!(scratch_bytes(), UPDATE_RECORD_BYTES * (1..=16).sum::()); + let sizes: Vec = (1..=MAX_MISSES).map(|k| k * UPDATE_RECORD_BYTES).collect(); + assert_eq!(sizes[0], 56); + assert_eq!(sizes[15], 16 * 56); + // `gather` builds `updates` as 56 bytes per miss, so `scratch[misses - 1]` is the buffer of exactly that length + for misses in 1..=16usize { + assert_eq!(sizes[misses - 1], misses * (4 + 50 + 2)); + } +} + +fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { + rows.chunks(16) + .map(|c| std::array::from_fn(|i| c[i % c.len()])) + .collect() +} +/// Every row maps to one slot and no slot serves two rows. +fn consistent(entries: &Residents) { + let mut seen = std::collections::HashSet::new(); + for entry in entries.map.values() { + assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); + } +} + +#[test] +fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { + let mut entries = Residents::default(); + let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); + let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); + assert_eq!(lookup.miss_rows.len(), 14); + let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); + assert_eq!(next, 14); + assert!(victims.iter().all(Option::is_none)); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + assert!(slots.iter().all(|s| *s < 14)); + assert_eq!(slots[0], slots[2]); + assert_eq!(slots[1], slots[4]); + apply(&mut entries, &lookup, &miss_slot, &victims, 1); + consistent(&entries); + assert_eq!(entries.len(), 14); +} + +#[test] +fn hits_keep_their_slots_and_refresh_their_age() { + let mut entries = Residents::default(); + let first = chunk(&[1, 2, 3, 4]); + let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries.map[r].slot)).collect(); + let second = chunk(&[3, 4, 5, 6]); + let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); + assert_eq!(lookup.miss_rows, vec![5, 6]); + assert_eq!(entries.map[&3].age, 2); + assert_eq!(entries.map[&1].age, 1); + for (row, slot) in before { + assert_eq!(entries.map[&row].slot, slot); + } +} + +#[test] +fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { + let mut entries = Residents::default(); + let capacity = 12u32; + let mut next = 0u32; + // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) + let rows1: Vec = (100..112).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + next = n; + assert_eq!(next, capacity); + let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); + assert!(lookup.miss_rows.is_empty()); + // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) + let rows3 = [100u64, 101, 500, 501, 502, 503]; + let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); + assert_eq!(n, capacity); + let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); + assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); + let distinct: std::collections::HashSet<_> = slot.iter().collect(); + assert_eq!(distinct.len(), 4); + // the evicted rows' slots are the ones handed out + for (i, v) in evicted.iter().enumerate() { + assert_eq!(entries.map[v].slot, slot[i]); + } + apply(&mut entries, &lookup, &slot, &victims, 3); + consistent(&entries); + assert_eq!(entries.len(), capacity as usize); + for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { + assert!(entries.contains_key(&r), "row {r}"); + } +} + +/// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row +/// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. +#[test] +fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { + let mut entries = Residents::default(); + let first: Vec = (1..=32).map(|r| r * 1000).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let given: std::collections::HashMap = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect(); + let slot_of = |row: u64| given[&row]; + let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; + let flat = |lookup: &Lookup| lookup.slots.clone(); + // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset + let mut swapped = first.clone(); + swapped.rotate_left(16); + let mut reversed = first.clone(); + reversed.reverse(); + let mut shifted = first.clone(); + shifted.rotate_left(1); + for (name, rows) in [ + ("swapped", swapped), + ("reversed", reversed), + ("shifted", shifted), + ("one row repeated", vec![first[5]; 16]), + ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), + ] { + let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); + assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); + assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); + } + // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats + let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; + let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); + for (at, &row) in mixed.iter().enumerate() { + let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; + // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves + assert_eq!(lookup.slots[at], want, "mixed position {at}"); + } + // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each + let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); + assert_eq!((named(0), named(1)), (4, 4)); +} + +#[test] +fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { + let mut entries = Residents::default(); + let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); + let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable + let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); + assert_eq!(lookup.miss_rows.len(), 4); + assert_eq!( + assign_slots(&entries, next, 8, 2, 4).err(), + Some(Error::InvalidDimension) + ); +} diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index d91c98a3..cfb43270 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -73,356 +73,7 @@ pub use sys::{FdMapping, raise_memlock_soft}; #[cfg(all(target_os = "linux", target_pointer_width = "64"))] #[allow(unsafe_code)] -mod sys { - use super::{LockOutcome, PAGE}; - use std::io; - use std::os::fd::{AsRawFd, BorrowedFd}; - - /// A read-only `MAP_SHARED` mapping of a descriptor, held only for `mlock`, `mincore` and `madvise`. - /// - /// Invariants (the whole safety argument of this module): - /// * `addr..addr+len` is a live mapping created by `mmap` in `map_readonly` and unmapped exactly once, in `Drop`; - /// * no reference or slice into it is ever created: the pointer is only passed to system calls, so there is - /// nothing to dangle, alias or fault on (and the sealed memfd cannot shrink under it); - /// * every range handed to a syscall is checked `offset + n <= len` and page aligned first. - pub struct FdMapping { - addr: *mut libc::c_void, - len: usize, - locked: u64, - /// Ranges locked by `lock_ranges` (a sparse archive locks its extents only; the prefix counter above stays 0). - locked_spans: Vec<(u64, u64)>, - } - - // SAFETY: the pointer is an address-space handle used only by thread-safe system calls on an immutable mapping; it - // is never dereferenced, so sharing it between threads cannot race. - unsafe impl Send for FdMapping {} - // SAFETY: see `Send`; all methods take `&self` and only issue syscalls, or `&mut self` for the lock counter. - unsafe impl Sync for FdMapping {} - - /// Raise the soft `RLIMIT_MEMLOCK` to `to` (never above the hard limit). - pub fn raise_memlock_soft(to: u64) -> io::Result<()> { - let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; - // SAFETY: `lim` is a valid, writable rlimit for the duration of the call. - if unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, &mut lim) } != 0 { - return Err(io::Error::last_os_error()); - } - lim.rlim_cur = to.min(lim.rlim_max); - // SAFETY: `lim` is a valid, initialized rlimit. - if unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &lim) } != 0 { - return Err(io::Error::last_os_error()); - } - Ok(()) - } - - impl FdMapping { - /// Map `len` bytes of `fd` read-only. `len` must be non-zero and the descriptor at least that long. - pub fn map_readonly(fd: BorrowedFd<'_>, len: usize) -> io::Result { - if len == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty mapping")); - } - // SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing - // mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED. - let addr = unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) }; - if addr == libc::MAP_FAILED { - return Err(io::Error::last_os_error()); - } - Ok(Self { addr, len, locked: 0, locked_spans: Vec::new() }) - } - pub fn start(&self) -> u64 { - self.addr as usize as u64 - } - pub fn len(&self) -> u64 { - self.len as u64 - } - pub fn is_empty(&self) -> bool { - self.len == 0 - } - pub fn locked_bytes(&self) -> u64 { - self.locked - } - fn range(&self, offset: u64, n: u64) -> io::Result<(*mut libc::c_void, usize)> { - if !offset.is_multiple_of(PAGE) - || n == 0 - || offset.checked_add(n).is_none_or(|end| end > self.len as u64) - || usize::try_from(offset).is_err() - || usize::try_from(n).is_err() - { - return Err(io::Error::new(io::ErrorKind::InvalidInput, "range outside the mapping")); - } - // SAFETY: `offset <= len` was checked, so the result stays inside (or one past) the mapping. - Ok((unsafe { self.addr.cast::().add(offset as usize) }.cast(), n as usize)) - } - /// Lock `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. - /// A chunk that is swapped out must be read back from swap (host memory), which is why the guard exists. - pub fn lock(&mut self, chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { - let chunk = chunk.max(PAGE) / PAGE * PAGE; - let total = self.len as u64; - let mut offset = self.locked; - while offset < total { - let n = chunk.min(total - offset); - if !allow(n) { - return LockOutcome::Partial { locked: self.locked, wanted: total, why: "host memory guard refused the next chunk".into() }; - } - let (ptr, n_usize) = match self.range(offset, n) { - Ok(r) => r, - Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() }, - }; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. - if unsafe { libc::mlock(ptr, n_usize) } != 0 { - let e = io::Error::last_os_error(); - return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") }; - } - offset += n; - self.locked = offset; - } - LockOutcome::Locked { bytes: self.locked } - } - /// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before - /// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file - /// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the - /// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans. - pub fn lock_ranges(&mut self, spans: &[super::Span], chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { - let wanted = super::spans_bytes(spans); - if let Err(why) = super::check_spans(spans, self.len as u64) { - return LockOutcome::Partial { locked: 0, wanted, why }; - } - let chunk = chunk.max(PAGE) / PAGE * PAGE; - let mut locked = 0u64; - for &(span_offset, span_len) in spans { - let mut done = 0u64; - while done < span_len { - let n = chunk.min(span_len - done); - if !allow(n) { - return LockOutcome::Partial { locked, wanted, why: "host memory guard refused the next chunk".into() }; - } - let (ptr, n_usize) = match self.range(span_offset + done, n) { - Ok(r) => r, - Err(e) => return LockOutcome::Partial { locked, wanted, why: e.to_string() }, - }; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. - if unsafe { libc::mlock(ptr, n_usize) } != 0 { - let e = io::Error::last_os_error(); - return LockOutcome::Partial { locked, wanted, why: format!("mlock: {e}") }; - } - self.locked_spans.push((span_offset + done, n)); - done += n; - locked += n; - self.locked = locked; - } - } - LockOutcome::Locked { bytes: locked } - } - /// Unlock everything this mapping locked. - pub fn unlock(&mut self) { - if self.locked > 0 && self.locked_spans.is_empty() { - // SAFETY: the locked prefix `addr..addr+locked` lies inside our live mapping. - let _ = unsafe { libc::munlock(self.addr, self.locked as usize) }; - } - for (offset, n) in std::mem::take(&mut self.locked_spans) { - if let Ok((ptr, n_usize)) = self.range(offset, n) { - // SAFETY: the span was locked by `lock_ranges` and lies inside our live mapping (checked by `range`). - let _ = unsafe { libc::munlock(ptr, n_usize) }; - } - } - self.locked = 0; - } - /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the caller - /// may not write, newer kernels report every page resident: use the smaps number for totals. - pub fn incore(&self, offset: u64, n: u64) -> io::Result> { - let (ptr, n_usize) = self.range(offset, n)?; - let pages = n_usize.div_ceil(PAGE as usize); - let mut vec = vec![0u8; pages]; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; `vec` has one byte per page of the range. - if unsafe { libc::mincore(ptr, n_usize, vec.as_mut_ptr()) } != 0 { - return Err(io::Error::last_os_error()); - } - Ok(vec.into_iter().map(|b| b & 1 == 1).collect()) - } - /// Bring `offset..offset+n` into memory (read faults, including from swap) without touching the bytes. - pub fn populate(&self, offset: u64, n: u64) -> io::Result<()> { - let (ptr, n_usize) = self.range(offset, n)?; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; MADV_POPULATE_READ changes no contents. - if unsafe { libc::madvise(ptr, n_usize, libc::MADV_POPULATE_READ) } != 0 { - return Err(io::Error::last_os_error()); - } - Ok(()) - } - } - - impl Drop for FdMapping { - fn drop(&mut self) { - // SAFETY: `addr`/`len` are exactly what `mmap` returned/was given, and `drop` runs once; nothing borrows - // the mapping (no references are ever created into it). munlock is implied by munmap. - unsafe { - libc::munmap(self.addr, self.len); - } - } - } - - #[cfg(all(test, not(miri)))] - mod tests { - use super::*; - use std::io::Write; - use std::os::fd::AsFd; - - fn file(len: usize) -> std::fs::File { - let mut f = tempfile_in_target(); - f.write_all(&vec![7u8; len]).unwrap(); - f.flush().unwrap(); - f - } - fn tempfile_in_target() -> std::fs::File { - // an unlinked file under the system temp dir - let path = std::env::temp_dir().join(format!("leleka-memory-lock-{}-{:?}", std::process::id(), std::thread::current().id())); - let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap(); - let _ = std::fs::remove_file(&path); - f - } - - #[test] - fn maps_locks_inside_the_limit_and_reports_incore() { - let f = file(64 * 4096); - let mut m = FdMapping::map_readonly(f.as_fd(), 64 * 4096).unwrap(); - assert_eq!(m.len(), 64 * 4096); - let mut asked = Vec::new(); - let outcome = m.lock(16 * 4096, |n| { - asked.push(n); - true - }); - // 64 pages = 256 KiB: inside any RLIMIT_MEMLOCK of 8 MiB - assert_eq!(outcome, LockOutcome::Locked { bytes: 64 * 4096 }, "{outcome:?}"); - assert_eq!(asked, vec![16 * 4096; 4]); - let pages = m.incore(0, 64 * 4096).unwrap(); - assert_eq!(pages.len(), 64); - assert!(pages.iter().all(|&p| p)); - m.populate(0, 64 * 4096).unwrap(); - m.unlock(); - assert_eq!(m.locked_bytes(), 0); - } - - #[test] - fn the_guard_stops_the_lock_between_chunks() { - let f = file(32 * 4096); - let mut m = FdMapping::map_readonly(f.as_fd(), 32 * 4096).unwrap(); - let mut calls = 0; - let outcome = m.lock(8 * 4096, |_| { - calls += 1; - calls <= 2 - }); - assert!(matches!(outcome, LockOutcome::Partial { locked, .. } if locked == 16 * 4096), "{outcome:?}"); - assert_eq!(m.locked_bytes(), 16 * 4096); - } - - #[test] - fn ranges_outside_the_mapping_or_unaligned_are_refused_before_any_syscall() { - let f = file(8 * 4096); - let m = FdMapping::map_readonly(f.as_fd(), 8 * 4096).unwrap(); - assert!(m.incore(4096, 8 * 4096).is_err()); - assert!(m.incore(1, 4096).is_err()); - assert!(m.populate(0, 0).is_err()); - assert!(m.populate(u64::MAX - 100, 4096).is_err()); - assert!(m.incore(0, 8 * 4096).is_ok()); - } - - #[test] - fn an_empty_mapping_is_refused() { - let f = file(4096); - assert!(FdMapping::map_readonly(f.as_fd(), 0).is_err()); - } - - /// An anonymous memfd of `pages` pages with data in the page ranges `data` (everything else is a hole). - fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File { - use std::os::fd::FromRawFd; - use std::os::unix::fs::FileExt; - // SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it. - let f = unsafe { - let fd = libc::memfd_create(c"leleka-lock-test".as_ptr(), 0); - assert!(fd >= 0, "memfd_create: {}", io::Error::last_os_error()); - std::fs::File::from_raw_fd(fd) - }; - f.set_len(pages * PAGE).unwrap(); - for &(first, count) in data { - for page in first..first + count { - f.write_all_at(&vec![0xA5u8; PAGE as usize], page * PAGE).unwrap(); - } - } - f - } - fn allocated(f: &std::fs::File) -> u64 { - use std::os::unix::fs::MetadataExt; - f.metadata().unwrap().blocks() * 512 - } - fn pages_to_spans(ranges: &[(u64, u64)]) -> Vec<(u64, u64)> { - ranges.iter().map(|&(first, count)| (first * PAGE, count * PAGE)).collect() - } - - #[test] - fn locking_and_populating_the_extents_of_a_sparse_memfd_allocates_nothing_in_the_holes() { - let data = [(10u64, 4u64), (100, 6)]; - let spans = pages_to_spans(&data); - let f = sparse_memfd(256, &data); - assert_eq!(allocated(&f), 10 * PAGE, "only the pages written exist"); - let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); - assert_eq!(allocated(&f), 10 * PAGE, "mapping a sparse file allocates nothing"); - let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| true); - assert_eq!(outcome, LockOutcome::Locked { bytes: 10 * PAGE }, "{outcome:?}"); - assert_eq!(m.locked_bytes(), 10 * PAGE); - assert_eq!(allocated(&f), 10 * PAGE, "locking the extents instantiated no hole"); - for &(offset, n) in &spans { - m.populate(offset, n).unwrap(); - } - assert_eq!(allocated(&f), 10 * PAGE, "populating the extents instantiated no hole"); - m.unlock(); - assert_eq!(m.locked_bytes(), 0); - assert_eq!(allocated(&f), 10 * PAGE); - } - - #[test] - fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() { - // the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be needed - let f = sparse_memfd(256, &[(10, 4), (100, 6)]); - let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); - let outcome = m.lock(64 * PAGE, |_| true); - assert_eq!(outcome, LockOutcome::Locked { bytes: 256 * PAGE }, "{outcome:?}"); - assert_eq!(allocated(&f), 256 * PAGE, "mlock of a shmem hole allocates a zero page"); - } - - #[test] - fn lock_ranges_refuses_spans_that_are_unaligned_overlapping_unsorted_or_outside_before_any_syscall() { - let f = sparse_memfd(16, &[(0, 2)]); - let mut m = FdMapping::map_readonly(f.as_fd(), (16 * PAGE) as usize).unwrap(); - for bad in [ - vec![(1, PAGE)], - vec![(0, 2 * PAGE), (PAGE, PAGE)], - vec![(4 * PAGE, PAGE), (0, PAGE)], - vec![(15 * PAGE, 2 * PAGE)], - vec![(0, 0)], - ] { - let outcome = m.lock_ranges(&bad, PAGE, |_| panic!("the guard must not be consulted for an invalid span")); - assert!(matches!(outcome, LockOutcome::Partial { locked: 0, .. }), "{bad:?}: {outcome:?}"); - } - assert_eq!(m.locked_bytes(), 0); - assert_eq!(allocated(&f), 2 * PAGE); - } - - #[test] - fn the_guard_can_stop_a_ranged_lock_between_chunks_and_unlock_releases_what_was_locked() { - let f = sparse_memfd(64, &[(0, 8), (32, 8)]); - let mut m = FdMapping::map_readonly(f.as_fd(), (64 * PAGE) as usize).unwrap(); - let spans = pages_to_spans(&[(0, 8), (32, 8)]); - let mut calls = 0; - let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| { - calls += 1; - calls <= 3 - }); - assert!(matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), "{outcome:?}"); - assert_eq!(m.locked_bytes(), 12 * PAGE); - m.unlock(); - assert_eq!(m.locked_bytes(), 0); - assert_eq!(allocated(&f), 16 * PAGE); - } - } -} +mod sys; #[cfg(test)] mod tests; diff --git a/crates/leleka-memory/src/lock/sys.rs b/crates/leleka-memory/src/lock/sys.rs new file mode 100644 index 00000000..acfb9ab2 --- /dev/null +++ b/crates/leleka-memory/src/lock/sys.rs @@ -0,0 +1,350 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::{LockOutcome, PAGE}; +use std::io; +use std::os::fd::{AsRawFd, BorrowedFd}; + +/// A read-only `MAP_SHARED` mapping of a descriptor, held only for `mlock`, `mincore` and `madvise`. +/// +/// Invariants (the whole safety argument of this module): +/// * `addr..addr+len` is a live mapping created by `mmap` in `map_readonly` and unmapped exactly once, in `Drop`; +/// * no reference or slice into it is ever created: the pointer is only passed to system calls, so there is +/// nothing to dangle, alias or fault on (and the sealed memfd cannot shrink under it); +/// * every range handed to a syscall is checked `offset + n <= len` and page aligned first. +pub struct FdMapping { + addr: *mut libc::c_void, + len: usize, + locked: u64, + /// Ranges locked by `lock_ranges` (a sparse archive locks its extents only; the prefix counter above stays 0). + locked_spans: Vec<(u64, u64)>, +} + +// SAFETY: the pointer is an address-space handle used only by thread-safe system calls on an immutable mapping; it +// is never dereferenced, so sharing it between threads cannot race. +unsafe impl Send for FdMapping {} +// SAFETY: see `Send`; all methods take `&self` and only issue syscalls, or `&mut self` for the lock counter. +unsafe impl Sync for FdMapping {} + +/// Raise the soft `RLIMIT_MEMLOCK` to `to` (never above the hard limit). +pub fn raise_memlock_soft(to: u64) -> io::Result<()> { + let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; + // SAFETY: `lim` is a valid, writable rlimit for the duration of the call. + if unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, &mut lim) } != 0 { + return Err(io::Error::last_os_error()); + } + lim.rlim_cur = to.min(lim.rlim_max); + // SAFETY: `lim` is a valid, initialized rlimit. + if unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &lim) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +impl FdMapping { + /// Map `len` bytes of `fd` read-only. `len` must be non-zero and the descriptor at least that long. + pub fn map_readonly(fd: BorrowedFd<'_>, len: usize) -> io::Result { + if len == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty mapping")); + } + // SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing + // mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED. + let addr = unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) }; + if addr == libc::MAP_FAILED { + return Err(io::Error::last_os_error()); + } + Ok(Self { addr, len, locked: 0, locked_spans: Vec::new() }) + } + pub fn start(&self) -> u64 { + self.addr as usize as u64 + } + pub fn len(&self) -> u64 { + self.len as u64 + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + pub fn locked_bytes(&self) -> u64 { + self.locked + } + fn range(&self, offset: u64, n: u64) -> io::Result<(*mut libc::c_void, usize)> { + if !offset.is_multiple_of(PAGE) + || n == 0 + || offset.checked_add(n).is_none_or(|end| end > self.len as u64) + || usize::try_from(offset).is_err() + || usize::try_from(n).is_err() + { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "range outside the mapping")); + } + // SAFETY: `offset <= len` was checked, so the result stays inside (or one past) the mapping. + Ok((unsafe { self.addr.cast::().add(offset as usize) }.cast(), n as usize)) + } + /// Lock `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. + /// A chunk that is swapped out must be read back from swap (host memory), which is why the guard exists. + pub fn lock(&mut self, chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { + let chunk = chunk.max(PAGE) / PAGE * PAGE; + let total = self.len as u64; + let mut offset = self.locked; + while offset < total { + let n = chunk.min(total - offset); + if !allow(n) { + return LockOutcome::Partial { locked: self.locked, wanted: total, why: "host memory guard refused the next chunk".into() }; + } + let (ptr, n_usize) = match self.range(offset, n) { + Ok(r) => r, + Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() }, + }; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + if unsafe { libc::mlock(ptr, n_usize) } != 0 { + let e = io::Error::last_os_error(); + return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") }; + } + offset += n; + self.locked = offset; + } + LockOutcome::Locked { bytes: self.locked } + } + /// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before + /// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file + /// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the + /// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans. + pub fn lock_ranges(&mut self, spans: &[super::Span], chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { + let wanted = super::spans_bytes(spans); + if let Err(why) = super::check_spans(spans, self.len as u64) { + return LockOutcome::Partial { locked: 0, wanted, why }; + } + let chunk = chunk.max(PAGE) / PAGE * PAGE; + let mut locked = 0u64; + for &(span_offset, span_len) in spans { + let mut done = 0u64; + while done < span_len { + let n = chunk.min(span_len - done); + if !allow(n) { + return LockOutcome::Partial { locked, wanted, why: "host memory guard refused the next chunk".into() }; + } + let (ptr, n_usize) = match self.range(span_offset + done, n) { + Ok(r) => r, + Err(e) => return LockOutcome::Partial { locked, wanted, why: e.to_string() }, + }; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + if unsafe { libc::mlock(ptr, n_usize) } != 0 { + let e = io::Error::last_os_error(); + return LockOutcome::Partial { locked, wanted, why: format!("mlock: {e}") }; + } + self.locked_spans.push((span_offset + done, n)); + done += n; + locked += n; + self.locked = locked; + } + } + LockOutcome::Locked { bytes: locked } + } + /// Unlock everything this mapping locked. + pub fn unlock(&mut self) { + if self.locked > 0 && self.locked_spans.is_empty() { + // SAFETY: the locked prefix `addr..addr+locked` lies inside our live mapping. + let _ = unsafe { libc::munlock(self.addr, self.locked as usize) }; + } + for (offset, n) in std::mem::take(&mut self.locked_spans) { + if let Ok((ptr, n_usize)) = self.range(offset, n) { + // SAFETY: the span was locked by `lock_ranges` and lies inside our live mapping (checked by `range`). + let _ = unsafe { libc::munlock(ptr, n_usize) }; + } + } + self.locked = 0; + } + /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the caller + /// may not write, newer kernels report every page resident: use the smaps number for totals. + pub fn incore(&self, offset: u64, n: u64) -> io::Result> { + let (ptr, n_usize) = self.range(offset, n)?; + let pages = n_usize.div_ceil(PAGE as usize); + let mut vec = vec![0u8; pages]; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; `vec` has one byte per page of the range. + if unsafe { libc::mincore(ptr, n_usize, vec.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(vec.into_iter().map(|b| b & 1 == 1).collect()) + } + /// Bring `offset..offset+n` into memory (read faults, including from swap) without touching the bytes. + pub fn populate(&self, offset: u64, n: u64) -> io::Result<()> { + let (ptr, n_usize) = self.range(offset, n)?; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; MADV_POPULATE_READ changes no contents. + if unsafe { libc::madvise(ptr, n_usize, libc::MADV_POPULATE_READ) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } +} + +impl Drop for FdMapping { + fn drop(&mut self) { + // SAFETY: `addr`/`len` are exactly what `mmap` returned/was given, and `drop` runs once; nothing borrows + // the mapping (no references are ever created into it). munlock is implied by munmap. + unsafe { + libc::munmap(self.addr, self.len); + } + } +} + +#[cfg(all(test, not(miri)))] +mod tests { + use super::*; + use std::io::Write; + use std::os::fd::AsFd; + + fn file(len: usize) -> std::fs::File { + let mut f = tempfile_in_target(); + f.write_all(&vec![7u8; len]).unwrap(); + f.flush().unwrap(); + f + } + fn tempfile_in_target() -> std::fs::File { + // an unlinked file under the system temp dir + let path = std::env::temp_dir().join(format!("leleka-memory-lock-{}-{:?}", std::process::id(), std::thread::current().id())); + let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap(); + let _ = std::fs::remove_file(&path); + f + } + + #[test] + fn maps_locks_inside_the_limit_and_reports_incore() { + let f = file(64 * 4096); + let mut m = FdMapping::map_readonly(f.as_fd(), 64 * 4096).unwrap(); + assert_eq!(m.len(), 64 * 4096); + let mut asked = Vec::new(); + let outcome = m.lock(16 * 4096, |n| { + asked.push(n); + true + }); + // 64 pages = 256 KiB: inside any RLIMIT_MEMLOCK of 8 MiB + assert_eq!(outcome, LockOutcome::Locked { bytes: 64 * 4096 }, "{outcome:?}"); + assert_eq!(asked, vec![16 * 4096; 4]); + let pages = m.incore(0, 64 * 4096).unwrap(); + assert_eq!(pages.len(), 64); + assert!(pages.iter().all(|&p| p)); + m.populate(0, 64 * 4096).unwrap(); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + } + + #[test] + fn the_guard_stops_the_lock_between_chunks() { + let f = file(32 * 4096); + let mut m = FdMapping::map_readonly(f.as_fd(), 32 * 4096).unwrap(); + let mut calls = 0; + let outcome = m.lock(8 * 4096, |_| { + calls += 1; + calls <= 2 + }); + assert!(matches!(outcome, LockOutcome::Partial { locked, .. } if locked == 16 * 4096), "{outcome:?}"); + assert_eq!(m.locked_bytes(), 16 * 4096); + } + + #[test] + fn ranges_outside_the_mapping_or_unaligned_are_refused_before_any_syscall() { + let f = file(8 * 4096); + let m = FdMapping::map_readonly(f.as_fd(), 8 * 4096).unwrap(); + assert!(m.incore(4096, 8 * 4096).is_err()); + assert!(m.incore(1, 4096).is_err()); + assert!(m.populate(0, 0).is_err()); + assert!(m.populate(u64::MAX - 100, 4096).is_err()); + assert!(m.incore(0, 8 * 4096).is_ok()); + } + + #[test] + fn an_empty_mapping_is_refused() { + let f = file(4096); + assert!(FdMapping::map_readonly(f.as_fd(), 0).is_err()); + } + + /// An anonymous memfd of `pages` pages with data in the page ranges `data` (everything else is a hole). + fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File { + use std::os::fd::FromRawFd; + use std::os::unix::fs::FileExt; + // SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it. + let f = unsafe { + let fd = libc::memfd_create(c"leleka-lock-test".as_ptr(), 0); + assert!(fd >= 0, "memfd_create: {}", io::Error::last_os_error()); + std::fs::File::from_raw_fd(fd) + }; + f.set_len(pages * PAGE).unwrap(); + for &(first, count) in data { + for page in first..first + count { + f.write_all_at(&vec![0xA5u8; PAGE as usize], page * PAGE).unwrap(); + } + } + f + } + fn allocated(f: &std::fs::File) -> u64 { + use std::os::unix::fs::MetadataExt; + f.metadata().unwrap().blocks() * 512 + } + fn pages_to_spans(ranges: &[(u64, u64)]) -> Vec<(u64, u64)> { + ranges.iter().map(|&(first, count)| (first * PAGE, count * PAGE)).collect() + } + + #[test] + fn locking_and_populating_the_extents_of_a_sparse_memfd_allocates_nothing_in_the_holes() { + let data = [(10u64, 4u64), (100, 6)]; + let spans = pages_to_spans(&data); + let f = sparse_memfd(256, &data); + assert_eq!(allocated(&f), 10 * PAGE, "only the pages written exist"); + let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); + assert_eq!(allocated(&f), 10 * PAGE, "mapping a sparse file allocates nothing"); + let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| true); + assert_eq!(outcome, LockOutcome::Locked { bytes: 10 * PAGE }, "{outcome:?}"); + assert_eq!(m.locked_bytes(), 10 * PAGE); + assert_eq!(allocated(&f), 10 * PAGE, "locking the extents instantiated no hole"); + for &(offset, n) in &spans { + m.populate(offset, n).unwrap(); + } + assert_eq!(allocated(&f), 10 * PAGE, "populating the extents instantiated no hole"); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 10 * PAGE); + } + + #[test] + fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() { + // the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be needed + let f = sparse_memfd(256, &[(10, 4), (100, 6)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); + let outcome = m.lock(64 * PAGE, |_| true); + assert_eq!(outcome, LockOutcome::Locked { bytes: 256 * PAGE }, "{outcome:?}"); + assert_eq!(allocated(&f), 256 * PAGE, "mlock of a shmem hole allocates a zero page"); + } + + #[test] + fn lock_ranges_refuses_spans_that_are_unaligned_overlapping_unsorted_or_outside_before_any_syscall() { + let f = sparse_memfd(16, &[(0, 2)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (16 * PAGE) as usize).unwrap(); + for bad in [ + vec![(1, PAGE)], + vec![(0, 2 * PAGE), (PAGE, PAGE)], + vec![(4 * PAGE, PAGE), (0, PAGE)], + vec![(15 * PAGE, 2 * PAGE)], + vec![(0, 0)], + ] { + let outcome = m.lock_ranges(&bad, PAGE, |_| panic!("the guard must not be consulted for an invalid span")); + assert!(matches!(outcome, LockOutcome::Partial { locked: 0, .. }), "{bad:?}: {outcome:?}"); + } + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 2 * PAGE); + } + + #[test] + fn the_guard_can_stop_a_ranged_lock_between_chunks_and_unlock_releases_what_was_locked() { + let f = sparse_memfd(64, &[(0, 8), (32, 8)]); + let mut m = FdMapping::map_readonly(f.as_fd(), (64 * PAGE) as usize).unwrap(); + let spans = pages_to_spans(&[(0, 8), (32, 8)]); + let mut calls = 0; + let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| { + calls += 1; + calls <= 3 + }); + assert!(matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), "{outcome:?}"); + assert_eq!(m.locked_bytes(), 12 * PAGE); + m.unlock(); + assert_eq!(m.locked_bytes(), 0); + assert_eq!(allocated(&f), 16 * PAGE); + } +} diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index 9a5a2c3e..2a4f769d 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -153,899 +153,7 @@ struct Cursor { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { - struct Counted { - bytes: std::io::Cursor>, - reads: usize, - seeks: usize, - requests: Vec, - } - impl Read for Counted { - fn read(&mut self, out: &mut [u8]) -> std::io::Result { - self.reads += 1; - self.requests.push(out.len()); - self.bytes.read(out) - } - } - impl Seek for Counted { - fn seek(&mut self, from: SeekFrom) -> std::io::Result { - self.seeks += 1; - self.bytes.seek(from) - } - } - let mut bytes = Vec::new(); - for _ in 0..512 { - bytes.extend(0x10203040u32.to_le_bytes()); - } - const SMALL_CAPACITY: usize = 64 * 1024; - bytes.resize(SMALL_CAPACITY - 4, 0); - string(&mut bytes, "edge-é"); // Eight-byte length crosses the buffer edge. - bytes.extend(0xa1b2c3d4u32.to_le_bytes()); - let skipped = SMALL_CAPACITY * 2 + 17; - bytes.resize(bytes.len() + skipped, 0); - bytes.extend(0x5678u16.to_le_bytes()); - let length = bytes.len() as u64; - let counted = Counted { - bytes: std::io::Cursor::new(bytes), - reads: 0, - seeks: 0, - requests: Vec::new(), - }; - let mut cursor = Cursor::with_test_capacity(counted, length, SMALL_CAPACITY); - for _ in 0..512 { - assert_eq!(cursor.u32().unwrap(), 0x10203040); - } - assert_eq!(cursor.position().unwrap(), 2048); - assert_eq!(cursor.file.get_ref().reads, 1); - assert_eq!(cursor.file.get_ref().seeks, 0); - assert_eq!(cursor.file.get_ref().bytes.position(), 65536); - cursor.skip(7).unwrap(); // Consume already read bytes, without a seek. - cursor.skip((65532 - 2055) as u64).unwrap(); - assert_eq!(cursor.file.get_ref().seeks, 0); - assert_eq!(cursor.string().unwrap(), "edge-é"); - assert_eq!(cursor.u32().unwrap(), 0xa1b2c3d4); - assert_eq!(cursor.position().unwrap(), 65551); - assert_eq!(cursor.file.get_ref().reads, 2); - cursor.skip(skipped as u64).unwrap(); // One absolute seek outside cache. - assert_eq!(cursor.file.get_ref().seeks, 1); - assert_eq!(cursor.u16().unwrap(), 0x5678); - assert_eq!(cursor.position().unwrap(), length); - assert_eq!(cursor.file.get_ref().reads, 3); - assert!(cursor.file.get_ref().requests.iter().all(|n| *n == 65536)); - assert_eq!( - cursor.skip(1).unwrap_err().to_string(), - "truncated GGUF header" - ); - assert_eq!( - cursor.u8().unwrap_err().to_string(), - "truncated GGUF header" - ); - assert_eq!( - cursor.skip(u64::MAX).unwrap_err().to_string(), - "GGUF offset overflow" - ); - - let mut production = Cursor::new( - Counted { - bytes: std::io::Cursor::new(vec![0x78, 0x56, 0x34, 0x12]), - reads: 0, - seeks: 0, - requests: Vec::new(), - }, - 4, - ); - assert_eq!(production.file.capacity(), 16 * 1024 * 1024); - assert_eq!(production.u32().unwrap(), 0x12345678); - assert_eq!(production.position().unwrap(), 4); - assert_eq!(production.file.get_ref().requests, [16 * 1024 * 1024]); - assert_eq!(production.file.get_ref().seeks, 0); - - let mut short = Cursor::new(std::io::Cursor::new(vec![0u8; 3]), 4); - assert_eq!( - short - .u32() - .unwrap_err() - .downcast_ref::() - .unwrap() - .kind(), - std::io::ErrorKind::UnexpectedEof - ); - let mut oversized = Cursor::new(std::io::Cursor::new(1_048_577u64.to_le_bytes()), 8); - assert_eq!( - oversized.string().unwrap_err().to_string(), - "GGUF header string is too large" - ); - let mut bad = Cursor::new(std::io::Cursor::new(9u32.to_le_bytes()), 4); - assert_eq!( - bad.skip_value(9).unwrap_err().to_string(), - "truncated GGUF header" - ); - let mut bad = Cursor::new(std::io::Cursor::new(Vec::new()), 0); - assert_eq!( - bad.skip_value(99).unwrap_err().to_string(), - "unknown GGUF metadata type 99" - ); - - // Actual parser entrypoints: literal metadata, a skipped long string, - // logical header alignment, and a subsequent read of the original FD. - let mut fixture = OwnedFixture::new(); - let mut data = b"GGUF".to_vec(); - data.extend(3u32.to_le_bytes()); - data.extend(1u64.to_le_bytes()); - data.extend(3u64.to_le_bytes()); - string(&mut data, "general.architecture"); - data.extend(8u32.to_le_bytes()); - string(&mut data, "qwen4exp"); - string(&mut data, "ignored"); - data.extend(8u32.to_le_bytes()); - string(&mut data, &"z".repeat(SMALL_CAPACITY + 11)); - string(&mut data, "qwen4exp.block_count"); - data.extend(4u32.to_le_bytes()); - data.extend(48u32.to_le_bytes()); - string(&mut data, "weight"); - data.extend(1u32.to_le_bytes()); - data.extend(4u64.to_le_bytes()); - data.extend(0u32.to_le_bytes()); - data.extend(0u64.to_le_bytes()); - let header_end = data.len(); - let data_start = header_end.div_ceil(32) * 32; - data.resize(data_start, 0); - data.extend([0x11u8, 0x22, 0x33, 0x44].repeat(4)); - fixture.bytes = data; - std::fs::write(&fixture.path, &fixture.bytes).unwrap(); - let mut verified = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert_eq!(verified.index().summary.data_start, data_start as u64); - assert_eq!( - verified.index().summary.architecture.as_deref(), - Some("qwen4exp") - ); - assert_eq!(verified.index().tensors[0].name, "weight"); - assert_eq!(verified.index().tensors[0].bytes, 16); - let snapshot = verified.profile_snapshot().unwrap(); - assert_eq!(snapshot.architecture.as_deref(), Some("qwen4exp")); - assert!(matches!( - snapshot.values.get("qwen4exp.block_count"), - Some(MetadataValue::Unsigned(48)) - )); - let mut payload = Vec::new(); - verified - .stream_tensor(0, 0, 16, |chunk| { - payload.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - assert_eq!(payload, [0x11u8, 0x22, 0x33, 0x44].repeat(4)); - assert_eq!( - verified.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); - - let mut duplicate = b"GGUF".to_vec(); - duplicate.extend(3u32.to_le_bytes()); - duplicate.extend(0u64.to_le_bytes()); - duplicate.extend(2u64.to_le_bytes()); - for _ in 0..2 { - string(&mut duplicate, "general.architecture"); - duplicate.extend(8u32.to_le_bytes()); - string(&mut duplicate, "qwen4exp"); - } - std::fs::write(&fixture.path, &duplicate).unwrap(); - let mut file = File::open(&fixture.path).unwrap(); - for result in [ - read_index_file(&mut file, duplicate.len() as u64, false).map(|_| ()), - read_metadata_snapshot(&mut file, duplicate.len() as u64, None, false).map(|_| ()), - ] { - assert_eq!( - result.unwrap_err().to_string(), - "duplicate GGUF metadata key: general.architecture" - ); - } - - // The production span bound is exercised independently of header strings - // (whose existing one-MiB limit remains intact). - let span = (0..STREAM_BUFFER_BYTES + 19) - .map(|at| (at % 251) as u8) - .collect::>(); - std::fs::write(&fixture.path, &span).unwrap(); - let mut file = File::open(&fixture.path).unwrap(); - let mut seen = 0; - let mut chunks = Vec::new(); - stream_file_span(&mut file, 7, (span.len() - 7) as u64, |chunk| { - assert_eq!(chunk, &span[7 + seen..7 + seen + chunk.len()]); - seen += chunk.len(); - chunks.push(chunk.len()); - Ok(()) - }) - .unwrap(); - assert_eq!(seen, span.len() - 7); - assert_eq!(chunks, [16 * 1024 * 1024, 12]); - let mut small = Vec::new(); - stream_file_span(&mut file, 13, 17, |chunk| { - assert_eq!(chunk.len(), 17); // Small spans do not allocate/read 16MiB. - small.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - assert_eq!(small, (13u8..30).collect::>()); - stream_file_span(&mut file, 0, 0, |_| panic!("empty span callback")).unwrap(); - assert_eq!( - stream_file_span(&mut file, 0, span.len() as u64 + 1, |_| Ok(())) - .unwrap_err() - .downcast_ref::() - .unwrap() - .kind(), - std::io::ErrorKind::UnexpectedEof - ); - assert_eq!( - stream_file_span(&mut file, 0, 17, |_| { - Err(std::io::Error::other("consumer sentinel")) - }) - .unwrap_err() - .to_string(), - "consumer sentinel" - ); - } - - fn string(out: &mut Vec, value: &str) { - out.extend_from_slice(&(value.len() as u64).to_le_bytes()); - out.extend_from_slice(value.as_bytes()); - } - - #[test] - fn admits_flash_metadata_and_rejects_incompatible_profiles() { - let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id())); - let fields = [ - ("qwen4exp.block_count", 48u32), - ("qwen4exp.embedding_length", 2560), - ("qwen4exp.attention.head_count", 24), - ("qwen4exp.attention.head_count_kv", 2), - ("qwen4exp.expert_count", 512), - ("qwen4exp.expert_used_count", 10), - ]; - let write = |entries: Vec<(&str, u32, Vec)>| { - let mut data = b"GGUF".to_vec(); - data.extend(3u32.to_le_bytes()); - data.extend(0u64.to_le_bytes()); - data.extend((entries.len() as u64 + 1).to_le_bytes()); - string(&mut data, "general.architecture"); - data.extend(8u32.to_le_bytes()); - string(&mut data, "qwen4exp"); - for (key, kind, bytes) in entries { - string(&mut data, key); - data.extend(kind.to_le_bytes()); - data.extend(bytes); - } - data.resize(data.len().div_ceil(32) * 32, 0); - std::fs::write(&path, data).unwrap(); - }; - let good = || { - fields - .iter() - .map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())) - .collect::>() - }; - write(good()); - check_flash_next_profile(&path).unwrap(); - for index in 0..fields.len() { - let mut entries = good(); - entries.remove(index); - write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains(fields[index].0) - ); - let mut entries = good(); - entries[index].2 = 0u32.to_le_bytes().to_vec(); - write(entries); - assert!(check_flash_next_profile(&path).is_err()); - } - for index in 0..4 { - let mut entries = good(); - entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec(); - write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains("expected") - ); - } - for (kind, bytes) in [ - (7, vec![1]), - (6, 48f32.to_le_bytes().to_vec()), - (5, (-1i32).to_le_bytes().to_vec()), - (10, (1u64 << 32).to_le_bytes().to_vec()), - ] { - let mut entries = good(); - entries[0] = (fields[0].0, kind, bytes); - write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains(fields[0].0) - ); - } - let mut entries = good(); - entries[4].2 = 256u32.to_le_bytes().to_vec(); - write(entries); - check_flash_next_profile(&path).unwrap(); - let mut entries = good(); - entries[5].2 = 513u32.to_le_bytes().to_vec(); - write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains("exceeds") - ); - for kind in [0, 1, 2, 3, 4, 5, 10, 11] { - let mut entries = good(); - let bytes = 48u64.to_le_bytes(); - let n = match kind { - 0 | 1 => 1, - 2 | 3 => 2, - 4 | 5 => 4, - _ => 8, - }; - entries[0] = (fields[0].0, kind, bytes[..n].to_vec()); - write(entries); - check_flash_next_profile(&path).unwrap(); - } - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn inspects_header_and_rejects_truncated_payload() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen4exp"); - string(&mut gguf, "test.weight"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&4u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(128, 0); - gguf.extend_from_slice(&[0; 16]); - let path = std::env::temp_dir().join(format!("strata-gguf-test-{}", std::process::id())); - std::fs::write(&path, &gguf).unwrap(); - let summary = inspect(&path).unwrap(); - assert_eq!(summary.tensors, 1); - assert_eq!(summary.architecture.as_deref(), Some("qwen4exp")); - assert_eq!(summary.types.get(&0), Some(&1)); - std::fs::write(&path, &gguf[..80]).unwrap(); - assert!(inspect(&path).is_err()); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&2u64.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - string(&mut gguf, "norm"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&4u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - string(&mut gguf, "expert"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - let shape_at = gguf.len(); - gguf.extend_from_slice(&256u64.to_le_bytes()); - let kind_at = gguf.len(); - gguf.extend_from_slice(&21u32.to_le_bytes()); - let offset_at = gguf.len(); - gguf.extend_from_slice(&32u64.to_le_bytes()); - let data_start = gguf.len().div_ceil(32) * 32; - gguf.resize(data_start, 0); - gguf.extend_from_slice(&[0u8; 16]); - gguf.extend_from_slice(&[0u8; 16]); - gguf.extend_from_slice(&[0u8; 110]); - let path = std::env::temp_dir().join(format!("strata-gguf-index-{}", std::process::id())); - std::fs::write(&path, &gguf).unwrap(); - let index = tensor_index(&path).unwrap(); - assert_eq!(index.summary.data_start, data_start as u64); - assert_eq!(index.tensors[0].bytes, 16); - assert_eq!(index.tensors[1].offset, 32); - assert_eq!(index.tensors[1].bytes, 110); - let expected: [u8; 32] = Sha256::digest([0u8; 110]).into(); - assert_eq!(tensor_sha256(&path, &index, 1).unwrap(), expected); - - gguf[offset_at..offset_at + 8].copy_from_slice(&0u64.to_le_bytes()); - std::fs::write(&path, &gguf).unwrap(); - assert!(tensor_index(&path).is_err()); - gguf[offset_at..offset_at + 8].copy_from_slice(&32u64.to_le_bytes()); - gguf[shape_at..shape_at + 8].copy_from_slice(&255u64.to_le_bytes()); - std::fs::write(&path, &gguf).unwrap(); - assert!(tensor_index(&path).is_err()); - gguf[shape_at..shape_at + 8].copy_from_slice(&256u64.to_le_bytes()); - gguf[kind_at..kind_at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); - std::fs::write(&path, &gguf).unwrap(); - assert!(tensor_index(&path).is_err()); - std::fs::remove_file(path).unwrap(); - } - - struct OwnedFixture { - directory: std::path::PathBuf, - path: std::path::PathBuf, - bytes: Vec, - small: Vec, - large: Vec, - kind_at: usize, - offset_at: usize, - } - - impl OwnedFixture { - fn new() -> Self { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT: AtomicU64 = AtomicU64::new(0); - let directory = std::env::temp_dir().join(format!( - "leleka-owned-gguf-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir(&directory).unwrap(); - let path = directory.join("fixture.gguf"); - let small = (0..16).collect::>(); - let large = (0..STREAM_BUFFER_BYTES * 3 + 11) - .map(|at| (at % 251) as u8) - .collect::>(); - let mut bytes = b"GGUF".to_vec(); - bytes.extend(3u32.to_le_bytes()); - bytes.extend(2u64.to_le_bytes()); - bytes.extend(0u64.to_le_bytes()); - string(&mut bytes, "fixture.small"); - bytes.extend(1u32.to_le_bytes()); - bytes.extend(4u64.to_le_bytes()); - bytes.extend(0u32.to_le_bytes()); - bytes.extend(0u64.to_le_bytes()); - string(&mut bytes, "fixture.large"); - bytes.extend(1u32.to_le_bytes()); - bytes.extend((large.len() as u64).to_le_bytes()); - let kind_at = bytes.len(); - bytes.extend(24u32.to_le_bytes()); - let offset_at = bytes.len(); - bytes.extend(32u64.to_le_bytes()); - bytes.resize(bytes.len().div_ceil(32) * 32, 0); - bytes.extend(&small); - bytes.extend([0u8; 16]); - bytes.extend(&large); - std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - small, - large, - kind_at, - offset_at, - } - } - - fn digest(&self) -> String { - let hex = Sha256::digest(&self.bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - format!("sha256:{hex}") - } - } - - impl Drop for OwnedFixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.directory); - } - } - - #[test] - fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() { - let fixture = OwnedFixture::new(); - let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); - assert_eq!(source.index().tensors.len(), 2); - assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64); - for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] { - assert_eq!( - source.tensor_sha256(number).unwrap(), - <[u8; 32]>::from(Sha256::digest(expected)) - ); - } - let mut seen = 0; - let mut callbacks = 0; - source - .stream_tensor(1, 0, fixture.large.len() as u64, |chunk| { - assert!(!chunk.is_empty() && chunk.len() <= STREAM_BUFFER_BYTES); - assert_eq!(chunk, &fixture.large[seen..seen + chunk.len()]); - seen += chunk.len(); - callbacks += 1; - Ok(()) - }) - .unwrap(); - assert_eq!(seen, fixture.large.len()); - assert_eq!(callbacks, 4); - let mut partial = Vec::new(); - source - .stream_tensor(1, 7, 13, |chunk| { - partial.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - assert_eq!(partial, fixture.large[7..20]); - } - - #[test] - fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { - let fixture = OwnedFixture::new(); - for digest in [ - "", - "abc", - "sha256:abc", - &format!("sha256:{}", "g".repeat(64)), - &format!("SHA256:{}", "a".repeat(64)), - ] { - assert!( - VerifiedGgufFile::open(&fixture.path, digest) - .unwrap_err() - .to_string() - .contains("invalid GGUF artifact digest") - ); - } - assert!( - VerifiedGgufFile::open(&fixture.directory, &fixture.digest()) - .unwrap_err() - .to_string() - .contains("regular file") - ); - let mut tampered = fixture.bytes.clone(); - *tampered.last_mut().unwrap() ^= 1; - std::fs::write(&fixture.path, tampered).unwrap(); - assert!( - VerifiedGgufFile::open(&fixture.path, &fixture.digest()) - .unwrap_err() - .to_string() - .contains("SHA256 mismatch") - ); - } - - #[test] - fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matching_digest() { - let mut fixture = OwnedFixture::new(); - let original = fixture.bytes.clone(); - for fault in 0..4 { - fixture.bytes = original.clone(); - match fault { - 0 => { - fixture.bytes.pop(); - } - 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4] - .copy_from_slice(&u32::MAX.to_le_bytes()), - 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8] - .copy_from_slice(&0u64.to_le_bytes()), - 3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()), - _ => unreachable!(), - } - std::fs::write(&fixture.path, &fixture.bytes).unwrap(); - assert!( - VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), - "fault {fault}" - ); - } - } - - #[test] - fn empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks() { - let fixture = OwnedFixture::new(); - let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - source.file.seek(SeekFrom::Start(3)).unwrap(); - source - .stream_tensor(0, 16, 0, |_| panic!("empty span invoked consumer")) - .unwrap(); - assert_eq!(source.file.stream_position().unwrap(), 3); - for (number, offset) in [(2, 0), (0, 17), (0, u64::MAX)] { - assert!( - source - .stream_tensor(number, offset, 0, |_| { - panic!("invalid empty span invoked consumer") - }) - .is_err() - ); - assert_eq!(source.file.stream_position().unwrap(), 3); - } - std::fs::OpenOptions::new() - .write(true) - .open(&fixture.path) - .unwrap() - .set_len(fixture.bytes.len() as u64 - 1) - .unwrap(); - assert!( - source - .stream_tensor(0, 16, 0, |_| { - panic!("changed-size empty span invoked consumer") - }) - .unwrap_err() - .to_string() - .contains("size changed") - ); - assert_eq!(source.file.stream_position().unwrap(), 3); - } - - #[test] - fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() { - let fixture = OwnedFixture::new(); - let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - for (number, offset, bytes) in [ - (2, 0, 1), - (0, 0, 17), - (0, 17, 0), - (0, u64::MAX, 1), - (0, 1, u64::MAX), - ] { - let mut called = false; - assert!( - source - .stream_tensor(number, offset, bytes, |_| { - called = true; - Ok(()) - }) - .is_err() - ); - assert!(!called); - } - source - .stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")) - .unwrap(); - assert!( - source - .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other( - "synthetic consumer failure" - ))) - .unwrap_err() - .to_string() - .contains("synthetic consumer failure") - ); - assert_eq!( - source.tensor_sha256(0).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.small)) - ); - } - - #[cfg(unix)] - #[test] - fn pathname_replacement_keeps_original_verified_file_and_index() { - let fixture = OwnedFixture::new(); - let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap(); - std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap(); - assert!(tensor_index(&fixture.path).is_err()); - assert_eq!( - source.tensor_sha256(1).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.large)) - ); - let mut small = Vec::new(); - source - .stream_tensor(0, 0, 16, |chunk| { - small.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - assert_eq!(small, fixture.small); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); - } - - #[test] - fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability() { - let fixture = OwnedFixture::new(); - let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - let mut mutated = fixture.bytes.clone(); - *mutated.last_mut().unwrap() ^= 1; - std::fs::write(&fixture.path, &mutated).unwrap(); - // Explicit counterexample: retaining the descriptor does not freeze bytes. - assert_ne!( - source.tensor_sha256(1).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.large)) - ); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); - std::fs::OpenOptions::new() - .write(true) - .open(&fixture.path) - .unwrap() - .set_len(0) - .unwrap(); - let mut called = false; - assert!( - source - .stream_tensor(0, 0, 16, |_| { - called = true; - Ok(()) - }) - .is_err() - ); - assert!(!called); - } - #[test] - fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_changes() { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT_FENCE: AtomicU64 = AtomicU64::new(0); - let directory = std::env::temp_dir().join(format!( - "leleka-source-fence-{}-{}", - std::process::id(), - NEXT_FENCE.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir(&directory).unwrap(); - struct Remove(std::path::PathBuf); - impl Drop for Remove { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - let _cleanup = Remove(directory.clone()); - let path = directory.join("source.gguf"); - // Real bounded verified source, not a synthetic model/Binding/row. - let expected: Vec = [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .flat_map(u32::to_le_bytes) - .collect(); - let mut bytes = b"GGUF".to_vec(); - bytes.extend(3u32.to_le_bytes()); - bytes.extend(1u64.to_le_bytes()); - bytes.extend(0u64.to_le_bytes()); - string(&mut bytes, "public.source"); - bytes.extend(1u32.to_le_bytes()); - bytes.extend(4u64.to_le_bytes()); - bytes.extend(0u32.to_le_bytes()); - bytes.extend(0u64.to_le_bytes()); - bytes.resize(bytes.len().div_ceil(32) * 32, 0); - bytes.extend(&expected); - assert!(bytes.len() <= 128); - std::fs::write(&path, &bytes).unwrap(); - let digest = format!( - "sha256:{}", - Sha256::digest(&bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::() - ); - let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); - // ORIGINAL empty descriptor + actual stream FIRST, before new scope. - source - .stream_tensor(0, 0, 0, |_| panic!("emptyspan callback")) - .unwrap(); - let mut original = Vec::new(); - source - .stream_tensor(0, 0, 16, |chunk| { - original.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - assert_eq!(original, expected); - let cursor = source.file.stream_position().unwrap(); - { - let mut fence = source.begin_source_fence(0).unwrap(); - fence.validate_tensor(0).unwrap(); - assert!(fence.validate_tensor(usize::MAX).is_err()); - let mut called = false; - assert!( - fence - .stream_tensor(0, 16, 1, |_| { - called = true; - Ok(()) - }) - .is_err() - ); - assert!(!called); - fence.finish().unwrap(); - } - assert_eq!(source.file.stream_position().unwrap(), cursor); - let mut actual = Vec::new(); - { - let mut fence = source.begin_source_fence(0).unwrap(); - fence - .stream_tensor(0, 0, 16, |chunk| { - actual.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - fence.finish().unwrap(); - } - assert_eq!(actual, original); - let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - writer.set_len(bytes.len() as u64 - 1).unwrap(); - // Original first refusal, then initial scoped refusal, same opened FD. - assert!(source.stream_tensor(0, 0, 0, |_| Ok(())).is_err()); - assert!(source.begin_source_fence(0).is_err()); - drop(writer); - drop(source); - std::fs::write(&path, &bytes).unwrap(); - let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); - let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - let mut pending = Vec::new(); - let mut fence = source.begin_source_fence(0).unwrap(); - fence - .stream_tensor(0, 0, 16, |chunk| { - pending.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - writer.set_len(bytes.len() as u64 - 1).unwrap(); - let accepted = fence.finish().map(|()| pending); - assert!(accepted.is_err()); // no successful return of pending payload - drop(writer); - drop(source); - std::fs::write(&path, &bytes).unwrap(); - let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); - let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - let mut fence = source.begin_source_fence(0).unwrap(); - let read = fence.stream_tensor(0, 0, 16, |_| { - writer.set_len(bytes.len() as u64 - 1)?; - Ok(()) - }); - assert!(read.is_err()); // unchanged cold stream AFTER-read check - assert!(fence.finish().is_err()); - drop(writer); - drop(source); - std::fs::write(&path, &bytes).unwrap(); - let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); - let mut fence = source.begin_source_fence(0).unwrap(); - let error = fence - .stream_tensor(0, 0, 16, |_| { - Err(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "public source consumer refusal", - )) - }) - .unwrap_err(); - assert!(error.to_string().contains("public source consumer refusal")); - fence.finish().unwrap(); - drop(source); - let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); - std::fs::rename(&path, directory.join("retained.gguf")).unwrap(); - std::fs::write(&path, b"different path occupant").unwrap(); - // Path replacement is not an in-place change to our opened source. - let mut original = Vec::new(); - source - .stream_tensor(0, 0, 16, |chunk| { - original.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - let mut actual = Vec::new(); - let mut fence = source.begin_source_fence(0).unwrap(); - fence - .stream_tensor(0, 0, 16, |chunk| { - actual.extend_from_slice(chunk); - Ok(()) - }) - .unwrap(); - fence.finish().unwrap(); - assert_eq!(actual, original); - assert_eq!(actual, expected); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&bytes)) - ); - drop(source); - } -} +mod tests; /// Same opened source, scoped observation of its indexed length. This private /// loan is not an immutable-file certificate; the original stable-content diff --git a/crates/model-format/src/gguf/tests.rs b/crates/model-format/src/gguf/tests.rs new file mode 100644 index 00000000..86122915 --- /dev/null +++ b/crates/model-format/src/gguf/tests.rs @@ -0,0 +1,89 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); +} + +struct OwnedFixture { + directory: std::path::PathBuf, + path: std::path::PathBuf, + bytes: Vec, + small: Vec, + large: Vec, + kind_at: usize, + offset_at: usize, +} + +impl OwnedFixture { + fn new() -> Self { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "leleka-owned-gguf-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&directory).unwrap(); + let path = directory.join("fixture.gguf"); + let small = (0..16).collect::>(); + let large = (0..STREAM_BUFFER_BYTES * 3 + 11) + .map(|at| (at % 251) as u8) + .collect::>(); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(2u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.small"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(4u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.large"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend((large.len() as u64).to_le_bytes()); + let kind_at = bytes.len(); + bytes.extend(24u32.to_le_bytes()); + let offset_at = bytes.len(); + bytes.extend(32u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(&small); + bytes.extend([0u8; 16]); + bytes.extend(&large); + std::fs::write(&path, &bytes).unwrap(); + Self { + directory, + path, + bytes, + small, + large, + kind_at, + offset_at, + } + } + + fn digest(&self) -> String { + let hex = Sha256::digest(&self.bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!("sha256:{hex}") + } +} + +impl Drop for OwnedFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } +} + +#[path = "tests/buffered_cursor_preserves_offsets_parsin.rs"] +mod buffered_cursor_preserves_offsets_parsin; +#[path = "tests/admits_flash_metadata_and_rejects.rs"] +mod admits_flash_metadata_and_rejects; +#[path = "tests/empty_owned_tensor_validation_preserves.rs"] +mod empty_owned_tensor_validation_preserves; +#[path = "tests/original_first_source_fence_retains.rs"] +mod original_first_source_fence_retains; diff --git a/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs new file mode 100644 index 00000000..18d121a8 --- /dev/null +++ b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs @@ -0,0 +1,284 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): admits_flash_metadata_and_rejects_incompatible_profiles, inspects_header_and_rejects_truncated_payload, indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts, owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks .... + +#[allow(unused_imports)] +use super::*; + + +#[test] +fn admits_flash_metadata_and_rejects_incompatible_profiles() { + let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id())); + let fields = [ + ("qwen4exp.block_count", 48u32), + ("qwen4exp.embedding_length", 2560), + ("qwen4exp.attention.head_count", 24), + ("qwen4exp.attention.head_count_kv", 2), + ("qwen4exp.expert_count", 512), + ("qwen4exp.expert_used_count", 10), + ]; + let write = |entries: Vec<(&str, u32, Vec)>| { + let mut data = b"GGUF".to_vec(); + data.extend(3u32.to_le_bytes()); + data.extend(0u64.to_le_bytes()); + data.extend((entries.len() as u64 + 1).to_le_bytes()); + string(&mut data, "general.architecture"); + data.extend(8u32.to_le_bytes()); + string(&mut data, "qwen4exp"); + for (key, kind, bytes) in entries { + string(&mut data, key); + data.extend(kind.to_le_bytes()); + data.extend(bytes); + } + data.resize(data.len().div_ceil(32) * 32, 0); + std::fs::write(&path, data).unwrap(); + }; + let good = || { + fields + .iter() + .map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())) + .collect::>() + }; + write(good()); + check_flash_next_profile(&path).unwrap(); + for index in 0..fields.len() { + let mut entries = good(); + entries.remove(index); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[index].0) + ); + let mut entries = good(); + entries[index].2 = 0u32.to_le_bytes().to_vec(); + write(entries); + assert!(check_flash_next_profile(&path).is_err()); + } + for index in 0..4 { + let mut entries = good(); + entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("expected") + ); + } + for (kind, bytes) in [ + (7, vec![1]), + (6, 48f32.to_le_bytes().to_vec()), + (5, (-1i32).to_le_bytes().to_vec()), + (10, (1u64 << 32).to_le_bytes().to_vec()), + ] { + let mut entries = good(); + entries[0] = (fields[0].0, kind, bytes); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[0].0) + ); + } + let mut entries = good(); + entries[4].2 = 256u32.to_le_bytes().to_vec(); + write(entries); + check_flash_next_profile(&path).unwrap(); + let mut entries = good(); + entries[5].2 = 513u32.to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("exceeds") + ); + for kind in [0, 1, 2, 3, 4, 5, 10, 11] { + let mut entries = good(); + let bytes = 48u64.to_le_bytes(); + let n = match kind { + 0 | 1 => 1, + 2 | 3 => 2, + 4 | 5 => 4, + _ => 8, + }; + entries[0] = (fields[0].0, kind, bytes[..n].to_vec()); + write(entries); + check_flash_next_profile(&path).unwrap(); + } + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn inspects_header_and_rejects_truncated_payload() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen4exp"); + string(&mut gguf, "test.weight"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&4u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(128, 0); + gguf.extend_from_slice(&[0; 16]); + let path = std::env::temp_dir().join(format!("strata-gguf-test-{}", std::process::id())); + std::fs::write(&path, &gguf).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.tensors, 1); + assert_eq!(summary.architecture.as_deref(), Some("qwen4exp")); + assert_eq!(summary.types.get(&0), Some(&1)); + std::fs::write(&path, &gguf[..80]).unwrap(); + assert!(inspect(&path).is_err()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&2u64.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + string(&mut gguf, "norm"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&4u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + let shape_at = gguf.len(); + gguf.extend_from_slice(&256u64.to_le_bytes()); + let kind_at = gguf.len(); + gguf.extend_from_slice(&21u32.to_le_bytes()); + let offset_at = gguf.len(); + gguf.extend_from_slice(&32u64.to_le_bytes()); + let data_start = gguf.len().div_ceil(32) * 32; + gguf.resize(data_start, 0); + gguf.extend_from_slice(&[0u8; 16]); + gguf.extend_from_slice(&[0u8; 16]); + gguf.extend_from_slice(&[0u8; 110]); + let path = std::env::temp_dir().join(format!("strata-gguf-index-{}", std::process::id())); + std::fs::write(&path, &gguf).unwrap(); + let index = tensor_index(&path).unwrap(); + assert_eq!(index.summary.data_start, data_start as u64); + assert_eq!(index.tensors[0].bytes, 16); + assert_eq!(index.tensors[1].offset, 32); + assert_eq!(index.tensors[1].bytes, 110); + let expected: [u8; 32] = Sha256::digest([0u8; 110]).into(); + assert_eq!(tensor_sha256(&path, &index, 1).unwrap(), expected); + + gguf[offset_at..offset_at + 8].copy_from_slice(&0u64.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + gguf[offset_at..offset_at + 8].copy_from_slice(&32u64.to_le_bytes()); + gguf[shape_at..shape_at + 8].copy_from_slice(&255u64.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + gguf[shape_at..shape_at + 8].copy_from_slice(&256u64.to_le_bytes()); + gguf[kind_at..kind_at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + assert_eq!(source.index().tensors.len(), 2); + assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64); + for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] { + assert_eq!( + source.tensor_sha256(number).unwrap(), + <[u8; 32]>::from(Sha256::digest(expected)) + ); + } + let mut seen = 0; + let mut callbacks = 0; + source + .stream_tensor(1, 0, fixture.large.len() as u64, |chunk| { + assert!(!chunk.is_empty() && chunk.len() <= STREAM_BUFFER_BYTES); + assert_eq!(chunk, &fixture.large[seen..seen + chunk.len()]); + seen += chunk.len(); + callbacks += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(seen, fixture.large.len()); + assert_eq!(callbacks, 4); + let mut partial = Vec::new(); + source + .stream_tensor(1, 7, 13, |chunk| { + partial.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(partial, fixture.large[7..20]); +} + +#[test] +fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { + let fixture = OwnedFixture::new(); + for digest in [ + "", + "abc", + "sha256:abc", + &format!("sha256:{}", "g".repeat(64)), + &format!("SHA256:{}", "a".repeat(64)), + ] { + assert!( + VerifiedGgufFile::open(&fixture.path, digest) + .unwrap_err() + .to_string() + .contains("invalid GGUF artifact digest") + ); + } + assert!( + VerifiedGgufFile::open(&fixture.directory, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("regular file") + ); + let mut tampered = fixture.bytes.clone(); + *tampered.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, tampered).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("SHA256 mismatch") + ); +} + +#[test] +fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matching_digest() { + let mut fixture = OwnedFixture::new(); + let original = fixture.bytes.clone(); + for fault in 0..4 { + fixture.bytes = original.clone(); + match fault { + 0 => { + fixture.bytes.pop(); + } + 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4] + .copy_from_slice(&u32::MAX.to_le_bytes()), + 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8] + .copy_from_slice(&0u64.to_le_bytes()), + 3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()), + _ => unreachable!(), + } + std::fs::write(&fixture.path, &fixture.bytes).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), + "fault {fault}" + ); + } +} diff --git a/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs new file mode 100644 index 00000000..350421df --- /dev/null +++ b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs @@ -0,0 +1,239 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads. + +#[allow(unused_imports)] +use super::*; + + +#[test] +fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { + struct Counted { + bytes: std::io::Cursor>, + reads: usize, + seeks: usize, + requests: Vec, + } + impl Read for Counted { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + self.reads += 1; + self.requests.push(out.len()); + self.bytes.read(out) + } + } + impl Seek for Counted { + fn seek(&mut self, from: SeekFrom) -> std::io::Result { + self.seeks += 1; + self.bytes.seek(from) + } + } + let mut bytes = Vec::new(); + for _ in 0..512 { + bytes.extend(0x10203040u32.to_le_bytes()); + } + const SMALL_CAPACITY: usize = 64 * 1024; + bytes.resize(SMALL_CAPACITY - 4, 0); + string(&mut bytes, "edge-é"); // Eight-byte length crosses the buffer edge. + bytes.extend(0xa1b2c3d4u32.to_le_bytes()); + let skipped = SMALL_CAPACITY * 2 + 17; + bytes.resize(bytes.len() + skipped, 0); + bytes.extend(0x5678u16.to_le_bytes()); + let length = bytes.len() as u64; + let counted = Counted { + bytes: std::io::Cursor::new(bytes), + reads: 0, + seeks: 0, + requests: Vec::new(), + }; + let mut cursor = Cursor::with_test_capacity(counted, length, SMALL_CAPACITY); + for _ in 0..512 { + assert_eq!(cursor.u32().unwrap(), 0x10203040); + } + assert_eq!(cursor.position().unwrap(), 2048); + assert_eq!(cursor.file.get_ref().reads, 1); + assert_eq!(cursor.file.get_ref().seeks, 0); + assert_eq!(cursor.file.get_ref().bytes.position(), 65536); + cursor.skip(7).unwrap(); // Consume already read bytes, without a seek. + cursor.skip((65532 - 2055) as u64).unwrap(); + assert_eq!(cursor.file.get_ref().seeks, 0); + assert_eq!(cursor.string().unwrap(), "edge-é"); + assert_eq!(cursor.u32().unwrap(), 0xa1b2c3d4); + assert_eq!(cursor.position().unwrap(), 65551); + assert_eq!(cursor.file.get_ref().reads, 2); + cursor.skip(skipped as u64).unwrap(); // One absolute seek outside cache. + assert_eq!(cursor.file.get_ref().seeks, 1); + assert_eq!(cursor.u16().unwrap(), 0x5678); + assert_eq!(cursor.position().unwrap(), length); + assert_eq!(cursor.file.get_ref().reads, 3); + assert!(cursor.file.get_ref().requests.iter().all(|n| *n == 65536)); + assert_eq!( + cursor.skip(1).unwrap_err().to_string(), + "truncated GGUF header" + ); + assert_eq!( + cursor.u8().unwrap_err().to_string(), + "truncated GGUF header" + ); + assert_eq!( + cursor.skip(u64::MAX).unwrap_err().to_string(), + "GGUF offset overflow" + ); + + let mut production = Cursor::new( + Counted { + bytes: std::io::Cursor::new(vec![0x78, 0x56, 0x34, 0x12]), + reads: 0, + seeks: 0, + requests: Vec::new(), + }, + 4, + ); + assert_eq!(production.file.capacity(), 16 * 1024 * 1024); + assert_eq!(production.u32().unwrap(), 0x12345678); + assert_eq!(production.position().unwrap(), 4); + assert_eq!(production.file.get_ref().requests, [16 * 1024 * 1024]); + assert_eq!(production.file.get_ref().seeks, 0); + + let mut short = Cursor::new(std::io::Cursor::new(vec![0u8; 3]), 4); + assert_eq!( + short + .u32() + .unwrap_err() + .downcast_ref::() + .unwrap() + .kind(), + std::io::ErrorKind::UnexpectedEof + ); + let mut oversized = Cursor::new(std::io::Cursor::new(1_048_577u64.to_le_bytes()), 8); + assert_eq!( + oversized.string().unwrap_err().to_string(), + "GGUF header string is too large" + ); + let mut bad = Cursor::new(std::io::Cursor::new(9u32.to_le_bytes()), 4); + assert_eq!( + bad.skip_value(9).unwrap_err().to_string(), + "truncated GGUF header" + ); + let mut bad = Cursor::new(std::io::Cursor::new(Vec::new()), 0); + assert_eq!( + bad.skip_value(99).unwrap_err().to_string(), + "unknown GGUF metadata type 99" + ); + + // Actual parser entrypoints: literal metadata, a skipped long string, + // logical header alignment, and a subsequent read of the original FD. + let mut fixture = OwnedFixture::new(); + let mut data = b"GGUF".to_vec(); + data.extend(3u32.to_le_bytes()); + data.extend(1u64.to_le_bytes()); + data.extend(3u64.to_le_bytes()); + string(&mut data, "general.architecture"); + data.extend(8u32.to_le_bytes()); + string(&mut data, "qwen4exp"); + string(&mut data, "ignored"); + data.extend(8u32.to_le_bytes()); + string(&mut data, &"z".repeat(SMALL_CAPACITY + 11)); + string(&mut data, "qwen4exp.block_count"); + data.extend(4u32.to_le_bytes()); + data.extend(48u32.to_le_bytes()); + string(&mut data, "weight"); + data.extend(1u32.to_le_bytes()); + data.extend(4u64.to_le_bytes()); + data.extend(0u32.to_le_bytes()); + data.extend(0u64.to_le_bytes()); + let header_end = data.len(); + let data_start = header_end.div_ceil(32) * 32; + data.resize(data_start, 0); + data.extend([0x11u8, 0x22, 0x33, 0x44].repeat(4)); + fixture.bytes = data; + std::fs::write(&fixture.path, &fixture.bytes).unwrap(); + let mut verified = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + assert_eq!(verified.index().summary.data_start, data_start as u64); + assert_eq!( + verified.index().summary.architecture.as_deref(), + Some("qwen4exp") + ); + assert_eq!(verified.index().tensors[0].name, "weight"); + assert_eq!(verified.index().tensors[0].bytes, 16); + let snapshot = verified.profile_snapshot().unwrap(); + assert_eq!(snapshot.architecture.as_deref(), Some("qwen4exp")); + assert!(matches!( + snapshot.values.get("qwen4exp.block_count"), + Some(MetadataValue::Unsigned(48)) + )); + let mut payload = Vec::new(); + verified + .stream_tensor(0, 0, 16, |chunk| { + payload.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(payload, [0x11u8, 0x22, 0x33, 0x44].repeat(4)); + assert_eq!( + verified.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + + let mut duplicate = b"GGUF".to_vec(); + duplicate.extend(3u32.to_le_bytes()); + duplicate.extend(0u64.to_le_bytes()); + duplicate.extend(2u64.to_le_bytes()); + for _ in 0..2 { + string(&mut duplicate, "general.architecture"); + duplicate.extend(8u32.to_le_bytes()); + string(&mut duplicate, "qwen4exp"); + } + std::fs::write(&fixture.path, &duplicate).unwrap(); + let mut file = File::open(&fixture.path).unwrap(); + for result in [ + read_index_file(&mut file, duplicate.len() as u64, false).map(|_| ()), + read_metadata_snapshot(&mut file, duplicate.len() as u64, None, false).map(|_| ()), + ] { + assert_eq!( + result.unwrap_err().to_string(), + "duplicate GGUF metadata key: general.architecture" + ); + } + + // The production span bound is exercised independently of header strings + // (whose existing one-MiB limit remains intact). + let span = (0..STREAM_BUFFER_BYTES + 19) + .map(|at| (at % 251) as u8) + .collect::>(); + std::fs::write(&fixture.path, &span).unwrap(); + let mut file = File::open(&fixture.path).unwrap(); + let mut seen = 0; + let mut chunks = Vec::new(); + stream_file_span(&mut file, 7, (span.len() - 7) as u64, |chunk| { + assert_eq!(chunk, &span[7 + seen..7 + seen + chunk.len()]); + seen += chunk.len(); + chunks.push(chunk.len()); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, span.len() - 7); + assert_eq!(chunks, [16 * 1024 * 1024, 12]); + let mut small = Vec::new(); + stream_file_span(&mut file, 13, 17, |chunk| { + assert_eq!(chunk.len(), 17); // Small spans do not allocate/read 16MiB. + small.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(small, (13u8..30).collect::>()); + stream_file_span(&mut file, 0, 0, |_| panic!("empty span callback")).unwrap(); + assert_eq!( + stream_file_span(&mut file, 0, span.len() as u64 + 1, |_| Ok(())) + .unwrap_err() + .downcast_ref::() + .unwrap() + .kind(), + std::io::ErrorKind::UnexpectedEof + ); + assert_eq!( + stream_file_span(&mut file, 0, 17, |_| { + Err(std::io::Error::other("consumer sentinel")) + }) + .unwrap_err() + .to_string(), + "consumer sentinel" + ); +} diff --git a/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs new file mode 100644 index 00000000..5f667f42 --- /dev/null +++ b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs @@ -0,0 +1,142 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks, owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover, pathname_replacement_keeps_original_verified_file_and_index, opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability. + +#[allow(unused_imports)] +use super::*; + + +#[test] +fn empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + source.file.seek(SeekFrom::Start(3)).unwrap(); + source + .stream_tensor(0, 16, 0, |_| panic!("empty span invoked consumer")) + .unwrap(); + assert_eq!(source.file.stream_position().unwrap(), 3); + for (number, offset) in [(2, 0), (0, 17), (0, u64::MAX)] { + assert!( + source + .stream_tensor(number, offset, 0, |_| { + panic!("invalid empty span invoked consumer") + }) + .is_err() + ); + assert_eq!(source.file.stream_position().unwrap(), 3); + } + std::fs::OpenOptions::new() + .write(true) + .open(&fixture.path) + .unwrap() + .set_len(fixture.bytes.len() as u64 - 1) + .unwrap(); + assert!( + source + .stream_tensor(0, 16, 0, |_| { + panic!("changed-size empty span invoked consumer") + }) + .unwrap_err() + .to_string() + .contains("size changed") + ); + assert_eq!(source.file.stream_position().unwrap(), 3); +} + +#[test] +fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + for (number, offset, bytes) in [ + (2, 0, 1), + (0, 0, 17), + (0, 17, 0), + (0, u64::MAX, 1), + (0, 1, u64::MAX), + ] { + let mut called = false; + assert!( + source + .stream_tensor(number, offset, bytes, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } + source + .stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")) + .unwrap(); + assert!( + source + .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other( + "synthetic consumer failure" + ))) + .unwrap_err() + .to_string() + .contains("synthetic consumer failure") + ); + assert_eq!( + source.tensor_sha256(0).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.small)) + ); +} + +#[cfg(unix)] +#[test] +fn pathname_replacement_keeps_original_verified_file_and_index() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap(); + std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap(); + assert!(tensor_index(&fixture.path).is_err()); + assert_eq!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + let mut small = Vec::new(); + source + .stream_tensor(0, 0, 16, |chunk| { + small.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(small, fixture.small); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); +} + +#[test] +fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let mut mutated = fixture.bytes.clone(); + *mutated.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, &mutated).unwrap(); + // Explicit counterexample: retaining the descriptor does not freeze bytes. + assert_ne!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + std::fs::OpenOptions::new() + .write(true) + .open(&fixture.path) + .unwrap() + .set_len(0) + .unwrap(); + let mut called = false; + assert!( + source + .stream_tensor(0, 0, 16, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); +} diff --git a/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs new file mode 100644 index 00000000..1dff2214 --- /dev/null +++ b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs @@ -0,0 +1,168 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_changes. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_changes() { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT_FENCE: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "leleka-source-fence-{}-{}", + std::process::id(), + NEXT_FENCE.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&directory).unwrap(); + struct Remove(std::path::PathBuf); + impl Drop for Remove { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let _cleanup = Remove(directory.clone()); + let path = directory.join("source.gguf"); + // Real bounded verified source, not a synthetic model/Binding/row. + let expected: Vec = [0x80000000u32, 0, 0x3f800000, 0xbf800000] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(1u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "public.source"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(4u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(&expected); + assert!(bytes.len() <= 128); + std::fs::write(&path, &bytes).unwrap(); + let digest = format!( + "sha256:{}", + Sha256::digest(&bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + // ORIGINAL empty descriptor + actual stream FIRST, before new scope. + source + .stream_tensor(0, 0, 0, |_| panic!("emptyspan callback")) + .unwrap(); + let mut original = Vec::new(); + source + .stream_tensor(0, 0, 16, |chunk| { + original.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(original, expected); + let cursor = source.file.stream_position().unwrap(); + { + let mut fence = source.begin_source_fence(0).unwrap(); + fence.validate_tensor(0).unwrap(); + assert!(fence.validate_tensor(usize::MAX).is_err()); + let mut called = false; + assert!( + fence + .stream_tensor(0, 16, 1, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + fence.finish().unwrap(); + } + assert_eq!(source.file.stream_position().unwrap(), cursor); + let mut actual = Vec::new(); + { + let mut fence = source.begin_source_fence(0).unwrap(); + fence + .stream_tensor(0, 0, 16, |chunk| { + actual.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + fence.finish().unwrap(); + } + assert_eq!(actual, original); + let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + writer.set_len(bytes.len() as u64 - 1).unwrap(); + // Original first refusal, then initial scoped refusal, same opened FD. + assert!(source.stream_tensor(0, 0, 0, |_| Ok(())).is_err()); + assert!(source.begin_source_fence(0).is_err()); + drop(writer); + drop(source); + std::fs::write(&path, &bytes).unwrap(); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + let mut pending = Vec::new(); + let mut fence = source.begin_source_fence(0).unwrap(); + fence + .stream_tensor(0, 0, 16, |chunk| { + pending.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + writer.set_len(bytes.len() as u64 - 1).unwrap(); + let accepted = fence.finish().map(|()| pending); + assert!(accepted.is_err()); // no successful return of pending payload + drop(writer); + drop(source); + std::fs::write(&path, &bytes).unwrap(); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + let mut fence = source.begin_source_fence(0).unwrap(); + let read = fence.stream_tensor(0, 0, 16, |_| { + writer.set_len(bytes.len() as u64 - 1)?; + Ok(()) + }); + assert!(read.is_err()); // unchanged cold stream AFTER-read check + assert!(fence.finish().is_err()); + drop(writer); + drop(source); + std::fs::write(&path, &bytes).unwrap(); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + let mut fence = source.begin_source_fence(0).unwrap(); + let error = fence + .stream_tensor(0, 0, 16, |_| { + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "public source consumer refusal", + )) + }) + .unwrap_err(); + assert!(error.to_string().contains("public source consumer refusal")); + fence.finish().unwrap(); + drop(source); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + std::fs::rename(&path, directory.join("retained.gguf")).unwrap(); + std::fs::write(&path, b"different path occupant").unwrap(); + // Path replacement is not an in-place change to our opened source. + let mut original = Vec::new(); + source + .stream_tensor(0, 0, 16, |chunk| { + original.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + let mut actual = Vec::new(); + let mut fence = source.begin_source_fence(0).unwrap(); + fence + .stream_tensor(0, 0, 16, |chunk| { + actual.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + fence.finish().unwrap(); + assert_eq!(actual, original); + assert_eq!(actual, expected); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&bytes)) + ); + drop(source); +} diff --git a/crates/model-format/src/qwen4exp.rs b/crates/model-format/src/qwen4exp.rs index b289b7ea..eb484dc4 100644 --- a/crates/model-format/src/qwen4exp.rs +++ b/crates/model-format/src/qwen4exp.rs @@ -212,364 +212,10 @@ struct ExpectedTensor { mod qwen_artifact_binding_tests; #[cfg(test)] -mod whole_moe_matrix_sdet { - use super::*; - - #[test] - fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() { - // Independent layout literals from upstream gguf_reader.hpp: - // GU has ten 256-element blocks; Down has twenty 32-element - // blocks or ten 64-element blocks. These are logical planner - // descriptors, never admitted artifact identities or file fixtures. - // kind, routed, Down, encoded row bytes, 64-row bytes, matrix bytes. - let layouts = [ - (18, true, false, 980, 62_720, 627_200), - (21, true, false, 1100, 70_400, 704_000), - (22, true, false, 820, 52_480, 524_800), - (23, true, false, 1360, 87_040, 870_400), - (20, true, true, 360, 23_040, 921_600), - (42, true, true, 180, 11_520, 460_800), - (12, false, false, 1440, 92_160, 921_600), - (13, false, false, 1760, 112_640, 1_126_400), - (14, false, false, 2100, 134_400, 1_344_000), - (23, false, false, 1360, 87_040, 870_400), - (20, false, true, 360, 23_040, 921_600), - (8, false, true, 680, 43_520, 1_740_800), - ]; - for (kind, routed, down, stride, tile_bytes, matrix_bytes) in layouts { - let (columns, rows) = if down { (640, 2560) } else { (2560, 640) }; - let dimensions = if routed { - vec![columns, rows, 512] - } else { - vec![columns, rows] - }; - let byte_length = matrix_bytes * if routed { 512 } else { 1 }; - let tensor = ResolvedTensor { - shard: 0, - tensor_number: 0, - name: "independent.logical.moe.span".to_owned(), - kind, - dimensions, - absolute_start: 4096, - byte_length, - file_size: 4096 + byte_length, - }; - let roles: &[LayerRole] = match (routed, down) { - (true, false) => &[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts], - (true, true) => &[LayerRole::FfnDownExperts], - (false, false) => &[LayerRole::FfnGateShared, LayerRole::FfnUpShared], - (false, true) => &[LayerRole::FfnDownShared], - }; - let experts: &[Option] = if routed { - &[Some(0), Some(1), Some(511)] - } else { - &[None] - }; - for &layer_role in roles { - let role = TensorRole::Layer { - layer: 47, - role: layer_role, - }; - for &expert in experts { - let base = expert.unwrap_or(0) * matrix_bytes; - assert_eq!( - plan_stream_rows(&tensor, role, 0, rows, expert).unwrap(), - (base, matrix_bytes) - ); - // The literal legacy offsets cover every byte once, in order, - // with no expert transition, tail, padding or hidden gap. - for tile in 0..rows / 64 { - let expected = (base + tile * tile_bytes, tile_bytes); - assert_eq!(plan_rows(&tensor, tile * 64, 64, expert).unwrap(), expected); - assert_eq!( - plan_stream_rows(&tensor, role, tile * 64, 64, expert).unwrap(), - expected - ); - } - assert_eq!( - plan_row(&tensor, rows - 1, expert).unwrap(), - (base + matrix_bytes - stride, stride) - ); - for (first, count) in [ - (0, 0), - (0, 65), - (0, rows - 1), - (0, rows + 1), - (1, rows), - (rows - 63, 64), - (rows, 1), - (u64::MAX, 64), - (1, u64::MAX), - ] { - assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); - } - let other_role = TensorRole::Layer { - layer: 47, - role: LayerRole::HcFfnNorm, - }; - assert!(plan_stream_rows(&tensor, other_role, 0, rows, expert).is_err()); - assert!(plan_rows(&tensor, 0, rows, expert).is_err()); - - let mut malformed = tensor.clone(); - malformed.dimensions[0] += 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.dimensions[1] -= 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.byte_length -= 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.file_size = 4096 + base + matrix_bytes - 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.absolute_start = u64::MAX - matrix_bytes + 1; - malformed.file_size = u64::MAX; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - } - let wrong_selector = if routed { None } else { Some(0) }; - assert!(plan_stream_rows(&tensor, role, 0, rows, wrong_selector).is_err()); - if routed { - assert!(plan_stream_rows(&tensor, role, 0, rows, Some(512)).is_err()); - let mut malformed = tensor.clone(); - malformed.dimensions[2] = 511; - assert!(plan_stream_rows(&malformed, role, 0, rows, Some(0)).is_err()); - } - } - } - } -} +mod whole_moe_matrix_sdet; #[cfg(test)] -mod whole_dense_matrix_transport_tests { - use super::*; - - #[test] - fn closed_ple_spans_keep_exact_tile_offsets_and_original_formats() { - for (role, kind, columns, rows) in [ - (LayerRole::PleKey, 30, 2560_u64, 10240_u64), - (LayerRole::PleValue, 30, 2560, 2560), - (LayerRole::PleConv1d, 1, 4, 10240), - ] { - let bytes = columns * rows * 2; - let tensor = ResolvedTensor { - shard: 0, - tensor_number: 0, - name: "closed.ple.test".into(), - kind, - dimensions: vec![columns, rows], - absolute_start: 4096, - byte_length: bytes, - file_size: 4096 + bytes, - }; - let closed = TensorRole::Layer { layer: 1, role }; - assert_eq!( - plan_stream_rows(&tensor, closed, 0, rows, None).unwrap(), - (0, bytes) - ); - for first in (0..rows).step_by(64) { - assert_eq!( - plan_rows(&tensor, first, 64, None).unwrap(), - (first * columns * 2, 64 * columns * 2) - ); - } - for (first, count, expert) in [ - (1, rows, None), - (0, rows - 1, None), - (0, rows + 1, None), - (0, rows, Some(0)), - (u64::MAX, rows, None), - ] { - assert!(plan_stream_rows(&tensor, closed, first, count, expert).is_err()); - } - assert!( - plan_stream_rows(&tensor, TensorRole::Layer { layer: 0, role }, 0, rows, None) - .is_err() - ); - let mut wrong = tensor.clone(); - wrong.kind = if kind == 30 { 1 } else { 30 }; - assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); - wrong = tensor.clone(); - wrong.dimensions[0] += 1; - assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); - wrong = tensor.clone(); - wrong.byte_length -= 1; - assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); - wrong = tensor.clone(); - wrong.file_size -= 1; - assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); - } - } - - #[test] - fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { - use LayerRole as L; - // Fixed native topology, BF16 row stride; compare every legacy tile, - // including tails, rather than calculating expected via the new planner. - let shapes = [ - ( - TensorRole::Layer { - layer: 0, - role: L::AttnQkv, - }, - 2560, - 10240, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::AttnGate, - }, - 2560, - 6144, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::SsmOut, - }, - 6144, - 2560, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnQ, - }, - 2560, - 12288, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnK, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnV, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::IndexerQProj, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::IndexerKProj, - }, - 2560, - 128, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnOutput, - }, - 6144, - 2560, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::FfnGateInp, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcAttnDown, - }, - 10240, - 320, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcFfnDown, - }, - 10240, - 320, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcAttnUp, - }, - 320, - 10240, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcFfnUp, - }, - 320, - 10240, - ), - (TensorRole::Global(GlobalRole::OutputHcDown), 10240, 320), - (TensorRole::Global(GlobalRole::OutputHcUp), 320, 10240), - ]; - for (role, columns, rows) in shapes { - let bytes = columns * rows * 2; - let tensor = ResolvedTensor { - shard: 0, - tensor_number: 0, - name: "closed.dense.test".into(), - kind: 30, - dimensions: vec![columns, rows], - absolute_start: 4096, - byte_length: bytes, - file_size: 4096 + bytes, - }; - assert_eq!( - plan_stream_rows(&tensor, role, 0, rows, None).unwrap(), - (0, bytes) - ); - let mut concatenated = 0; - for first in (0..rows).step_by(64) { - let count = (rows - first).min(64); - let legacy = plan_rows(&tensor, first, count, None).unwrap(); - assert_eq!(legacy, (first * columns * 2, count * columns * 2)); - assert_eq!(legacy.0, concatenated); - concatenated += legacy.1; - } - assert_eq!(concatenated, bytes); - for (first, count, expert) in [ - (1, rows, None), - (0, rows - 1, None), - (0, rows + 1, None), - (0, rows, Some(0)), - (u64::MAX, rows, None), - ] { - assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); - } - let mut changed = tensor.clone(); - changed.dimensions[0] += 1; - assert!(plan_stream_rows(&changed, role, 0, rows, None).is_err()); - changed = tensor.clone(); - changed.file_size -= 1; - assert!(plan_stream_rows(&changed, role, 0, rows, None).is_err()); - let scalar_role = TensorRole::Layer { - layer: 0, - role: L::HcFfnNorm, - }; - assert!(plan_stream_rows(&tensor, scalar_role, 0, rows, None).is_err()); - } - } -} +mod whole_dense_matrix_transport_tests; /// Noncloneable, fixed routed Gate/Up/Down source loan. No arbitrary tensor, /// source FD, span, buffer or success certificate is exposed. It validates diff --git a/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs b/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs new file mode 100644 index 00000000..ecd70755 --- /dev/null +++ b/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs @@ -0,0 +1,229 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +#[test] +fn closed_ple_spans_keep_exact_tile_offsets_and_original_formats() { + for (role, kind, columns, rows) in [ + (LayerRole::PleKey, 30, 2560_u64, 10240_u64), + (LayerRole::PleValue, 30, 2560, 2560), + (LayerRole::PleConv1d, 1, 4, 10240), + ] { + let bytes = columns * rows * 2; + let tensor = ResolvedTensor { + shard: 0, + tensor_number: 0, + name: "closed.ple.test".into(), + kind, + dimensions: vec![columns, rows], + absolute_start: 4096, + byte_length: bytes, + file_size: 4096 + bytes, + }; + let closed = TensorRole::Layer { layer: 1, role }; + assert_eq!( + plan_stream_rows(&tensor, closed, 0, rows, None).unwrap(), + (0, bytes) + ); + for first in (0..rows).step_by(64) { + assert_eq!( + plan_rows(&tensor, first, 64, None).unwrap(), + (first * columns * 2, 64 * columns * 2) + ); + } + for (first, count, expert) in [ + (1, rows, None), + (0, rows - 1, None), + (0, rows + 1, None), + (0, rows, Some(0)), + (u64::MAX, rows, None), + ] { + assert!(plan_stream_rows(&tensor, closed, first, count, expert).is_err()); + } + assert!( + plan_stream_rows(&tensor, TensorRole::Layer { layer: 0, role }, 0, rows, None) + .is_err() + ); + let mut wrong = tensor.clone(); + wrong.kind = if kind == 30 { 1 } else { 30 }; + assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); + wrong = tensor.clone(); + wrong.dimensions[0] += 1; + assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); + wrong = tensor.clone(); + wrong.byte_length -= 1; + assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); + wrong = tensor.clone(); + wrong.file_size -= 1; + assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); + } +} + +#[test] +fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { + use LayerRole as L; + // Fixed native topology, BF16 row stride; compare every legacy tile, + // including tails, rather than calculating expected via the new planner. + let shapes = [ + ( + TensorRole::Layer { + layer: 0, + role: L::AttnQkv, + }, + 2560, + 10240, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::AttnGate, + }, + 2560, + 6144, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::SsmOut, + }, + 6144, + 2560, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::AttnQ, + }, + 2560, + 12288, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::AttnK, + }, + 2560, + 512, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::AttnV, + }, + 2560, + 512, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::IndexerQProj, + }, + 2560, + 512, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::IndexerKProj, + }, + 2560, + 128, + ), + ( + TensorRole::Layer { + layer: 3, + role: L::AttnOutput, + }, + 6144, + 2560, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::FfnGateInp, + }, + 2560, + 512, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::HcAttnDown, + }, + 10240, + 320, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::HcFfnDown, + }, + 10240, + 320, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::HcAttnUp, + }, + 320, + 10240, + ), + ( + TensorRole::Layer { + layer: 0, + role: L::HcFfnUp, + }, + 320, + 10240, + ), + (TensorRole::Global(GlobalRole::OutputHcDown), 10240, 320), + (TensorRole::Global(GlobalRole::OutputHcUp), 320, 10240), + ]; + for (role, columns, rows) in shapes { + let bytes = columns * rows * 2; + let tensor = ResolvedTensor { + shard: 0, + tensor_number: 0, + name: "closed.dense.test".into(), + kind: 30, + dimensions: vec![columns, rows], + absolute_start: 4096, + byte_length: bytes, + file_size: 4096 + bytes, + }; + assert_eq!( + plan_stream_rows(&tensor, role, 0, rows, None).unwrap(), + (0, bytes) + ); + let mut concatenated = 0; + for first in (0..rows).step_by(64) { + let count = (rows - first).min(64); + let legacy = plan_rows(&tensor, first, count, None).unwrap(); + assert_eq!(legacy, (first * columns * 2, count * columns * 2)); + assert_eq!(legacy.0, concatenated); + concatenated += legacy.1; + } + assert_eq!(concatenated, bytes); + for (first, count, expert) in [ + (1, rows, None), + (0, rows - 1, None), + (0, rows + 1, None), + (0, rows, Some(0)), + (u64::MAX, rows, None), + ] { + assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); + } + let mut changed = tensor.clone(); + changed.dimensions[0] += 1; + assert!(plan_stream_rows(&changed, role, 0, rows, None).is_err()); + changed = tensor.clone(); + changed.file_size -= 1; + assert!(plan_stream_rows(&changed, role, 0, rows, None).is_err()); + let scalar_role = TensorRole::Layer { + layer: 0, + role: L::HcFfnNorm, + }; + assert!(plan_stream_rows(&tensor, scalar_role, 0, rows, None).is_err()); + } +} diff --git a/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs new file mode 100644 index 00000000..71a78e8a --- /dev/null +++ b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs @@ -0,0 +1,127 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +#[test] +fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() { + // Independent layout literals from upstream gguf_reader.hpp: + // GU has ten 256-element blocks; Down has twenty 32-element + // blocks or ten 64-element blocks. These are logical planner + // descriptors, never admitted artifact identities or file fixtures. + // kind, routed, Down, encoded row bytes, 64-row bytes, matrix bytes. + let layouts = [ + (18, true, false, 980, 62_720, 627_200), + (21, true, false, 1100, 70_400, 704_000), + (22, true, false, 820, 52_480, 524_800), + (23, true, false, 1360, 87_040, 870_400), + (20, true, true, 360, 23_040, 921_600), + (42, true, true, 180, 11_520, 460_800), + (12, false, false, 1440, 92_160, 921_600), + (13, false, false, 1760, 112_640, 1_126_400), + (14, false, false, 2100, 134_400, 1_344_000), + (23, false, false, 1360, 87_040, 870_400), + (20, false, true, 360, 23_040, 921_600), + (8, false, true, 680, 43_520, 1_740_800), + ]; + for (kind, routed, down, stride, tile_bytes, matrix_bytes) in layouts { + let (columns, rows) = if down { (640, 2560) } else { (2560, 640) }; + let dimensions = if routed { + vec![columns, rows, 512] + } else { + vec![columns, rows] + }; + let byte_length = matrix_bytes * if routed { 512 } else { 1 }; + let tensor = ResolvedTensor { + shard: 0, + tensor_number: 0, + name: "independent.logical.moe.span".to_owned(), + kind, + dimensions, + absolute_start: 4096, + byte_length, + file_size: 4096 + byte_length, + }; + let roles: &[LayerRole] = match (routed, down) { + (true, false) => &[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts], + (true, true) => &[LayerRole::FfnDownExperts], + (false, false) => &[LayerRole::FfnGateShared, LayerRole::FfnUpShared], + (false, true) => &[LayerRole::FfnDownShared], + }; + let experts: &[Option] = if routed { + &[Some(0), Some(1), Some(511)] + } else { + &[None] + }; + for &layer_role in roles { + let role = TensorRole::Layer { + layer: 47, + role: layer_role, + }; + for &expert in experts { + let base = expert.unwrap_or(0) * matrix_bytes; + assert_eq!( + plan_stream_rows(&tensor, role, 0, rows, expert).unwrap(), + (base, matrix_bytes) + ); + // The literal legacy offsets cover every byte once, in order, + // with no expert transition, tail, padding or hidden gap. + for tile in 0..rows / 64 { + let expected = (base + tile * tile_bytes, tile_bytes); + assert_eq!(plan_rows(&tensor, tile * 64, 64, expert).unwrap(), expected); + assert_eq!( + plan_stream_rows(&tensor, role, tile * 64, 64, expert).unwrap(), + expected + ); + } + assert_eq!( + plan_row(&tensor, rows - 1, expert).unwrap(), + (base + matrix_bytes - stride, stride) + ); + for (first, count) in [ + (0, 0), + (0, 65), + (0, rows - 1), + (0, rows + 1), + (1, rows), + (rows - 63, 64), + (rows, 1), + (u64::MAX, 64), + (1, u64::MAX), + ] { + assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); + } + let other_role = TensorRole::Layer { + layer: 47, + role: LayerRole::HcFfnNorm, + }; + assert!(plan_stream_rows(&tensor, other_role, 0, rows, expert).is_err()); + assert!(plan_rows(&tensor, 0, rows, expert).is_err()); + + let mut malformed = tensor.clone(); + malformed.dimensions[0] += 1; + assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); + malformed = tensor.clone(); + malformed.dimensions[1] -= 1; + assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); + malformed = tensor.clone(); + malformed.byte_length -= 1; + assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); + malformed = tensor.clone(); + malformed.file_size = 4096 + base + matrix_bytes - 1; + assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); + malformed = tensor.clone(); + malformed.absolute_start = u64::MAX - matrix_bytes + 1; + malformed.file_size = u64::MAX; + assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); + } + let wrong_selector = if routed { None } else { Some(0) }; + assert!(plan_stream_rows(&tensor, role, 0, rows, wrong_selector).is_err()); + if routed { + assert!(plan_stream_rows(&tensor, role, 0, rows, Some(512)).is_err()); + let mut malformed = tensor.clone(); + malformed.dimensions[2] = 511; + assert!(plan_stream_rows(&malformed, role, 0, rows, Some(0)).is_err()); + } + } + } +} diff --git a/scripts/dev/extract_modules.py b/scripts/dev/extract_modules.py index 3a37cfdc..26dfc699 100644 --- a/scripts/dev/extract_modules.py +++ b/scripts/dev/extract_modules.py @@ -50,7 +50,7 @@ def dedent(body): return "\n".join(row[4:] if row.startswith(" ") else row for row in body.split("\n")) -def plan(text, directory, min_lines): +def plan(text, directory, min_lines, explicit=False): """(new source text, {file: text}, [skipped reasons]) for the inline modules of `text` with at least `min_lines` lines.""" edits, files, skipped = [], {}, [] for item in parse_items(text): @@ -68,14 +68,32 @@ def plan(text, directory, min_lines): else: content = INCLUDE.sub(lambda m: m.group(1) + "../", dedent(body).strip("\n")) files[directory / f"{name}.rs"] = HEADER + content + "\n" - edits.append((opening, item.end)) - for start, end in sorted(edits, reverse=True): - text = text[:start].rstrip() + ";" + text[end:] + # explicit `#[path]` for a module file that is not a mod.rs: right whether the file is a plain module, was itself + # loaded through `#[path]` (its `mod x;` would look beside it), or is an integration test crate root + attr = f'#[path = "{directory.name}/{name}.rs"]' + chr(10) if explicit else "" + edits.append((item.head, item.end, attr + text[item.head:opening].rstrip() + ";")) + for start, end, replacement in sorted(edits, reverse=True): + text = text[:start] + replacement + text[end:] return text, files, skipped +_LOADED = [] + + +def loaded_by_path(): + """File names that some source file loads through `#[path = "...name.rs"]` (scanned once).""" + if not _LOADED: + from split_module import path_targets + _LOADED.append(path_targets()) + return _LOADED[0] + + def process(path, min_lines, dry_run): - text, files, skipped = plan(read(path), child_dir(path), min_lines) + # explicit `#[path]` only where `mod x;` would look in the wrong place: a file loaded through `#[path]` (its children are + # searched beside it) or an integration test crate root; a plain module finds `foo/x.rs` by itself + integration_root = path.parent.name == "tests" and path.parent.parent.joinpath("Cargo.toml").exists() + explicit = path.name not in ("mod.rs", "lib.rs", "main.rs") and (path.name in loaded_by_path() or integration_root) + text, files, skipped = plan(read(path), child_dir(path), min_lines, explicit) if not files: return "skipped", "; ".join(skipped) or "no inline module of that size" if not dry_run: diff --git a/scripts/dev/rustsplit/testsplit.py b/scripts/dev/rustsplit/testsplit.py index 99cb05f5..91d3c5ea 100644 --- a/scripts/dev/rustsplit/testsplit.py +++ b/scripts/dev/rustsplit/testsplit.py @@ -97,7 +97,8 @@ def plan_test_split(text, target, stem, explicit_dir=None, reserved=()): """(new parent text, {child name: child text}), or None when there is nothing worth moving.""" items = parse_items(text) runs = chunks_of(text, items, target) - if len(runs) < 2 and not (runs and lines_of(text) > 400): + # one test fn per file cannot be made smaller by moving it into a module of its own + if len(runs) < 2 and (not runs or len(runs[0]) < 2): return None used = set(reserved) | {item.name for item in items if item.kind != "fn"} # a module and a fn live in different namespaces children = {}