Continuous batching and scheduling
Build an iteration-level scheduler that admits and completes requests, chunks prefill and preempts with recomputation, then compare latency and throughput under Poisson load with static batching.
After this lesson you can
- Implement the engine loop with waiting, running and preemption queues.
- Mix chunked prefill and decode in one token-budgeted step.
- Implement admission based on free blocks and preemption with recomputation.
- Measure latency-throughput curves under Poisson load.
Before you start
Each iteration changes the batch
If eight static requests generate 50, 80, 120, 400, 60, 90, 300 and 70 tokens, the batch occupies slots and produces 1170 tokens. Slot utilization is 36.56%. This is not a direct measure of GPU utilization: kernels, prefill and scheduling also consume time. The example shows why variable lengths can leave capacity unused.
The continuous scheduler maintains waiting and running requests. On each iteration it selects work, frees finished requests’ cache and can admit new requests. Orca describes iteration-level scheduling. Batch composition changes, so each row must retain its identity, state, positions and block table as other rows enter or leave.
Safe admission considers the block budget. If future lengths are known, the maximum can be reserved; in production they are usually uncertain and headroom, an output limit or an out-of-memory policy is needed. Admitting merely because the first token fits can trigger cascading evictions as all caches grow together. Reserving too much leaves capacity idle while other requests wait. The policy must state its guarantees and what happens when reservation fails.
The waiting queue and running set are not interchangeable. A waiting request must not yet write to a block table; an active request owns its references and may occupy memory even when it receives no budget in the next iteration. A completed request frees its table only after kernels reading it finish. This example synchronizes everything before freeing; a concurrent engine needs events or an equivalent memory-lifetime policy.
Prefill, decode and memory
Chunked prefill and preemption are decisions of the same scheduler. It can first reserve one budget token for each active decode, then use the remainder to advance prefills. A large prompt is split across steps, leaving opportunities to emit tokens for already-active conversations. SARATHI studies this combination. A small chunk reduces maximum work per iteration but adds steps and may delay the new prompt’s first token.
When preempting for recomputation, free the cache, retain the prompt and already-sent output, and rebuild context before continuing. Replayed tokens used for reconstruction are not sent again. The last emitted token remains pending as the next decode input; processing it twice would alter the cache. Swapping to RAM preserves state but requires memory, transfer and synchronization. A laptop with 32 GB RAM does not alone determine which is better: measure sizes, link latency, available memory and SLO.
The lab uses maximum reservations to prevent overcommitment. In a controlled test, an urgent request arrives after two tokens and preempts another; the second recomputes its context and both finish with the same sequences as without preemption. Freed pages are checked too. This is a small correctness test, not evidence that preemption improves throughput. A priority policy must avoid permanently starving a low-priority request.
The preemption test forces insufficient reservation to exercise that code path. With abundant memory alone, results may be correct without ever checking recomputation. It is also useful to preempt after emitting tokens, verify the client receives no duplicates and check the logical context order on resumption. One sequence and seed are a first check, not proof of all possible interleavings.
Load and percentiles
A load test must define request arrivals, duration and where times are measured. In a constant-rate Poisson process with rate , intervals are exponential with mean . Rate is an average, not a regular-spacing guarantee. Fixing the seed reproduces a trace; multiple seeds reveal variation between traces.
Initial queue time runs from scheduled arrival to first admission. TTFT runs until the first token, total latency until the last. If a request is preempted later, resumption waiting affects token pace and latency but is not added again to the initial queue. Throughput is completed requests or tokens per time; report both alongside percentiles and the fraction meeting the SLO. An average alone can hide a long tail.
Real trials use the same prompts and scheduled times for each pair of modes but run at different moments. Times include waiting for arrivals and process work; the one-layer model is untrained and measurements exclude network and a remote client. In the first trial at nominal rate 15/s, p99 queue was 0.527 s static and 0.205 s continuous; at 30/s it was 2.047 and 2.671 s. In the second 30/s trial it was 3.404 and 3.194 s. These results show variation and do not establish that continuous batching sustains more load at the same p99 in this implementation.
The p99 of 64 requests depends on very few extreme observations. With a queue that keeps growing, apparent throughput and percentiles depend on duration and whether the test waits for draining to finish. Estimating sustained capacity needs warmup, longer periods, multiple replicates and stable load; errors, cancellations, memory and concurrency must also be documented. This lesson’s sweep tests the harness and explores uncertainty, not a production-capacity figure.
Open-loop load schedules arrivals without waiting for the previous response. If the generator cannot send on time, measuring from actual send instead of scheduled time can hide the wait it introduces itself. In this lab the clock starts before arrivals and queue time uses the scheduled instant; client and engine share a process, so network contention and a remote generator are not measured. Closed-loop load, where each client waits for a response before sending the next, self-regulates as latency rises and answers a different question.
Nominal rate and completed throughput also differ when the system saturates. If 60 requests arrive per second but fewer finish, a finite test may drain the queue long after the final arrival. Dividing by the whole interval to completion includes draining; measuring only the arrival period uses another denominator. Both can be useful, but must be named so a server is not credited with sustained capacity unsupported by its queue.
Local lab
The mini engine uses PyTorch CUDA, a synthetic one-layer model and a small paged cache. It concatenates tokens from different segments, projects the batch and computes attention per sequence through its table. The correctness test compares gather with contiguous history at every token and checks two modes over eight requests. Streaming events are stored in process; there is no HTTP or real tokenizer. A complete service test would connect the project model, an API and an independent load generator.
The sweep runs two seeds per rate and 64 requests per cell. Lengths, budget and reservation remain fixed between modes; the GPU is shared and experiments run sequentially. Example measurements are saved in a temporary file unless P10_L05_OUT is set. Execution may take several minutes and requires CUDA-compatible PyTorch.
For a quick check, set P10_L05_COUNT=8 and P10_L05_REPEATS=1. That reduced run verifies flow and tests, but its percentiles do not replace the full sweep or establish sustained capacity. The graph uses recorded measurements with 64 requests and two trials, not results from a later run.
import json, math, os, random, tempfile, time, torch
torch.set_num_threads(1);torch.manual_seed(733);assert torch.cuda.is_available();dev='cuda'
D=32;V=64;BS=8;N_BLOCKS=32
emb=torch.randn(V,D,device=dev);wq=torch.randn(D,D,device=dev)/math.sqrt(D);wk=torch.randn_like(wq)/math.sqrt(D);wv=torch.randn_like(wq)/math.sqrt(D);wo=torch.randn(D,V,device=dev)/math.sqrt(D)
class Cache:
def __init__(self):
self.k=torch.empty(N_BLOCKS,BS,D,device=dev);self.v=torch.empty_like(self.k);self.free=list(reversed(range(N_BLOCKS)));self.tables={};self.n={};self.peak=0
def create(self,i):self.tables[i]=[];self.n[i]=0
def append(self,i,k,v):
n=self.n[i]
if n%BS==0:
if not self.free:raise MemoryError('sin páginas')
self.tables[i].append(self.free.pop());self.peak=max(self.peak,N_BLOCKS-len(self.free))
p=self.tables[i][n//BS];self.k[p,n%BS]=k;self.v[p,n%BS]=v;self.n[i]+=1
def gather(self,i):
pos=torch.arange(self.n[i],device=dev);table=torch.tensor(self.tables[i],device=dev);return self.k[table[pos//BS],pos%BS],self.v[table[pos//BS],pos%BS]
def release(self,i):self.free.extend(self.tables.pop(i));del self.n[i]
def trace(rate,count=48,seed=227):
rng=random.Random(seed);arrival=0.;rows=[]
for i in range(count):
arrival+=rng.expovariate(rate);n=rng.choice([8,12,16,24]);output=rng.choice([4,5,8,24]);prompt=[rng.randrange(V) for _ in range(n)]
rows.append({'id':i,'arrival':arrival,'prompt':prompt,'limit':output,'priority':rng.randrange(3),'pages':math.ceil((n+output-1)/BS)})
return rows
def serve(items,mode='continuous',chunk=8,budget=16,reserve_limit=24,priority=False,preempt=False,verify=False,inject_after=None):
jobs=[dict(j,offset=0,generated=[],stamps=[],first_admit=None,refk=[],refv=[]) for j in items];cache=Cache();active=[];waiting=[];used=0;cursor=0;start=time.perf_counter();evictions=0;steps=0;maxerr=0.
order=lambda j:(j['priority'],j['id']) if priority else (j['id'],)
while cursor<len(jobs) or waiting or active:
now=time.perf_counter()-start
if inject_after is not None and cursor==1 and len(jobs[0]['generated'])>=inject_after:jobs[1]['arrival']=now
while cursor<len(jobs) and jobs[cursor]['arrival']<=now:waiting.append(jobs[cursor]);cursor+=1
waiting.sort(key=order)
if mode=='continuous' and preempt and waiting and active and used+waiting[0]['pages']>reserve_limit:
victim=max(active,key=order)
if order(waiting[0])<order(victim):
active.remove(victim);cache.release(victim['id']);used-=victim['pages'];victim['offset']=0;victim['refk']=[];victim['refv']=[];waiting.append(victim);waiting.sort(key=order);evictions+=1
if mode=='continuous' or not active:
while len(active)<4 and waiting and used+waiting[0]['pages']<=reserve_limit:
j=waiting.pop(0);cache.create(j['id']);used+=j['pages'];active.append(j)
if j['first_admit'] is None:j['first_admit']=time.perf_counter()-start
if not active:
if waiting:raise ValueError('reserva menor que una petición')
time.sleep(max(0,items[cursor]['arrival']-(time.perf_counter()-start)));continue
left=budget;pieces=[]
for j in active:
context=j['prompt']+j['generated'][:-1]
if j['generated'] and j['offset']==len(context) and left:
pieces.append((j,[j['generated'][-1]],'decode'));left-=1
for j in active:
context=j['prompt']+j['generated'][:-1] if j['generated'] else j['prompt']
if j['offset']<len(context) and left:
n=min(chunk,left,len(context)-j['offset']);pieces.append((j,context[j['offset']:j['offset']+n],'prefill'));left-=n
flat=[t for _,part,_ in pieces for t in part];offsets=[0]
for _,part,_ in pieces:offsets.append(offsets[-1]+len(part))
x=emb[torch.tensor(flat,device=dev)];q=x@wq;k=x@wk;v=x@wv;emits=[]
for index,(j,part,phase) in enumerate(pieces):
final=None
for z in range(offsets[index],offsets[index+1]):
cache.append(j['id'],k[z],v[z]);keys,values=cache.gather(j['id']);final=torch.softmax(keys@q[z]/math.sqrt(D),0)@values@wo
if verify:
j['refk'].append(k[z]);j['refv'].append(v[z]);ref=torch.softmax(torch.stack(j['refk'])@q[z]/math.sqrt(D),0)@torch.stack(j['refv'])@wo;maxerr=max(maxerr,float((final-ref).abs().max()))
j['offset']+=len(part)
if phase=='decode' or (not j['generated'] and j['offset']==len(j['prompt'])):emits.append((j,final.argmax()))
tokens=torch.stack([x for _,x in emits]).cpu().tolist() if emits else []
torch.cuda.synchronize();stamp=time.perf_counter()-start;steps+=1
for (j,_),token in zip(emits,tokens):j['generated'].append(token);j['stamps'].append(stamp)
for j in list(active):
if len(j['generated'])==j['limit']:
cache.release(j['id']);used-=j['pages'];active.remove(j)
wall=time.perf_counter()-start;assert len(cache.free)==N_BLOCKS and used==0 and maxerr<1e-5
def pct(values,q):return sorted(values)[math.floor((len(values)-1)*q)]
queue=[j['first_admit']-j['arrival'] for j in jobs];ttft=[j['stamps'][0]-j['arrival'] for j in jobs];latency=[j['stamps'][-1]-j['arrival'] for j in jobs];tokens=sum(len(j['generated']) for j in jobs)
return {'mode':mode,'wall':wall,'requests_per_s':len(jobs)/wall,'tokens_per_s':tokens/wall,'queue50':pct(queue,.5),'queue99':pct(queue,.99),'ttft50':pct(ttft,.5),'ttft99':pct(ttft,.99),'latency99':pct(latency,.99),'evictions':evictions,'steps':steps,'peak_blocks':cache.peak,'max_error':maxerr,'outputs':[j['generated'] for j in jobs]}
def main():
print('GPU',torch.cuda.get_device_name(),'modelo sintético una capa D=32; eventos de streaming en proceso, no HTTP',flush=True)
torch.cuda.synchronize();_=emb[:2]@wq;torch.cuda.synchronize()
small=trace(40,8);a=serve(small,'static',verify=True);b=serve(small,'continuous',verify=True)
print('verificación gather',a['max_error'],b['max_error'],'salidas iguales',sum(x==y for x,y in zip(a['outputs'],b['outputs'])),'de',len(small),flush=True)
assert a['max_error']<1e-5 and b['max_error']<1e-5
# Fuerza una expulsión: la petición urgente llega durante un prefill largo.
forced=[{'id':0,'arrival':0.,'prompt':list(range(24)),'limit':24,'priority':2,'pages':6},
{'id':1,'arrival':.001,'prompt':list(range(24,48)),'limit':24,'priority':0,'pages':6}]
reference=serve(forced,'continuous',reserve_limit=6,verify=True)
delayed=[dict(forced[0]),dict(forced[1],arrival=999.)]
pressure=serve(delayed,'continuous',reserve_limit=6,priority=True,preempt=True,verify=True,inject_after=2)
assert pressure['evictions']>=1 and pressure['outputs']==reference['outputs']
print('presión tras dos tokens: expulsiones',pressure['evictions'],'salidas iguales a referencia',pressure['outputs']==reference['outputs'],'error gather',pressure['max_error'],'todos los bloques liberados',flush=True)
results=[]
count=int(os.environ.get('P10_L05_COUNT','64'));repeats=int(os.environ.get('P10_L05_REPEATS','2'))
assert count>=2 and repeats>=1
for rate in (15,30,45,60):
for trial in range(repeats):
items=trace(rate,count,227+trial)
for mode in ('static','continuous'):
result=serve(items,mode);result.pop('outputs');result['rate']=rate;result['trial']=trial;results.append(result)
print('tasa',rate,'ensayo',trial,mode,'pet/s',round(result['requests_per_s'],2),'tokens/s',round(result['tokens_per_s'],2),'cola p50/p99',round(result['queue50'],3),round(result['queue99'],3),'TTFT p50/p99',round(result['ttft50'],3),round(result['ttft99'],3),'fin p99',round(result['latency99'],3),flush=True)
out=os.environ.get('P10_L05_OUT') or os.path.join(tempfile.mkdtemp(prefix='p10-l05-'),'load_data.json')
with open(out,'w',encoding='utf8') as f:json.dump({'gpu':torch.cuda.get_device_name(),'results':results},f)
print('datos guardados en',out)
if __name__=='__main__':main()
npm run lab and open the connection link.Exercises
class Scheduler:
def __init__(self,waiting,running,free_blocks,token_budget,chunk):
...
def step(self):
...