Skip to content

Commit d19707d

Browse files
voidstackloopclaude
andcommitted
ServingEngine: prefix-cache reuse, KV block growth with eviction, regex-constrained requests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 335c82b commit d19707d

2 files changed

Lines changed: 181 additions & 7 deletions

File tree

‎crates/oxideon-core/src/grammar/regex.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ impl Regex {
337337
}
338338

339339
/// Tracks the text generated so far and masks the logits of a vocabulary accordingly.
340+
#[derive(Clone)]
340341
pub struct RegexConstraint {
341342
re: std::sync::Arc<Regex>,
342343
state: MatchState,
@@ -469,3 +470,9 @@ mod tests {
469470
assert!(r.is_err());
470471
}
471472
}
473+
474+
impl std::fmt::Debug for RegexConstraint {
475+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476+
write!(f, "RegexConstraint({} live states)", self.state.len())
477+
}
478+
}

‎crates/oxideon-core/src/serving/engine.rs‎

Lines changed: 174 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
use std::collections::VecDeque;
88

99
use super::paged_kv::{BlockAllocator, BlockTable, PagedKVCache};
10+
use super::prefix_cache::PrefixCache;
11+
use crate::grammar::regex::{Regex, RegexConstraint};
12+
use std::sync::Arc;
1013
use crate::dtype::DType;
1114
use crate::error::Result;
1215

@@ -24,6 +27,10 @@ pub struct BatchRequest {
2427
pub generated_tokens: Vec<usize>,
2528
pub block_table: BlockTable,
2629
pub is_finished: bool,
30+
/// Leading prompt tokens whose keys and values came from the prefix cache (the model need not recompute them).
31+
pub cached_prefix_tokens: usize,
32+
/// Optional output-format constraint; mask the logits with it, the engine advances it after every token.
33+
pub constraint: Option<RegexConstraint>,
2734
}
2835

2936
impl BatchRequest {
@@ -42,6 +49,8 @@ impl BatchRequest {
4249
generated_tokens: Vec::new(),
4350
block_table: BlockTable::new(),
4451
is_finished: false,
52+
cached_prefix_tokens: 0,
53+
constraint: None,
4554
}
4655
}
4756

@@ -67,6 +76,8 @@ pub struct ContinuousBatchScheduler {
6776
waiting: VecDeque<BatchRequest>,
6877
running: Vec<BatchRequest>,
6978
next_id: usize,
79+
/// When set, finished prompts leave their full blocks here and new prompts reuse them.
80+
pub prefix_cache: Option<PrefixCache>,
7081
}
7182

7283
impl ContinuousBatchScheduler {
@@ -77,6 +88,7 @@ impl ContinuousBatchScheduler {
7788
waiting: VecDeque::new(),
7889
running: Vec::new(),
7990
next_id: 1,
91+
prefix_cache: None,
8092
}
8193
}
8294

@@ -114,6 +126,9 @@ impl ContinuousBatchScheduler {
114126
let mut active = Vec::with_capacity(self.running.len());
115127
for req in self.running.drain(..) {
116128
if req.is_finished {
129+
if let Some(pc) = &mut self.prefix_cache {
130+
pc.insert(allocator, &req.prompt_tokens, &req.block_table.physical_blocks);
131+
}
117132
for &b in &req.block_table.physical_blocks {
118133
allocator.free(b);
119134
}
@@ -127,17 +142,31 @@ impl ContinuousBatchScheduler {
127142
while self.running.len() < self.max_batch_size && !self.waiting.is_empty() {
128143
let mut req = self.waiting.pop_front().unwrap();
129144

130-
// Allocate necessary initial physical blocks for prompt tokens
131-
let needed_blocks = req
132-
.prompt_tokens
133-
.len()
134-
.div_ceil(allocator.block_size)
135-
.max(1);
145+
// Reuse cached prefix blocks (never the last prompt token: its logits must be computed), allocate the rest
146+
let bs = allocator.block_size;
147+
let total_blocks = req.prompt_tokens.len().div_ceil(bs).max(1);
148+
let shared = match &mut self.prefix_cache {
149+
Some(pc) => pc.match_prefix(allocator, &req.prompt_tokens[..req.prompt_tokens.len().saturating_sub(1)]),
150+
None => Vec::new(),
151+
};
152+
let needed_blocks = total_blocks - shared.len();
153+
if allocator.num_free_blocks() < needed_blocks
154+
&& let Some(pc) = &mut self.prefix_cache
155+
{
156+
pc.evict(allocator, needed_blocks - allocator.num_free_blocks());
157+
}
136158
if allocator.num_free_blocks() < needed_blocks {
137-
// Not enough KV memory right now; push back to front of waiting queue
159+
// Not enough KV memory right now; give the shared references back and retry later
160+
for b in shared {
161+
allocator.free(b);
162+
}
138163
self.waiting.push_front(req);
139164
break;
140165
}
166+
req.cached_prefix_tokens = shared.len() * bs;
167+
for b in shared {
168+
req.block_table.append_block(b);
169+
}
141170
for _ in 0..needed_blocks {
142171
let blk = allocator.allocate()?;
143172
req.block_table.append_block(blk);
@@ -148,6 +177,25 @@ impl ContinuousBatchScheduler {
148177
Ok(self.running.iter().map(|r| r.id).collect())
149178
}
150179

180+
/// Gives every running request a block for the token it will write next; a request that cannot get one (KV memory
181+
/// exhausted even after evicting cached prefixes) is finished instead of corrupting another sequence's block.
182+
pub fn ensure_capacity(&mut self, allocator: &mut BlockAllocator) {
183+
let bs = allocator.block_size;
184+
for req in &mut self.running {
185+
while !req.is_finished && req.block_table.physical_blocks.len() < (req.total_tokens() + 1).div_ceil(bs) {
186+
if allocator.num_free_blocks() == 0
187+
&& let Some(pc) = &mut self.prefix_cache
188+
{
189+
pc.evict(allocator, 1);
190+
}
191+
match allocator.allocate() {
192+
Ok(b) => req.block_table.append_block(b),
193+
Err(_) => req.is_finished = true,
194+
}
195+
}
196+
}
197+
}
198+
151199
pub fn running_requests_mut(&mut self) -> &mut [BatchRequest] {
152200
&mut self.running
153201
}
@@ -162,6 +210,8 @@ pub struct ServingEngine {
162210
pub scheduler: ContinuousBatchScheduler,
163211
pub allocator: BlockAllocator,
164212
pub paged_kv: PagedKVCache,
213+
/// Token id → text, needed to advance regex constraints (set with [`ServingEngine::set_vocab`]).
214+
pub vocab: Option<Arc<Vec<String>>>,
165215
}
166216

167217
impl ServingEngine {
@@ -186,9 +236,33 @@ impl ServingEngine {
186236
scheduler,
187237
allocator,
188238
paged_kv,
239+
vocab: None,
189240
})
190241
}
191242

243+
/// Turns on prefix caching: prompts that start with tokens of an earlier request reuse its KV blocks.
244+
pub fn enable_prefix_cache(&mut self) {
245+
self.scheduler.prefix_cache.get_or_insert_with(PrefixCache::new);
246+
}
247+
248+
pub fn set_vocab(&mut self, vocab: Vec<String>) {
249+
self.vocab = Some(Arc::new(vocab));
250+
}
251+
252+
/// Submits a request whose output must match `pattern` (it finishes once an EOS is sampled after a full match).
253+
/// Requires [`set_vocab`](Self::set_vocab); the forward callback masks logits via `req.constraint`.
254+
pub fn submit_constrained(&mut self, prompt: Vec<usize>, config: crate::sampling::SamplingConfig, pattern: Arc<Regex>) -> Result<RequestId> {
255+
if self.vocab.is_none() {
256+
return Err(crate::error::Error::Msg("submit_constrained: call set_vocab first".into()));
257+
}
258+
let id = self.scheduler.submit_with_config(prompt, config);
259+
let c = RegexConstraint::new(pattern);
260+
if let Some(r) = self.scheduler.waiting.iter_mut().find(|r| r.id == id) {
261+
r.constraint = Some(c);
262+
}
263+
Ok(id)
264+
}
265+
192266
/// Submits a request and returns its assigned ID.
193267
pub fn submit(&mut self, prompt: Vec<usize>, max_new_tokens: usize) -> RequestId {
194268
self.scheduler.submit(prompt, max_new_tokens)
@@ -234,13 +308,106 @@ impl ServingEngine {
234308
{
235309
req.generated_tokens.push(tok);
236310
completed_step.push((req.id, tok));
311+
if let (Some(c), Some(v)) = (&mut req.constraint, &self.vocab)
312+
&& req.eos_token_id != Some(tok)
313+
&& let Some(text) = v.get(tok)
314+
{
315+
c.advance(text);
316+
}
237317

238318
// Check stopping conditions
239319
if req.generated_tokens.len() >= req.max_new_tokens || req.eos_token_id == Some(tok) {
240320
req.is_finished = true;
241321
}
242322
}
243323

324+
self.scheduler.ensure_capacity(&mut self.allocator);
244325
Ok(completed_step)
245326
}
246327
}
328+
329+
#[cfg(test)]
330+
mod tests {
331+
use super::*;
332+
use crate::sampling::SamplingConfig;
333+
use crate::tensor::Tensor;
334+
335+
fn engine(blocks: usize) -> ServingEngine {
336+
ServingEngine::new(4, blocks, 4, 1, 2).unwrap()
337+
}
338+
339+
#[test]
340+
fn a_second_request_reuses_the_first_requests_prompt_blocks() {
341+
let mut e = engine(8);
342+
e.enable_prefix_cache();
343+
let prompt: Vec<usize> = (10..20).collect(); // 2 full blocks + 2 tokens
344+
e.submit(prompt.clone(), 1);
345+
e.step(|r| Ok(vec![5; r.len()])).unwrap(); // finishes after one token
346+
let mut p2 = prompt[..8].to_vec();
347+
p2.extend([77, 78, 79]);
348+
e.submit(p2, 1);
349+
let mut seen = Vec::new();
350+
e.step(|r| {
351+
seen.extend(r.iter().map(|q| q.cached_prefix_tokens));
352+
Ok(vec![5; r.len()])
353+
})
354+
.unwrap();
355+
assert_eq!(seen, vec![8]);
356+
// the shared blocks are held by the cache and the new request, the rest was allocated fresh
357+
let free_before = e.allocator.num_free_blocks();
358+
e.step(|r| Ok(vec![5; r.len()])).unwrap(); // request 2 is finished and released here
359+
assert!(e.allocator.num_free_blocks() > free_before - 1);
360+
}
361+
362+
#[test]
363+
fn running_out_of_kv_memory_ends_the_request_instead_of_overwriting_blocks() {
364+
let mut e = engine(2); // 8 token slots in total
365+
e.submit(vec![10, 11, 12], 100);
366+
let mut steps = 0;
367+
while steps < 50 {
368+
if e.step(|r| Ok(vec![5; r.len()])).unwrap().is_empty() {
369+
break;
370+
}
371+
steps += 1;
372+
}
373+
assert!(steps < 50, "the request must stop when memory runs out");
374+
assert!(steps <= 6, "{steps}");
375+
}
376+
377+
#[test]
378+
fn constrained_requests_only_ever_emit_text_that_matches_the_pattern() {
379+
let vocab: Vec<String> = ["<pad>", "<unk>", "<eos>", "a", "b"].iter().map(|s| s.to_string()).collect();
380+
let mut e = engine(8);
381+
e.set_vocab(vocab.clone());
382+
let re = Arc::new(Regex::new("ab+").unwrap());
383+
let cfg = SamplingConfig { max_new_tokens: 4, ..SamplingConfig::greedy() };
384+
let id = e.submit_constrained(vec![9], cfg, re.clone()).unwrap();
385+
let logits = Tensor::from_slice(&[0.0f32, 0.0, 1.0, 3.0, 2.0], &[5]).unwrap(); // the "model" always prefers a > b > eos
386+
let mut text = String::new();
387+
loop {
388+
let out = e
389+
.step(|reqs| {
390+
reqs.iter()
391+
.map(|r| {
392+
let mut c = r.constraint.clone().unwrap();
393+
let m = c.mask_logits(&logits, &vocab, Some(2)).unwrap().to_vec::<f32>().unwrap();
394+
Ok((0..m.len()).max_by(|&a, &b| m[a].partial_cmp(&m[b]).unwrap()).unwrap())
395+
})
396+
.collect()
397+
})
398+
.unwrap();
399+
if out.is_empty() {
400+
break;
401+
}
402+
for (rid, tok) in out {
403+
assert_eq!(rid, id);
404+
text.push_str(&vocab[tok]);
405+
}
406+
}
407+
assert_eq!(text, "abbb");
408+
assert!(re.is_match(&text));
409+
assert!(e.submit_constrained(vec![1], SamplingConfig::greedy(), re).is_ok());
410+
let mut bare = engine(2);
411+
assert!(bare.submit_constrained(vec![1], SamplingConfig::greedy(), Arc::new(Regex::new("a").unwrap())).is_err());
412+
}
413+
}

0 commit comments

Comments
 (0)