Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions crates/dluth-cuda/examples/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,40 @@ fn main() {
}
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).
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!("(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!(
"{: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;
}
if mode.as_deref() == Some("draft") {
// Generation twice on the same model: without guesses, then with guesses looked up
// in the text so far (the last `run` tokens, where they last appeared), `most` at a
Expand Down Expand Up @@ -213,6 +247,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,
Expand Down
41 changes: 40 additions & 1 deletion crates/dluth-cuda/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,15 @@ pub struct CudaDevice {
capability: (u32, u32),
/// Device pointer to size in bytes, for every live allocation.
live: RefCell<HashMap<u64, usize>>,
/// While kernels are being timed: per kernel name and grid size, the time and the count.
timed: RefCell<Option<KernelTimes>>,
}

/// 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 {
CoreError::Backend(e.to_string())
}
Expand Down Expand Up @@ -55,14 +62,46 @@ 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).
pub fn compute_capability(&self) -> (u32, u32) {
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()
Expand Down
12 changes: 11 additions & 1 deletion crates/dluth-cuda/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.saturating_mul(grid.1).saturating_mul(grid.2), started.elapsed());
}
Ok(())
}
}

Expand Down
10 changes: 8 additions & 2 deletions crates/dluth-cuda/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions crates/dluth-cuda/tests/inkling_golden_cuda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
51 changes: 51 additions & 0 deletions crates/dluth-cuda/tests/vecadd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
15 changes: 15 additions & 0 deletions tools/mutants/172-timing-launches-not-counted.patch
Original file line number Diff line number Diff line change
@@ -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;
}
}

16 changes: 16 additions & 0 deletions tools/mutants/173-timing-not-cleared-on-start.patch
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 16 additions & 0 deletions tools/mutants/174-timing-keyed-by-name-only.patch
Original file line number Diff line number Diff line change
@@ -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(())
}
15 changes: 15 additions & 0 deletions tools/mutants/175-waits-not-timed.patch
Original file line number Diff line number Diff line change
@@ -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
}

Loading