From cb70f0cd90c5665350d6fc220f01f5cc54913fca Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:59:11 -0800 Subject: [PATCH 1/5] feat(cuda): every kernel timed by itself, to see where a token's time goes --- crates/dluth-cuda/examples/generate.rs | 30 ++++++++++++++++++++ crates/dluth-cuda/src/device.rs | 39 +++++++++++++++++++++++++- crates/dluth-cuda/src/module.rs | 12 +++++++- 3 files changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index c73bcae..70c6b8f 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -143,6 +143,36 @@ fn main() { ); if let Some(error) = &head.last_error { println!("the head's last error: {error}"); + if mode.as_deref() == Some("kernels") { + // Every kernel timed by itself: where a token's time goes on the device, kernel by + // kernel and by grid size (which tells the shapes of a kernel's uses apart). + let ops = CudaOps::new(&dev, &module).expect("the kernels"); + let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).expect("the model"); + let mut counted = 0; + let generated = model + .generate_greedy_with(&ids, max_new, eos, |_| { + // From the first new token on, with the weights on the device. + if counted == 0 { + dev.time_kernels(true); + } + counted += 1; + }) + .expect("generation"); + let times = dev.kernel_times(); + dev.time_kernels(false); + let tokens = generated.len().saturating_sub(1).max(1) as f64; + let mut rows: Vec<_> = times.into_iter().collect(); + rows.sort_by_key(|(_, (spent, _))| std::cmp::Reverse(*spent)); + let total: f64 = rows.iter().map(|(_, (spent, _))| spent.as_secs_f64()).sum(); + println!("per token, each kernel timed by itself: {:.1} ms in kernels", total * 1e3 / tokens); + println!("{:>9} {:>8} {:>9} kernel (blocks)", "ms/token", "launches", "us each"); + for ((name, blocks), (spent, count)) in rows { + println!( + "{:9.3} {:8.1} {:9.1} {name} ({blocks})", + spent.as_secs_f64() * 1e3 / tokens, + count as f64 / tokens, + spent.as_secs_f64() * 1e6 / count as f64 + ); } return; } diff --git a/crates/dluth-cuda/src/device.rs b/crates/dluth-cuda/src/device.rs index d46e84d..43393d6 100644 --- a/crates/dluth-cuda/src/device.rs +++ b/crates/dluth-cuda/src/device.rs @@ -20,8 +20,13 @@ pub struct CudaDevice { capability: (u32, u32), /// Device pointer to size in bytes, for every live allocation. live: RefCell>, + /// While kernels are being timed: per kernel name and grid size, the time and the count. + timed: RefCell>, } +/// Per kernel name and number of blocks: total time, and how often it ran. +pub type KernelTimes = HashMap<(String, u32), (std::time::Duration, usize)>; + fn backend(e: CudaError) -> CoreError { CoreError::Backend(e.to_string()) } @@ -55,7 +60,7 @@ impl CudaDevice { let mut ctx = std::ptr::null_mut(); // SAFETY: `device` came from cuDeviceGet. The matching release is in Drop. check("cuDevicePrimaryCtxRetain", unsafe { sys::cuDevicePrimaryCtxRetain(&mut ctx, device) }, "")?; - Ok(CudaDevice { device, ctx, capability, live: RefCell::new(HashMap::new()) }) + Ok(CudaDevice { device, ctx, capability, live: RefCell::new(HashMap::new()), timed: RefCell::new(None) }) } /// The device's compute capability as (major, minor); a GB10 reports (12, 1). @@ -63,6 +68,38 @@ impl CudaDevice { self.capability } + /// Starts or stops timing every kernel by itself: while on, each launch waits for the + /// device before and after, and the time between goes to the kernel's name and grid + /// size. That shows what each kernel costs when nothing overlaps it, at the price of + /// making everything slower; it is for finding out where time goes. Starting clears + /// what was gathered. + pub fn time_kernels(&self, on: bool) { + *self.timed.borrow_mut() = on.then(HashMap::new); + } + + /// What `time_kernels` has gathered so far. + pub fn kernel_times(&self) -> KernelTimes { + self.timed.borrow().clone().unwrap_or_default() + } + + pub(crate) fn timing(&self) -> bool { + self.timed.borrow().is_some() + } + + pub(crate) fn wait(&self) -> Result<(), CudaError> { + self.make_current()?; + // SAFETY: the context is current; the call only waits for submitted work. + check("cuCtxSynchronize", unsafe { sys::cuCtxSynchronize() }, "") + } + + pub(crate) fn add_time(&self, name: &str, blocks: u32, spent: std::time::Duration) { + if let Some(times) = self.timed.borrow_mut().as_mut() { + let entry = times.entry((name.to_string(), blocks)).or_default(); + entry.0 += spent; + entry.1 += 1; + } + } + /// How many buffers this device has handed out and not been given back. pub fn live_buffers(&self) -> usize { self.live.borrow().len() diff --git a/crates/dluth-cuda/src/module.rs b/crates/dluth-cuda/src/module.rs index 08a33a8..9d51fd1 100644 --- a/crates/dluth-cuda/src/module.rs +++ b/crates/dluth-cuda/src/module.rs @@ -96,6 +96,11 @@ impl Kernel<'_> { args: &mut [*mut c_void], ) -> Result<(), CudaError> { self.dev.make_current()?; + let timing = self.dev.timing(); + if timing { + self.dev.wait()?; + } + let started = std::time::Instant::now(); // SAFETY: `function` belongs to a module that is still loaded (the borrow says so); // the argument list is the caller's promise. let code = unsafe { @@ -113,7 +118,12 @@ impl Kernel<'_> { std::ptr::null_mut(), ) }; - check("cuLaunchKernel", code, &format!("kernel {}", self.name)) + check("cuLaunchKernel", code, &format!("kernel {}", self.name))?; + if timing { + self.dev.wait()?; + self.dev.add_time(&self.name, grid.0, started.elapsed()); + } + Ok(()) } } From 9523927732daf68ff5b7773b9d57598b84025d4f Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:28:45 -0800 Subject: [PATCH 2/5] feat(cuda): how long the host waits for the device, per token --- crates/dluth-cuda/examples/generate.rs | 4 ++++ crates/dluth-cuda/src/ops.rs | 10 ++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 70c6b8f..f5cee40 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -243,6 +243,10 @@ fn main() { "generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", decoded as f64 / seconds ); + println!( + "of which the host waited for the device {:.1} ms per token; the rest it spent handing work over", + (total.waiting - at_first.waiting).as_secs_f64() * 1000.0 / decoded as f64 + ); println!( "per generated token: {:.1} ms; {:.0} waits for the device, {:.0} copies in, {:.0} copies out", seconds * 1000.0 / decoded as f64, diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index 6f32db3..827aecc 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -178,6 +178,8 @@ pub struct OpsStats { pub waits: usize, pub copies_in: usize, pub copies_out: usize, + /// Time the host spent waiting for the device to finish what it had been given. + pub waiting: std::time::Duration, } /// The operations of an Inkling forward pass on a CUDA device. @@ -270,8 +272,12 @@ impl<'m> CudaOps<'m> { } fn wait(&self) -> Result<(), ModelError> { - self.stats.borrow_mut().waits += 1; - self.dev.synchronize().map_err(failed) + let started = std::time::Instant::now(); + let done = self.dev.synchronize().map_err(failed); + let mut stats = self.stats.borrow_mut(); + stats.waits += 1; + stats.waiting += started.elapsed(); + done } /// Copies floats from the host into `buffer`. The caller has just waited for the From 19a1c1138b8d39cb9b4e03b62fbb1acbe8d1f6fe Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:39:37 -0800 Subject: [PATCH 3/5] fix(cuda): the generation example after joining the timing tools --- crates/dluth-cuda/examples/generate.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index f5cee40..9c50b64 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -143,6 +143,9 @@ fn main() { ); if let Some(error) = &head.last_error { println!("the head's last error: {error}"); + } + return; + } if mode.as_deref() == Some("kernels") { // Every kernel timed by itself: where a token's time goes on the device, kernel by // kernel and by grid size (which tells the shapes of a kernel's uses apart). From 8854d93bc85e0993469fb5d379724c039acbd158 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:44:02 -0800 Subject: [PATCH 4/5] fix(cuda): kernel times keyed by the whole grid; the table says what each time includes; tests for the timing tool and the timed waits; review fixes --- crates/dluth-cuda/examples/generate.rs | 1 + crates/dluth-cuda/src/device.rs | 4 +- crates/dluth-cuda/src/module.rs | 2 +- .../dluth-cuda/tests/inkling_golden_cuda.rs | 1 + crates/dluth-cuda/tests/vecadd.rs | 51 +++++++++++++++++++ 5 files changed, 57 insertions(+), 2 deletions(-) diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 9c50b64..982b4fe 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -168,6 +168,7 @@ fn main() { rows.sort_by_key(|(_, (spent, _))| std::cmp::Reverse(*spent)); let total: f64 = rows.iter().map(|(_, (spent, _))| spent.as_secs_f64()).sum(); println!("per token, each kernel timed by itself: {:.1} ms in kernels", total * 1e3 / tokens); + println!("(each launch includes starting the kernel and one wait for the device)"); println!("{:>9} {:>8} {:>9} kernel (blocks)", "ms/token", "launches", "us each"); for ((name, blocks), (spent, count)) in rows { println!( diff --git a/crates/dluth-cuda/src/device.rs b/crates/dluth-cuda/src/device.rs index 43393d6..56205bc 100644 --- a/crates/dluth-cuda/src/device.rs +++ b/crates/dluth-cuda/src/device.rs @@ -24,7 +24,9 @@ pub struct CudaDevice { timed: RefCell>, } -/// Per kernel name and number of blocks: total time, and how often it ran. +/// Per kernel name and number of blocks: total time, and how often it ran. Each time includes +/// starting the kernel and one wait for the device, a few microseconds that the kernel itself +/// does not cost in normal running. pub type KernelTimes = HashMap<(String, u32), (std::time::Duration, usize)>; fn backend(e: CudaError) -> CoreError { diff --git a/crates/dluth-cuda/src/module.rs b/crates/dluth-cuda/src/module.rs index 9d51fd1..326cd2a 100644 --- a/crates/dluth-cuda/src/module.rs +++ b/crates/dluth-cuda/src/module.rs @@ -121,7 +121,7 @@ impl Kernel<'_> { check("cuLaunchKernel", code, &format!("kernel {}", self.name))?; if timing { self.dev.wait()?; - self.dev.add_time(&self.name, grid.0, started.elapsed()); + self.dev.add_time(&self.name, grid.0.saturating_mul(grid.1).saturating_mul(grid.2), started.elapsed()); } Ok(()) } diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 2baa388..521a3cb 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -234,6 +234,7 @@ mod on_the_device { // However many positions: one wait for the embeddings, one per layer pass // for the router's scores, one for the scores of the vocabulary. assert_eq!(stats.borrow().waits - waits, passes + 2, "a batch of {n}"); + assert!(stats.borrow().waiting > std::time::Duration::ZERO, "the waits are timed"); assert_eq!(got.len(), n * vocab); for (i, scores) in got.chunks_exact(vocab).enumerate() { let want = cpu.forward_token(tokens[i], pos + i).unwrap(); diff --git a/crates/dluth-cuda/tests/vecadd.rs b/crates/dluth-cuda/tests/vecadd.rs index abf5ed0..a760811 100644 --- a/crates/dluth-cuda/tests/vecadd.rs +++ b/crates/dluth-cuda/tests/vecadd.rs @@ -152,3 +152,54 @@ fn opening_a_device_that_does_not_exist_is_refused() { // Assumes a machine with fewer than 100 GPUs. assert!(matches!(CudaDevice::open(99), Err(CudaError::NoDevice { ordinal: 99, .. }))); } + +#[test] +fn timed_kernels_are_counted_by_name_and_blocks_and_only_while_timing() { + let dev = CudaDevice::open(0).expect("GPU"); + dev.preflight(BUILT_FOR).unwrap(); + let module = Module::load(&dev, KERNELS_CUBIN).unwrap(); + let n = 1000usize; + let (da, db, dc) = (dev.alloc(n * 4).unwrap(), dev.alloc(n * 4).unwrap(), dev.alloc(n * 4).unwrap()); + dev.upload(&da, &to_bytes(&vec![1.0; n])).unwrap(); + dev.upload(&db, &to_bytes(&vec![2.0; n])).unwrap(); + let run = |count: usize| { + let (mut pa, mut pb, mut pc, mut pn) = (da.handle, db.handle, dc.handle, count as i32); + let mut args = [ + &mut pa as *mut u64 as *mut c_void, + &mut pb as *mut u64 as *mut c_void, + &mut pc as *mut u64 as *mut c_void, + &mut pn as *mut i32 as *mut c_void, + ]; + let blocks = count.div_ceil(256) as u32; + // SAFETY: the argument list matches vecadd_f32, and the buffers hold n >= count floats. + unsafe { module.launch("vecadd_f32", (blocks, 1, 1), (256, 1, 1), &mut args).unwrap() }; + }; + + // Not timing: nothing is gathered. + run(n); + assert!(dev.kernel_times().is_empty()); + + dev.time_kernels(true); + run(n); // 4 blocks + run(n); // 4 blocks + run(300); // 2 blocks + let times = dev.kernel_times(); + assert_eq!(times.len(), 2, "{times:?}"); + let four = times[&("vecadd_f32".to_string(), 4)]; + let two = times[&("vecadd_f32".to_string(), 2)]; + assert_eq!((four.1, two.1), (2, 1)); + assert!(four.0 > std::time::Duration::ZERO && two.0 > std::time::Duration::ZERO); + + // Starting again clears what was gathered; stopping gathers nothing more. + dev.time_kernels(true); + assert!(dev.kernel_times().is_empty()); + dev.time_kernels(false); + run(n); + dev.synchronize().unwrap(); + assert!(dev.kernel_times().is_empty()); + + // The timed runs computed what an untimed run computes. + let mut out = vec![0u8; n * 4]; + dev.download(&dc, &mut out).unwrap(); + assert!(out.as_chunks::<4>().0.iter().all(|c| f32::from_le_bytes(*c) == 3.0)); +} From b05a31bad49ab5bbe8c6b4d3f3603524a131f57d Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:44:35 -0800 Subject: [PATCH 5/5] test: planted bugs for the timing tool and the timed waits --- .../172-timing-launches-not-counted.patch | 15 +++++++++++++++ .../173-timing-not-cleared-on-start.patch | 16 ++++++++++++++++ .../mutants/174-timing-keyed-by-name-only.patch | 16 ++++++++++++++++ tools/mutants/175-waits-not-timed.patch | 15 +++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 tools/mutants/172-timing-launches-not-counted.patch create mode 100644 tools/mutants/173-timing-not-cleared-on-start.patch create mode 100644 tools/mutants/174-timing-keyed-by-name-only.patch create mode 100644 tools/mutants/175-waits-not-timed.patch diff --git a/tools/mutants/172-timing-launches-not-counted.patch b/tools/mutants/172-timing-launches-not-counted.patch new file mode 100644 index 0000000..19faa03 --- /dev/null +++ b/tools/mutants/172-timing-launches-not-counted.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-cuda --test vecadd timed_kernels +# needs: gpu +# Bug: a timed launch adds its time but is not counted +diff --git a/crates/dluth-cuda/src/device.rs b/crates/dluth-cuda/src/device.rs +index 56205bc..bd4a53a 100644 +--- a/crates/dluth-cuda/src/device.rs ++++ b/crates/dluth-cuda/src/device.rs +@@ -98,7 +98,6 @@ impl CudaDevice { + if let Some(times) = self.timed.borrow_mut().as_mut() { + let entry = times.entry((name.to_string(), blocks)).or_default(); + entry.0 += spent; +- entry.1 += 1; + } + } + diff --git a/tools/mutants/173-timing-not-cleared-on-start.patch b/tools/mutants/173-timing-not-cleared-on-start.patch new file mode 100644 index 0000000..bd6bedb --- /dev/null +++ b/tools/mutants/173-timing-not-cleared-on-start.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test vecadd timed_kernels +# needs: gpu +# Bug: starting the timing again keeps what was gathered +diff --git a/crates/dluth-cuda/src/device.rs b/crates/dluth-cuda/src/device.rs +index 56205bc..11946e5 100644 +--- a/crates/dluth-cuda/src/device.rs ++++ b/crates/dluth-cuda/src/device.rs +@@ -76,7 +76,7 @@ impl CudaDevice { + /// making everything slower; it is for finding out where time goes. Starting clears + /// what was gathered. + pub fn time_kernels(&self, on: bool) { +- *self.timed.borrow_mut() = on.then(HashMap::new); ++ if on { self.timed.borrow_mut().get_or_insert_with(HashMap::new); } else { *self.timed.borrow_mut() = None; } + } + + /// What `time_kernels` has gathered so far. diff --git a/tools/mutants/174-timing-keyed-by-name-only.patch b/tools/mutants/174-timing-keyed-by-name-only.patch new file mode 100644 index 0000000..74393a3 --- /dev/null +++ b/tools/mutants/174-timing-keyed-by-name-only.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test vecadd timed_kernels +# needs: gpu +# Bug: kernel times of every grid size go to one row +diff --git a/crates/dluth-cuda/src/module.rs b/crates/dluth-cuda/src/module.rs +index 326cd2a..76d6032 100644 +--- a/crates/dluth-cuda/src/module.rs ++++ b/crates/dluth-cuda/src/module.rs +@@ -121,7 +121,7 @@ impl Kernel<'_> { + check("cuLaunchKernel", code, &format!("kernel {}", self.name))?; + if timing { + self.dev.wait()?; +- self.dev.add_time(&self.name, grid.0.saturating_mul(grid.1).saturating_mul(grid.2), started.elapsed()); ++ self.dev.add_time(&self.name, 0, started.elapsed()); + } + Ok(()) + } diff --git a/tools/mutants/175-waits-not-timed.patch b/tools/mutants/175-waits-not-timed.patch new file mode 100644 index 0000000..fba7883 --- /dev/null +++ b/tools/mutants/175-waits-not-timed.patch @@ -0,0 +1,15 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda +# needs: gpu +# Bug: the time the host waits for the device is not added up +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index 827aecc..8b287af 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -276,7 +276,6 @@ impl<'m> CudaOps<'m> { + let done = self.dev.synchronize().map_err(failed); + let mut stats = self.stats.borrow_mut(); + stats.waits += 1; +- stats.waiting += started.elapsed(); + done + } +