Simulate a chunked prefill scheduler with a per-step token budget

A long prompt can take a whole forward pass to prefill, stalling every user who is waiting for their next token. Chunked prefill caps the tokens processed per step and splits long prompts across steps, while decodes go first. This is a discrete-step simulation in plain Python.

requests is a list of (arrival_step, prompt_len, output_len) with prompt_len >= 1 and output_len >= 1. Each step processes at most budget tokens (budget >= 1). At each step t = 0, 1, 2, ...:
1. Decode phase: in input order, every unfinished request that already has at least one output token (at the start of this step) generates one more token, costing 1 budget, while budget remains.
2. Prefill phase: in input order, every unfinished request with arrival_step <= t and prompt tokens left gets min(prompt left, budget left) prompt tokens. If this finishes its prompt, that same step also produces its first output token.
3. A request finishes at the step where it produces its output_len-th token.
Return the finishing step of each request, in input order.

Signaturedef chunked_prefill(requests, budget)

Example

requests = [(0, 5, 3), (0, 2, 2)], budget = 4. Step 0 prefills 4 of request 0's 5 tokens. Step 1 finishes request 0's prompt (first token) and all of request 1's (first token). Step 2 decodes both, so request 1 finishes. Step 3 decodes request 0, which finishes. Answer: [3, 2].

Understand the idea

Prefill reads a whole prompt, decode produces one token at a time. A huge prompt in one step would freeze every user waiting for their next token. Chunked prefill gives each step a token budget: decodes go first because each costs only 1 token, then leftover budget is spent on prompts, splitting long prompts over several steps. Worked example: requests (arrival 0, prompt 3, output 2) and (arrival 0, prompt 2, output 1), budget 2. Step 0: nobody is decoding; request A prefills 2 of 3. Step 1: still no decodes; A prefills its last token and emits its first output; 1 budget left goes to B, 1 of 2. Step 2: A decodes its second token and finishes; B prefills its last token and emits its only output, so it finishes too. Answer [2, 2]. Rules: decode phase in input order for requests that already had an output token at the start of the step; prefill phase in input order for arrived requests with prompt left, taking min(left, budget left); finishing a prompt emits the first token in that same step. Used in vLLM and similar servers to keep latency smooth.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplechunked_prefill([(0, 5, 3), (0, 2, 2)], 4)
  • Sample 2: long prompt arrives mid-decodechunked_prefill([(0, 3, 6), (0, 2, 5), (2, 20, 2)], 6)