diff --git a/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs b/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs new file mode 100644 index 00000000..6dd72e4b --- /dev/null +++ b/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs @@ -0,0 +1,175 @@ +//! Model-free GPU smoke of the verify window's PCIe staging copy (`publish_gpu_plan`'s DMA arm): the expert pieces of a group +//! travel from host memory to device staging by `OriginalGpuStream::enqueue_copy_h2d_many`, either as one driver entry per +//! piece or as one `cuMemcpyBatchAsync`, from pageable memory, from page-locked (registered) memory and from a mix of both. +//! +//! Why it exists: on the RTX 3080 laptop under Windows (driver 617.42) `cuMemcpyBatchAsync_v2` from page-locked host memory +//! raised CUDA error 700 (illegal address) in the first decode window of every request that staged a PCIe share. The batch call +//! faults there for a single 16-byte piece, for every source access order and every registration flag; the same pieces +//! copied one call each are exact, and pageable sources are exact either way. `dma_options` therefore leaves the batch call off +//! on Windows and WSL2 (docs/windows.md, "PCIe tier on the laptop"). The `raw_batch_*` cases call the batch whatever the platform +//! default is: they are the check to repeat on a new driver, and FAIL on that laptop. +//! +//! The piece sizes and offsets are those of the real copy (up to 640 KiB, 16-byte aligned, arbitrary page offsets); every round +//! checks every destination byte, including that nothing outside the pieces was written. +//! +//! Run one case per process (a fault poisons the context; `PCIE_COPY_ROUNDS=N` sets the rounds, default 200): +//! cargo test --release -p leleka-cuda-driver --features cuda-driver,sm86 --lib -- --ignored --nocapture pcie_copy_gpu_ +use super::dma_options; +use crate::{Driver, OriginalStreamKind, api::MappedApi}; + +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 + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +const PAGE: usize = 4096; +const SOURCE: usize = 24 << 20; +const DEST: usize = 12 << 20; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Memory { + Pageable, + PageLocked, + /// the first half of the source is page-locked, the second half is not + Mixed, +} + +fn rounds() -> usize { + std::env::var("PCIE_COPY_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(200) +} + +fn run(batch: bool, memory: Memory) { + let driver = Driver::load().unwrap(); + let ctx = driver.device(0).unwrap().create_context(64 << 20).unwrap(); + let mut dest = ctx.allocate(DEST).unwrap(); + let destination = dest.handle.expect("live buffer").qwen_address(); + let mut stream = ctx.original_gpu_stream(OriginalStreamKind::NonBlocking).unwrap(); + + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + // a page-aligned window inside a heap allocation: pageable unless registered below + let mut heap = vec![0u8; SOURCE + 2 * PAGE]; + let skew = heap.as_ptr().align_offset(PAGE); + for (i, b) in heap[skew..skew + SOURCE].iter_mut().enumerate() { + *b = (rng.next() >> 11) as u8 ^ (i as u8); + } + let source = &heap[skew..skew + SOURCE]; + let base = source.as_ptr() as usize; + let locked_end = match memory { + Memory::Pageable => base, + Memory::PageLocked => base + SOURCE, + Memory::Mixed => base + SOURCE / 2, + }; + let api = (locked_end > base).then(|| { + // the bank copy module loads into the current context + let guard = ctx.enter().unwrap(); + let api = MappedApi::load().unwrap(); + api.register_staging(base, locked_end - base).unwrap(); + guard.finish().unwrap(); + api + }); + + let mut expected = vec![0xA5u8; DEST]; + dest.copy_from(&expected).unwrap(); + let mut checked = 0usize; + for round in 0..rounds() { + // one group: 3..24 pieces (three spans per expert in the real copy), contiguous in staging, cut at the register boundary + let experts = 1 + rng.below(8) as usize; + let mut pieces: Vec<(u64, &[u8])> = Vec::new(); + let mut cursor = 0usize; + for _ in 0..experts * 3 { + let len = 16 * (1 + rng.below(40_000) as usize); + if cursor + len > DEST { + break; + } + let at = 16 * rng.below(((SOURCE - len) / 16) as u64) as usize; + let (lo, hi) = (base + at, base + at + len); + let cuts: Vec<(usize, usize)> = if lo < locked_end && hi > locked_end { vec![(lo, locked_end), (locked_end, hi)] } else { vec![(lo, hi)] }; + for (a, b) in cuts { + let piece = &source[a - base..b - base]; + expected[cursor..cursor + piece.len()].copy_from_slice(piece); + pieces.push((destination + cursor as u64, piece)); + cursor += piece.len(); + } + cursor = cursor.next_multiple_of(PAGE); + } + stream.enqueue_copy_h2d_many(&pieces, batch).unwrap_or_else(|e| panic!("round {round}: enqueue failed: {e:?}")); + stream.synchronize().unwrap_or_else(|e| panic!("round {round}: stream failed after {} pieces: {e:?}", pieces.len())); + let mut got = vec![0u8; DEST]; + dest.copy_to(&mut got).unwrap_or_else(|e| panic!("round {round}: readback failed: {e:?}")); + if let Some(i) = (0..DEST).find(|&i| got[i] != expected[i]) { + panic!("round {round}: byte {i} is {:#x}, want {:#x} ({} pieces)", got[i], expected[i], pieces.len()); + } + checked += pieces.len(); + } + println!( + "pcie copy smoke: batch={batch} memory={} rounds={} pieces={checked}: all bytes exact", + match memory { + Memory::Pageable => "pageable", + Memory::PageLocked => "page-locked", + Memory::Mixed => "mixed", + }, + rounds() + ); + if let Some(api) = &api { + let guard = ctx.enter().unwrap(); + api.unregister_at(base).unwrap(); + guard.finish().unwrap(); + } + drop(stream); + drop(dest); + ctx.close().unwrap(); +} + +/// The form `publish_gpu_plan` uses on this platform. +fn production() -> bool { + dma_options().1 +} + +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_production_pageable() { + run(production(), Memory::Pageable); +} +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_production_page_locked() { + run(production(), Memory::PageLocked); +} +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_production_mixed() { + run(production(), Memory::Mixed); +} +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_raw_loop_pageable() { + run(false, Memory::Pageable); +} +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_raw_loop_page_locked() { + run(false, Memory::PageLocked); +} +#[test] +#[ignore = "needs a CUDA device"] +fn pcie_copy_gpu_raw_batch_pageable() { + run(true, Memory::Pageable); +} +#[test] +#[ignore = "needs a CUDA device; FAILS (error 700) on the RTX 3080 laptop under Windows, driver 617.42"] +fn pcie_copy_gpu_raw_batch_page_locked() { + run(true, Memory::PageLocked); +} +#[test] +#[ignore = "needs a CUDA device; FAILS (error 700) on the RTX 3080 laptop under Windows, driver 617.42"] +fn pcie_copy_gpu_raw_batch_mixed() { + run(true, Memory::Mixed); +} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index 58edb95d..8cd275bd 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -335,26 +335,39 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { } } -/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except on WSL (job 981: +6 % over the per-piece path): -/// `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, `LELEKA_PCIE_DMA_BATCH=off` to one +/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except where noted (job 981: +6 % over the +/// per-piece path on the 5090): `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, `LELEKA_PCIE_DMA_BATCH=off` to one /// `cuMemcpyBatchAsync`-free loop inside the entry, `LELEKA_PCIE_FLAGB=host` raises flag B with a host callback instead of /// `cuStreamWriteValue32`. A driver without the batch / write calls takes the loop / host callback by itself. -fn dma_options() -> (bool, bool, bool) { +/// +/// The batch call is off by default on native Windows and under WSL2: on the RTX 3080 laptop `cuMemcpyBatchAsync_v2` from page-locked +/// host memory raises CUDA error 700 for any piece, source access order or registration flag, which killed the first decode window +/// of every request with a PCIe share (docs/windows.md, "PCIe tier on the laptop"; `pcie_copy_gpu_raw_batch_page_locked` repeats the +/// check). The stream write of flag B is also opt-in under WSL2 only. `=on` / `=write` force either call. +pub(crate) fn dma_options() -> (bool, bool, bool) { static OPTIONS: std::sync::OnceLock<(bool, bool, bool)> = std::sync::OnceLock::new(); *OPTIONS.get_or_init(|| { - let env = |name: &str| std::env::var(name).unwrap_or_default(); - // WSL2's GPU paravirtualisation: the batch copy faulted in a microbenchmark on the RTX 3080 laptop (illegal memory - // access at the next synchronize), so there both advanced calls are opt-in let wsl = std::fs::read_to_string("/proc/sys/kernel/osrelease").is_ok_and(|v| v.to_ascii_lowercase().contains("microsoft")); - let default = |name: &str| match env(name).as_str() { - "on" | "write" => true, - "off" | "host" => false, - _ => !wsl, - }; - (env("LELEKA_PCIE_DMA_MANY") != "off", default("LELEKA_PCIE_DMA_BATCH"), env("LELEKA_PCIE_FLAGB") != "host" && (!wsl || env("LELEKA_PCIE_FLAGB") == "write")) + dma_options_for(wsl, cfg!(windows), |name| std::env::var(name).unwrap_or_default()) }) } +/// `dma_options` for a platform and an environment: `wsl` (WSL2 passthrough) makes the batch copy and the stream write opt-in, +/// `windows` (native) the batch copy only. +fn dma_options_for(wsl: bool, windows: bool, env: impl Fn(&str) -> String) -> (bool, bool, bool) { + let default = |name: &str, off_by_default: bool| match env(name).as_str() { + "on" | "write" => true, + "off" | "host" => false, + _ => !off_by_default, + }; + (env("LELEKA_PCIE_DMA_MANY") != "off", default("LELEKA_PCIE_DMA_BATCH", wsl || windows), default("LELEKA_PCIE_FLAGB", wsl) && env("LELEKA_PCIE_FLAGB") != "host") +} + +// Model-free GPU smoke of the PCIe staging copy: pageable / page-locked / mixed sources, one call per piece and the batch call. +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[path = "original_pcie_copy_gpu_smoke.rs"] +mod pcie_copy_smoke; + #[cfg(test)] mod tests { use super::*; @@ -363,6 +376,18 @@ mod tests { bytes.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().unwrap())).collect() } + #[test] + fn the_batch_copy_is_off_on_windows_and_wsl_and_the_switches_still_force_it() { + let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|p| p.0 == name).map_or(String::new(), |p| p.1.to_string()); + // (many, batch, flag B by stream write) + assert_eq!(dma_options_for(false, false, env(&[])), (true, true, true), "Linux keeps everything on"); + assert_eq!(dma_options_for(false, true, env(&[])), (true, false, true), "native Windows: no batch, stream write kept"); + assert_eq!(dma_options_for(true, false, env(&[])), (true, false, false), "WSL2: neither"); + assert_eq!(dma_options_for(false, true, env(&[("LELEKA_PCIE_DMA_BATCH", "on")])).1, true); + assert_eq!(dma_options_for(true, false, env(&[("LELEKA_PCIE_FLAGB", "write")])).2, true); + assert_eq!(dma_options_for(false, false, env(&[("LELEKA_PCIE_DMA_BATCH", "off"), ("LELEKA_PCIE_DMA_MANY", "off"), ("LELEKA_PCIE_FLAGB", "host")])), (false, false, false)); + } + #[test] fn the_block_is_the_literal_gpu_plan_sink_carve() { // a 3-row group of a max_t = 4 window: cap = 40, 30 entries diff --git a/crates/libc-shim/src/cuda_trace.rs b/crates/libc-shim/src/cuda_trace.rs index c8936c3e..10319058 100644 --- a/crates/libc-shim/src/cuda_trace.rs +++ b/crates/libc-shim/src/cuda_trace.rs @@ -194,6 +194,7 @@ fn describe(state: &State, e: &Entry) -> String { e.grid[0], e.grid[1], e.grid[2], e.block[0], e.block[1], e.block[2], e.smem, e.stream, c ), "graph" => format!("#{} graph-launch exec {:#x} stream {:#x}", e.seq, e.a, e.stream), + "batch-async" => format!("#{} batch-async copies {} dsts {:#x} srcs {:#x} stream {:#x}{}", e.seq, e.n, e.a, e.b, e.stream, c), "set" => format!("#{} memset dst {:#x} value {:#x} bytes {} stream {:#x}{}", e.seq, e.a, e.b & 0xff, e.n, e.stream, c), k => format!("#{} {} dst {:#x} src {:#x} bytes {} stream {:#x}{}", e.seq, k, e.a, e.b, e.n, e.stream, c), } @@ -327,6 +328,9 @@ copy!(w_h2d, 12, "cuMemcpyHtoD_v2", "h2d", 0, true, (a0, a1, a2), a0, a1, a2); copy!(w_d2h, 13, "cuMemcpyDtoH_v2", "d2h", 0, true, (a0, a1, a2), a0, a1, a2); copy!(w_d2d, 14, "cuMemcpyDtoD_v2", "d2d", 0, true, (a0, a1, a2), a0, a1, a2); copy!(w_set, 15, "cuMemsetD8_v2", "set", 0, true, (a0, a1, a2), a0, a1, a2); +// cuMemcpyBatchAsync_v2(dsts, srcs, sizes, count, attrs, attrsIdxs, numAttrs, stream): the batched PCIe copy of a verify window +// (driver 617.42 on the RTX 3080 laptop faults on it from page-locked memory, docs/windows.md "PCIe tier on the laptop") +copy!(w_batch_async, 21, "cuMemcpyBatchAsync_v2", "batch-async", a7, false, (a0, a1, a2, a3, a4, a5, a6, a7), a0, a1, a3); unsafe extern "C" fn w_graph_launch(a0: usize, a1: usize) -> c_int { // SAFETY: slot 16 holds cuGraphLaunch. @@ -429,6 +433,7 @@ pub(crate) fn interpose(handle: *mut c_void, symbol: &CStr, real: *mut c_void) - b"cuMemcpyDtoH_v2" => (13, w_d2h as *const () as usize), b"cuMemcpyDtoD_v2" => (14, w_d2d as *const () as usize), b"cuMemsetD8_v2" => (15, w_set as *const () as usize), + b"cuMemcpyBatchAsync_v2" => (21, w_batch_async as *const () as usize), b"cuGraphLaunch" => (16, w_graph_launch as *const () as usize), b"cuLaunchKernel" => (17, w_launch as *const () as usize), b"cuModuleGetFunction" => (18, w_get_function as *const () as usize), @@ -452,6 +457,13 @@ mod tests { assert_eq!(interpose(nvcuda(), c"cuInit", marker), marker); } + #[test] + fn a_batched_copy_is_described_by_its_count_and_stream() { + let s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() }; + let e = Entry { seq: 9, a: 0x1000, b: 0x2000, n: 21, stream: 0x30, ..blank("batch-async") }; + assert_eq!(describe(&s, &e), "#9 batch-async copies 21 dsts 0x1000 srcs 0x2000 stream 0x30"); + } + #[test] fn the_ring_describes_a_kernel_by_name() { let mut s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() };