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
40 changes: 40 additions & 0 deletions crates/dluth-cuda/examples/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
//! 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.
//!
//! With `draft [guesses per sweep] [tokens that must match]` as the last words, the text is
//! generated without guesses and then with guesses looked up in the text so far, and both
//! speeds are printed.
//!
//! 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. In the default mode
//! the text is then read again in batches of 1 to 16 positions, to show what a batch costs.
Expand Down Expand Up @@ -69,6 +73,42 @@ fn main() {
}
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
// time. The first run also brings the weights to the device.
let most: usize = args.next().map_or(4, |n| n.parse().expect("how many guesses per sweep"));
let run: usize = args.next().map_or(2, |n| n.parse().expect("how many tokens must match"));
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");
model.set_prompt_batch(16).expect("a prompt batch");
let mut timed = |drafter: &mut dyn dluth_model::inkling::Drafter, most: usize| {
let mut first = None;
let (tokens, stats) = model
.generate_greedy_drafted(&ids, max_new, eos, drafter, most, |_| {
first.get_or_insert_with(Instant::now);
})
.expect("generation");
let seconds = first.map_or(0.0, |f| f.elapsed().as_secs_f64());
(tokens, stats, seconds)
};
timed(&mut dluth_model::inkling::NoDraft, 0);
let (plain, _, plain_seconds) = timed(&mut dluth_model::inkling::NoDraft, 0);
let (drafted, stats, seconds) = timed(&mut dluth_model::inkling::LookupDrafter::new(run.max(4), run), most);
println!("{}", tokenizer.decode(&drafted));
let n = plain.len().saturating_sub(1) as f64;
println!("without guesses: {n:.0} tokens in {plain_seconds:.2} s, {:.1} tokens per second", n / plain_seconds);
println!(
"with up to {most} guesses after a match of {run}: {:.2} s, {:.1} tokens per second; {} sweeps, {} guessed, {} right",
seconds,
n / seconds,
stats.sweeps,
stats.drafted,
stats.accepted
);
println!("the same tokens: {}", plain == drafted);
return;
}
if mode.as_deref() != Some("products") {
let ops = CudaOps::new(&dev, &module).expect("the kernels");
let stats = ops.stats();
Expand Down
38 changes: 21 additions & 17 deletions crates/dluth-cuda/kernels/attention.cu
Original file line number Diff line number Diff line change
Expand Up @@ -76,36 +76,40 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign
}

// The token `lag` steps before position b of a batch whose first token is at `pos`,
// channel c: from the batch itself if it is that recent, else from a ring of the last
// n - 1 tokens before the batch; zero before the start of the sequence.
// channel c: from the batch itself if it is that recent, else from a ring of `slots`
// recent tokens (the token at position p is in slot p % slots; at least the n - 1 before
// the batch are there); zero before the start of the sequence.
__device__ __forceinline__ float earlier_token(const float* current, const float* ring, unsigned int channels,
unsigned int n, unsigned long long pos, unsigned int b,
unsigned int slots, unsigned long long pos, unsigned int b,
unsigned int lag, unsigned int c) {
if (b >= lag) return current[(size_t)(b - lag) * channels + c];
unsigned long long at = pos + b;
return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f;
return at >= lag ? ring[((at - lag) % slots) * channels + c] : 0.0f;
}

// Short convolution with fixed taps, for a batch of `batch` consecutive tokens of
// `channels` floats: taps[c * n + j] weighs the token n - 1 - j steps back.
// out[b][c] = (sum of taps times tokens + current[b][c]) * norm
// The ring may have more than the n - 1 slots a convolution reads; the spare ones are what
// lets the newest tokens be taken back (the tokens before them are still there).
// With a batch of one, the token then takes its place in the ring. With a larger batch
// the ring is only read here (another position's thread may be reading the slot a write
// would hit); `ring_store` puts the batch's last tokens in afterwards.
// CPU reference: sconv::fixed, token after token.
extern "C" __global__ void sconv_fixed(const float* current, float* ring, const float* taps, float* out,
unsigned int channels, unsigned int n, unsigned long long pos,
float norm, unsigned int batch) {
float norm, unsigned int batch, unsigned int slots) {
unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned int b = (unsigned int)(index / channels);
unsigned int c = (unsigned int)(index % channels);
if (b >= batch) return;
float x = current[index];
const float* w = taps + (size_t)c * n;
float sum = w[n - 1] * x;
for (unsigned int j = 0; j + 1 < n; ++j) sum += w[j] * earlier_token(current, ring, channels, n, pos, b, n - 1 - j, c);
for (unsigned int j = 0; j + 1 < n; ++j)
sum += w[j] * earlier_token(current, ring, channels, slots, pos, b, n - 1 - j, c);
out[index] = (sum + x) * norm;
if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x;
if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x;
}

// Short convolution whose taps are a fixed part per channel plus a part computed for each
Expand All @@ -115,7 +119,7 @@ extern "C" __global__ void sconv_fixed(const float* current, float* ring, const
extern "C" __global__ void sconv_dynamic(const float* current, float* ring, const float* fixed_taps,
const float* token_taps, float* out, unsigned int channels,
unsigned int n, unsigned int heads, unsigned long long pos,
float norm, unsigned int batch) {
float norm, unsigned int batch, unsigned int slots) {
unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned int b = (unsigned int)(index / channels);
unsigned int c = (unsigned int)(index % channels);
Expand All @@ -125,22 +129,22 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons
float sum = (fixed_taps[c] + head_taps[0]) * x;
for (unsigned int lag = 1; lag < n; ++lag)
sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag])
* earlier_token(current, ring, channels, n, pos, b, lag, c);
* earlier_token(current, ring, channels, slots, pos, b, lag, c);
out[index] = (sum + x) * norm;
if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x;
if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x;
}

// After a convolution over a batch larger than one: the batch's last n - 1 tokens (or all
// of them, if it has fewer) take their places in the ring. The token at position p goes to
// slot p % (n - 1); the tokens stored here have different slots.
// After a convolution over a batch larger than one: the batch's last `slots` tokens (all of
// them, if it has no more) take their places in the ring. The token at position p goes to
// slot p % slots; the tokens stored here have different slots.
extern "C" __global__ void ring_store(const float* current, float* ring, unsigned int channels,
unsigned int n, unsigned long long pos, unsigned int batch) {
unsigned int slots, unsigned long long pos, unsigned int batch) {
unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned int b = (unsigned int)(index / channels);
unsigned int c = (unsigned int)(index % channels);
if (b >= batch || n < 2) return;
if (batch - b > n - 1) return;
ring[((pos + b) % (n - 1)) * channels + c] = current[index];
if (b >= batch || slots == 0) return;
if (batch - b > slots) return;
ring[((pos + b) % slots) * channels + c] = current[index];
}

// The keys or values of a batch go to their rows of the history: the token at position p
Expand Down
57 changes: 40 additions & 17 deletions crates/dluth-cuda/src/attention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ impl<'m> Attention<'m> {

/// The short convolution with fixed taps (`channels * n` of them) of a batch of `batch`
/// consecutive tokens, the first at `pos`, written to `out`. `current` and `out` hold
/// the tokens one after another. `ring` holds the `n - 1` tokens before the batch.
/// the tokens one after another. `ring` holds recent tokens, at least the `n - 1` before
/// the batch: it is a whole number of slots of one token each, at least `n - 1` of them,
/// and the token at position p is in slot `p % slots`. With more slots than `n - 1`,
/// tokens older than a convolution reads stay available, which is what lets the newest
/// tokens be dropped again: feed the next batch at an earlier position.
///
/// With a batch of one the token then takes its place in the ring. With a larger batch
/// the ring is left as it was: call `ring_store` after this. Batches must be given in
Expand All @@ -211,14 +215,15 @@ impl<'m> Attention<'m> {
batch: usize,
) -> Result<(), CudaError> {
let what = "sconv_fixed";
let channels = self.conv_checks(what, current, ring, out, n, batch)?;
let (channels, slots) = self.conv_checks(what, current, ring, out, n, batch)?;
taps.check(self.dev, what, channels * n)?;
if taps.overlaps(&out) || taps.overlaps(&ring) {
return refuse(what, "the taps overlap the output or the ring".into());
}
let (mut pc, mut pr, mut pt, mut po) = (current.address(), ring.address(), taps.address(), out.address());
let (mut c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32);
let mut norm = 1.0 / ((n + 1) as f32).sqrt();
let mut s = slots as u32;
let mut args = [
ptr(&mut pc),
ptr(&mut pr),
Expand All @@ -229,10 +234,12 @@ impl<'m> Attention<'m> {
big(&mut p),
real(&mut norm),
num(&mut b),
num(&mut s),
];
// SAFETY: the arguments match sconv_fixed(const float*, float*, const float*, float*,
// unsigned, unsigned, unsigned long long, float, unsigned). It reads batch * channels
// floats of `current`, channels * n of `taps` and (n - 1) * channels of `ring`,
// unsigned, unsigned, unsigned long long, float, unsigned, unsigned). It reads
// batch * channels floats of `current`, channels * n of `taps` and slots below
// `slots` of `ring`, which holds slots * channels floats,
// writes batch * channels to `out`, and writes the ring only for a batch of one; all
// checked, and `out` overlaps none of the inputs.
unsafe { self.sconv_fixed.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) }
Expand All @@ -255,7 +262,7 @@ impl<'m> Attention<'m> {
batch: usize,
) -> Result<(), CudaError> {
let what = "sconv_dynamic";
let channels = self.conv_checks(what, current, ring, out, n, batch)?;
let (channels, slots) = self.conv_checks(what, current, ring, out, n, batch)?;
if heads == 0 || !channels.is_multiple_of(heads) {
return refuse(what, format!("{channels} channels in {heads} heads"));
}
Expand All @@ -273,6 +280,7 @@ impl<'m> Attention<'m> {
let (mut c, mut taps_n, mut h, mut p, mut b) =
(channels as u32, n as u32, heads as u32, pos as u64, batch as u32);
let mut norm = 1.0 / ((2 * n + 1) as f32).sqrt();
let mut s = slots as u32;
let mut args = [
ptr(&mut pc),
ptr(&mut pr),
Expand All @@ -285,15 +293,17 @@ impl<'m> Attention<'m> {
big(&mut p),
real(&mut norm),
num(&mut b),
num(&mut s),
];
// SAFETY: the arguments match sconv_dynamic(const float*, float*, const float*,
// const float*, float*, unsigned, unsigned, unsigned, unsigned long long, float,
// unsigned). Extents as for sconv_fixed, plus batch * heads * n floats of
// unsigned, unsigned). Extents as for sconv_fixed, plus batch * heads * n floats of
// `token_taps`; all checked.
unsafe { self.sconv_dynamic.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) }
}

/// Checks what both convolutions share and returns the number of channels.
/// Checks what both convolutions share and returns the number of channels and of the
/// ring's slots.
fn conv_checks(
&self,
what: &str,
Expand All @@ -302,7 +312,7 @@ impl<'m> Attention<'m> {
out: Floats,
n: usize,
batch: usize,
) -> Result<usize, CudaError> {
) -> Result<(usize, usize), CudaError> {
if n == 0 || n > 64 || batch == 0 || batch > MAX_BATCH || !current.len.is_multiple_of(batch) {
return refuse(what, format!("{n} taps, {} floats for a batch of {batch}", current.len));
}
Expand All @@ -312,21 +322,32 @@ impl<'m> Attention<'m> {
}
current.check(self.dev, what, batch * channels)?;
out.check(self.dev, what, batch * channels)?;
let mut slots = 0;
if n > 1 {
ring.check(self.dev, what, (n - 1) * channels)?;
slots = Self::ring_slots(what, ring, channels, n)?;
ring.check(self.dev, what, slots * channels)?;
if ring.overlaps(&current) || ring.overlaps(&out) {
return refuse(what, "the ring overlaps the tokens or the output".into());
}
}
if out.overlaps(&current) {
return refuse(what, "the output overlaps the tokens".into());
}
Ok(channels)
Ok((channels, slots))
}

/// After a convolution over a batch larger than one: the batch's last `n - 1` tokens
/// take their places in `ring`. After a batch of one, which stored its token itself,
/// it stores the same token again.
/// How many tokens a ring holds: a whole number, at least the `n - 1` a convolution reads.
fn ring_slots(what: &str, ring: Floats, channels: usize, n: usize) -> Result<usize, CudaError> {
let slots = ring.len / channels;
if !ring.len.is_multiple_of(channels) || slots < n - 1 || slots > 1 << 16 {
return refuse(what, format!("a ring of {} floats for {} tokens of {channels}", ring.len, n - 1));
}
Ok(slots)
}

/// After a convolution over a batch larger than one: the batch's tokens take their
/// places in `ring` (all of them if the ring has that many slots, else the last ones).
/// After a batch of one, which stored its token itself, it stores the same token again.
pub fn ring_store(
&self,
current: Floats,
Expand All @@ -346,17 +367,19 @@ impl<'m> Attention<'m> {
if channels == 0 || channels > 1 << 24 {
return refuse(what, format!("{channels} channels"));
}
let slots = Self::ring_slots(what, ring, channels, n)?;
current.check(self.dev, what, batch * channels)?;
ring.check(self.dev, what, (n - 1) * channels)?;
ring.check(self.dev, what, slots * channels)?;
if ring.overlaps(&current) {
return refuse(what, "the ring overlaps the tokens".into());
}
let (mut pc, mut pr) = (current.address(), ring.address());
let (mut c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32);
let mut args = [ptr(&mut pc), ptr(&mut pr), num(&mut c), num(&mut taps_n), big(&mut p), num(&mut b)];
let (mut c, mut s, mut p, mut b) = (channels as u32, slots as u32, pos as u64, batch as u32);
let mut args = [ptr(&mut pc), ptr(&mut pr), num(&mut c), num(&mut s), big(&mut p), num(&mut b)];
// SAFETY: the arguments match ring_store(const float*, float*, unsigned, unsigned,
// unsigned long long, unsigned). It reads batch * channels floats of `current` and
// writes at most (n - 1) * channels of `ring`, each slot from one token; all checked.
// writes into slots below `slots` of `ring`, each slot from one token (it stores at
// most `slots` consecutive tokens); all checked.
unsafe { self.ring_store.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) }
}

Expand Down
Loading
Loading