phase 9: KV cache + autoregressive generation

- KVCache: per-layer, per-head storage with append + reconstruct
- forward_with_cache: prefill (full prompt) + decode (single token) modes
- Fixed data layout bug: per-head vectors avoid cross-head interleaving
- CLI updated to use KV cache by default
- bench-gpt2 supports --no-cache flag for comparison

Benchmark results (50 prompts × 20 tokens):
- KV cache vs no-cache: 50/50 bit-identical (cache is correct)
- 18x speedup: TTFT 400→24ms, TBT 407→22ms, throughput 2.5→44 tok/s
- vs HF transformers: 40/50 match (10 are FP divergence, avg logit gap 0.20)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-21 23:39:41 +08:00
parent cb12250ef0
commit 64084d3489
7 changed files with 395 additions and 121 deletions

View File

@@ -6,27 +6,83 @@ use crate::config::ModelConfig;
pub struct GPT2 {
pub config: ModelConfig,
wte: Tensor, // [vocab_size, hidden]
wpe: Tensor, // [max_pos, hidden]
wte: Tensor,
wpe: Tensor,
layers: Vec<GPT2Block>,
ln_f_g: Tensor, // [hidden]
ln_f_b: Tensor, // [hidden]
ln_f_g: Tensor,
ln_f_b: Tensor,
lm_head: Tensor, // precomputed wte^T
}
struct GPT2Block {
ln_1_g: Tensor,
ln_1_b: Tensor,
// Attention: combined QKV weight + bias, output weight + bias
attn_qkv_w: Tensor, // [hidden, 3*hidden]
attn_qkv_b: Tensor, // [3*hidden]
attn_out_w: Tensor, // [hidden, hidden]
attn_out_b: Tensor, // [hidden]
attn_qkv_w: Tensor,
attn_qkv_b: Tensor,
attn_out_w: Tensor,
attn_out_b: Tensor,
ln_2_g: Tensor,
ln_2_b: Tensor,
mlp_fc_w: Tensor, // [hidden, 4*hidden]
mlp_fc_b: Tensor, // [4*hidden]
mlp_proj_w: Tensor, // [4*hidden, hidden]
mlp_proj_b: Tensor, // [hidden]
mlp_fc_w: Tensor,
mlp_fc_b: Tensor,
mlp_proj_w: Tensor,
mlp_proj_b: Tensor,
}
pub struct KVCache {
// Per layer, per head: k[layer][head] has seq_len * head_dim floats
k: Vec<Vec<Vec<f32>>>, // [num_layers][num_heads][seq_len * head_dim]
v: Vec<Vec<Vec<f32>>>,
len: usize,
num_heads: usize,
head_dim: usize,
device: Device,
}
impl KVCache {
pub fn new(num_layers: usize, num_heads: usize, head_dim: usize, device: Device) -> Self {
Self {
k: (0..num_layers).map(|_| vec![vec![]; num_heads]).collect(),
v: (0..num_layers).map(|_| vec![vec![]; num_heads]).collect(),
len: 0,
num_heads,
head_dim,
device,
}
}
pub fn seq_len(&self) -> usize { self.len }
/// Append new K/V data. k_new is in [1, H, new_tokens, D] layout (flat).
fn append_kv(&mut self, layer: usize, k_new: &[f32], v_new: &[f32], new_tokens: usize) {
let hd = self.head_dim;
for h in 0..self.num_heads {
let off = h * new_tokens * hd;
self.k[layer][h].extend_from_slice(&k_new[off..off + new_tokens * hd]);
self.v[layer][h].extend_from_slice(&v_new[off..off + new_tokens * hd]);
}
if layer == 0 {
self.len += new_tokens;
}
}
/// Reconstruct [1, H, seq_len, D] tensors from per-head cache.
fn get_kv_tensors(&self, layer: usize) -> (Tensor, Tensor) {
let sl = self.len;
let hd = self.head_dim;
let nh = self.num_heads;
let mut k_data = vec![0.0f32; nh * sl * hd];
let mut v_data = vec![0.0f32; nh * sl * hd];
for h in 0..nh {
let off = h * sl * hd;
k_data[off..off + sl * hd].copy_from_slice(&self.k[layer][h]);
v_data[off..off + sl * hd].copy_from_slice(&self.v[layer][h]);
}
let shape = &[1, nh, sl, hd];
let k = Tensor::from_slice(&k_data, shape).to_device(self.device);
let v = Tensor::from_slice(&v_data, shape).to_device(self.device);
(k, v)
}
}
impl GPT2 {
@@ -39,6 +95,7 @@ impl GPT2 {
let wpe = take(&mut w, "wpe.weight");
let ln_f_g = take(&mut w, "ln_f.weight");
let ln_f_b = take(&mut w, "ln_f.bias");
let lm_head = wte.transpose(0, 1).contiguous();
let num_layers = config.num_layers();
let mut layers = Vec::with_capacity(num_layers);
@@ -60,81 +117,108 @@ impl GPT2 {
});
}
Self { config, wte, wpe, layers, ln_f_g, ln_f_b }
Self { config, wte, wpe, layers, ln_f_g, ln_f_b, lm_head }
}
/// Full forward pass, returns logits [seq_len, vocab_size].
/// Full forward pass without KV cache (for testing / correctness comparison).
pub fn forward(&self, token_ids: &[u32]) -> Tensor {
let seq_len = token_ids.len();
let hidden = self.config.hidden();
let num_heads = self.config.num_heads();
let head_dim = self.config.head_dim();
// Token + position embedding
let tok_emb = embedding(&self.wte, token_ids);
let pos_ids: Vec<u32> = (0..seq_len as u32).collect();
let pos_emb = embedding(&self.wpe, &pos_ids);
let mut x = add_tensors(&tok_emb, &pos_emb);
// Transformer layers
for layer in &self.layers {
// Pre-LN attention
let residual = x.clone();
let normed = layernorm(&x, &layer.ln_1_g, &layer.ln_1_b, self.config.ln_eps());
// QKV projection: [S, H] @ [H, 3H] + [3H] → [S, 3H]
let qkv = linear(&normed, &layer.attn_qkv_w, Some(&layer.attn_qkv_b));
// Split into Q, K, V and reshape for multi-head
let (q, k, v) = split_qkv(&qkv, num_heads, head_dim, seq_len);
// Attention: [1, H, S, D]
let attn_out = attention(&q, &k, &v, true);
// Merge heads: [1, H, S, D] → [S, hidden]
let attn_out = merge_heads(&attn_out, seq_len, hidden);
// Output projection
let attn_out = linear(&attn_out, &layer.attn_out_w, Some(&layer.attn_out_b));
x = add_tensors(&residual, &attn_out);
// Pre-LN MLP
let residual = x.clone();
let normed = layernorm(&x, &layer.ln_2_g, &layer.ln_2_b, self.config.ln_eps());
let fc = linear(&normed, &layer.mlp_fc_w, Some(&layer.mlp_fc_b));
let activated = gelu(&fc);
let proj = linear(&activated, &layer.mlp_proj_w, Some(&layer.mlp_proj_b));
x = add_tensors(&residual, &proj);
x = self.transformer_block(layer, &x, None, 0, seq_len, num_heads, head_dim, hidden);
}
// Final layer norm
let x = layernorm(&x, &self.ln_f_g, &self.ln_f_b, self.config.ln_eps());
matmul_2d(&x, &self.lm_head)
}
// LM head (tied with wte): [S, H] @ [H, V] → [S, V]
// wte is [V, H], so we need wte^T
let lm_head = self.wte.transpose(0, 1).contiguous();
matmul_2d(&x, &lm_head)
/// Forward pass with KV cache. First call = prefill, subsequent = decode.
pub fn forward_with_cache(&self, token_ids: &[u32], cache: &mut KVCache) -> Tensor {
let new_tokens = token_ids.len();
let pos_offset = cache.seq_len();
let hidden = self.config.hidden();
let num_heads = self.config.num_heads();
let head_dim = self.config.head_dim();
let tok_emb = embedding(&self.wte, token_ids);
let pos_ids: Vec<u32> = (pos_offset..pos_offset + new_tokens).map(|p| p as u32).collect();
let pos_emb = embedding(&self.wpe, &pos_ids);
let mut x = add_tensors(&tok_emb, &pos_emb);
for (layer_idx, layer) in self.layers.iter().enumerate() {
x = self.transformer_block(
layer, &x, Some((cache, layer_idx)),
pos_offset, new_tokens, num_heads, head_dim, hidden,
);
}
let x = layernorm(&x, &self.ln_f_g, &self.ln_f_b, self.config.ln_eps());
matmul_2d(&x, &self.lm_head)
}
fn transformer_block(
&self,
layer: &GPT2Block,
x: &Tensor,
cache: Option<(&mut KVCache, usize)>,
pos_offset: usize,
new_tokens: usize,
num_heads: usize,
head_dim: usize,
hidden: usize,
) -> Tensor {
let residual = x.clone();
let normed = layernorm(x, &layer.ln_1_g, &layer.ln_1_b, self.config.ln_eps());
let qkv = linear(&normed, &layer.attn_qkv_w, Some(&layer.attn_qkv_b));
let (q, k_new, v_new) = split_qkv(&qkv, num_heads, head_dim, new_tokens);
// KV cache: append new K/V, use full cached K/V for attention
let (k_full, v_full) = if let Some((cache, layer_idx)) = cache {
let k_cpu = k_new.to_device(Device::Cpu);
let v_cpu = v_new.to_device(Device::Cpu);
cache.append_kv(layer_idx, k_cpu.as_slice::<f32>(), v_cpu.as_slice::<f32>(), new_tokens);
cache.get_kv_tensors(layer_idx)
} else {
(k_new, v_new)
};
let attn_out = attention(&q, &k_full, &v_full, true);
let attn_out = merge_heads(&attn_out, new_tokens, hidden);
let attn_out = linear(&attn_out, &layer.attn_out_w, Some(&layer.attn_out_b));
let x = add_tensors(&residual, &attn_out);
let residual = x.clone();
let normed = layernorm(&x, &layer.ln_2_g, &layer.ln_2_b, self.config.ln_eps());
let fc = linear(&normed, &layer.mlp_fc_w, Some(&layer.mlp_fc_b));
let activated = gelu(&fc);
let proj = linear(&activated, &layer.mlp_proj_w, Some(&layer.mlp_proj_b));
add_tensors(&residual, &proj)
}
}
// --- Helper ops ---
// --- Helper ops (unchanged) ---
fn linear(x: &Tensor, weight: &Tensor, bias: Option<&Tensor>) -> Tensor {
// GPT-2 stores weights as [in, out] (not transposed), so x @ w
let out = matmul_2d(x, weight);
if let Some(b) = bias {
add_bias(&out, b)
} else {
out
}
if let Some(b) = bias { add_bias(&out, b) } else { out }
}
fn matmul_2d(a: &Tensor, b: &Tensor) -> Tensor {
// a: [S, K], b: [K, N] → [S, N]
assert_eq!(a.ndim(), 2);
assert_eq!(b.ndim(), 2);
matmul(a, b, GemmBackend::CuBlas)
}
fn add_tensors(a: &Tensor, b: &Tensor) -> Tensor {
// Element-wise add on GPU via a simple approach: scale(a, 1.0) + scale(b, 1.0)
// TODO: proper add kernel. For now, go through CPU.
assert_eq!(a.shape(), b.shape());
assert_eq!(a.dtype(), DType::F32);
let a_cpu = a.to_device(Device::Cpu);
@@ -146,7 +230,6 @@ fn add_tensors(a: &Tensor, b: &Tensor) -> Tensor {
}
fn add_bias(x: &Tensor, bias: &Tensor) -> Tensor {
// x: [S, N], bias: [N] → broadcast add
assert_eq!(x.ndim(), 2);
assert_eq!(bias.ndim(), 1);
assert_eq!(x.shape()[1], bias.shape()[0]);
@@ -160,12 +243,10 @@ fn add_bias(x: &Tensor, bias: &Tensor) -> Tensor {
}
fn split_qkv(qkv: &Tensor, num_heads: usize, head_dim: usize, seq_len: usize) -> (Tensor, Tensor, Tensor) {
// qkv: [S, 3*H] → Q, K, V each [1, num_heads, S, head_dim]
let hidden = num_heads * head_dim;
let qkv_cpu = qkv.to_device(Device::Cpu);
let data = qkv_cpu.as_slice::<f32>();
// Split into Q, K, V and directly write in [1, num_heads, S, head_dim] layout
let mut q_data = vec![0.0f32; num_heads * seq_len * head_dim];
let mut k_data = vec![0.0f32; num_heads * seq_len * head_dim];
let mut v_data = vec![0.0f32; num_heads * seq_len * head_dim];
@@ -189,14 +270,11 @@ fn split_qkv(qkv: &Tensor, num_heads: usize, head_dim: usize, seq_len: usize) ->
}
fn merge_heads(x: &Tensor, seq_len: usize, hidden: usize) -> Tensor {
// [1, num_heads, S, head_dim] → [S, hidden]
let num_heads = x.shape()[1];
let head_dim = x.shape()[3];
let x_cpu = x.to_device(Device::Cpu);
let src = x_cpu.as_slice::<f32>();
// src layout: [1][num_heads][seq_len][head_dim]
// dst layout: [seq_len][hidden] where hidden = num_heads * head_dim
let mut out = vec![0.0f32; seq_len * hidden];
for s in 0..seq_len {
for h in 0..num_heads {
@@ -210,7 +288,7 @@ fn merge_heads(x: &Tensor, seq_len: usize, hidden: usize) -> Tensor {
/// Greedy sampling: return the argmax token ID from the last position's logits.
pub fn sample_greedy(logits: &Tensor) -> u32 {
assert_eq!(logits.ndim(), 2); // [S, V]
assert_eq!(logits.ndim(), 2);
let logits_cpu = logits.to_device(Device::Cpu);
let data = logits_cpu.as_slice::<f32>();
let vocab_size = logits.shape()[1];