Implement a function continuous_batching_sim(requests, max_batch_size) that simulates the continuous batching (also called in-flight batching) strategy used in modern LLM serving systems.
In traditional static batching, the server waits for all sequences in a batch to finish generating tokens before admitting new requests. This wastes GPU cycles on padding shorter sequences.
Continuous batching solves this by allowing new requests to fill freed slots immediately when existing sequences complete, maximizing GPU utilization.
At each discrete time step (starting at time 0), the following events occur in this exact order:
arrival_time <= current_time that has not yet been enqueued is added to the waiting queue (in the order they appear in the input list).max_batch_size total active slots. Each admitted request records its processing start time.The simulation ends when all requests have been completed.
requests: A list of dicts, each with 'arrival_time' (int >= 0) and 'tokens_needed' (int >= 1)max_batch_size: Maximum number of concurrent sequences (int >= 1)Return a dictionary with:
'total_time': The total number of time steps simulated (final time value when all requests complete)'avg_latency': Average of (completion_time - arrival_time) across all requests, rounded to 4 decimal places'avg_ttft': Average time-to-first-token (start_time - arrival_time) across all requests, rounded to 4 decimal places'throughput': Total tokens generated divided by total_time, rounded to 4 decimal places