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
5 changes: 3 additions & 2 deletions crates/dluth-cuda/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ workspace = true
dluth-core = { version = "0.0.0", path = "../dluth-core" }
# The Inkling forward pass, whose matrix products this crate computes on the device.
dluth-model = { version = "0.0.0", path = "../dluth-model" }
# The CPU reference every GPU kernel is compared with in tests; the device model also uses
# its expert choice and the few scalar formulas that stay on the host.
dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" }

[dev-dependencies]
# The CPU reference that every GPU kernel's result is compared with.
dluth-kernels = { version = "0.0.0", path = "../dluth-kernels" }
# Reads the recorded runs of the reference implementation that the golden tests compare with.
serde_json = "1.0.154"

Expand Down
85 changes: 83 additions & 2 deletions crates/dluth-cuda/examples/generate.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
//! Generates text from Inkling 2 Mini with the matrix products on the GPU, and says how
//! fast it went and where the time was spent.
//!
//! cargo run --release -p dluth-cuda --example generate -- <model directory> "<prompt>" [max new tokens]
//! cargo run --release -p dluth-cuda --example generate -- <model directory> "<prompt>" [max new tokens] [products]
//!
//! By default every value of the forward pass stays on the device. With `timed` as the
//! last word the device is waited for after every operation and the time per kind of
//! operation is printed (which makes the run itself slower). With `products` as the
//! last word only the matrix products run there and the rest on the CPU, as an earlier step
//! of the port did, with that step's own breakdown of a token's time.
//!
//! Greedy, reasoning effort "none". Speed is counted from the first generated token to the
//! last, so loading the weights and reading the prompt are not in it.

use dluth_cuda::inkling::CudaProducts;
use dluth_cuda::ops::{CudaOps, TimedOps};
use dluth_cuda::{CudaDevice, Module};
use dluth_model::inkling::prompt::{single_turn, Effort};
use dluth_model::inkling::{load_config, InklingCpu};
use dluth_model::inkling::{load_config, Inkling, InklingCpu};
use dluth_model::tokenizer::Tokenizer;
use dluth_model::weights::Weights;
use std::path::PathBuf;
Expand All @@ -29,6 +36,80 @@ fn main() {

let dev = CudaDevice::open(0).expect("a CUDA device");
let module = Module::load_embedded(&dev).expect("the embedded kernels");
let mode = args.next();
if mode.as_deref() == Some("timed") {
let ops = TimedOps::new(CudaOps::new(&dev, &module).expect("the kernels"));
let spent = ops.spent();
let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).expect("the model");
let mut fed = 0usize;
let generated = model
.generate_greedy_with(&ids, max_new, eos, |_| {
// Start counting once the prompt is in and the weights are on the device.
if fed == 0 {
spent.borrow_mut().clear();
}
fed += 1;
})
.expect("generation");
let decoded = generated.len().saturating_sub(1).max(1) as f64;
let mut rows = spent.borrow().clone();
rows.sort_by_key(|row| std::cmp::Reverse(row.1));
let total: f64 = rows.iter().map(|r| r.1.as_secs_f64()).sum();
println!(
"per generated token, waiting for the device after every operation: {:.1} ms",
total * 1000.0 / decoded
);
for (name, time, count) in rows {
println!(
" {name:<26} {:6.2} ms ({:.0} times)",
time.as_secs_f64() * 1000.0 / decoded,
count as f64 / decoded
);
}
return;
}
if mode.as_deref() != Some("products") {
let ops = CudaOps::new(&dev, &module).expect("the kernels");
let stats = ops.stats();
let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).expect("the model");
let started = Instant::now();
let mut first = None;
let mut at_first = Default::default();
let generated = model
.generate_greedy_with(&ids, max_new, eos, |_| {
if first.is_none() {
first = Some(Instant::now());
at_first = *stats.borrow();
}
})
.expect("generation");
let finished = Instant::now();
let first = first.unwrap_or(finished);
println!("{}", tokenizer.decode(&generated));
let decoded = generated.len().saturating_sub(1);
let seconds = (finished - first).as_secs_f64();
println!(
"prompt: {} tokens in {:.1} s (weights are copied to the device as they are first used)",
ids.len(),
(first - started).as_secs_f64()
);
if decoded > 0 {
let total = *stats.borrow();
println!(
"generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second",
decoded as f64 / seconds
);
println!(
"per generated token: {:.1} ms; {:.0} waits for the device, {:.0} copies in, {:.0} copies out",
seconds * 1000.0 / decoded as f64,
(total.waits - at_first.waits) as f64 / decoded as f64,
(total.copies_in - at_first.copies_in) as f64 / decoded as f64,
(total.copies_out - at_first.copies_out) as f64 / decoded as f64
);
}
return;
}

let products = CudaProducts::new(&dev, &module).expect("the product kernels");
let stats = products.stats();
let mut model =
Expand Down
92 changes: 92 additions & 0 deletions crates/dluth-cuda/examples/matmat_alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//! Does it matter how a matrix got onto the device? Times the BF16 product on 48 matrices of
//! 3,072 by 2,304 laid out four ways. Run on an idle machine:
//!
//! cargo run --release -p dluth-cuda --example matmat_alloc
//!
//! GB of weights per second, median of five runs, one vector per product.

use dluth_core::{Backend, Buffer};
use dluth_cuda::matmat::{Bf16Matrix, Matmat};
use dluth_cuda::probe::Probe;
use dluth_cuda::{CudaDevice, Module};
use std::time::Instant;

fn median_of_five(mut run: impl FnMut() -> f64) -> f64 {
let mut v: Vec<f64> = (0..5).map(|_| run()).collect();
v.sort_by(f64::total_cmp);
v[2]
}

fn main() {
let dev = CudaDevice::open(0).expect("a CUDA device");
let module = Module::load_embedded(&dev).expect("the embedded kernels");
let mm = Matmat::new(&dev, &module).expect("the matrix kernels");
let probe = Probe::new(&dev, &module).expect("the probe kernels");
let (count, rows, cols) = (48usize, 3072usize, 2304usize);
let one = rows * cols * 2;
let x = dev.alloc(cols * 4).expect("device memory");
dev.upload(&x, &vec![0u8; cols * 4]).expect("upload");
let y = dev.alloc(rows * 4).expect("device memory");
let host: Vec<u8> = (0..one).map(|i| (i * 31 + 7) as u8).collect();

let time = |name: &str, matrices: &dyn Fn(usize) -> (Buffer, usize), wait_each: bool| {
let rate = median_of_five(|| {
dev.synchronize().expect("synchronize");
let started = Instant::now();
for i in 0..count {
let (buffer, offset) = matrices(i);
mm.bf16(Bf16Matrix { buffer: &buffer, offset, rows, cols }, &x, 1, &y, 16).expect("launch");
if wait_each {
dev.synchronize().expect("synchronize");
}
}
dev.synchronize().expect("synchronize");
(count * one) as f64 / 1e9 / started.elapsed().as_secs_f64()
});
println!(" {name:<64} {rate:7.1}");
};

println!("48 matrices of {rows} by {cols} ({:.1} MB each), GB/s", one as f64 / 1e6);
let big = dev.alloc(count * one).expect("device memory");
probe.fill(&big, (count * one / 4) as u64).expect("fill");
time("one buffer, filled by a kernel", &|i| (big, i * one), false);
time("one buffer, filled by a kernel, waiting after each product", &|i| (big, i * one), true);

let big_copied = dev.alloc(count * one).expect("device memory");
let all: Vec<u8> = host.iter().cycle().take(count * one).copied().collect();
dev.upload(&big_copied, &all).expect("upload");
time("one buffer, copied from the host", &|i| (big_copied, i * one), false);

let separate: Vec<Buffer> = (0..count)
.map(|_| {
let b = dev.alloc(one).expect("device memory");
dev.upload(&b, &host).expect("upload");
b
})
.collect();
time("a buffer per matrix, copied from the host", &|i| (separate[i], 0), false);
time("a buffer per matrix, copied from the host, waiting after each", &|i| (separate[i], 0), true);

// The model's rhythm: light kernels between the products. Only the products are timed.
println!("the same products with light work in between, microseconds per product (median of five passes over 48)");
for (light, pause_us) in [(0usize, 0u64), (20, 0), (200, 0), (0, 50), (0, 200), (0, 1000)] {
let micros = median_of_five(|| {
let mut total = 0.0;
for i in 0..count {
for _ in 0..light {
probe.launch_empty().expect("launch");
}
dev.synchronize().expect("synchronize");
if pause_us > 0 {
std::thread::sleep(std::time::Duration::from_micros(pause_us));
}
let started = Instant::now();
mm.bf16(Bf16Matrix { buffer: &big, offset: i * one, rows, cols }, &x, 1, &y, 16).expect("launch");
dev.synchronize().expect("synchronize");
total += started.elapsed().as_secs_f64();
}
total * 1e6 / count as f64
});
println!(" {light:>4} empty kernels, then {pause_us:>5} us idle, before each product: {micros:7.1}");
}
}
Loading
Loading