[Proto] serve: chunked batched prefill (forward_batch) replaces M=1 per-token loop

serve_gen prefills the prompt suffix in chunks of VETTA_PREFILL_CHUNK (default
256) via eng.forward_batched -> forward_batch (M=B), amortizing weight streaming
+ kernel launches across B tokens instead of one model pass per token. take==1
falls back to the M=1 forward; chunk=1 restores the sequential path (A/B).
Aligns decode to f16 device MoE (VETTA_DEVICE_MOE) to match the batched prefill
precision (moe_device bit-identical to moe_batched).

Verified EXACT through the serve: serve_gen_multi_token_parity (5-tok prompt ->
batched chunk, 16 decode tokens identical to reference) + serve_gen_emits_eos_then_stop
(27-tok prompt -> batched chunk, EOS exact). gw CPU 14 + GPU 5 green.
This commit is contained in:
adm committed 2026-12-02 00:31:15 +01:00
1 parent b41a71f2f7
commit c059a20aa9
1 file changed
+47 -8
+47 -8
View File
@@ -27,7 +27,7 @@ use vetta_infer_abi::sampler::{
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config;
use vetta_infer_ld::layer::{forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
use vetta_infer_ld::SafetensorsArchive;
use crate::session::ServeSession;
@@ -155,6 +155,10 @@ impl InklingEngine {
// half the VRAM of the F32 CPU-oracle baseline). The ld parity tests keep
// the F32 default; the resident serve opts in here.
vetta_infer_ld::layer::set_kv_f16(true);
// Batched prefill uses the device-resident f16 MoE (moe_batched). Align the
// M=1 decode to the same f16 device path (moe_device, bit-identical math) so
// prefill and decode share one expert precision (verified EXACT greedy).
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
let ar = Arc::new(SafetensorsArchive::open(dir)?);
let cfg_path = ar.dir.join("config.json");
let raw = std::fs::read_to_string(&cfg_path)
@@ -213,6 +217,27 @@ impl InklingEngine {
) -> Result<DeviceBuf, String> {
forward_inkling_with_state(&self.cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
}
/// Batched prefill chunk (M=B): one forward over B tokens, logits for the last.
fn forward_batched(
&self,
tokens: &[i32],
pos: i32,
max_seq: usize,
states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_batch(&self.cache, &self.d, tokens, self.vocab, max_seq, pos, self.cap, states)
}
}
/// Prefill chunk size (M=B per batched forward). Default 256 amortizes weight
/// streaming + kernel launches across 256 tokens vs the old M=1 per-token path.
/// VETTA_PREFILL_CHUNK overrides; 1 forces the sequential path (A/B parity).
fn prefill_chunk_size() -> usize {
std::env::var("VETTA_PREFILL_CHUNK").ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&c| c >= 1)
.unwrap_or(256)
}
fn emit_all(emit: &mut dyn FnMut(String), lines: Vec<String>) {
@@ -279,13 +304,19 @@ pub fn serve_gen(
// Weights are resident in eng.cache (loaded once at boot, reused across all
// requests): no per-request NVMe re-read or re-upload.
// --- Prefill: run the forward over the NEW prompt tokens, growing KV/history. ---
// --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. ---
// Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel
// launches amortized across B), growing KV/history; logits come from the last
// token of the final chunk. VETTA_PREFILL_CHUNK=1 restores the M=1 path (A/B).
let t0 = Instant::now();
let mut pos = start as i32;
let mut history: Vec<i32> = g.ids[..start].to_vec();
history.reserve(n_prompt - start + g.max_new);
let mut logits: Option<DeviceBuf> = None;
for (i, &tok) in g.ids.iter().enumerate().skip(start) {
let chunk = prefill_chunk_size();
let suffix = &g.ids[start..];
let mut done = 0usize;
while done < suffix.len() {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
let ms = t0.elapsed().as_secs_f64() * 1000.0;
@@ -293,18 +324,26 @@ pub fn serve_gen(
stop.store(false, Ordering::Relaxed);
return;
}
match eng.forward(tok, pos, max_seq, &mut states) {
Ok(lg) => logits = Some(lg),
let take = chunk.min(suffix.len() - done);
let toks = &suffix[done..done + take];
let lg = if take == 1 {
eng.forward(toks[0], pos, max_seq, &mut states)
} else {
eng.forward_batched(toks, pos, max_seq, &mut states)
};
match lg {
Ok(l) => logits = Some(l),
Err(e) => {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
}
history.push(tok);
pos += 1;
history.extend_from_slice(toks);
pos += take as i32;
done += take;
let ms = t0.elapsed().as_secs_f64() * 1000.0;
if let Ok(pp) = sess.on_prefill_chunk((i + 1) as u32, n_prompt as u32, ms) {
if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) {
emit_all(emit, pp);
}
}