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
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ CPU, slowly, as the reference each faster path is checked against.
within four times the reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny
model of the same architecture, small enough to exercise every rule, is checked the same way in CI.

On the GB10, Inkling 2 Mini generates about 24 tokens per second one token at a time and reads a prompt at
about 120 tokens per second. Guessed tokens are checked several per sweep of the weights, which speeds up
text that repeats itself; the model's own draft head is not used yet. Deliberately planted bugs must make
On the GB10, Inkling 2 Mini generates about 28 tokens per second one token at a time and reads a prompt at
about 120 tokens per second. With the draft head that ships in the checkpoint proposing tokens, which the
model checks several per sweep of the weights, it generates 30 to 39 tokens per second depending on the
text, and the text is the same as without. Deliberately planted bugs must make
named tests fail, on the CPU and on the GPU.

cargo run --release -- generate --model <model directory> --prompt "What is the capital of Ireland?"
Expand All @@ -41,8 +42,9 @@ CPU, which is only good for trying the interface). It answers `POST /v1/chat/com
| `--listen <address:port>` | where to listen; `0.0.0.0:8080` for other machines | `127.0.0.1:8080` |
| `--context <tokens>` | longest conversation, prompt and reply together | 8192 |
| `--name <name>` | the name the model is listed under | the directory's name |
| `--guesses <n>` | guessed tokens checked per sweep; 0 for none | 4 |
| `--match <n>` | last tokens that must have appeared before for a guess | 2 |
| `--guesses <n>` | guessed tokens checked per sweep; 0 for none | 2 with the draft head, else 4 |
| `--head on\|off` | use the checkpoint's draft head as the guesser, where it has one (GPU only) | on |
| `--match <n>` | without the head: last tokens that must have appeared before for a guess | 2 |
| `--prompt-batch <n>` | tokens of a prompt read per sweep, at most 16 on the GPU | 16 |
| `--temperature <t>` | used when a request does not set one; 0 is greedy | 1 |
| `--effort <level>` | reasoning effort when a request does not set `reasoning_effort` | high |
Expand Down
75 changes: 74 additions & 1 deletion crates/dluth-cuda/examples/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,79 @@ fn main() {
}
return;
}
if mode.as_deref() == Some("head") {
// Generation twice on the same model: without guesses, then with the model's own
// draft head proposing up to `most` tokens per sweep.
use dluth_cuda::draft_head::CudaDraftHead;
use dluth_model::inkling::mtp::load_mtp_config;
let most: usize = args.next().map_or(4, |n| n.parse().expect("how many guesses per sweep"));
let (h, vocab_out) = (cfg.hidden, cfg.vocab_out);
let mut ops = CudaOps::new(&dev, &module).expect("the kernels");
let unembed = &weights.bytes("model.llm.unembed.weight").expect("the output table")[..vocab_out * h * 2];
let table = ops.device_weight(unembed).expect("the output table on the device");
let embed_norm: Vec<f32> = weights
.bytes("model.llm.embed_norm.weight")
.expect("the embedding norm")
.as_chunks::<2>()
.0
.iter()
.map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16))
.collect();
let capacity = ids.len() + max_new;
let started = Instant::now();
let mut head = CudaDraftHead::load(
&dev,
&module,
&dir,
load_mtp_config(&dir).expect("the head's configuration").expect("a draft head"),
weights.bytes("model.llm.embed.weight").expect("the embedding table"),
embed_norm,
table,
vocab_out,
capacity,
)
.expect("the draft head");
println!("the draft head loaded in {:.1} s", started.elapsed().as_secs_f64());
let mut model = Inkling::with_ops(cfg, &weights, capacity, ops).expect("the model");
model.set_prompt_batch(16).expect("a prompt batch");
let mut timed = |drafter: &mut dyn dluth_model::inkling::Drafter<dluth_cuda::ops::DeviceVec>, 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 head, 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 the draft head, up to {most} guesses: {:.2} s, {:.1} tokens per second; {} sweeps, {} guessed, {} right",
seconds,
n / seconds,
stats.sweeps,
stats.drafted,
stats.accepted
);
println!("the same tokens: {}", plain == drafted);
let per_sweep = |d: std::time::Duration| d.as_secs_f64() * 1e3 / stats.sweeps.max(1) as f64;
println!(
"per sweep: {:.1} ms in all; of the head's part, {:.1} ms the block, {:.1} ms the step on the host, {:.1} ms the guesses' scores",
seconds * 1e3 / stats.sweeps.max(1) as f64,
per_sweep(head.spent[0]),
per_sweep(head.spent[1]),
per_sweep(head.spent[2])
);
if let Some(error) = &head.last_error {
println!("the head's last error: {error}");
}
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 All @@ -82,7 +155,7 @@ fn main() {
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 timed = |drafter: &mut dyn dluth_model::inkling::Drafter<dluth_cuda::ops::DeviceVec>, most: usize| {
let mut first = None;
let (tokens, stats) = model
.generate_greedy_drafted(&ids, max_new, eos, drafter, most, |_| {
Expand Down
117 changes: 117 additions & 0 deletions crates/dluth-cuda/kernels/draft_head.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// The draft head's operations that are not matrix products or the model's own small
// operations. The head (a small network that guesses the next few tokens) is described
// where it is implemented on the CPU, dluth-model's inkling/mtp.rs; each kernel here
// names the part of that implementation it stands for.

// Each vector of `dim` in `x`: divided by sqrt(mean of its squares + eps), multiplied
// element by element by `weights` (one vector of `dim`, the same for all), then rotated by
// its position: element i and element i + dim/2 are a pair, turned by the angle
// position * theta^(-2i/dim). `x` holds, for each of `count` positions, `heads` vectors;
// the positions are `pos`, `pos + 1`, ... One block of threads per vector; dim is at most
// 256 and even.
// CPU reference: MtpHead::head_norm_rope (cpu::rmsnorm per head, then cpu::rope_inplace).
extern "C" __global__ void head_norm_rope(float* x, const float* weights, unsigned int count,
unsigned int heads, unsigned int dim, float eps,
unsigned long long pos, float theta) {
__shared__ float part[256];
__shared__ float normed[256];
unsigned int vector = blockIdx.x;
if (vector >= count * heads) return;
float* v = x + (size_t)vector * dim;
float squares = 0.0f;
for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) squares += v[i] * v[i];
part[threadIdx.x] = squares;
__syncthreads();
if (threadIdx.x == 0) {
for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t];
part[0] = 1.0f / sqrtf(squares / (float)dim + eps);
}
__syncthreads();
float scale = part[0];
for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) normed[i] = v[i] * scale * weights[i];
__syncthreads();
unsigned int half = dim / 2;
float at = (float)(pos + vector / heads);
for (unsigned int i = threadIdx.x; i < half; i += blockDim.x) {
float frequency = 1.0f / powf(theta, (float)(2 * i) / (float)dim);
float s, c;
sincosf(at * frequency, &s, &c);
float a = normed[i], b = normed[i + half];
v[i] = a * c - b * s;
v[i + half] = a * s + b * c;
}
}

// The block's attention scores. A block of `block` positions follows `context` positions
// of text. For block position k, head h and key j: the dot product of the head's query
// with key j's vector for the head's key-value group, times `scale`. Keys 0 to
// context - 1 are the text's (`context_keys`, one row of kv_heads * dim per position);
// keys context to context + block - 1 are the block's own (`block_keys`): every block
// position sees the whole block. Each (position, head) has a run of context + block scores.
// CPU reference: the scoring in MtpDrafter::block.
extern "C" __global__ void draft_scores(const float* q, const float* context_keys, const float* block_keys,
float* scores, unsigned int heads, unsigned int kv_heads,
unsigned int dim, unsigned long long context,
unsigned int block, float scale) {
unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long keys = context + block;
unsigned long long run = index / keys;
unsigned long long j = index % keys;
if (run >= (unsigned long long)block * heads) return;
unsigned int h = (unsigned int)(run % heads);
size_t group = (size_t)(h / (heads / kv_heads)) * dim;
const float* key = (j < context ? context_keys + j * kv_heads * dim : block_keys + (j - context) * kv_heads * dim) + group;
const float* query = q + run * dim;
float dot = 0.0f;
for (unsigned int i = 0; i < dim; ++i) dot += query[i] * key[i];
scores[index] = dot * scale;
}

// The weighted sum of the values for the block's attention: out[k][h][e] = sum over the
// keys j of weights[k][h][j] times value j's element e for the head's group. `segs`
// threads share one output element, each taking every segs-th key, combined with warp
// shuffles (segs a power of two up to 32, the block size a multiple of 32).
// CPU reference: the summing in MtpDrafter::block.
extern "C" __global__ void draft_values(const float* weights, const float* context_values,
const float* block_values, float* out, unsigned int heads,
unsigned int kv_heads, unsigned int dim,
unsigned long long context, unsigned int block,
unsigned int segs) {
unsigned long long thread = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
unsigned long long element = thread / segs;
unsigned int seg = (unsigned int)(thread % segs);
unsigned long long run = element / dim;
unsigned int e = (unsigned int)(element % dim);
unsigned long long keys = context + block;
bool live = run < (unsigned long long)block * heads;
float total = 0.0f;
if (live) {
unsigned int h = (unsigned int)(run % heads);
size_t column = (size_t)(h / (heads / kv_heads)) * dim + e;
const float* w = weights + run * keys;
for (unsigned long long j = seg; j < keys; j += segs) {
const float* value = j < context ? context_values + j * kv_heads * dim : block_values + (j - context) * kv_heads * dim;
total += w[j] * value[column];
}
}
for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset);
if (live && seg == 0) out[element] = total;
}

// out[i] = gate[i] * sigmoid(gate[i]) * up[i]: the gated activation of the head's
// feed-forward part. CPU reference: cpu::silu_mul.
extern "C" __global__ void silu_mul(const float* gate, const float* up, float* out, unsigned int n) {
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
float g = gate[i];
out[i] = g / (1.0f + expf(-g)) * up[i];
}

// out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i]: the mix of up to four of the
// model's values that a layer of the head reads its context from (unused ones are given a
// weight of 0 and any valid pointer). CPU reference: the sum in MtpHead::mixed.
extern "C" __global__ void mix_four(const float* a, const float* b, const float* c, const float* d,
float* out, float w0, float w1, float w2, float w3, unsigned int n) {
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i];
}
60 changes: 56 additions & 4 deletions crates/dluth-cuda/src/bin/dluth-cuda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
//! through the model, which copies every layer's weights to the device, so that the first
//! request does not pay for that.

use dluth_cuda::ops::CudaOps;
use dluth_cuda::draft_head::CudaDraftHead;
use dluth_cuda::ops::{CudaOps, DeviceVec};
use dluth_cuda::{CudaDevice, Module};
use dluth_model::inkling::{load_config, model_kind, Inkling, ModelKind};
use dluth_model::inkling::mtp::load_mtp_config;
use dluth_model::inkling::{load_config, model_kind, Drafter, Inkling, ModelKind};
use dluth_model::tokenizer::Tokenizer;
use dluth_model::weights::Weights;
use dluth_serve::cli;
Expand All @@ -29,7 +31,57 @@ fn run(args: &[String]) -> Result<(), String> {
let cfg = load_config(&args.model).map_err(|e| text(&e))?;
let dev = CudaDevice::open(0).map_err(|e| text(&e))?;
let module = Module::load_embedded(&dev).map_err(|e| text(&e))?;
let ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?;
let mut ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?;
// The model's own draft head, if the checkpoint has one: it proposes tokens that the
// model then checks several at a time. It reads the model's output table on the device.
let mut args = args;
if args.options.prompt_batch > 16 {
return Err("--prompt-batch: the device takes at most 16 positions at a time".into());
}
// A head that is switched off is not looked at; one whose description cannot be read
// is done without, with the reason said.
let described = if args.head {
load_mtp_config(&args.model).unwrap_or_else(|e| {
eprintln!("going without the draft head: {e}");
None
})
} else {
None
};
let head: Option<Box<dyn Drafter<DeviceVec> + '_>> = match described {
Some(head_cfg) if args.model.join("mtp.safetensors").exists() => {
let (h, vocab_out) = (cfg.hidden, cfg.vocab_out);
let unembed = &weights.bytes("model.llm.unembed.weight").map_err(|e| text(&e))?[..vocab_out * h * 2];
let table = ops.device_weight(unembed).map_err(|e| text(&e))?;
let embed_norm: Vec<f32> = weights
.bytes("model.llm.embed_norm.weight")
.map_err(|e| text(&e))?
.as_chunks::<2>()
.0
.iter()
.map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16))
.collect();
let embed = weights.bytes("model.llm.embed.weight").map_err(|e| text(&e))?;
let head = CudaDraftHead::load(
&dev,
&module,
&args.model,
head_cfg,
embed,
embed_norm,
table,
vocab_out,
args.context,
)
.map_err(|e| text(&e))?;
// Two guesses a sweep is where this head pays best on this machine.
if !args.guesses_given {
args.options.guesses = 2;
}
Some(Box::new(head))
}
_ => None,
};
let mut model = Inkling::with_ops(cfg, &weights, args.context, ops).map_err(|e| text(&e))?;

// Any token will do: each layer's weights go to the device the first time the layer runs.
Expand All @@ -40,7 +92,7 @@ fn run(args: &[String]) -> Result<(), String> {
model.ops().weight_bytes() as f64 / 1e9,
started.elapsed().as_secs_f64()
);
cli::run(model, &tokenizer, &args)
cli::run(model, &tokenizer, &args, head)
}

fn main() -> ExitCode {
Expand Down
Loading
Loading