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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/dluth-cuda/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ workspace = true
[dependencies]
# The Backend trait this crate implements for a CUDA device, and its buffer and error types.
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" }

[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"

[build-dependencies]
# Generates Rust declarations for the CUDA driver API from NVIDIA's own header at build time,
Expand Down
79 changes: 79 additions & 0 deletions crates/dluth-cuda/examples/generate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! 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]
//!
//! 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::{CudaDevice, Module};
use dluth_model::inkling::prompt::{single_turn, Effort};
use dluth_model::inkling::{load_config, InklingCpu};
use dluth_model::tokenizer::Tokenizer;
use dluth_model::weights::Weights;
use std::path::PathBuf;
use std::time::Instant;

fn main() {
let mut args = std::env::args().skip(1);
let dir = PathBuf::from(args.next().expect("a model directory"));
let prompt = args.next().expect("a prompt");
let max_new: usize = args.next().map_or(128, |n| n.parse().expect("a number of tokens"));

let weights = Weights::open_dir(&dir).expect("the weights");
let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).expect("the tokenizer");
let cfg = load_config(&dir).expect("the configuration");
let eos = cfg.eos;
let ids = tokenizer.encode(&single_turn(&prompt, Effort::None)).expect("the prompt's tokens");

let dev = CudaDevice::open(0).expect("a CUDA device");
let module = Module::load_embedded(&dev).expect("the embedded kernels");
let products = CudaProducts::new(&dev, &module).expect("the product kernels");
let stats = products.stats();
let mut model =
InklingCpu::with_products(cfg, &weights, ids.len() + max_new, Box::new(products)).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();
let total = *stats.borrow();
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 {
println!("generation: {decoded} tokens in {seconds:.2} s, {:.1} tokens per second", decoded as f64 / seconds);
let per = |n: usize| n as f64 / decoded as f64;
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0 / decoded as f64;
let bf16 = total.bf16_time - at_first.bf16_time;
let experts = total.expert_time - at_first.expert_time;
println!("per generated token: {:.1} ms in all", seconds * 1000.0 / decoded as f64);
println!(
" BF16 products: {:.0} of them, {:.1} ms",
per(total.bf16_products - at_first.bf16_products),
ms(bf16)
);
println!(
" expert launches: {:.0} of them, {:.1} ms",
per(total.expert_launches - at_first.expert_launches),
ms(experts)
);
println!(" everything else, on the CPU: {:.1} ms", seconds * 1000.0 / decoded as f64 - ms(bf16) - ms(experts));
}
}
32 changes: 32 additions & 0 deletions crates/dluth-cuda/kernels/expert_ops.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// The two small steps of an expert layer that sit between and after its matrix products.
// They are cheap arithmetic, but on the CPU they cost a round trip to the device and well
// over a million tanh and exp calls per token; here they keep the whole expert stage on
// the device.

// The activation inside an expert, for a run of (gate, up) pairs:
// act[i] = softcap(gate, gate_cap) * sigmoid(gate) * softcap(up, up_cap)
// where gate = both[2i], up = both[2i + 1] and softcap(x, c) = c * tanh(x / c).
// The sigmoid sees the raw gate, not the limited one.
// CPU reference: dluth_kernels::cpu::capped_gate_mul.
extern "C" __global__ void capped_gate_pairs(const float* both, float* act, unsigned int pairs,
float gate_cap, float up_cap) {
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= pairs) return;
float2 gu = reinterpret_cast<const float2*>(both)[i];
float gate = gate_cap * tanhf(gu.x / gate_cap);
float up = up_cap * tanhf(gu.y / up_cap);
act[i] = gate * (1.0f / (1.0f + expf(-gu.x))) * up;
}

// The weighted sum of the chosen experts' outputs:
// y[r] = sum over j of weights[j] * outs[j][r]
// `outs` is count vectors of width floats, one after another. The sum runs in the order of
// j, like the CPU reference (the loop in the model's expert step).
extern "C" __global__ void weighted_sum(const float* outs, const float* weights, float* y,
unsigned int count, unsigned int width) {
unsigned int r = blockIdx.x * blockDim.x + threadIdx.x;
if (r >= width) return;
float total = 0.0f;
for (unsigned int j = 0; j < count; ++j) total += weights[j] * outs[(size_t)j * width + r];
y[r] = total;
}
102 changes: 102 additions & 0 deletions crates/dluth-cuda/src/expert_ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! The small steps of an expert layer: the activation between its two matrix products and
//! the weighted sum after them.

use crate::device::CudaDevice;
use crate::error::CudaError;
use crate::module::{Kernel, Module};
use dluth_core::{Buffer, CoreError};
use std::ffi::c_void;

fn unknown(e: CoreError) -> CudaError {
CudaError::Refused(e.to_string())
}

/// The expert-step kernels of a loaded module.
pub struct ExpertOps<'m> {
dev: &'m CudaDevice,
gate: Kernel<'m>,
sum: Kernel<'m>,
}

impl<'m> ExpertOps<'m> {
pub fn new(dev: &'m CudaDevice, module: &'m Module<'m>) -> Result<Self, CudaError> {
Ok(ExpertOps { dev, gate: module.kernel("capped_gate_pairs")?, sum: module.kernel("weighted_sum")? })
}

/// Starts `act[i] = softcap(gate_i, gate_cap) * sigmoid(gate_i) * softcap(up_i, up_cap)`
/// for `pairs` pairs and returns without waiting. `both` holds the pairs as
/// gate, up, gate, up, ...; `act` receives one float per pair.
pub fn capped_gate_pairs(
&self,
both: &Buffer,
act: &Buffer,
pairs: usize,
gate_cap: f32,
up_cap: f32,
) -> Result<(), CudaError> {
let refuse = |why: String| Err(CudaError::Refused(format!("capped_gate_pairs: {why}")));
let (both_have, act_have) = (self.dev.size_of(both).map_err(unknown)?, self.dev.size_of(act).map_err(unknown)?);
if pairs == 0 || pairs > u32::MAX as usize / 2 || pairs * 8 > both_have || pairs * 4 > act_have {
return refuse(format!("{pairs} pairs with buffers of {both_have} and {act_have} bytes"));
}
// Written as "not greater than zero" so that a cap that is not a number is refused too.
if !(gate_cap > 0.0 && up_cap > 0.0) || !gate_cap.is_finite() || !up_cap.is_finite() {
return refuse(format!("caps of {gate_cap} and {up_cap}; both must be positive"));
}
if both.handle == act.handle {
return refuse("the same buffer for input and output".into());
}
let (mut pb, mut pa, mut n, mut gc, mut uc) = (both.handle, act.handle, pairs as u32, gate_cap, up_cap);
let mut args = [
&mut pb as *mut u64 as *mut c_void,
&mut pa as *mut u64 as *mut c_void,
&mut n as *mut u32 as *mut c_void,
&mut gc as *mut f32 as *mut c_void,
&mut uc as *mut f32 as *mut c_void,
];
// SAFETY: the arguments match capped_gate_pairs(const float*, float*, unsigned,
// float, float). The kernel reads 2 * pairs floats from `both` (as 8-byte pairs;
// device buffers are aligned far beyond that) and writes pairs floats to `act`;
// both extents were checked against the real buffer sizes.
unsafe { self.gate.launch(((pairs as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) }
}

/// Starts `y[r] = sum_j weights[j] * outs[j][r]` over `count` vectors of `width` floats
/// and returns without waiting.
pub fn weighted_sum(
&self,
outs: &Buffer,
weights: &Buffer,
y: &Buffer,
count: usize,
width: usize,
) -> Result<(), CudaError> {
let refuse = |why: String| Err(CudaError::Refused(format!("weighted_sum: {why}")));
let have = |b: &Buffer| self.dev.size_of(b).map_err(unknown);
let (outs_have, weights_have, y_have) = (have(outs)?, have(weights)?, have(y)?);
if count == 0 || width == 0 || count > 1 << 16 || width > 1 << 24 {
return refuse(format!("{count} vectors of {width}"));
}
if count * width * 4 > outs_have || count * 4 > weights_have || width * 4 > y_have {
return refuse(format!(
"{count} vectors of {width} with buffers of {outs_have}, {weights_have} and {y_have} bytes"
));
}
if y.handle == outs.handle || y.handle == weights.handle || outs.handle == weights.handle {
return refuse("one buffer used for two of the three arguments".into());
}
let (mut po, mut pw, mut py, mut c, mut w) =
(outs.handle, weights.handle, y.handle, count as u32, width as u32);
let mut args = [
&mut po as *mut u64 as *mut c_void,
&mut pw as *mut u64 as *mut c_void,
&mut py as *mut u64 as *mut c_void,
&mut c as *mut u32 as *mut c_void,
&mut w as *mut u32 as *mut c_void,
];
// SAFETY: the arguments match weighted_sum(const float*, const float*, float*,
// unsigned, unsigned). The kernel reads count * width floats from `outs` and count
// from `weights`, and writes width floats to `y`; all checked above.
unsafe { self.sum.launch(((width as u32).div_ceil(256), 1, 1), (256, 1, 1), &mut args) }
}
}
Loading
Loading