A simulation system for modeling LLM serving with fluid ODEs in the Operations Research framework.
# 1. Generate test data
python data/input/generate_requests.py
# 2. Run advanced strategy simulation (default: swap + conservative)
python experiments/run_advanced.py
# 3. Test different strategy combinations
python experiments/run_advanced.py --mode sacrifice --strategy aggressive
# 4. Generate visualizations
python visualization/plot_dynamics.pyM_total(int): Total GPU memory in tokens (default: 10000)- Controls when swapping is triggered
- Larger values reduce swapping but may affect batch size
B(int): Maximum batch token budget (default: 2000)- Upper limit for tokens processed in a single batch
- Affects throughput vs latency tradeoff
d_0(float): Base batch execution time (default: 1.0)- Fixed overhead per batch regardless of size
d_1(float): Per-token execution time coefficient (default: 0.001)- Marginal time cost per token
- Total batch time = d_0 + d_1 * batch_size
The system supports 4 strategy combinations: (swap/sacrifice) × (conservative/aggressive)
preemption_mode(string): Preemption mode"swap": Preserve KV cache and progress, swap to CPU (default)"sacrifice": Clear KV cache, reset progress
preemption_strategy(string): Preemption strategy"conservative": Preempt only when necessary (default)"aggressive": Actively preempt for high-priority requests
allow_waiting_preempt(bool): Whether WAITING requests can trigger preemption (default: false)queue_policy(string): Queue scheduling policy -"FCFS"victim_policy(string): Victim selection policy -"LIFO"
request_file(string): Input request CSV file pathexperiments_dir(string): Experiments directory (auto-generates timestamped subdirectories)L_filter(int/null): Maximum decode length filter (null = no filter)
seed(int): Random seed for reproducibility (default: 42)verbose(bool): Enable detailed logging (default: true)progress_interval(int): Progress report interval in batches (default: 100)
When using data/input/generate_requests.py:
--num_requests(int): Number of requests to generate (default: 100)--arrival_rate(float): Average arrival rate in requests/time unit (default: 0.5)--scenario(string): Load scenario type"normal": Standard load with mixed request lengths"heavy": High arrival rate (2.0) with longer requests"bursty": Burst pattern with periods of intense load
--output(string): Output filename (default: "requests.csv")
- 80% short requests:
- prefill_length: 10-60 tokens
- decode_length: 10-40 tokens
- 20% long requests:
- prefill_length: 150-200 tokens
- decode_length: 80-100 tokens
All output files are saved in data/experiments/experiment_YYYYMMDD_HHMMSS_XXXX/ directory:
System state after each batch execution:
time: Cumulative simulation timebatch_id: Unique batch identifierbatch_count: Actual executed requests (subset constrained by B)batch_tokens: Total tokens in execution batchrunning_count: All requests in GPU memory (≥ batch_count)waiting_count: Requests in waiting queueswapped_count: Requests swapped to CPUcompleted_count: Total completed requestsgpu_memory_used: Current GPU memory usagememory_utilization: GPU memory utilization ratiobatch_duration: Execution time of this batch
Complete lifecycle trace for each request:
req_id: Unique request identifierarrival_time: When request arrived at decode nodeprefill_length: Size of prefill KV cachedecode_length: Number of tokens to decodecompletion_time: When request completedtotal_delay: End-to-end latencywaiting_time: Time spent waitingexecution_time: Time spent executingswap_count: Number of times swapped outtotal_swapped_time: Total time swappedsacrifice_count: Number of times sacrificed
Detailed event log:
time: Event timestampbatch_id: Batch IDevent_type: Type of event (arrival, completion, swap_out, swap_in, etc.)req_id: Request involveddetails: Additional event information
Queue state timeline:
time: Timestampbatch_id: Batch IDqueue_type: Queue type (waiting/running/swapped)req_ids: List of request IDs in queue
Memory management events:
time: Event timestampbatch_id: Batch IDevent: Event type (swap_out/swap_in/arrival/completion)req_id: Related requestdecode_position: Decode positionmemory_change: Memory changegpu_memory_after: GPU memory after event
Human-readable summary report with:
- Basic statistics (total time, batches, completions)
- System statistics (queue lengths, swap counts)
- Performance metrics (throughput, latency, utilization)
- Sacrifice statistics (if using sacrifice mode)
Complete configuration snapshot used for the experiment
Experiment metadata (time, paths, strategy combination, etc.)
# Generate standard load and run simulation
python data/input/generate_requests.py --num_requests 100
python experiments/run_advanced.py
python visualization/plot_dynamics.py# Generate heavy load scenario
python data/input/generate_requests.py --scenario heavy --num_requests 200
python experiments/run_advanced.py --requests data/input/requests.csv# Test different strategy combinations
# Swap + Conservative (default)
python experiments/run_advanced.py
# Swap + Aggressive
python experiments/run_advanced.py --mode swap --strategy aggressive
# Sacrifice + Conservative
python experiments/run_advanced.py --mode sacrifice --strategy conservative
# Sacrifice + Aggressive
python experiments/run_advanced.py --mode sacrifice --strategy aggressive
# Or automatically test all 4 combinations
python experiments/test_all_strategies.py# List all experiments
ls data/experiments/
# View latest experiment summary
cat data/experiments/experiment_*/summary.txt
# Clean old experiment results
bash scripts/clean.shLocated in scripts/ directory:
clean.sh: Clean output directorymanage_experiments.sh: Experiment management tool
The visualization/plot_dynamics.py script generates two main plots:
-
system_dynamics.png: 6-panel system metrics over time
- Queue states (waiting/running/swapped)
- GPU memory usage
- Memory utilization percentage
- Batch execution times
- Cumulative completions
- Throughput (moving average)
-
request_timeline.png: Gantt-style chart showing:
- Request lifecycles (waiting time in blue, execution in green)
- Swap events marked with "S:n" labels
- Sample of 20 requests for clarity
Create custom request files with specific patterns:
# In Python script or notebook
import csv
requests = [
{"arrival_time": 0.0, "prefill_length": 100, "decode_length": 50},
{"arrival_time": 0.5, "prefill_length": 150, "decode_length": 30},
# ... more requests
]
with open("custom_requests.csv", "w") as f:
writer = csv.DictWriter(f, fieldnames=["arrival_time", "prefill_length", "decode_length"])
writer.writeheader()
writer.writerows(requests)Edit control/advanced_policy.py to implement custom scheduling or preemption strategies.
Use pandas to analyze CSV outputs:
import pandas as pd
# Find the latest experiment directory
import glob
import os
exp_dirs = glob.glob("data/experiments/experiment_*")
latest_exp = max(exp_dirs, key=os.path.getmtime)
# Load and analyze results
traces = pd.read_csv(f"{latest_exp}/request_traces.csv")
print(f"Average latency: {traces['total_delay'].mean():.2f}")
print(f"P95 latency: {traces['total_delay'].quantile(0.95):.2f}")
print(f"Swap rate: {(traces['swap_count'] > 0).mean():.2%}")
print(f"Sacrifice rate: {(traces['sacrifice_count'] > 0).mean():.2%}")fluid_ode_simulation/
├── config/ # Configuration files
│ ├── config.yaml # Main configuration (supports 4 strategy combinations)
│ └── advanced_test.yaml # Test configuration (smaller parameters)
├── core/ # Core data structures
│ ├── request.py # Request class
│ └── system_state.py # System state management
├── simulation/ # Simulation engine
│ ├── vllm_simulator.py # Unified simulator (supports all 4 strategy combinations)
│ └── event_logger.py # Event logging and CSV output
├── control/ # Control policies
│ ├── base_policy.py # Policy base class
│ └── advanced_policy.py # Advanced policy (implements 4 combinations)
├── data/
│ ├── input/ # Input data generation
│ │ └── generate_requests.py
│ └── experiments/ # Experiment results
│ └── experiment_* # Timestamped experiment directories
├── experiments/ # Experiment scripts
│ ├── run_advanced.py # Main run script
│ └── test_all_strategies.py # Test all strategy combinations
├── visualization/ # Plotting tools
│ └── plot_dynamics.py
├── scripts/ # Shell scripts
│ ├── clean.sh # Cleanup script
│ └── manage_experiments.sh # Experiment management tool
└── CLAUDE.md # Detailed technical documentation
-
How to choose strategy combination?
- swap + conservative: Stable load, long requests
- swap + aggressive: Balanced performance, vLLM default
- sacrifice + conservative: Short requests, simple and efficient
- sacrifice + aggressive: Burst load, strict priorities
-
Difference between batch_count and running_count?
batch_count: Actually executed requests (constrained by B)running_count: All requests in GPU memory- Relationship:
batch_count ≤ running_count
-
Memory overflow: Reduce
Bparameter or increaseM_totalin config -
Slow simulation: Reduce number of requests or increase arrival intervals
- For large-scale experiments, disable verbose output
- Use binary search for parameter tuning
- Monitor
data/experiments/*/summary.txtfor quick metrics - Adjust
progress_intervalfor less frequent updates
- CLAUDE.md: Complete technical documentation with ODE equations
- fluid_modeling.tex: Theoretical fluid model derivation
- Related papers: PagedAttention, vLLM, SGLang
This project is for research and educational purposes.