Module contents
Lesson 20 of 28Advanced 110 min

Continuous batching and scheduling: chunked prefill, disaggregation and determinism

In a static batch a long request holds up the others. Iteration-level scheduling lets requests enter and leave each step and leads to a modern engine scheduler: unpadded ragged batches, free-block admission, preemption, chunked prefill, service-level policies, prefill/decode disaggregation and inference model parallelism. We finish with batch-dependent nondeterminism and how to avoid it.

After this lesson you can

  • Implement continuous batching with flattened ragged batches and variable-length attention.
  • Implement token-budgeted chunked prefill and measure its effect on TTFT and TPOT.
  • Compare scheduling and preemption policies by goodput under service objectives.
  • Decide when prefill/decode disaggregation is worthwhile and which inference parallelism to use.
  • Explain and reproduce batch-dependent nondeterminism and build a batch-invariant reduction.

Before you start

From full batches to iterations

In a static batch requests start together and no new one is added until the longest finishes. With outputs of 50, 100, and 1000 tokens, 3000 token slots are reserved and 1150 used: 1850, or 61.67%, are wasted. This counts batch steps, not energy or bytes. Continuous scheduling can fill gaps with waiting requests; if none wait, the slot stays empty. Orca proposes iteration-level scheduling and selective batching.

Continuous batching redecides composition after each step. A finished request releases its cache and another can enter without waiting for the rest. This increases occupancy opportunities, but each addition needs memory, prefill work, and coordination with active decodes. Capacity does not automatically increase if the GPU is saturated by another phase or free cache runs out.

InteractiveStatic and continuous
Static · 27 iterations
1
2
3
1
2
3
1
2
3
2
3
2
3
3
3
3
3
3
3
3
3
3
3
3
4
5
6
4
5
6
4
5
6
4
5
5
5
7
8
7
8
7
8
7
8
7
Each column is an iteration; numbers identify requests and empty slots appear gray. Scroll horizontally if needed.
Continuous · 16 iterations
1
2
3
1
2
3
1
2
3
2
3
4
2
3
4
3
4
5
3
4
5
3
5
6
3
5
6
3
5
6
3
5
7
3
7
8
3
7
8
3
7
8
3
7
8
3
Each column is an iteration; numbers identify requests and empty slots appear gray. Scroll horizontally if needed.
16
Static / continuous iterations27 / 16
Mean completion static / continuous17.3 / 10.3
All requests are ready from the start. Each column represents an iteration and each number a request; scroll the schedule horizontally when needed.

The figure uses three slots and identical step times. A real service receives requests over time with different input and output lengths and may not have a new request ready when a slot frees up. Compare throughput, latency distribution, and goodput on the same trace rather than only counting occupied slots in a favorable example.

Batches without padding

A ragged batch concatenates tokens from multiple sequences and stores cumulative offsets. For lengths 3, 2, and 4 the vector has nine tokens and boundaries 0, 3, 5, and 9. Per-token operations can use the flattened vector, while attention must respect boundaries and causality. An incorrect mask allowing attention to another sequence mixes information across users.

Packing removes padding positions but not the cost of scheduling different-length sequences. A variable attention kernel can use offsets, block tables, and lengths; another may work per sequence. The local mini-engine jointly projects flattened tokens and traverses each sequence to compute attention with its own cache. That implementation favors clarity and checking, not proof of production-kernel speed.

To check batch boundaries, compare each output with a separate run of the same sequence. Include each segment’s first and last token, length-one sequences, and sequences sharing text but not context. If a request’s prefix occupies five KV positions, its next token must attend to those five and itself, not the preceding five tokens of the concatenated vector when they belong to another user. Offsets mark where current work begins; cache table and length identify each request’s past.

Budget and chunked prefill

Chunked prefill divides a long prompt into fragments fitting across several iterations. If existing decodes are prioritized and remaining budget used for prefill, a new request progresses without completely stopping current outputs. SARATHI and Sarathi-Serve study this combination and its tradeoffs.

InteractiveChunk prefill

The three decodes receive one token per iteration. Chunking prefill reduces maximum per-iteration pause, but adds steps and fixed overhead. The new prompt’s first token emerges when its prefill finishes.

128
64
Prompt TTFT153.0 ms
Peak ITL of other requests19.1 ms
Prefill iterations8
Synthetic cost model with three active decodes and a 512-token prompt. Adjust budget and chunk size to compare maximum pause with first-token time.

With large chunks an iteration can take longer and worsen other requests’ inter-token interval. With small chunks fixed overhead repeats and the prompt’s first token can arrive later. The decision depends on shapes, kernels, load, and goals; the figure’s curve is not a GPU measurement. The budget must count both prefill and decode tokens and must not admit more work than memory supports.

Memory, preemption, and objectives

Scheduling policies order a queue and manage blocks. FCFS is simple and preserves arrival order, but a long request can delay others. Shortest-first can reduce the mean while harming long requests; priorities need anti-starvation rules. Future-length estimates may be right or wrong: unknown output requires reserved headroom or a decision about growth.

If blocks are scarce, the scheduler can wait, preempt a request and recover its KV from CPU, or release it and recompute its context when it returns. Swapping costs transfer and external memory; recomputation consumes operations and adds delay. Both can affect other requests. The simulator reserves each trace’s known maximum in advance, a deliberate simplification; preemption occurs only when a preferred request does not fit.

When recomputing a request that has already emitted tokens, repeating the prompt is insufficient: state for tokens preceding the last emitted one must also be reconstructed without resending them to the client. The last emitted token remains pending input for the next decode. The simulator counts this extra work before resumption. Swapping retains progress and adds synthetic 30 ms; it is not a measurement or a model of shared-link contention. Pinned buffers, copies, and synchronization were studied in the previous lesson.

Shortest-first depends on an estimate that may be wrong. A priority policy can use aging or wait limits to prevent long requests from indefinite starvation. The choice also affects user fairness: optimizing an aggregate mean can hide that one group waits much longer. Record per-request times and separate rejected, canceled, or preempted requests before interpreting the SLO-compliant percentage.

InteractiveScheduler with SLOs

A request with lower numeric priority or smaller size may preempt another only if blocks are scarce. FCFS does not preempt by priority. Blocks are reserved using known final length in this simulation; reality must allow for growth.

20
36
128
64
TTFT p50 / p99730 / 1905 ms
TPOT p50 / p9918 / 22 ms
Goodput6.08 requests/s
Meet SLO22 / 36
Preemptions0
Fixed synthetic trace of 36 arrivals; percentiles and goodput depend on its parameters. Memory and times are a model, not a benchmark.

Goodput counts requests meeting both TTFT and TPOT per unit time. The figure uses TTFT ≤ 1 s and TPOT ≤ 80 ms. P50 and P99 are statistics from a small sample; they do not guarantee extreme-tail behavior. Policy comparison requires the same trace, measurement window, rejection rules, and memory limits. Higher throughput with many requests outside SLO may mean less useful work for users.

Separate the two phases

Prefill and decode disaggregation assigns separate GPU groups to each phase. It can reduce interference and allow different batch sizes or parallelisms, but KV must be transferred, queues coordinated, and capacity reserved on both sides. DistServe and Splitwise analyze this design. If requests are short or the link slow, transfer and idle capacity can outweigh benefits.

An 8000-token prompt with 128 decimal KB of KV per token transfers 1.024 GB. At sustained 50 GB/s the ideal bound is 20.48 ms, excluding network latency, serialization, and contention. The first token might be obtained in prefill before transfer, but the next cannot arrive until decode has the state. Comparing with prefill time requires a measurement or model for that hardware and context; bytes alone do not determine it.

Model parallelism in serving also changes the budget. TP divides operations across devices and can lower latency if communication pays off; PP distributes layers for capacity but adds stages and bubbles; EP distributes MoE experts and requires token dispatch. Each phase may favor a different partition. Model size, link, batch, expert distribution, and SLO determine the choice.

Same request, different batch

Batch invariance requires a request’s output to remain the same when other rows or batch size change. Floating-point operations are not associative: in BF16, rounding after each operation, (256+1)−256=0(256+1)-256=0, whereas 256+(1−256)=1256+(1-256)=1. A kernel may choose a different partition or reduction tree for another shape and produce small differences. Greedy removes sampling randomness, but a near tie can amplify numerical differences in later tokens.

InteractiveThe batch effect
  • Native PyTorch
  • Fixed order

The first row is compared against batch one. Fixed reduction gives bitwise equality in this test; the first greedy token is 69 and no divergence was observed in eight steps. Small differences do not guarantee different output.

3
Batch8
Maximum native difference3.81e-6
Fixed-order difference0.00e+0
First divergent tokenNone in 8 steps
Measured results for toy RMSNorm and matmul on RTX 3060. The fixed curve is identical in this test; no divergence was observed across eight tokens.

The experiment compares the same first row in batches from 1 to 64. Native PyTorch showed maximum differences of 3.81e-6 to 5.72e-6 against batch one; fixed-reduction kernels matched bitwise for that row. Across eight greedy steps no token diverged. This demonstrates a numerical difference and a property of two specific operations, not that every transformer is invariant. Attention, other reductions, precision, versions, hardware, and any randomness also matter. Thinking Machines’ notes distinguish determinism of a fixed run from batch-composition invariance.

If two logits are separated by more than the observed change, the winning token may remain; if very close, ordering may reverse. After selecting another token, inputs and cache are no longer equal, and continuation differences are no longer just the initial numerical error. Conversely, repeating an operation with the same batch and kernel can always give the same result yet vary when the batch changes. To assess reproducibility, record composition, version, precision, seed, and stopping rule, and check results under different conditions.

Lab: schedule a trace

The event simulator uses exponential arrivals, 16-token blocks, at most four active requests, chunked prefill, and an ideal roofline model inspired by lesson 18. It adds prefill and decode bounds without overlap and adds fixed overhead; it excludes some attention costs. It runs the same trace with FCFS, length, and priority; compares static and continuous batches; and models recomputation or a fixed swap penalty. Disaggregation is another model with one worker per phase and transfer without contention. These are not GPU measurements or a controlled comparison of complete architectures.

[ ]Event schedulingBrowser
import math, random, statistics

def trace(seed=194,count=36,rate=20):
    rng=random.Random(seed);arrival=0.;items=[]
    for i in range(count):
        arrival+=rng.expovariate(rate);prompt=rng.choice([32,64,128,256]);output=rng.randint(8,20)
        items.append({'id':i,'arrival':arrival,'prompt':prompt,'output':output,'priority':rng.randrange(3),'pages':math.ceil((prompt+output)/16)})
    return items

def simulate(items,blocks=36,budget=128,chunk=64,policy='fcfs',eviction='none',mode='continuous'):
    jobs=[dict(x,prefill=0,generated=0,events=[],first=None,end=None) for x in items]
    def key(j):
        return (j['prompt']+j['output'],j['id']) if policy=='shortest' else (j['priority'],j['id']) if policy=='priority' else (j['id'],)
    active=[];waiting=[];cursor=0;time=0.;used=0;preemptions=0;iterations=0
    while cursor<len(jobs) or waiting or active:
        iterations+=1
        if iterations>100000:raise RuntimeError('sin progreso')
        while cursor<len(jobs) and jobs[cursor]['arrival']<=time:waiting.append(jobs[cursor]);cursor+=1
        waiting.sort(key=key)
        if mode=='continuous' and eviction!='none' and waiting and active and used+waiting[0]['pages']>blocks:
            candidate=waiting[0];victim=max(active,key=key)
            if key(candidate)<key(victim):
                active.remove(victim);used-=victim['pages'];preemptions+=1
                if eviction=='recompute':victim['prefill']=-max(0,victim['generated']-1)
                else:time+=.03
                waiting.append(victim);waiting.sort(key=key)
        if mode=='continuous' or not active:
            while len(active)<4 and waiting and used+waiting[0]['pages']<=blocks:
                job=waiting.pop(0);active.append(job);used+=job['pages']
        if not active:
            if cursor<len(jobs):time=max(time,jobs[cursor]['arrival']);continue
            raise ValueError('la petición no cabe')
        left=budget;prefill_tokens=0;decodes=[];completed=[]
        for j in active:
            if j['prefill']==j['prompt'] and j['generated']<j['output'] and left>0:decodes.append(j);left-=1
        for j in active:
            if j['prefill']<j['prompt'] and left>0:
                n=min(chunk,left,j['prompt']-j['prefill']);j['prefill']+=n;prefill_tokens+=n;left-=n
                if j['prefill']==j['prompt'] and j['generated']==0:completed.append(j)
        # Aproximación secuencial con cotas roofline de la lección 18, no tiempos GPU reales.
        weights=3e9;bw=230e9;flops=30e12;params=1.5e9;kv=28000
        prefill_time=max(weights/bw,2*params*prefill_tokens/flops) if prefill_tokens else 0
        decode_time=max((weights+sum((j['prompt']+j['generated'])*kv for j in decodes))/bw,2*params*len(decodes)/flops) if decodes else 0
        time+=.002+prefill_time+decode_time
        for j in decodes+completed:
            j['generated']+=1;j['events'].append(time)
            if j['first'] is None:j['first']=time
        for j in list(active):
            if j['generated']==j['output']:j['end']=time;used-=j['pages'];active.remove(j)
    ttft=[j['first']-j['arrival'] for j in jobs];tpot=[(j['events'][-1]-j['events'][0])/(len(j['events'])-1) for j in jobs]
    def quantile(x,q):return sorted(x)[math.floor((len(x)-1)*q)]
    good=sum(a<=1 and b<=.08 for a,b in zip(ttft,tpot))
    return {'ttft50':quantile(ttft,.5),'ttft99':quantile(ttft,.99),'tpot50':quantile(tpot,.5),'tpot99':quantile(tpot,.99),'good':good,'goodput':good/time,'seconds':time,'preemptions':preemptions,'jobs':jobs}

def disaggregated(items,kv_bytes=28000,link=50e9):
    # Un trabajador por fase, FCFS, transferencia secuencial sin contención.
    p_free=d_free=0.;first=[];end=[]
    for j in items:
        start=max(j['arrival'],p_free);p_free=start+.008+.00008*j['prompt'];first.append(p_free)
        transfer=j['prompt']*kv_bytes/link
        begin=max(p_free+transfer,d_free);d_free=begin+.015*(j['output']-1);end.append(d_free)
    ttft=[t-j['arrival'] for j,t in zip(items,first)]
    tpot=[(finish-t)/(j['output']-1) for j,t,finish in zip(items,first,end)]
    good=sum(a<=1 and b<=.08 for a,b in zip(ttft,tpot));wall=max(end)
    return {'ttft_mean':statistics.mean(ttft),'tpot_mean':statistics.mean(tpot),'good':good,'goodput':good/wall,'seconds':wall,'transfer_bytes':sum(j['prompt']*kv_bytes for j in items)}

def demo():
    items=trace()
    for policy,eviction in [('fcfs','none'),('shortest','recompute'),('priority','swap')]:
        for mode in ['static','continuous']:
            r=simulate(items,policy=policy,eviction=eviction,mode=mode)
            assert all(j['generated']==j['output'] for j in r['jobs']) and len(r['jobs'])==len(items)
            print(mode,policy,eviction,'TTFT p50/p99',round(r['ttft50'],3),round(r['ttft99'],3),'TPOT p50/p99',round(r['tpot50'],3),round(r['tpot99'],3),'goodput',round(r['goodput'],3),'expulsiones',r['preemptions'])
    print('desagregación modelo separado',disaggregated(items))
if __name__=='__main__':demo()

Local lab: engine and reductions

The mini-engine runs an untrained synthetic one-layer model on CUDA with dimension 32 and vocabulary 64. It jointly projects flattened tokens, applies per-sequence causal attention over a block pool, and sends one in-process event per token. Offsets separate requests and prefill is chunked under a budget. Every paged attention is checked against a contiguous reference and all cache freed. It does not implement an HTTP API, a full transformer, or optimized-engine performance.

In one RTX 3060 run with six Poisson arrivals, both variants returned the same six greedy sequences and attention error was zero. Duration included waiting for arrivals, so tokens/s do not represent a saturated system. Figures vary with shared load. The local comparison uses the same prompts, weights, and lengths, but one repetition cannot establish a stable scheduling improvement.

[ ]Ragged mini-engine on CUDALocal GPU
import math, random, time, torch
torch.set_num_threads(1);torch.manual_seed(77);assert torch.cuda.is_available()
device='cuda';D=32;V=64;BS=8;POOL=64
emb=torch.randn(V,D,device=device);wq=torch.randn(D,D,device=device)/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=device)/math.sqrt(D)

class Pages:
    def __init__(self):
        self.keys=torch.empty(POOL,BS,D,device=device);self.values=torch.empty_like(self.keys);self.free=list(reversed(range(POOL)));self.tables={};self.length={};self.peak=0
    def start(self,i):self.tables[i]=[];self.length[i]=0
    def append(self,i,k,v):
        n=self.length[i]
        if n%BS==0:
            if not self.free:raise MemoryError('se agotaron bloques')
            self.tables[i].append(self.free.pop());self.peak=max(self.peak,POOL-len(self.free))
        page=self.tables[i][n//BS];self.keys[page,n%BS]=k;self.values[page,n%BS]=v;self.length[i]+=1
    def gather(self,i):
        positions=torch.arange(self.length[i],device=device);table=torch.tensor(self.tables[i],device=device)
        return self.keys[table[positions//BS],positions%BS],self.values[table[positions//BS],positions%BS]
    def release(self,i):self.free.extend(self.tables.pop(i));del self.length[i]

def trace():
    rng=random.Random(39);arrival=0.;items=[]
    for i,(n,out) in enumerate(zip([21,15,32,10,25,18],[5,8,6,9,7,6])):
        arrival+=rng.expovariate(5);items.append({'id':i,'arrival':arrival,'prompt':[rng.randrange(V) for _ in range(n)],'limit':out})
    return items

def stream_event(job,token,stamp):
    # Un consumidor puede procesar cada evento antes de que termine la petición.
    job['generated'].append(token);job['stamps'].append(stamp)

def serve(mode,items,chunk=8,budget=16):
    jobs=[dict(x,offset=0,generated=[],stamps=[],refk=[],refv=[]) for x in items];cache=Pages();active=[];cursor=0;start=time.perf_counter();maxerr=0.;steps=0
    while cursor<len(jobs) or active:
        now=time.perf_counter()-start
        if mode=='continuous' or not active:
            while cursor<len(jobs) and len(active)<4 and jobs[cursor]['arrival']<=now:
                job=jobs[cursor];cursor+=1;cache.start(job['id']);active.append(job)
        if not active:
            time.sleep(max(0,items[cursor]['arrival']-(time.perf_counter()-start)));continue
        # Cada entrada es un trozo de prompt o un token de decode; offsets delimitan secuencias.
        left=budget;pieces=[]
        for j in active:
            if j['offset']==len(j['prompt']) and len(j['generated'])<j['limit'] and left:
                pieces.append((j,[j['generated'][-1]],'decode'));left-=1
        for j in active:
            if j['offset']<len(j['prompt']) and left:
                n=min(chunk,left,len(j['prompt'])-j['offset']);pieces.append((j,j['prompt'][j['offset']:j['offset']+n],'prefill'));left-=n
        flat=[token for _,part,_ in pieces for token in part];offsets=[0]
        for _,part,_ in pieces:offsets.append(offsets[-1]+len(part))
        ids=torch.tensor(flat,device=device);x=emb[ids];q=x@wq;k=x@wk;v=x@wv;emits=[]
        for index,(j,part,phase) in enumerate(pieces):
            final_logits=None
            for z in range(offsets[index],offsets[index+1]):
                cache.append(j['id'],k[z],v[z]);j['refk'].append(k[z]);j['refv'].append(v[z]);keys,values=cache.gather(j['id'])
                logits=torch.softmax(keys@q[z]/math.sqrt(D),0)@values@wo
                reference=torch.softmax(torch.stack(j['refk'])@q[z]/math.sqrt(D),0)@torch.stack(j['refv'])@wo
                maxerr=max(maxerr,float((logits-reference).abs().max()));final_logits=logits
            if phase=='prefill':j['offset']+=len(part)
            if phase=='decode' or j['offset']==len(j['prompt']):emits.append((j,int(final_logits.argmax())))
        torch.cuda.synchronize();stamp=time.perf_counter()-start;steps+=1
        for j,token in emits:stream_event(j,token,stamp)
        for j in list(active):
            if len(j['generated'])==j['limit']:cache.release(j['id']);active.remove(j)
    wall=time.perf_counter()-start;assert len(cache.free)==POOL and maxerr<1e-5
    ttft=[j['stamps'][0]-j['arrival'] for j in jobs];tpot=[(j['stamps'][-1]-j['stamps'][0])/(len(j['stamps'])-1) for j in jobs]
    good=sum(a<=2 and b<=.5 for a,b in zip(ttft,tpot));count=sum(len(j['generated']) for j in jobs)
    pct=lambda x,q:sorted(x)[math.floor((len(x)-1)*q)]
    print(mode,'segundos',round(wall,3),'salida/s',round(count/wall,2),'TTFT p50/p95',round(pct(ttft,.5),3),round(pct(ttft,.95),3),'TPOT p50/p95',round(pct(tpot,.5),3),round(pct(tpot,.95),3),'goodput',round(good/wall,3),'pasos',steps,'pico bloques',cache.peak,'error gather',maxerr)
    return jobs

def main():
    items=trace();print('GPU',torch.cuda.get_device_name(),'modelo sintético: una capa, D=32, vocabulario=64, sin entrenamiento')
    # Calentamiento fuera del tiempo de la carga.
    torch.cuda.synchronize();_=(emb[:2]@wq);torch.cuda.synchronize()
    static=serve('static',items);continuous=serve('continuous',items)
    same=sum(a['generated']==b['generated'] for a,b in zip(static,continuous))
    print('secuencias greedy iguales estático/continuo',same,'de',len(items),'carga Poisson de 6 solicitudes; tiempos variables bajo uso compartido')
if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second block tests RMSNorm and matmul with fixed-order per-row reduction. It requires PyTorch CUDA and Triton; sizes are powers of two and weights synthetic. Bitwise equality of each operation is checked for the first row and a sequence of eight greedy choices compared. It does not replace every kernel of a model.

[ ]Fixed-order reductionsLocal GPU
import json, torch, triton, triton.language as tl

@triton.jit
def fixed_rms(X,Y,K:tl.constexpr,EPS:tl.constexpr):
    row=tl.program_id(0);k=tl.arange(0,K);x=tl.load(X+row*K+k).to(tl.float32)
    variance=tl.sum(x*x,0)/K;y=x*tl.rsqrt(variance+EPS);tl.store(Y+row*K+k,y)

@triton.jit
def fixed_matmul(X,W,Y,K:tl.constexpr,N:tl.constexpr):
    row=tl.program_id(0);column=tl.program_id(1);k=tl.arange(0,K)
    x=tl.load(X+row*K+k).to(tl.float32);w=tl.load(W+k*N+column).to(tl.float32)
    tl.store(Y+row*N+column,tl.sum(x*w,0))

def invariant(x,w):
    B,K=x.shape;N=w.shape[1];norm=torch.empty_like(x);out=torch.empty((B,N),device=x.device)
    fixed_rms[(B,)](x,norm,K=K,EPS=1e-5);fixed_matmul[(B,N)](norm,w,out,K=K,N=N)
    return norm,out

def run():
    torch.manual_seed(410);torch.set_num_threads(1);torch.backends.cuda.matmul.allow_tf32=False
    dev='cuda';K=N=128;w=torch.randn(K,N,device=dev);emb=torch.randn(N,K,device=dev);x=torch.randn(1,K,device=dev)
    torch.cuda.synchronize();base=torch.nn.functional.normalize(x,dim=1)*K**.5
    native0=(x*torch.rsqrt((x*x).mean(-1,keepdim=True)+1e-5))@w;nr0,fix0=invariant(x,w)
    sizes=[1,2,4,8,16,32,64];rows=[]
    for B in sizes:
        batch=torch.cat([x,torch.randn(B-1,K,device=dev)],dim=0) if B>1 else x.clone()
        norm=batch*torch.rsqrt((batch*batch).mean(-1,keepdim=True)+1e-5);native=norm@w
        nf,fixed=invariant(batch,w);torch.cuda.synchronize()
        assert torch.equal(nf[0],nr0[0]) and torch.equal(fixed[0],fix0[0])
        def greedy(batch_size,locked):
            state=x.clone();tokens=[]
            for _ in range(8):
                others=torch.zeros((batch_size-1,K),device=dev);a=torch.cat([state,others],0)
                if locked: logits=invariant(a,w)[1]
                else: logits=(a*torch.rsqrt((a*a).mean(-1,keepdim=True)+1e-5))@w
                token=int(logits[0].argmax());tokens.append(token);state=emb[token:token+1]
            return tokens
        ordinary=greedy(B,False);same=greedy(B,True);reference=greedy(1,False);ref_fixed=greedy(1,True)
        first=next((i+1 for i,(a,b) in enumerate(zip(ordinary,reference)) if a!=b),None)
        assert same==ref_fixed
        rows.append({'batch':B,'native_max':float((native[0]-native0[0]).abs().max()),'fixed_max':float((fixed[0]-fix0[0]).abs().max()),'first_divergence':first,'native_first':ordinary[0]})
    a=torch.tensor(256.,dtype=torch.bfloat16,device=dev);b=torch.tensor(1.,dtype=torch.bfloat16,device=dev);c=torch.tensor(-256.,dtype=torch.bfloat16,device=dev)
    left=float((a+b)+c);right=float(a+(b+c));assert left==0 and right==1
    print('GPU',torch.cuda.get_device_name(),'RMSNorm y matmul de juguete K=N=128')
    print('diferencias por lote',json.dumps(rows));print('BF16:',left,right)
    # Para guardar resultados, escribe rows como JSON en el destino elegido.
if __name__=='__main__':run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
In a batch of three outputs of 50, 100 and 1000 tokens, what percentage of the 3000 slots stays empty when waiting for the maximum?
Numeric
Ideally, how many milliseconds does transferring 8000 KV tokens of 128 decimal KB each over a 50 GB/s link take?
Proof
Prove: Explain why summation order can affect BF16 results.
The proof will appear here as you work.

Step 1 of 2. Rounding after each addition, what is 256+1 in BF16?

Code
Implement schedule_step(waiting,running,free_blocks,token_budget). Each running element has id, phase ('decode' or 'prefill') and remaining; each waiting element has id, blocks and remaining. Return (actions, free_blocks) without mutating the lists. Each action is (phase,id,tokens). Serve active decodes first with one token each, then active prefills and finally waiting in FIFO order. Prefill takes up to 4 tokens and the remaining budget. Admitting waiting reserves its blocks; if the first does not fit, stop admission.
def schedule_step(waiting,running,free_blocks,token_budget):
  ...
Shift+Enter to run
Quiz
What is a reasonable choice for interactive chat with a latency SLO?
Key idea
Iteration-level scheduling helps fill slots but requires coordinating prefill, memory, and SLOs. A batch-invariant reduction controls one source of variation, not all those in a complete system.