Spaces:
Running
Running
Commit ·
44745f2
1
Parent(s): 20fb354
Commiting v0.3
Browse filesFiles changed (35)
- CHANGELOG.md+33-2
- README.md+158-97
- app.js+613-59
- docs/architecture.md+34-13
- docs/methodology.md+75-31
- docs/research.md+43-13
- docs/validation.md+34-18
- index.html+256-39
- py/inferscale/__init__.py+4-2
- py/inferscale/api.py+10-4
- py/inferscale/diagnostics.py+35-10
- py/inferscale/disaggregated.pyAdded+362
- py/inferscale/kv_cache.py+9-7
- py/inferscale/latency.py+1-1
- py/inferscale/models.py+32
- py/inferscale/optimizer.py+142
- py/inferscale/simulator.py+22-7
- py/inferscale/workloads.py+7-4
- pyproject.toml+1-1
- scripts/release_check.py+54-10
- src/inferscale/__init__.py+4-2
- src/inferscale/api.py+10-4
- src/inferscale/diagnostics.py+35-10
- src/inferscale/disaggregated.pyAdded+362
- src/inferscale/kv_cache.py+9-7
- src/inferscale/latency.py+1-1
- src/inferscale/models.py+32
- src/inferscale/optimizer.py+142
- src/inferscale/simulator.py+22-7
- src/inferscale/workloads.py+7-4
- styles.css+288-12
- tests/test_design_space.pyAdded+41
- tests/test_disaggregated.pyAdded+39
- tests/test_prefix_cache.pyAdded+28
- worker.mjs+1
1234567894 unmodified lines14151617181920# Changelog## v0.2.0- auto-hide runtime header after Pyodide becomes ready; hover/focus at the top edge reveals it- redesigned the interface around a flatter, quieter engineering-dashboard visual system- replaced decorative/non-ASCII ranking glyphs with explicit text labels- added chart expansion with Escape-to-close support- added copy-to-clipboard and CSV export for Scheduler Arena and Capacity Planner tables4 unmodified lines- made capacity feasibility conservative across repetitions: every repetition must meet the target and fully drain- added minimum/mean/maximum repetition evidence to capacity traces- changed the capacity plot to a true linear request-rate x-axis and added worst-repetition evidence- strengthened release checks for browser-module synchronization, package version, provenance, and ASCII-safe UI labels## v0.1.012345678910111213141516171819202122232425262728293031323334353637383940414 unmodified lines464748495051# Changelog## v0.3.0### Research / simulator- added prefill/decode disaggregation with independent accelerator profiles and worker counts- added a genuine event-driven P/D pipeline with overlapping prefill, transfer, and decode activity- added explicit serialized KV-transfer modeling with bandwidth/base-latency controls- added P/D telemetry: role utilization, transfer volume, mean/p95 transfer latency, and transfer utilization- added P/D-specific bottleneck diagnoses for prefill-pool, decode-pool, and KV-transfer pressure- added deterministic shared-prefix reuse with independent cache RNG so enabling cache preserves the workload trace- added shared-prefix KV accounting and saved-prefill-token telemetry- added four-way colocated/P-D x cache-off/on comparison- added bounded design-space exploration and goodput/p95-TTFT Pareto-frontier marking### UI / usability- removed the product-style footer- simplified top branding toward a research-prototype presentation- added explicit Worst repetition and Target columns to Capacity Planner tables/exports- removed area fill from the capacity line chart- changed line-chart legends to line swatches rather than rectangle blocks- added PNG download controls to every chart- added meaningful experiment-aware PNG filenames instead of generic chart names- retained full-screen chart expansion and Escape-to-close behavior- added Modern Serving and Design Explorer sections- added live topology, shared-prefix, P/D worker, and interconnect controls to Serving Lab### Validation- expanded tests to 17 deterministic cases- release check now validates P/D transfer telemetry, design-space output, PNG controls, planner evidence columns, UI ASCII safety, and absence of the old footer## v0.2.0- auto-hide runtime header after Pyodide becomes ready; hover/focus at the top edge reveals it- redesigned the interface around a flatter engineering-dashboard visual system- replaced decorative/non-ASCII ranking glyphs with explicit text labels- added chart expansion with Escape-to-close support- added copy-to-clipboard and CSV export for Scheduler Arena and Capacity Planner tables4 unmodified lines- made capacity feasibility conservative across repetitions: every repetition must meet the target and fully drain- added minimum/mean/maximum repetition evidence to capacity traces- changed the capacity plot to a true linear request-rate x-axis and added worst-repetition evidence## v0.1.0
9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495965 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231242 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052069 unmodified linesshort_description: Interactive LLM serving simulator and SLO planner---# InferScale-Sim v0.2.0**Interactive LLM serving simulator and SLO-aware capacity planner — written in Python, executed entirely in the browser.**InferScale-Sim explores a practical systems question:> How do scheduling, batching, workload shape, KV-cache pressure, and hardware assumptions change tail latency and sustainable LLM-serving capacity?The public Hugging Face Space uses **no server CPU, no GPU, no API key, and no paid inference provider**. Hugging Face serves static files; Pyodide executes the same Python simulator used by the local test suite inside a Web Worker on the visitor's ordinary CPU.> [!IMPORTANT]> v0.2 ships with **analytical reference latency profiles**, not measured GPU calibration data. The simulator is useful for studying serving-system dynamics and relative scheduler behavior, but its absolute latency predictions must not be presented as benchmark measurements. A future calibrated profile bundle can replace the analytical backend without changing the simulator.## Why simulation?Exhaustively testing LLM serving configurations on real GPU clusters is expensive. Microsoft's **Vidur** demonstrated the motivation dramatically: its paper reports finding a LLaMA2-70B deployment configuration in about one CPU-hour where deployment-based exploration was estimated to require **42,000 GPU-hours (~$218K)**. Vidur reported <9% latency-estimation error across its evaluated range.The area has continued moving quickly. InferScale-Sim references the broader line of work including **TokenSim (2025)**, **Revati (2026)**, **LLMServingSim 2.0 (2026)**, and **Frontier (2026)**. Recent systems increasingly model disaggregation, heterogeneous hardware, runtime control logic, memory behavior, and stateful workloads.InferScale-Sim is intentionally narrower: a compact, inspectable Python implementation focused on workload dynamics, scheduling, KV-cache behavior, SLOs, and interactive configuration search.## v0.2 capabilities- deterministic **constant, Poisson, and bursty** arrival processes- log-normal prompt/output-length distributions- **static batching** baseline- **continuous batching** with FCFS- shortest-job-first scheduling- deadline/SLO-aware scheduling- **chunked prefill** interleaved with decode- paged KV-cache accounting and VRAM admission control- analytical roofline-style prefill/decode latency proxy- FP16 / INT8 / INT4 weight-footprint scenarios- TTFT, TPOT, E2E and queue latency distributions- throughput, output-token throughput, **goodput**, and SLO attainment- live queue / decode / KV-cache timeline- scheduler arena using an identical deterministic workload- conservative binary **capacity search** where every repetition must meet the target and drain- repetition min/mean/max SLO evidence for searched rates- simulator-side **bottleneck diagnosis** from queueing, SLO misses, busy fraction, unfinished work, and KV pressure- exposed burst stress controls- copy-to-clipboard and CSV export for Arena / Planner tables- expandable full-screen charts- JSON experiment copy/export- completely client-side Hugging Face deployment via **Pyodide Web Worker**## Architecture```textHugging Face Static Space││ serves files only▼┌─────────────────────────────────────────────────────────────┐│ Browser ││ ││ UI / Chart.js Pyodide Web Worker ││ │ │ ││ │ config │ ││ └──────────────────────────►│ ││ ▼ ││ Python inferscale package ││ │ ││ ┌────────────────────┼──────────────────┐ ││ │ │ │ ││ workload scheduler KV cache ││ │ │ │ ││ └────────────────────┼──────────────────┘ ││ ▼ ││ discrete-event loop ││ │ ││ ▼ ││ metrics / SLO / capacity ││ │ ││ ◄───────────────────────────┘ │└─────────────────────────────────────────────────────────────┘```## Run locallyThe simulator itself has **zero runtime dependencies** beyond Python 3.10+.```bashpython -m venv .venv5 unmodified linespython scripts/release_check.py```Run one simulation from Python:```bashpython scripts/run_simulation.py```Serve the browser app locally:```bashpython -m http.server 8000```Open `http://localhost:8000`. The first page load downloads the Pyodide runtime from its CDN; subsequent simulation runs execute locally in the Web Worker.## Deploy to Hugging FaceCreate a **Static Space**, then push this repository. The root metadata already contains:```yamlsdk: static2 unmodified linesNo Hugging Face secret is required.Before every deployment:```bashpython scripts/sync_web_python.pypython scripts/release_check.pypytest -q````sync_web_python.py` mirrors the canonical `src/inferscale/` package into `py/inferscale/`, which is what Pyodide imports in the deployed application. CI fails if the browser copy is stale.## Core concepts### GoodputRaw throughput alone can reward an overloaded system. InferScale therefore reports:```textgoodput = completed requests satisfying all configured SLOs / simulated makespan```A configuration processing 10 req/s with only 60% SLO attainment can have lower useful capacity than one processing 7 req/s with 99% attainment.### Static vs continuous batchingThe static baseline admits a batch, completes that batch, and only then admits new work. Continuous batching admits new requests as slots become available between decode iterations. This exposes queueing and head-of-line effects under heterogeneous output lengths.### KV-cache modelThe model accounts for K/V state across layers and grouped-query attention heads. Paged configurations round live sequence lengths to configurable token blocks; the static baseline intentionally reserves each admitted request's full prompt + maximum output sequence to expose over-reservation effects.### Latency profile honestyThe default backend estimates operation time from model architecture, accelerator peak FP16 throughput / memory bandwidth, quantization footprint, and conservative efficiency factors. This is a **reference analytical model**, not a substitute for real profiling. Every result carries provenance explicitly identifying this fact.The extension point is `src/inferscale/latency.py`: a later empirical profile interpolator can satisfy the same interface.## Research lineage- **Vidur: A Large-Scale Simulation Framework for LLM Inference** (2024) — simulation + predictive profiling + deployment search. https://arxiv.org/abs/2405.05465- **TokenSim: Enabling Hardware and Software Exploration for Large Language Model Inference Systems** (2025) — extensible scheduling/memory simulation. https://arxiv.org/abs/2503.08415- **Revati: Transparent GPU-Free Time-Warp Emulation for LLM Serving** (2026) — executes real serving control logic while virtualizing GPU time. https://arxiv.org/abs/2601.00397- **LLMServingSim 2.0** (2026) — heterogeneous/disaggregated serving, runtime interaction, memory/power modeling. https://arxiv.org/abs/2602.23036- **Frontier: Towards Comprehensive and Accurate LLM Inference Simulation** (2026) — modern disaggregated serving, runtime optimizations, stateful workloads, and large-scale exploration. https://arxiv.org/abs/2605.21312See [`docs/research.md`](docs/research.md) and [`docs/methodology.md`](docs/methodology.md) for project scope and limitations.## Repository```text.├── src/inferscale/ # canonical Python simulator├── py/inferscale/ # generated browser mirror├── tests/ # deterministic simulation tests├── scripts/ # local runner + release tooling├── docs/ # architecture / methodology / research notes├── index.html # HF Static Space entry point├── app.js # UI + charts├── worker.mjs # Pyodide Web Worker bridge└── styles.css```## Roadmap**v0.2** keeps the single-accelerator serving loop while improving inspectability and planner robustness. It adds bottleneck explanations, repetition-aware capacity evidence, burst controls, copy/CSV tooling, expandable charts, and a restrained engineering-oriented interface.Potential v0.3 extensions, only after v0.2 validation:- empirical calibration profile import- prefill/decode disaggregation + KV transfer- prefix caching- multi-replica routing- request priorities / tenant fairness- trace upload (ShareGPT-style token lengths)- calibration-vs-held-out validation report## License9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451465 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731742 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662679 unmodified linesshort_description: Interactive LLM serving simulator and SLO planner---# InferScale-Sim v0.3.0**Interactive LLM serving simulator and SLO-aware design laboratory - written in Python and executed entirely in the browser.**InferScale-Sim explores a systems question:> How do workload shape, batching, scheduling, KV-cache pressure, reusable prefixes, and prefill/decode disaggregation change tail latency and sustainable LLM-serving capacity?The public Hugging Face Space uses **no server CPU, no GPU, no API key, and no paid inference provider**. Hugging Face serves static files; Pyodide executes the same Python package used by the local test suite inside a Web Worker on the visitor's ordinary CPU.> [!IMPORTANT]> v0.3 ships with **analytical reference latency profiles**, not measured GPU calibration data. It is designed for systems behavior, what-if studies, and comparative exploration. Absolute milliseconds must not be presented as empirical L4/A10G/A100 benchmark results.## Why simulation?Exhaustively testing serving configurations on real GPU clusters is expensive. **Vidur** reported finding a LLaMA2-70B deployment configuration in roughly one CPU-hour while estimating that deployment-based exploration would require about **42,000 GPU-hours (~$218K)**. Its evaluated latency predictions were within 9% error.That research direction has continued. **Revati (2026)** explores GPU-free time-warp emulation of real serving control paths; **LLMServingSim 2.0 (2026)** models heterogeneous and disaggregated serving; **Frontier (May 2026)** models P/D disaggregation, communication, runtime optimizations, stateful workloads, and SLA-dependent Pareto exploration; and **HeteroPanacea (Aug 2026)** studies heterogeneous specialization across prefill/decode/attention/FFN serving stages.InferScale-Sim is deliberately smaller: a dependency-light, inspectable Python implementation intended to make the core serving trade-offs interactive and understandable.## v0.3 capabilities### Workload and serving loop- deterministic constant, Poisson, and bursty arrival processes- log-normal prompt/output-length distributions- static batching baseline- continuous batching with FCFS- shortest-job-first scheduling- least-slack/SLO-aware scheduling- chunked prefill- paged KV-cache accounting and VRAM admission control- analytical roofline-style prefill/decode latency proxy- FP16 / INT8 / INT4 weight-footprint scenarios### Metrics and SLOs- TTFT, TPOT, E2E and queue-latency percentiles- request and output-token throughput- **goodput**: completed requests that satisfy both configured SLOs per simulated second- component TTFT/E2E SLO attainment- virtual resource utilization- peak KV usage- heuristic bottleneck diagnosis with explicit simulator provenance### Prefix reuse - new in v0.3v0.3 adds a controlled shared-prefix scenario:- configurable shared-prefix length- configurable request reuse fraction- deterministic cache-hit assignment independent of the generated workload trace- cached prefill tokens skipped on a hit- one persistent shared KV allocation instead of per-request duplication- cache-hit rate and saved-prefill-token telemetryThis is intentionally **not** a complete RadixAttention implementation. It isolates the compute/memory effect of exact reusable prefixes while keeping the simulator small enough to inspect.### Prefill/decode disaggregation - new in v0.3The simulator now supports a separate P/D topology with:- independent prefill/decode accelerator profiles- configurable prefill and decode worker counts- independent role utilization- continuous decode admission between iterations- explicit KV transfer after prefill- serialized analytical interconnect model- configurable interconnect GB/s and base transfer latency- p95 KV-transfer latency, total transfer volume, and link utilization- P/D-specific bottleneck diagnoses such as prefill-pool, decode-pool, and transfer pressure### Interactive tools**Serving Lab** - run one colocated or P/D scenario and inspect live metrics, timelines, cache behavior, and diagnostics.**Scheduler Arena** - run every colocated scheduler against the identical deterministic workload.**Capacity Planner** - robust binary search for the highest request rate where **every repetition** satisfies the target and drains. The trace exposes mean SLO attainment, worst repetition, target, and min/max range.**Modern Serving Lab** - compare four controlled variants on one workload:1. colocated2. colocated + prefix reuse3. P/D disaggregated4. P/D disaggregated + prefix reuse**Design Explorer** - runs a bounded live sweep over scheduler, batch size, prefix caching, and P/D worker splits, then reports two non-dominated frontiers: **raw goodput vs p95 TTFT** and **goodput per accelerator vs p95 TTFT**. The second view makes the resource cost of multi-worker P/D layouts explicit.All charts can be expanded and exported as meaningfully named PNG files. Result tables support clipboard copy and CSV export.## Architecture```textHugging Face Static Space|| serves files onlyv+----------------------------------------------------------------+| Browser || || UI / Chart.js Pyodide Web Worker || | | || +------------------------------->| || v || Python inferscale package || | || +--------------------------------+-------------------+ || | | | | || workload schedulers KV cache profiles || | | | | || +--------------------+-----------------+-------------+ || | || +--------------------+------------------+ || | | || colocated simulator P/D simulator || | || prefill -> transfer -> decode|| | | || +--------------------+------------------+ || v || metrics / SLO / search |+----------------------------------------------------------------+```The discrete-event engine never sleeps for simulated compute time. A predicted 40 ms decode step advances virtual time by 0.040 seconds immediately.## Run locallyThe Python simulator has **zero runtime dependencies** beyond Python 3.10+.```bashpython -m venv .venv5 unmodified linespython scripts/release_check.py```Run one simulation:```bashpython scripts/run_simulation.py```Serve the browser app:```bashpython -m http.server 8000```Open `http://localhost:8000`. The first page load downloads Pyodide and Chart.js from the CDN; simulation runs then execute locally in the worker.## Deploy to Hugging FaceCreate or reuse a **Static Space** and push this repository. Root metadata already contains:```yamlsdk: static2 unmodified linesNo Hugging Face secret is required.Before deployment:```bashpython scripts/sync_web_python.pypytest -qpython scripts/release_check.py````sync_web_python.py` mirrors the canonical `src/inferscale/` package into `py/inferscale/`, which the Pyodide worker imports. CI fails if the mirror is stale.## Core modeling choices### Goodput```textgoodput = requests satisfying TTFT and E2E SLOs / simulated makespan```Raw throughput can reward overload. Goodput penalizes requests that finish too late to be useful.### KV-cache modelPer-token KV bytes are approximated as:```text2 x layers x KV heads x head dimension x 2 bytes```for K and V with FP16 KV state. Paged allocation rounds live per-request state to configurable token blocks.With prefix reuse enabled, the shared prefix is represented once as persistent KV state and request allocations contain only the uncached suffix plus generated tokens.### P/D transfer modelAfter prefill, newly computed prompt KV is moved to the decode pool through a serialized reference link:```texttransfer_time = base_latency + KV_bytes / interconnect_bandwidth```The link is intentionally simple and explicit. It does not claim to reproduce NCCL, NIXL, RDMA, PCIe, or NVLink behavior.### Latency-profile honesty`AnalyticalLatencyModel` estimates operation duration from model architecture, accelerator peak FP16 compute, memory bandwidth, quantization footprint, context length, and conservative efficiency factors. It is an analytical proxy.A future empirical interpolator can replace that backend without rewriting workload generation, scheduling, KV logic, P/D orchestration, or metrics.## Research lineage- **Vidur: A Large-Scale Simulation Framework for LLM Inference** (MLSys 2024) - profiling + simulation + deployment search. https://arxiv.org/abs/2405.05465- **SGLang: Efficient Execution of Structured Language Model Programs** (NeurIPS 2024) - RadixAttention motivates exact shared-prefix reuse. https://arxiv.org/abs/2312.07104- **TokenSim** (2025) - extensible scheduling and memory-management simulation. https://arxiv.org/abs/2503.08415- **Revati: Transparent GPU-Free Time-Warp Emulation for LLM Serving** (2026) - real control logic with virtualized GPU time. https://arxiv.org/abs/2601.00397- **LLMServingSim 2.0** (2026) - heterogeneous/disaggregated infrastructure and runtime interactions. https://arxiv.org/abs/2602.23036- **Frontier: Towards Comprehensive and Accurate LLM Inference Simulation** (2026) - P/D and Attention-FFN disaggregation, runtime optimizations, stateful workloads, and Pareto exploration. https://arxiv.org/abs/2605.21312- **When Does Disaggregation Pay? / HeteroPanacea** (Aug 2026) - heterogeneous P/D/attention/FFN specialization and cross-stack design exploration. https://arxiv.org/abs/2608.03741See `docs/research.md`, `docs/methodology.md`, and `docs/validation.md` for scope and limitations.## Repository```text.|-- src/inferscale/ canonical Python simulator|-- py/inferscale/ generated browser mirror|-- tests/ deterministic unit tests|-- scripts/ local runner + release tooling|-- docs/ architecture / methodology / research notes|-- index.html HF Static Space entry point|-- app.js UI + charts + export tooling|-- worker.mjs Pyodide Web Worker bridge`-- styles.css```## Roadmapv0.3 deliberately stops short of pretending to be a production-runtime emulator. Strong next steps would be:- empirical latency-profile import and held-out calibration report- multi-turn / agentic session traces- speculative decoding- multi-replica routing and tenant fairness- richer prefix-tree eviction/scheduling- attention/FFN disaggregation## License
12345678910111213141516171819202122234 unmodified lines2829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586const $ = (id) => document.getElementById(id);const runtimePill = $("runtimePill");const runtimeText = $("runtimeText");const charts = {};const pending = new Map();let lastResult = null;let lastArenaRows = [];let lastCapacityTrace = [];let requestId = 0;let toastTimer = null;const COLORS = {blue:"#79a7ff", blue2:"#5d8fe9", steel:"#92a2b5", green:"#69c99a", amber:"#dfb966", grid:"rgba(140,155,175,.14)"};const worker = new Worker("./worker.mjs", {type:"module"});worker.addEventListener("message", (event) => {const data = event.data || {};if (data.type === "ready") {runtimePill.classList.add("ready");runtimeText.textContent = "Python runtime ready";["runBtn","arenaBtn","capacityBtn"].forEach((id) => $(id).disabled = false);window.setTimeout(() => document.body.classList.add("runtime-ready"), 650);return;}4 unmodified linesreturn;}if (!pending.has(data.id)) return;const {resolve,reject} = pending.get(data.id);pending.delete(data.id);data.error ? reject(new Error(data.error)) : resolve(data.result);});function callPython(action,payload){const id=++requestId;return new Promise((resolve,reject)=>{pending.set(id,{resolve,reject});worker.postMessage({id,action,payload});});}function num(id){return Number($(id).value);}function configFromUI(overrides={}){return {model:$("model").value,accelerator:$("accelerator").value,scheduler:$("scheduler").value,quantization:$("quantization").value,arrival_process:$("arrival").value,request_rate_rps:num("rate"),duration_s:num("duration"),prompt_tokens_mean:num("promptMean"),prompt_tokens_cv:num("promptCv"),output_tokens_mean:num("outputMean"),output_tokens_cv:num("outputCv"),max_batch_size:num("maxBatch"),max_batch_tokens:num("maxBatchTokens"),chunk_size:num("chunkSize"),kv_block_tokens:num("kvBlock"),burst_multiplier:num("burstMultiplier"),burst_period_s:num("burstPeriod"),seed:num("seed"),slo_ttft_ms:num("sloTtft"),slo_e2e_ms:num("sloE2e"),slo_attainment_target:.99,...overrides};}function fmt(value,digits=1){if(!Number.isFinite(value))return "N/A";return value.toLocaleString(undefined,{maximumFractionDigits:digits});}function pct(value,digits=1){return `${fmt(value*100,digits)}%`;}function escapeHtml(value){return String(value).replace(/[&<>'"]/g,(c)=>({"&":"&","<":"<",">":">","'":"'",'"':"""})[c]);}function destroyChart(name){if(charts[name]){charts[name].destroy();delete charts[name];}}function showToast(message){const toast=$("toast");toast.textContent=message;toast.classList.add("show");if(toastTimer)clearTimeout(toastTimer);toastTimer=setTimeout(()=>toast.classList.remove("show"),1800);}async function copyText(text,message){try{await navigator.clipboard.writeText(text);showToast(message);}catch{const area=document.createElement("textarea");area.value=text;area.style.position="fixed";area.style.opacity="0";document.body.appendChild(area);area.select();document.execCommand("copy");area.remove();showToast(message);}}function csvCell(value){const text=String(value??"");return /[",\n]/.test(text)?`"${text.replaceAll('"','""')}"`:text;}function tableText(headers,rows,separator="\t"){return [headers,...rows].map((row)=>row.join(separator)).join("\n");}function downloadCsv(filename,headers,rows){const csv=[headers,...rows].map((row)=>row.map(csvCell).join(",")).join("\n");const blob=new Blob([csv],{type:"text/csv;charset=utf-8"});const url=URL.createObjectURL(blob);const a=document.createElement("a");a.href=url;a.download=filename;a.click();URL.revokeObjectURL(url);}Chart.defaults.color="#929dab";Chart.defaults.borderColor=COLORS.grid;Chart.defaults.font.family=getComputedStyle(document.body).fontFamily;Chart.defaults.animation.duration=180;function commonChartOptions(){return {responsive:true,maintainAspectRatio:false,plugins:{legend:{labels:{boxWidth:12,boxHeight:8}}}};}function renderSimulation(result){lastResult=result;$("emptyState").classList.add("hidden");$("resultContent").classList.remove("hidden");$("exportBtn").disabled=false;$("copyResultBtn").disabled=false;const s=result.summary,l=result.latency,r=result.resource,d=result.diagnostics||{};$("mTtft").textContent=`${fmt(l.ttft_ms.p95)} ms`;$("mE2e").textContent=`${fmt(l.e2e_ms.p95)} ms`;$("mGoodput").textContent=`${fmt(s.goodput_rps,2)} req/s`;$("mSlo").textContent=pct(s.slo_attainment);$("mReq").textContent=`${fmt(s.request_throughput_rps,2)} req/s`;$("mKv").textContent=`${fmt(r.peak_kv_gb,2)} GB`;const tag=$("runState");tag.textContent=`${s.requests_completed}/${s.requests_generated} completed`;tag.className=`tag ${s.slo_attainment>=.99&&s.requests_unfinished===0?"good":"bad"}`;$("mBottleneck").textContent=d.label||"N/A";$("mDiagnosis").textContent=d.explanation||"No simulator diagnosis available.";$("mRecommendation").textContent=d.recommendation?`Next check: ${d.recommendation}`:"";const e=d.evidence||{};$("mEvidence").innerHTML=[`busy ${pct(e.busy_fraction??s.busy_fraction)}`,`KV ${pct(e.peak_kv_utilization??r.peak_kv_utilization)}`,`TTFT pass ${pct(e.ttft_slo_attainment??s.ttft_slo_attainment)}`,`E2E pass ${pct(e.e2e_slo_attainment??s.e2e_slo_attainment)}`,`queue p95 ${fmt(e.queue_p95_ms??l.queue_ms.p95)} ms`,`target 99%`].map((x)=>`<span>${escapeHtml(x)}</span>`).join("");destroyChart("latency");charts.latency=new Chart($("latencyChart"),{type:"bar",data:{labels:["TTFT p50","TTFT p95","E2E p50","E2E p95","Queue p95"],datasets:[{label:"Milliseconds",data:[l.ttft_ms.p50,l.ttft_ms.p95,l.e2e_ms.p50,l.e2e_ms.p95,l.queue_ms.p95],backgroundColor:[COLORS.steel,COLORS.blue,"#8196b1",COLORS.blue2,COLORS.amber]}]},options:{...commonChartOptions(),plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}});const timeline=result.timeline||[];destroyChart("timeline");charts.timeline=new Chart($("timelineChart"),{type:"line",data:{datasets:[{label:"Waiting",data:timeline.map((x)=>({x:x.time_s,y:x.waiting})),borderColor:COLORS.amber,pointRadius:0,tension:.08,yAxisID:"y"},{label:"Decoding",data:timeline.map((x)=>({x:x.time_s,y:x.decoding})),borderColor:COLORS.blue,pointRadius:0,tension:.08,yAxisID:"y"},{label:"KV GB",data:timeline.map((x)=>({x:x.time_s,y:x.kv_used_gb})),borderColor:COLORS.green,pointRadius:0,tension:.08,yAxisID:"y1"}]},options:{...commonChartOptions(),parsing:false,interaction:{mode:"nearest",intersect:false},scales:{x:{type:"linear",title:{display:true,text:"Virtual time (s)"}},y:{beginAtZero:true,title:{display:true,text:"Requests"}},y1:{beginAtZero:true,position:"right",grid:{drawOnChartArea:false},title:{display:true,text:"KV GB"}}}}});const sample=result.requests||[];destroyChart("scatter");charts.scatter=new Chart($("scatterChart"),{type:"scatter",data:{datasets:[{label:"Requests",data:sample.map((x)=>({x:x.prompt_tokens,y:x.ttft_ms})),backgroundColor:"rgba(121,167,255,.52)",pointRadius:2.2}]},options:{...commonChartOptions(),plugins:{legend:{display:false}},scales:{x:{title:{display:true,text:"Prompt tokens"}},y:{title:{display:true,text:"TTFT (ms)"},beginAtZero:true}}}});const warnings=$("warnings"),all=[...(result.warnings||[])];if(result.provenance?.profile_warning)all.unshift(result.provenance.profile_warning);if(all.length){warnings.innerHTML=all.map((w)=>`<div>${escapeHtml(w)}</div>`).join("");warnings.classList.remove("hidden");}else warnings.classList.add("hidden");}$("runBtn").addEventListener("click",async()=>{const b=$("runBtn"),s=$("runState");b.disabled=true;b.textContent="Running simulation...";s.textContent="Simulating...";s.className="tag neutral";try{renderSimulation(await callPython("simulate",configFromUI()));}catch(e){s.textContent="Error";s.className="tag bad";alert(`Simulation failed: ${e.message}`);}finally{b.textContent="Run simulation";b.disabled=false;}});$("copyResultBtn").addEventListener("click",()=>{if(lastResult)copyText(JSON.stringify(lastResult,null,2),"Result JSON copied");});$("exportBtn").addEventListener("click",()=>{if(!lastResult)return;const blob=new Blob([JSON.stringify(lastResult,null,2)],{type:"application/json"});const url=URL.createObjectURL(blob);const a=document.createElement("a");a.href=url;a.download=`inferscale-run-${Date.now()}.json`;a.click();URL.revokeObjectURL(url);});function schedulerLabel(s){return ({static_fcfs:"Static FCFS",continuous_fcfs:"Continuous FCFS",continuous_sjf:"Continuous SJF",continuous_slo:"Continuous SLO",chunked_slo:"Chunked SLO"})[s]||s;}$("arenaBtn").addEventListener("click",async()=>{const b=$("arenaBtn");b.disabled=true;b.textContent="Comparing...";try{renderArena((await callPython("compare",{config:configFromUI()})).rows);}catch(e){alert(`Scheduler comparison failed: ${e.message}`);}finally{b.disabled=false;b.textContent="Compare schedulers";}});function arenaTableRows(rows){return rows.map((r)=>[schedulerLabel(r.scheduler),`${fmt(r.goodput_rps,2)} req/s`,pct(r.slo_attainment),`${fmt(r.p95_ttft_ms)} ms`,`${fmt(r.p95_e2e_ms)} ms`,pct(r.peak_kv_utilization),fmt(r.unfinished,0),r.bottleneck||"N/A"]);}function renderArena(rows){lastArenaRows=rows;$("arenaEmpty").classList.add("hidden");$("arenaContent").classList.remove("hidden");$("arenaCopyBtn").disabled=false;$("arenaCsvBtn").disabled=false;$("arenaRows").innerHTML=rows.map((r,i)=>`<tr><td>${escapeHtml(schedulerLabel(r.scheduler))}${i===0?'<span class="best-label">Best</span>':""}</td><td>${fmt(r.goodput_rps,2)} req/s</td><td>${pct(r.slo_attainment)}</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td><td>${pct(r.peak_kv_utilization)}</td><td>${fmt(r.unfinished,0)}</td><td>${escapeHtml(r.bottleneck||"N/A")}</td></tr>`).join("");destroyChart("arena");charts.arena=new Chart($("arenaChart"),{type:"bar",data:{labels:rows.map((r)=>schedulerLabel(r.scheduler)),datasets:[{label:"Goodput (req/s)",data:rows.map((r)=>r.goodput_rps),backgroundColor:COLORS.blue},{label:"Raw throughput (req/s)",data:rows.map((r)=>r.request_throughput_rps),backgroundColor:"#53677f"}]},options:{...commonChartOptions(),scales:{y:{beginAtZero:true}}}});}const arenaHeaders=["Scheduler","Goodput","SLO attainment","p95 TTFT","p95 E2E","KV peak","Unfinished","Diagnosis"];$("arenaCopyBtn").addEventListener("click",()=>copyText(tableText(arenaHeaders,arenaTableRows(lastArenaRows)),"Scheduler table copied"));$("arenaCsvBtn").addEventListener("click",()=>downloadCsv("inferscale-scheduler-arena.csv",arenaHeaders,arenaTableRows(lastArenaRows)));$("capacityBtn").addEventListener("click",async()=>{const b=$("capacityBtn"),s=$("plannerState");b.disabled=true;b.textContent="Searching...";s.textContent="Running simulations...";s.className="tag neutral";try{renderCapacity(await callPython("capacity",{config:configFromUI({slo_attainment_target:num("targetSlo")}),min_rate:num("minRate"),max_rate:num("maxRate"),iterations:num("searchIter"),repetitions:num("repetitions"),headroom:num("headroom")}));}catch(e){s.textContent="Error";s.className="tag bad";alert(`Capacity search failed: ${e.message}`);}finally{b.disabled=false;b.textContent="Find sustainable capacity";}});function capacityTableRows(trace){return trace.map((r)=>[`${fmt(r.rate_rps,2)} req/s`,r.passed?"PASS":"FAIL",pct(r.slo_attainment),`${pct(r.slo_attainment_min)} - ${pct(r.slo_attainment_max)}`,`${fmt(r.goodput_rps,2)} req/s`,`${fmt(r.p95_ttft_ms)} ms`,`${fmt(r.p95_e2e_ms)} ms`]);}function renderCapacity(result){lastCapacityTrace=result.trace||[];$("plannerEmpty").classList.add("hidden");$("plannerContent").classList.remove("hidden");$("capacityCopyBtn").disabled=false;$("capacityCsvBtn").disabled=false;$("pCapacity").textContent=`${fmt(result.capacity_rps,2)} req/s`;$("pRecommended").textContent=`${fmt(result.recommended_rps,2)} req/s`;$("pHeadroom").textContent=pct(result.headroom??num("headroom"));$("pStatus").textContent=result.status.replaceAll("_"," ");const state=$("plannerState");state.textContent=result.status==="ok"?"Search complete":result.status.replaceAll("_"," ");state.className=`tag ${result.capacity_rps>0?"good":"bad"}`;$("capacityRows").innerHTML=lastCapacityTrace.map((r)=>`<tr><td>${fmt(r.rate_rps,2)} req/s</td><td class="${r.passed?"pass":"fail"}">${r.passed?"PASS":"FAIL"}</td><td>${pct(r.slo_attainment)}</td><td>${pct(r.slo_attainment_min)} - ${pct(r.slo_attainment_max)}</td><td>${fmt(r.goodput_rps,2)} req/s</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td></tr>`).join("");const target=num("targetSlo"),mean=lastCapacityTrace.map((r)=>({x:r.rate_rps,y:r.slo_attainment})),worst=lastCapacityTrace.map((r)=>({x:r.rate_rps,y:r.slo_attainment_min})),xs=lastCapacityTrace.map((r)=>r.rate_rps),minX=Math.min(...xs),maxX=Math.max(...xs);destroyChart("capacity");charts.capacity=new Chart($("capacityChart"),{type:"line",data:{datasets:[{label:"Mean SLO attainment",data:mean,borderColor:COLORS.blue,backgroundColor:"rgba(121,167,255,.10)",fill:true,tension:.08,pointRadius:3},{label:"Worst repetition",data:worst,borderColor:COLORS.amber,borderDash:[5,4],pointRadius:2,tension:.08},{label:"Target",data:[{x:minX,y:target},{x:maxX,y:target}],borderColor:COLORS.green,borderDash:[6,5],pointRadius:0}]},options:{...commonChartOptions(),parsing:false,scales:{x:{type:"linear",title:{display:true,text:"Offered load (req/s)"},ticks:{maxTicksLimit:8}},y:{min:0,max:1,ticks:{callback:(v)=>`${Math.round(v*100)}%`}}}}});}const capacityHeaders=["Rate","Pass","Mean SLO","SLO range","Goodput","p95 TTFT","p95 E2E"];$("capacityCopyBtn").addEventListener("click",()=>copyText(tableText(capacityHeaders,capacityTableRows(lastCapacityTrace)),"Capacity table copied"));$("capacityCsvBtn").addEventListener("click",()=>downloadCsv("inferscale-capacity-trace.csv",capacityHeaders,capacityTableRows(lastCapacityTrace)));$("arrival").addEventListener("change",()=>$("burstControls").classList.toggle("hidden",$("arrival").value!=="bursty"));for(const tab of document.querySelectorAll(".tab")){tab.addEventListener("click",()=>{document.querySelectorAll(".tab").forEach((t)=>t.classList.remove("active"));document.querySelectorAll(".tab-panel").forEach((p)=>p.classList.remove("active"));tab.classList.add("active");$(tab.dataset.tab).classList.add("active");setTimeout(()=>Object.values(charts).forEach((chart)=>chart.resize()),20);});}function closeExpandedChart(){const card=document.querySelector(".chart-card.chart-expanded");if(!card)return;card.classList.remove("chart-expanded");const b=card.querySelector(".chart-expand");if(b)b.textContent="Expand";document.body.classList.remove("chart-open");setTimeout(()=>Chart.getChart(card.querySelector("canvas"))?.resize(),20);}for(const b of document.querySelectorAll(".chart-expand")){b.addEventListener("click",()=>{const card=b.closest(".chart-card"),was=card.classList.contains("chart-expanded");closeExpandedChart();if(!was){card.classList.add("chart-expanded");b.textContent="Close";document.body.classList.add("chart-open");setTimeout(()=>Chart.getChart(card.querySelector("canvas"))?.resize(),20);}});}document.addEventListener("keydown",(e)=>{if(e.key==="Escape")closeExpandedChart();});12345678910111213141516171819202122232425262728293031323334354 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640const $ = (id) => document.getElementById(id);const charts = {};const pending = new Map();let requestId = 0;let toastTimer = null;let lastResult = null;let lastArenaRows = [];let lastCapacityTrace = [];let lastTopologyRows = [];let lastDesignRows = [];const COLORS = {blue: "#79a7ff",blue2: "#5d8fe9",steel: "#92a2b5",green: "#69c99a",amber: "#dfb966",red: "#df7d89",gray: "#667384",grid: "rgba(140,155,175,.14)",};const runtimePill = $("runtimePill");const runtimeText = $("runtimeText");const worker = new Worker("./worker.mjs", { type: "module" });worker.addEventListener("message", (event) => {const data = event.data || {};if (data.type === "ready") {runtimePill.classList.add("ready");runtimeText.textContent = "Python runtime ready";["runBtn", "arenaBtn", "capacityBtn", "topologyBtn", "designBtn"].forEach((id) => { $(id).disabled = false; });window.setTimeout(() => document.body.classList.add("runtime-ready"), 650);return;}4 unmodified linesreturn;}if (!pending.has(data.id)) return;const { resolve, reject } = pending.get(data.id);pending.delete(data.id);data.error ? reject(new Error(data.error)) : resolve(data.result);});function callPython(action, payload) {const id = ++requestId;return new Promise((resolve, reject) => {pending.set(id, { resolve, reject });worker.postMessage({ id, action, payload });});}function num(id) { return Number($(id).value); }function boolSelect(id) { return $(id).value === "on"; }function configFromUI(overrides = {}) {return {model: $("model").value,accelerator: $("accelerator").value,prefill_accelerator: $("prefillAccelerator").value,decode_accelerator: $("decodeAccelerator").value,prefill_workers: num("prefillWorkers"),decode_workers: num("decodeWorkers"),interconnect_gbps: num("interconnect"),transfer_base_ms: num("transferBase"),topology: $("topology").value,scheduler: $("scheduler").value,quantization: $("quantization").value,prefix_cache_enabled: boolSelect("prefixCache"),shared_prefix_tokens: num("sharedPrefix"),prefix_reuse_fraction: num("prefixReuse"),arrival_process: $("arrival").value,request_rate_rps: num("rate"),duration_s: num("duration"),prompt_tokens_mean: num("promptMean"),prompt_tokens_cv: num("promptCv"),output_tokens_mean: num("outputMean"),output_tokens_cv: num("outputCv"),max_batch_size: num("maxBatch"),max_batch_tokens: num("maxBatchTokens"),chunk_size: num("chunkSize"),kv_block_tokens: num("kvBlock"),burst_multiplier: num("burstMultiplier"),burst_period_s: num("burstPeriod"),seed: num("seed"),slo_ttft_ms: num("sloTtft"),slo_e2e_ms: num("sloE2e"),slo_attainment_target: 0.99,...overrides,};}function fmt(value, digits = 1) {if (!Number.isFinite(value)) return "N/A";return value.toLocaleString(undefined, { maximumFractionDigits: digits });}function pct(value, digits = 1) { return `${fmt(value * 100, digits)}%`; }function escapeHtml(value) {return String(value).replace(/[&<>'"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", "'": "'", '"': """ })[c]);}function slug(value) {return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");}function stamp() {const d = new Date();const pad = (v) => String(v).padStart(2, "0");return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;}function showToast(message) {const toast = $("toast");toast.textContent = message;toast.classList.add("show");if (toastTimer) clearTimeout(toastTimer);toastTimer = setTimeout(() => toast.classList.remove("show"), 1800);}async function copyText(text, message) {try {await navigator.clipboard.writeText(text);showToast(message);} catch {const area = document.createElement("textarea");area.value = text;area.style.position = "fixed";area.style.opacity = "0";document.body.appendChild(area);area.select();document.execCommand("copy");area.remove();showToast(message);}}function csvCell(value) {const text = String(value ?? "");return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;}function tableText(headers, rows, separator = "\t") {return [headers, ...rows].map((row) => row.join(separator)).join("\n");}function downloadCsv(filename, headers, rows) {const csv = [headers, ...rows].map((row) => row.map(csvCell).join(",")).join("\n");const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });const url = URL.createObjectURL(blob);const a = document.createElement("a");a.href = url;a.download = filename;a.click();URL.revokeObjectURL(url);}function downloadJson(result) {const cfg = result.config || configFromUI();const topology = cfg.topology === "disaggregated_pd" ? `pd-${cfg.prefill_workers}p-${cfg.decode_workers}d` : `colocated-${cfg.accelerator}`;const name = `inferscale-run_${slug(cfg.model)}_${slug(topology)}_${slug(cfg.scheduler)}_${stamp()}.json`;const blob = new Blob([JSON.stringify(result, null, 2)], { type: "application/json" });const url = URL.createObjectURL(blob);const a = document.createElement("a");a.href = url;a.download = name;a.click();URL.revokeObjectURL(url);}Chart.defaults.color = "#929dab";Chart.defaults.borderColor = COLORS.grid;Chart.defaults.font.family = getComputedStyle(document.body).fontFamily;Chart.defaults.animation.duration = 160;function commonChartOptions() {return { responsive: true, maintainAspectRatio: false };}function lineLegend() {return {labels: {usePointStyle: true,pointStyle: "line",pointStyleWidth: 26,boxWidth: 26,boxHeight: 2,padding: 14,},};}function pointLegend() {return {labels: {usePointStyle: true,pointStyle: "circle",boxWidth: 8,boxHeight: 8,padding: 14,},};}function destroyChart(name) {if (charts[name]) {charts[name].destroy();delete charts[name];}}function chartFileName(card) {const cfg = configFromUI();const chartName = card.dataset.chartName || "figure";const topology = cfg.topology === "disaggregated_pd"? `pd-${cfg.prefill_workers}p-${cfg.decode_workers}d-${cfg.prefill_accelerator}-${cfg.decode_accelerator}`: `colocated-${cfg.accelerator}`;return `inferscale_${slug(chartName)}_${slug(cfg.model)}_${slug(topology)}_${slug(cfg.scheduler)}_${stamp()}.png`;}function downloadChart(card) {const canvas = card.querySelector("canvas");const chart = Chart.getChart(canvas);if (!chart) return;const exportCanvas = document.createElement("canvas");exportCanvas.width = canvas.width;exportCanvas.height = canvas.height;const ctx = exportCanvas.getContext("2d");ctx.fillStyle = "#0a0f15";ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);ctx.drawImage(canvas, 0, 0);exportCanvas.toBlob((blob) => {if (!blob) return;const url = URL.createObjectURL(blob);const a = document.createElement("a");a.href = url;a.download = chartFileName(card);a.click();URL.revokeObjectURL(url);showToast("Chart PNG downloaded");}, "image/png");}function renderSimulation(result) {lastResult = result;$("emptyState").classList.add("hidden");$("resultContent").classList.remove("hidden");$("exportBtn").disabled = false;$("copyResultBtn").disabled = false;const s = result.summary;const l = result.latency;const r = result.resource;const d = result.diagnostics || {};$("mTtft").textContent = `${fmt(l.ttft_ms.p95)} ms`;$("mE2e").textContent = `${fmt(l.e2e_ms.p95)} ms`;$("mGoodput").textContent = `${fmt(s.goodput_rps, 2)} req/s`;$("mSlo").textContent = pct(s.slo_attainment);$("mReq").textContent = `${fmt(s.request_throughput_rps, 2)} req/s`;$("mKv").textContent = `${fmt(r.peak_kv_gb, 2)} GB`;const tag = $("runState");tag.textContent = `${s.requests_completed}/${s.requests_generated} completed`;tag.className = `tag ${s.slo_attainment >= .99 && s.requests_unfinished === 0 ? "good" : "bad"}`;$("mBottleneck").textContent = d.label || "N/A";$("mDiagnosis").textContent = d.explanation || "No simulator diagnosis available.";$("mRecommendation").textContent = d.recommendation ? `Next check: ${d.recommendation}` : "";const e = d.evidence || {};const evidence = [`topology ${r.topology || result.config.topology || "colocated"}`,`busy ${pct(e.busy_fraction ?? s.busy_fraction)}`,`KV ${pct(e.peak_kv_utilization ?? r.peak_kv_utilization)}`,`TTFT pass ${pct(e.ttft_slo_attainment ?? s.ttft_slo_attainment)}`,`E2E pass ${pct(e.e2e_slo_attainment ?? s.e2e_slo_attainment)}`,`queue p95 ${fmt(e.queue_p95_ms ?? l.queue_ms.p95)} ms`,];if ((r.prefix_cache_hit_rate ?? 0) > 0) evidence.push(`cache hit ${pct(r.prefix_cache_hit_rate)}`, `prefill saved ${fmt(r.prefill_tokens_saved, 0)} tok`);if (r.topology === "disaggregated_pd") evidence.push(`prefill busy ${pct(r.prefill_busy_fraction)}`,`decode busy ${pct(r.decode_busy_fraction)}`,`link busy ${pct(r.transfer_busy_fraction)}`,`transfer p95 ${fmt(r.p95_transfer_ms, 2)} ms`,);$("mEvidence").innerHTML = evidence.map((x) => `<span>${escapeHtml(x)}</span>`).join("");destroyChart("latency");charts.latency = new Chart($("latencyChart"), {type: "bar",data: {labels: ["TTFT p50", "TTFT p95", "E2E p50", "E2E p95", "Queue p95"],datasets: [{label: "Milliseconds",data: [l.ttft_ms.p50, l.ttft_ms.p95, l.e2e_ms.p50, l.e2e_ms.p95, l.queue_ms.p95],backgroundColor: [COLORS.steel, COLORS.blue, "#8196b1", COLORS.blue2, COLORS.amber],}],},options: { ...commonChartOptions(), plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } },});const timeline = result.timeline || [];const lineDatasets = [{ label: r.topology === "disaggregated_pd" ? "Prefill queue" : "Waiting", data: timeline.map((x) => ({ x: x.time_s, y: x.waiting })), borderColor: COLORS.amber, pointRadius: 0, tension: .08, yAxisID: "y" },{ label: "Decoding", data: timeline.map((x) => ({ x: x.time_s, y: x.decoding })), borderColor: COLORS.blue, pointRadius: 0, tension: .08, yAxisID: "y" },{ label: "KV GB", data: timeline.map((x) => ({ x: x.time_s, y: x.kv_used_gb })), borderColor: COLORS.green, pointRadius: 0, tension: .08, yAxisID: "y1" },];if (r.topology === "disaggregated_pd") {lineDatasets.splice(1, 0, { label: "Decode queue", data: timeline.map((x) => ({ x: x.time_s, y: x.decode_ready || 0 })), borderColor: COLORS.steel, borderDash: [4, 3], pointRadius: 0, tension: .08, yAxisID: "y" });}destroyChart("timeline");charts.timeline = new Chart($("timelineChart"), {type: "line",data: { datasets: lineDatasets },options: {...commonChartOptions(),parsing: false,interaction: { mode: "nearest", intersect: false },plugins: { legend: lineLegend() },scales: {x: { type: "linear", title: { display: true, text: "Virtual time (s)" } },y: { beginAtZero: true, title: { display: true, text: "Requests" } },y1: { beginAtZero: true, position: "right", grid: { drawOnChartArea: false }, title: { display: true, text: "KV GB" } },},},});const sample = result.requests || [];destroyChart("scatter");charts.scatter = new Chart($("scatterChart"), {type: "scatter",data: { datasets: [{ label: "Requests", data: sample.map((x) => ({ x: x.prompt_tokens, y: x.ttft_ms })), backgroundColor: "rgba(121,167,255,.55)", pointRadius: 2.2 }] },options: { ...commonChartOptions(), plugins: { legend: { display: false } }, scales: { x: { title: { display: true, text: "Prompt tokens" } }, y: { title: { display: true, text: "TTFT (ms)" }, beginAtZero: true } } },});const warnings = $("warnings");const allWarnings = [...(result.warnings || [])];if (result.provenance?.profile_warning) allWarnings.unshift(result.provenance.profile_warning);if (allWarnings.length) {warnings.innerHTML = allWarnings.map((w) => `<div>${escapeHtml(w)}</div>`).join("");warnings.classList.remove("hidden");} else {warnings.classList.add("hidden");}}$("runBtn").addEventListener("click", async () => {const button = $("runBtn");const state = $("runState");button.disabled = true;button.textContent = "Running simulation...";state.textContent = "Simulating...";state.className = "tag neutral";try {renderSimulation(await callPython("simulate", configFromUI()));} catch (error) {state.textContent = "Error";state.className = "tag bad";alert(`Simulation failed: ${error.message}`);} finally {button.textContent = "Run simulation";button.disabled = false;}});$("copyResultBtn").addEventListener("click", () => { if (lastResult) copyText(JSON.stringify(lastResult, null, 2), "Result JSON copied"); });$("exportBtn").addEventListener("click", () => { if (lastResult) downloadJson(lastResult); });function schedulerLabel(value) {return ({static_fcfs: "Static FCFS",continuous_fcfs: "Continuous FCFS",continuous_sjf: "Continuous SJF",continuous_slo: "Continuous SLO",chunked_slo: "Chunked SLO",})[value] || value;}function arenaTableRows(rows) {return rows.map((r) => [schedulerLabel(r.scheduler), `${fmt(r.goodput_rps, 2)} req/s`, pct(r.slo_attainment), `${fmt(r.p95_ttft_ms)} ms`, `${fmt(r.p95_e2e_ms)} ms`, pct(r.peak_kv_utilization), fmt(r.unfinished, 0), r.bottleneck || "N/A"]);}function renderArena(rows) {lastArenaRows = rows;$("arenaEmpty").classList.add("hidden");$("arenaContent").classList.remove("hidden");$("arenaCopyBtn").disabled = false;$("arenaCsvBtn").disabled = false;$("arenaRows").innerHTML = rows.map((r, index) => `<tr><td>${escapeHtml(schedulerLabel(r.scheduler))}${index === 0 ? '<span class="best-label">Best</span>' : ""}</td><td>${fmt(r.goodput_rps, 2)} req/s</td><td>${fmt(r.goodput_per_accelerator, 2)} req/s/GPU</td><td>${pct(r.slo_attainment)}</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td><td>${pct(r.peak_kv_utilization)}</td><td>${fmt(r.unfinished, 0)}</td><td>${escapeHtml(r.bottleneck || "N/A")}</td></tr>`).join("");destroyChart("arena");charts.arena = new Chart($("arenaChart"), {type: "bar",data: { labels: rows.map((r) => schedulerLabel(r.scheduler)), datasets: [{ label: "Goodput (req/s)", data: rows.map((r) => r.goodput_rps), backgroundColor: COLORS.blue }, { label: "Raw throughput (req/s)", data: rows.map((r) => r.request_throughput_rps), backgroundColor: "#53677f" }] },options: { ...commonChartOptions(), scales: { y: { beginAtZero: true } } },});}$("arenaBtn").addEventListener("click", async () => {const button = $("arenaBtn");button.disabled = true;button.textContent = "Comparing...";try { renderArena((await callPython("compare", { config: configFromUI() })).rows); }catch (error) { alert(`Scheduler comparison failed: ${error.message}`); }finally { button.disabled = false; button.textContent = "Compare schedulers"; }});const arenaHeaders = ["Scheduler", "Goodput", "SLO attainment", "p95 TTFT", "p95 E2E", "KV peak", "Unfinished", "Diagnosis"];$("arenaCopyBtn").addEventListener("click", () => copyText(tableText(arenaHeaders, arenaTableRows(lastArenaRows)), "Scheduler table copied"));$("arenaCsvBtn").addEventListener("click", () => downloadCsv(`inferscale_scheduler-arena_${stamp()}.csv`, arenaHeaders, arenaTableRows(lastArenaRows)));function capacityTableRows(trace) {return trace.map((r) => [`${fmt(r.rate_rps, 2)} req/s`,r.passed ? "PASS" : "FAIL",pct(r.slo_attainment),pct(r.slo_attainment_min),pct(r.target ?? num("targetSlo")),`${pct(r.slo_attainment_min)} - ${pct(r.slo_attainment_max)}`,`${fmt(r.goodput_rps, 2)} req/s`,`${fmt(r.p95_ttft_ms)} ms`,`${fmt(r.p95_e2e_ms)} ms`,]);}function renderCapacity(result) {lastCapacityTrace = result.trace || [];$("plannerEmpty").classList.add("hidden");$("plannerContent").classList.remove("hidden");$("capacityCopyBtn").disabled = false;$("capacityCsvBtn").disabled = false;$("pCapacity").textContent = `${fmt(result.capacity_rps, 2)} req/s`;$("pRecommended").textContent = `${fmt(result.recommended_rps, 2)} req/s`;$("pHeadroom").textContent = pct(result.headroom ?? num("headroom"));$("pStatus").textContent = result.status.replaceAll("_", " ");const state = $("plannerState");state.textContent = result.status === "ok" ? "Search complete" : result.status.replaceAll("_", " ");state.className = `tag ${result.capacity_rps > 0 ? "good" : "bad"}`;$("capacityRows").innerHTML = lastCapacityTrace.map((r) => `<tr><td>${fmt(r.rate_rps, 2)} req/s</td><td class="${r.passed ? "pass" : "fail"}">${r.passed ? "PASS" : "FAIL"}</td><td>${pct(r.slo_attainment)}</td><td>${pct(r.slo_attainment_min)}</td><td>${pct(r.target ?? num("targetSlo"))}</td><td>${pct(r.slo_attainment_min)} - ${pct(r.slo_attainment_max)}</td><td>${fmt(r.goodput_rps, 2)} req/s</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td></tr>`).join("");if (!lastCapacityTrace.length) return;const target = num("targetSlo");const mean = lastCapacityTrace.map((r) => ({ x: r.rate_rps, y: r.slo_attainment }));const worst = lastCapacityTrace.map((r) => ({ x: r.rate_rps, y: r.slo_attainment_min }));const xs = lastCapacityTrace.map((r) => r.rate_rps);const minX = Math.min(...xs);const maxX = Math.max(...xs);destroyChart("capacity");charts.capacity = new Chart($("capacityChart"), {type: "line",data: { datasets: [{ label: "Mean SLO attainment", data: mean, borderColor: COLORS.blue, backgroundColor: COLORS.blue, fill: false, tension: .06, pointRadius: 3 },{ label: "Worst repetition", data: worst, borderColor: COLORS.amber, backgroundColor: COLORS.amber, borderDash: [5, 4], fill: false, pointRadius: 2, tension: .06 },{ label: "Target", data: [{ x: minX, y: target }, { x: maxX, y: target }], borderColor: COLORS.green, backgroundColor: COLORS.green, borderDash: [6, 5], fill: false, pointRadius: 0 },] },options: { ...commonChartOptions(), parsing: false, plugins: { legend: lineLegend() }, scales: { x: { type: "linear", title: { display: true, text: "Offered load (req/s)" }, ticks: { maxTicksLimit: 8 } }, y: { min: 0, max: 1, ticks: { callback: (v) => `${Math.round(v * 100)}%` } } } },});}$("capacityBtn").addEventListener("click", async () => {const button = $("capacityBtn");const state = $("plannerState");button.disabled = true;button.textContent = "Searching...";state.textContent = "Running simulations...";state.className = "tag neutral";try {renderCapacity(await callPython("capacity", {config: configFromUI({ slo_attainment_target: num("targetSlo") }),min_rate: num("minRate"),max_rate: num("maxRate"),iterations: num("searchIter"),repetitions: num("repetitions"),headroom: num("headroom"),}));} catch (error) {state.textContent = "Error";state.className = "tag bad";alert(`Capacity search failed: ${error.message}`);} finally {button.disabled = false;button.textContent = "Find sustainable capacity";}});const capacityHeaders = ["Rate", "Pass", "Mean SLO", "Worst repetition", "Target", "SLO range", "Goodput", "p95 TTFT", "p95 E2E"];$("capacityCopyBtn").addEventListener("click", () => copyText(tableText(capacityHeaders, capacityTableRows(lastCapacityTrace)), "Capacity table copied"));$("capacityCsvBtn").addEventListener("click", () => downloadCsv(`inferscale_capacity-trace_${stamp()}.csv`, capacityHeaders, capacityTableRows(lastCapacityTrace)));function scenarioLabel(value) {return ({colocated: "Colocated",colocated_cache: "Colocated + prefix cache",disaggregated_pd: "P/D disaggregated",disaggregated_pd_cache: "P/D + prefix cache",})[value] || value;}function topologyTableRows(rows) {return rows.map((r) => [scenarioLabel(r.scenario),fmt(r.accelerator_instances, 0),`${fmt(r.goodput_rps, 2)} req/s`,`${fmt(r.goodput_per_accelerator, 2)} req/s/GPU`,pct(r.slo_attainment),`${fmt(r.p95_ttft_ms)} ms`,`${fmt(r.p95_e2e_ms)} ms`,`${fmt(r.p95_transfer_ms, 2)} ms`,pct(r.prefix_hit_rate),`${fmt(r.prefill_tokens_saved, 0)} tok`,r.bottleneck || "N/A",]);}function renderTopology(rows) {lastTopologyRows = rows;$("topologyEmpty").classList.add("hidden");$("topologyContent").classList.remove("hidden");$("topologyCopyBtn").disabled = false;$("topologyCsvBtn").disabled = false;$("topologyRows").innerHTML = rows.map((r, index) => `<tr><td>${escapeHtml(scenarioLabel(r.scenario))}${index === 0 ? '<span class="best-label">Best</span>' : ""}</td><td>${fmt(r.accelerator_instances, 0)}</td><td>${fmt(r.goodput_rps, 2)} req/s</td><td>${fmt(r.goodput_per_accelerator, 2)} req/s/GPU</td><td>${pct(r.slo_attainment)}</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td><td>${fmt(r.p95_transfer_ms, 2)} ms</td><td>${pct(r.prefix_hit_rate)}</td><td>${fmt(r.prefill_tokens_saved, 0)} tok</td><td>${escapeHtml(r.bottleneck || "N/A")}</td></tr>`).join("");const palette = [COLORS.blue, COLORS.green, COLORS.amber, COLORS.red];destroyChart("topology");charts.topology = new Chart($("topologyChart"), {type: "scatter",data: { datasets: rows.map((r, i) => ({ label: scenarioLabel(r.scenario), data: [{ x: r.p95_ttft_ms, y: r.goodput_rps }], backgroundColor: palette[i % palette.length], borderColor: palette[i % palette.length], pointRadius: 6, pointHoverRadius: 8 })) },options: { ...commonChartOptions(), plugins: { legend: pointLegend() }, scales: { x: { title: { display: true, text: "p95 TTFT (ms)" }, beginAtZero: true }, y: { title: { display: true, text: "Goodput (req/s)" }, beginAtZero: true } } },});}$("topologyBtn").addEventListener("click", async () => {const button = $("topologyBtn");button.disabled = true;button.textContent = "Comparing...";try { renderTopology((await callPython("topology_compare", { config: configFromUI() })).rows); }catch (error) { alert(`Topology comparison failed: ${error.message}`); }finally { button.disabled = false; button.textContent = "Compare 4 scenarios"; }});const topologyHeaders = ["Scenario", "GPU instances", "Goodput", "Goodput / GPU", "SLO attainment", "p95 TTFT", "p95 E2E", "p95 KV transfer", "Cache hit", "Prefill saved", "Diagnosis"];$("topologyCopyBtn").addEventListener("click", () => copyText(tableText(topologyHeaders, topologyTableRows(lastTopologyRows)), "Topology table copied"));$("topologyCsvBtn").addEventListener("click", () => downloadCsv(`inferscale_topology-cache-study_${stamp()}.csv`, topologyHeaders, topologyTableRows(lastTopologyRows)));function designTableRows(rows) {return rows.map((r) => [r.label,r.pareto ? "YES" : "NO",r.efficiency_pareto ? "YES" : "NO",r.slo_pass ? "PASS" : "FAIL",fmt(r.accelerator_instances, 0),`${fmt(r.goodput_rps, 2)} req/s`,`${fmt(r.goodput_per_accelerator, 2)} req/s/GPU`,`${fmt(r.p95_ttft_ms)} ms`,`${fmt(r.p95_e2e_ms)} ms`,pct(r.peak_kv_utilization),r.bottleneck || "N/A",]);}function renderDesign(result) {lastDesignRows = result.rows || [];$("designEmpty").classList.add("hidden");$("designContent").classList.remove("hidden");$("designCopyBtn").disabled = false;$("designCsvBtn").disabled = false;$("dCandidates").textContent = fmt(result.candidate_count, 0);$("dPareto").textContent = fmt(result.pareto_count, 0);$("dEfficiencyPareto").textContent = fmt(result.efficiency_pareto_count, 0);$("designRows").innerHTML = lastDesignRows.map((r) => `<tr><td>${escapeHtml(r.label)}${r.pareto ? '<span class="pareto-label">Perf</span>' : ""}${r.efficiency_pareto ? '<span class="pareto-label">Eff</span>' : ""}</td><td class="${r.pareto ? "pass" : ""}">${r.pareto ? "YES" : "NO"}</td><td class="${r.efficiency_pareto ? "pass" : ""}">${r.efficiency_pareto ? "YES" : "NO"}</td><td class="${r.slo_pass ? "pass" : "fail"}">${r.slo_pass ? "PASS" : "FAIL"}</td><td>${fmt(r.accelerator_instances, 0)}</td><td>${fmt(r.goodput_rps, 2)} req/s</td><td>${fmt(r.goodput_per_accelerator, 2)} req/s/GPU</td><td>${fmt(r.p95_ttft_ms)} ms</td><td>${fmt(r.p95_e2e_ms)} ms</td><td>${pct(r.peak_kv_utilization)}</td><td>${escapeHtml(r.bottleneck || "N/A")}</td></tr>`).join("");const passPoints = lastDesignRows.filter((r) => r.slo_pass).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_rps }));const failPoints = lastDesignRows.filter((r) => !r.slo_pass).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_rps }));const frontier = lastDesignRows.filter((r) => r.pareto).sort((a, b) => a.p95_ttft_ms - b.p95_ttft_ms).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_rps }));destroyChart("design");charts.design = new Chart($("designChart"), {type: "scatter",data: { datasets: [{ label: "SLO pass", data: passPoints, backgroundColor: COLORS.green, borderColor: COLORS.green, pointRadius: 4 },{ label: "SLO fail", data: failPoints, backgroundColor: COLORS.gray, borderColor: COLORS.gray, pointRadius: 4 },{ type: "line", label: "Performance frontier", data: frontier, borderColor: COLORS.blue, backgroundColor: COLORS.blue, pointBackgroundColor: COLORS.blue, pointRadius: 5, fill: false, tension: 0 },] },options: { ...commonChartOptions(), parsing: false, plugins: { legend: pointLegend() }, scales: { x: { title: { display: true, text: "p95 TTFT (ms)" }, beginAtZero: true }, y: { title: { display: true, text: "Goodput (req/s)" }, beginAtZero: true } } },});const efficiencyPass = lastDesignRows.filter((r) => r.slo_pass).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_per_accelerator }));const efficiencyFail = lastDesignRows.filter((r) => !r.slo_pass).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_per_accelerator }));const efficiencyFrontier = lastDesignRows.filter((r) => r.efficiency_pareto).sort((a, b) => a.p95_ttft_ms - b.p95_ttft_ms).map((r) => ({ x: r.p95_ttft_ms, y: r.goodput_per_accelerator }));destroyChart("designEfficiency");charts.designEfficiency = new Chart($("designEfficiencyChart"), {type: "scatter",data: { datasets: [{ label: "SLO pass", data: efficiencyPass, backgroundColor: COLORS.green, borderColor: COLORS.green, pointRadius: 4 },{ label: "SLO fail", data: efficiencyFail, backgroundColor: COLORS.gray, borderColor: COLORS.gray, pointRadius: 4 },{ type: "line", label: "Efficiency frontier", data: efficiencyFrontier, borderColor: COLORS.amber, backgroundColor: COLORS.amber, pointBackgroundColor: COLORS.amber, pointRadius: 5, fill: false, tension: 0 },] },options: { ...commonChartOptions(), parsing: false, plugins: { legend: pointLegend() }, scales: { x: { title: { display: true, text: "p95 TTFT (ms)" }, beginAtZero: true }, y: { title: { display: true, text: "Goodput / accelerator (req/s/GPU)" }, beginAtZero: true } } },});}$("designBtn").addEventListener("click", async () => {const button = $("designBtn");button.disabled = true;button.textContent = "Exploring...";try { renderDesign(await callPython("design_space", { config: configFromUI(), include_disaggregated: $("includePd").checked })); }catch (error) { alert(`Design-space exploration failed: ${error.message}`); }finally { button.disabled = false; button.textContent = "Explore design space"; }});const designHeaders = ["Candidate", "Perf Pareto", "Efficiency Pareto", "SLO pass", "GPU instances", "Goodput", "Goodput / GPU", "p95 TTFT", "p95 E2E", "KV peak", "Diagnosis"];$("designCopyBtn").addEventListener("click", () => copyText(tableText(designHeaders, designTableRows(lastDesignRows)), "Design table copied"));$("designCsvBtn").addEventListener("click", () => downloadCsv(`inferscale_design-space_${stamp()}.csv`, designHeaders, designTableRows(lastDesignRows)));function syncConditionalControls() {const pd = $("topology").value === "disaggregated_pd";$("pdControls").classList.toggle("hidden", !pd);$("colocatedAcceleratorLabel").classList.toggle("hidden", pd);if (pd && $("scheduler").value === "static_fcfs") {$("scheduler").value = "continuous_fcfs";showToast("Static FCFS switched to Continuous FCFS for P/D topology");}$("prefixControls").classList.toggle("hidden", !boolSelect("prefixCache"));$("burstControls").classList.toggle("hidden", $("arrival").value !== "bursty");}$("topology").addEventListener("change", syncConditionalControls);$("prefixCache").addEventListener("change", syncConditionalControls);$("arrival").addEventListener("change", syncConditionalControls);syncConditionalControls();for (const tab of document.querySelectorAll(".tab")) {tab.addEventListener("click", () => {document.querySelectorAll(".tab").forEach((item) => item.classList.remove("active"));document.querySelectorAll(".tab-panel").forEach((panel) => panel.classList.remove("active"));tab.classList.add("active");$(tab.dataset.tab).classList.add("active");setTimeout(() => Object.values(charts).forEach((chart) => chart.resize()), 20);});}function closeExpandedChart() {const card = document.querySelector(".chart-card.chart-expanded");if (!card) return;card.classList.remove("chart-expanded");const button = card.querySelector(".chart-expand");if (button) button.textContent = "Expand";document.body.classList.remove("chart-open");setTimeout(() => Chart.getChart(card.querySelector("canvas"))?.resize(), 20);}for (const button of document.querySelectorAll(".chart-expand")) {button.addEventListener("click", () => {const card = button.closest(".chart-card");const wasExpanded = card.classList.contains("chart-expanded");closeExpandedChart();if (!wasExpanded) {card.classList.add("chart-expanded");button.textContent = "Close";document.body.classList.add("chart-open");setTimeout(() => Chart.getChart(card.querySelector("canvas"))?.resize(), 20);}});}for (const button of document.querySelectorAll(".chart-download")) {button.addEventListener("click", () => downloadChart(button.closest(".chart-card")));}document.addEventListener("keydown", (event) => { if (event.key === "Escape") closeExpandedChart(); });
12345678910111213141516171819202122232425262728293031# ArchitectureInferScale-Sim deliberately separates **serving-system logic** from **latency estimation**.## Simulation pipeline1. `workloads.py` generates a deterministic request trace from an arrival process and token-length distributions.2. `simulator.py` advances virtual time through prefill and decode work.3. `kv_cache.py` handles admission based on model weights, KV state and accelerator memory.4. `latency.py` predicts the duration of each virtual prefill/decode step.5. `metrics.py` derives TTFT, TPOT, E2E, queueing, throughput and SLO goodput.6. `optimizer.py` reruns deterministic scenarios at different offered loads or scheduling policies.The discrete-event engine never sleeps for simulated compute time. If a virtual decode step costs 40 ms, the simulator advances `now += 0.040` immediately.## Browser executionThe canonical source lives in `src/inferscale`. `scripts/sync_web_python.py` mirrors those modules into `py/inferscale`. A module Web Worker loads Pyodide and writes the Python modules into Pyodide's virtual filesystem before importing `inferscale.api`.The UI remains responsive because the Python simulation does not run on the browser's main thread.## Extension boundary`AnalyticalLatencyModel` is intentionally replaceable. A calibrated implementation can provide:- `prefill_seconds(token_counts)`- `decode_step_seconds(context_lengths)`- `model_weight_gb`- `kv_bytes_per_token()`without changing scheduling, workload or metric code.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# ArchitectureInferScale-Sim separates **serving-system logic** from **latency estimation**.## Main Python modules1. `workloads.py` creates deterministic workload traces and shared-prefix hit assignments.2. `simulator.py` implements the colocated serving loop.3. `disaggregated.py` implements separate prefill/decode worker pools plus KV transfer.4. `kv_cache.py` handles memory/admission and shared-prefix allocation.5. `latency.py` predicts reference prefill/decode operation durations.6. `metrics.py` derives request-level TTFT, TPOT, E2E, queueing, throughput, and goodput.7. `diagnostics.py` converts simulated telemetry into explicit heuristic bottleneck labels.8. `optimizer.py` implements capacity search, scheduler comparison, topology/cache comparison, and the bounded Pareto sweep.9. `api.py` exposes JSON-like actions to both local Python and Pyodide.## Colocated path```textarrival -> waiting -> prefill -> active decode batch -> complete```## P/D path```textarrival-> prefill queue-> prefill worker batch-> KV-transfer link-> decode-ready queue-> continuous decode worker-> complete```The P/D path is a genuine discrete-event loop: prefill workers, decode workers, and the transfer link can have overlapping virtual activity.## Browser executionCanonical source lives in `src/inferscale`. `scripts/sync_web_python.py` mirrors it into `py/inferscale`. A module Web Worker loads Pyodide, writes those files into Pyodide's virtual filesystem, imports `inferscale.api`, and exchanges JSON messages with the UI.The simulator therefore runs away from the browser main thread and uses the same Python implementation as the local tests.## Extension boundary`AnalyticalLatencyModel` can later be replaced by an empirical profile interpolator exposing:- `prefill_seconds(token_counts)`- `decode_step_seconds(context_lengths)`- `model_weight_gb`- `kv_bytes_per_token()`without rewriting scheduling, cache, P/D orchestration, SLO metrics, or search tooling.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Methodology and limitations## What v0.2 simulatesInferScale models request arrival, queueing, admission, prefill, autoregressive decode, dynamic batch membership, KV-cache memory and request completion. Metrics are computed from per-request virtual timestamps.## Scheduler semantics- `static_fcfs`: admits one batch and drains it before admitting new requests.- `continuous_fcfs`: admits FCFS work whenever decode slots become available.- `continuous_sjf`: prioritizes shorter prompt+output jobs at admission.- `continuous_slo`: prioritizes earliest E2E deadlines.- `chunked_slo`: combines deadline ordering with chunked prompt prefill interleaved with decode.These are pedagogically transparent approximations, not line-by-line reproductions of vLLM or SGLang schedulers.## Workload semanticsPoisson arrivals use exponentially distributed inter-arrival times. Constant arrivals are evenly spaced. Bursty arrivals alternate lower and higher rate periods to expose transient queue growth.Prompt/output lengths are sampled from log-normal distributions parameterized by mean and coefficient of variation (CV), which provides positive heavy-tailed lengths without external dependencies.## Latency modelThe default reference model is roofline-inspired:- dense transformer FLOPs scale approximately with model parameter count and token count;- attention adds a context-length-dependent term;- decode includes a shared model-weight memory stream and context-dependent KV reads;- operation time is approximated from the larger of compute and memory costs plus a small launch/scheduling proxy;- conservative efficiency factors prevent peak-spec numbers from being treated as achieved throughput.This produces useful qualitative dynamics but is **not empirically calibrated**. Absolute milliseconds should not be cited as hardware benchmark results.## QuantizationINT8 and INT4 alter model weight footprint and apply a conservative compute-overhead multiplier. v0.2 does not claim a specific kernel implementation, quantization scheme, or quality impact.## KV-cacheKV bytes per token are computed as:```text2 × layers × KV heads × head dimension × 2 bytes```for K and V with FP16 KV state. Paged allocation rounds live sequence lengths to `kv_block_tokens`. Static batching reserves full prompt+requested-output capacity.## Capacity searchCapacity search evaluates an offered request rate over multiple deterministic seeds and marks the rate feasible only when **every repetition**:1. reaches the configured SLO-attainment target; and2. leaves no requests unfinished after the simulated drain.A bounded binary search then estimates the highest feasible offered rate. Mean/min/max attainment are retained for evidence, and the recommended rate applies user-configured safety headroom.## Validation statusv0.2 validates software invariants and expected qualitative behavior through unit tests. It does **not** yet provide held-out GPU calibration error. Empirical profile calibration and validation remain future work rather than being fabricated for this release.## v0.2 bottleneck diagnosisInferScale derives a compact explanation from the simulator's own state: component SLO attainment, p95 queue latency, virtual device busy fraction, peak KV utilization, and unfinished requests. These are heuristic simulator diagnoses, not hardware-counter diagnoses of a real GPU.## v0.2 robust capacity criterionFor each searched load, the planner repeats the workload with deterministic seed offsets. A rate passes only when every repetition reaches the configured SLO target and fully drains. Mean attainment is plotted while minimum and maximum attainment remain visible in the trace.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Methodology and limitations## What v0.3 simulatesInferScale models request arrival, queueing, admission, prefill, autoregressive decode, dynamic batch membership, KV-cache memory, and request completion.For P/D disaggregation it additionally models independent prefill/decode worker pools and explicit prompt-KV transfer before decode admission.Metrics are computed from per-request virtual timestamps.## Scheduler semantics- `static_fcfs`: admits one colocated batch and drains it before admitting new requests.- `continuous_fcfs`: admits FCFS work whenever decode slots become available.- `continuous_sjf`: prioritizes shorter estimated jobs at admission.- `continuous_slo`: uses a least-slack-style ordering based on E2E deadline and an analytical remaining-service estimate.- `chunked_slo`: combines least-slack ordering with chunked prompt prefill.These are transparent approximations, not line-by-line reproductions of vLLM or SGLang.Static batching is intentionally excluded from the P/D comparison; if requested for P/D, the simulator warns and uses continuous semantics.## Workload semanticsPoisson arrivals use exponentially distributed inter-arrival times. Constant arrivals are evenly spaced. Bursty arrivals alternate lower and higher rate periods.Prompt/output lengths are sampled from log-normal distributions parameterized by mean and coefficient of variation (CV).## Shared-prefix modelv0.3 models one reusable exact prefix:1. cache hits are assigned deterministically with a separate seeded RNG so enabling cache does **not** change the underlying arrival/prompt/output trace;2. a hit reduces prefill work by the configured reusable-prefix length, bounded by the request prompt;3. shared prefix KV consumes one persistent allocation per serving worker rather than being duplicated per request;4. decode still uses the full logical context length for attention-cost estimation.This isolates prefix reuse without implementing radix-tree lookup, eviction, or prefix-aware scheduling.## P/D disaggregationP/D uses a global discrete-event queue with four main event classes:```textarrivalprefill_donetransfer_donedecode_done```Prefill workers batch queued requests independently. Completed prompt state is placed on a serialized transfer link. Decode workers admit transferred requests only between decode iterations, preserving continuous-batching semantics.The transfer model is:```textbase_latency + bytes / bandwidth```where transferred bytes correspond to newly computed prompt KV. With a cache hit, shared-prefix state is assumed resident in both role pools and only the uncached suffix is transferred.The model does not claim protocol-level fidelity to PCIe, NVLink, RDMA, NIXL, or NCCL.## Latency modelThe default reference model is roofline-inspired:- dense transformer FLOPs scale with parameter count and processed tokens;- attention adds context-length-dependent work;- decode includes model-weight traffic and context-dependent KV reads;- time is approximated from compute/memory costs plus a launch/scheduling proxy;- conservative efficiency factors keep accelerator peak specs from being treated as achieved throughput.This creates useful qualitative dynamics but is **not empirically calibrated**.## KV cacheKV bytes per token are approximated as:```text2 x layers x KV heads x head dimension x 2 bytes```for K and V with FP16 KV state. Paged allocation rounds live sequence lengths to `kv_block_tokens`. Static batching reserves full prompt+requested-output capacity.## Capacity searchEach offered rate is evaluated over deterministic seed offsets and is feasible only when **every repetition**:1. reaches the configured SLO-attainment target; and2. fully drains all generated requests.The result retains mean, worst, best, and standard-deviation evidence. A bounded binary search estimates the highest feasible rate and a recommended rate after user-selected headroom.## Design-space explorerThe browser-safe v0.3 sweep evaluates:- three colocated continuous schedulers over batch sizes 8/16/32;- one additional cached SLO-aware colocated point at the user's current batch size;- optionally P/D worker splits 1P:1D, 1P:2D, and 2P:1D, each with cache off/on.A candidate is Pareto-optimal when no other candidate has both **at least as much goodput** and **no worse p95 TTFT**, with at least one strict improvement.This is a bounded interactive study, not exhaustive global optimization.## Validation statusv0.3 validates deterministic software invariants and expected qualitative behavior through tests. It does **not** provide held-out GPU calibration error. Empirical profile import/calibration remains a future extension rather than being fabricated for this release.## Resource-normalized design comparisonP/D candidates can use more simulated accelerator instances than colocated candidates. v0.3 therefore reports both raw goodput and `goodput / accelerator`. The Design Explorer computes a separate Pareto frontier for each throughput objective against p95 TTFT. This avoids treating additional hardware as a free improvement and keeps raw performance distinct from resource efficiency.
12345678910111213141516171819202122232425262728293031323334353637# Research contextInferScale-Sim is a portfolio-scale implementation situated within a broader research line on replacing expensive deployment sweeps with modeling, simulation or emulation.## Vidur (2024)Vidur combines experimental profiling, predictive models and end-to-end inference simulation. Its paper reports <9% inference-latency estimation error across evaluated configurations and a configuration-search example where LLaMA2-70B exploration took about one CPU-hour versus an estimated 42K GPU-hours (~$218K) for deployment-based exploration.Project inspiration: explicit performance profiles, separation of prediction from event simulation, SLO-oriented configuration search.## TokenSim (2025)TokenSim emphasizes extensible exploration of scheduling and memory-management choices, with reported sub-1% error in its evaluated real-world workloads.Project inspiration: scheduler modularity and comparative policy experiments.## Revati (2026)Revati takes a different approach: instead of reimplementing every serving-system control decision, it executes real vLLM/SGLang control paths and virtualizes CUDA time. It reports <5% prediction error and 5–17× faster execution than real GPU runs in the reported evaluation.Project lesson: control-path fidelity is a real limitation of pure simulators. InferScale intentionally documents its scheduler semantics rather than claiming production-framework equivalence.## LLMServingSim 2.0 (2026)LLMServingSim 2.0 focuses on heterogeneous and disaggregated infrastructure, integrating batching, routing, placement, offloading, memory and power into the serving loop. The 2026 version reports ~0.97% average error in its validation.Project inspiration: profile-based hardware abstraction and future disaggregation support.## Frontier (2026)Frontier models modern serving structures including co-location, prefill/decode disaggregation, Attention-FFN disaggregation, runtime optimizations and stateful workloads. Its May 2026 paper reports average throughput error below 4% on a 16-H800 testbed and large improvements in end-to-end latency error over baseline simulators.Project inspiration for future work: prefill/decode disaggregation, KV transfer and workload-state dependencies.## Scope boundaryInferScale-Sim v0.2 is not intended to compete with these research systems on fidelity or scale. Its contribution is an inspectable, dependency-light Python implementation and a zero-backend interactive interface for exploring the underlying serving dynamics.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Research contextInferScale-Sim is a portfolio-scale implementation situated within the research line on replacing expensive deployment sweeps with modeling, simulation, or emulation.## Vidur (2024)Vidur combines experimental profiling, predictive models, and end-to-end inference simulation. Its paper reports under 9% inference-latency estimation error across the evaluated range and a configuration-search example where LLaMA2-70B exploration took about one CPU-hour versus an estimated 42K GPU-hours (~$218K) for deployment-based exploration.InferScale inspiration: workload-aware configuration search, explicit performance-profile provenance, and separation between latency prediction and event simulation.Source: https://arxiv.org/abs/2405.05465## SGLang / RadixAttention (2024)SGLang introduced RadixAttention for automatic KV-cache reuse across shared prompt prefixes. A radix tree retains reusable prompt/generation state and combines prefix lookup with cache-aware scheduling and eviction.InferScale v0.3 does not implement a radix tree. It adds a deliberately smaller controlled shared-prefix abstraction so the effect of avoiding repeated prefill and duplicate KV allocation can be studied independently.Source: https://arxiv.org/abs/2312.07104## TokenSim (2025)TokenSim emphasizes extensible exploration of scheduling and memory-management choices and reports sub-1% error in its evaluated workloads.InferScale inspiration: modular scheduler/memory experiments.Source: https://arxiv.org/abs/2503.08415## Revati (2026)Revati avoids reimplementing every evolving serving-system control decision: it executes real vLLM/SGLang control paths while virtualizing CUDA time. The paper reports less than 5% prediction error across its evaluated scenarios and 5-17x faster execution than real GPU serving runs.InferScale lesson: pure simulation has a control-path fidelity ceiling. Our schedulers therefore document their semantics rather than claiming framework equivalence.Source: https://arxiv.org/abs/2601.00397## LLMServingSim 2.0 (2026)LLMServingSim 2.0 focuses on heterogeneous and disaggregated infrastructure and integrates batching, routing, offloading, memory, communication, and power into a unified runtime loop. The 2026 paper reports about 0.97% average error in its validation.InferScale v0.3 inspiration: role-specific resources and explicit data movement rather than assuming a monolithic replica.Source: https://arxiv.org/abs/2602.23036## Frontier (May 2026)Frontier models co-location, Prefill-Decode Disaggregation, Attention-FFN Disaggregation, runtime optimizations such as speculative decoding, and stateful workloads. It reports average throughput error below 4% on its 16-H800 evaluation and explicitly supports SLA-dependent Pareto-frontier exploration.InferScale v0.3 inspiration:- separate prefill and decode worker pools;- communication/KV-transfer cost;- role-specific bottleneck telemetry;- an interactive bounded Pareto design-space study.Source: https://arxiv.org/abs/2605.21312## Scope boundaryInferScale-Sim v0.3 is not intended to compete with these research systems on fidelity, hardware scale, or runtime compatibility. Its goal is an inspectable, dependency-light Python implementation with a zero-backend interactive interface for understanding the systems mechanisms that motivate them.## HeteroPanacea / When Does Disaggregation Pay? (Aug 2026)**When Does Disaggregation Pay? Simulating Prefill--Decode--Attention--FFN Specialization for Agentic LLM Inference** pushes the simulator design space toward heterogeneous stage-specific hardware and automated cross-stack exploration. InferScale-Sim v0.3 does not model Attention--FFN disaggregation or custom NPUs, but its P/D topology already permits independent prefill and decode accelerator profiles and reports resource-normalized efficiency so heterogeneous layouts can be compared without treating extra accelerators as free.- arXiv: https://arxiv.org/abs/2608.03741
1234567891011121314151617181920212223242526272829303132333435# v0.2 validation checklistThe release check is designed to prevent deployment and provenance mistakes rather than pretend the analytical profile has empirical accuracy.## Automated- deterministic workload generation- constant-arrival timing- prefill latency monotonicity with token count- quantization footprint ordering- successful end-to-end request completion- queueing/tail-latency response under increased load- static vs continuous batching behavioral difference- capacity-search output sanity- scheduler-arena output sanity- component TTFT/E2E SLO-attainment accounting- simulator bottleneck diagnosis provenance- capacity repetition range / conservative pass criterion- ASCII-only public UI labels for reliable rendering- Hugging Face `short_description` <= 60 characters- `sdk: static` metadata- canonical Python source == browser mirror- provenance remains `analytical-reference`- JavaScript syntax parse- Python compilation## Not claimed in v0.2- empirical L4/A10G/A100 latency accuracy- exact vLLM/SGLang scheduler equivalence- CUDA-kernel modeling- multi-GPU communication- P/D disaggregationThose require calibration/profiling or additional systems components and are explicitly deferred rather than approximated silently.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# v0.3 validation checklistThe release checks prevent software, deployment, and provenance mistakes; they do not pretend the analytical profile has measured-hardware fidelity.## Automated- deterministic workload generation- constant/Poisson/bursty workload behavior- prefill latency monotonicity- quantization footprint ordering- colocated end-to-end completion- static vs continuous behavioral difference- component TTFT/E2E SLO accounting- robust repetition-aware capacity search- bottleneck-diagnosis provenance- prefix hits do not alter the underlying generated request trace- prefix reuse reduces modeled prefill work- P/D pipeline completion- non-zero P/D transfer telemetry- configurable P/D worker counts- four-scenario topology/cache comparison- bounded design-space sweep and Pareto marking- ASCII-only public UI labels- chart export controls present- explicit planner worst-repetition and target columns- no product-style footer- Hugging Face `short_description` <= 60 characters- `sdk: static` metadata- canonical Python source equals browser mirror- every Python module is included by the worker- provenance remains `analytical-reference`- JavaScript syntax parse- Python compilation## Not claimed in v0.3- empirical L4/A10G/A100 latency accuracy- exact vLLM/SGLang scheduler equivalence- CUDA-kernel modeling- real network-protocol fidelity- radix-tree prefix-cache eviction/scheduling- speculative decoding- Attention-FFN disaggregation- multi-turn/agentic session fidelityThese remain explicit future extensions.## Design-space sanity checksThe release suite verifies that the bounded design sweep returns at least one raw-performance Pareto point and at least one resource-efficiency Pareto point. P/D candidates also expose accelerator-instance counts so raw and normalized throughput can be interpreted separately.
10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606110 unmodified lines</head><body><header class="topbar" id="topbar"><div class="brand-wrap"><div class="logo">IS</div><div><div class="brand">InferScale-Sim</div><div class="subtitle">LLM serving systems laboratory</div></div></div><div class="runtime-pill" id="runtimePill"><span class="dot"></span><span id="runtimeText">Loading Python runtime...</span></div></header><main class="shell"><section class="intro"><div class="intro-copy"><div class="eyebrow">InferScale-Sim / v0.2.0</div><h1>Explore LLM serving dynamics without provisioning a GPU.</h1><p>Generate workloads, compare schedulers, inspect queueing and KV pressure, and search for the highest SLO-compliant request rate. The simulator is Python running locally in a Pyodide Web Worker.</p></div><dl class="project-facts"><div><dt>Backend</dt><dd>None</dd></div><div><dt>Runtime</dt><dd>Python / WASM</dd></div><div><dt>Network data</dt><dd>None after load</dd></div><div><dt>Profiles</dt><dd>Analytical reference</dd></div></dl></section><div class="reference-note"><strong>Reference-profile mode.</strong> Absolute L4, A10G, and A100 latency values are analytical predictions, not measured GPU benchmarks. Scheduler, queueing, KV-cache, and SLO behavior is simulated live.</div><nav class="tabs" aria-label="InferScale sections"><button class="tab active" data-tab="lab">Serving Lab</button><button class="tab" data-tab="arena">Scheduler Arena</button><button class="tab" data-tab="planner">Capacity Planner</button><button class="tab" data-tab="method">Methodology</button></nav><section id="lab" class="tab-panel active"><div class="workspace"><aside class="panel controls-panel"><div class="panel-title-row"><h2>Experiment</h2><span class="tag">Deterministic seed</span></div><div class="field-grid two"><label>Model<select id="model"><option>Qwen2.5-3B</option><option>Llama-3.1-8B</option><option>Mistral-7B-v0.3</option></select></label><label>Accelerator<select id="accelerator"><option value="L4">NVIDIA L4</option><option value="A10G">NVIDIA A10G</option><option value="A100-40GB">NVIDIA A100 40GB</option></select></label></div><div class="field-grid two"><label>Scheduler<select id="scheduler"><option value="continuous_fcfs">Continuous - FCFS</option><option value="continuous_sjf">Continuous - SJF</option><option value="continuous_slo">Continuous - SLO-aware</option><option value="chunked_slo">Chunked prefill - SLO-aware</option><option value="static_fcfs">Static batching - FCFS</option></select></label><label>Weight precision<select id="quantization"><option value="fp16">FP16</option><option value="int8" selected>INT8 scenario</option><option value="int4">INT4 scenario</option></select></label></div><hr /><div class="section-kicker">Workload</div><div class="field-grid two"><label>Arrival process<select id="arrival"><option value="poisson">Poisson</option><option value="constant">Constant</option><option value="bursty">Bursty</option></select></label><label>Request rate<input id="rate" type="number" min="0.1" step="0.1" value="4" /><span class="unit">req/s</span></label><label>Duration<input id="duration" type="number" min="2" step="1" value="30" /><span class="unit">sim s</span></label><label>Seed<input id="seed" type="number" step="1" value="7" /></label></div><div id="burstControls" class="field-grid two hidden"><label>Burst multiplier<input id="burstMultiplier" type="number" min="1" step="0.25" value="3" /><span class="unit">x</span></label><label>Burst period<input id="burstPeriod" type="number" min="0.5" step="0.5" value="10" /><span class="unit">s</span></label></div><div class="field-grid two"><label>Prompt mean<input id="promptMean" type="number" min="16" value="512" /><span class="unit">tokens</span></label><label>Prompt CV<input id="promptCv" type="number" min="0" max="2" step="0.05" value="0.50" /></label><label>Output mean<input id="outputMean" type="number" min="1" value="64" /><span class="unit">tokens</span></label><label>Output CV<input id="outputCv" type="number" min="0" max="2" step="0.05" value="0.60" /></label></div><hr /><div class="section-kicker">Serving controls</div><div class="field-grid two"><label>Max batch size<input id="maxBatch" type="number" min="1" max="128" value="16" /></label><label>Max batch tokens<input id="maxBatchTokens" type="number" min="128" step="128" value="8192" /></label><label>Prefill chunk<input id="chunkSize" type="number" min="64" step="64" value="512" /><span class="unit">tokens</span></label><label>KV block<input id="kvBlock" type="number" min="1" value="16" /><span class="unit">tokens</span></label></div><hr /><div class="section-kicker">SLO</div><div class="field-grid two"><label>TTFT limit<input id="sloTtft" type="number" min="1" value="500" /><span class="unit">ms</span></label><label>E2E limit<input id="sloE2e" type="number" min="100" value="5000" /><span class="unit">ms</span></label></div><button id="runBtn" class="primary" disabled>Run simulation</button><div class="button-row"><button id="copyResultBtn" class="secondary" disabled>Copy JSON</button><button id="exportBtn" class="secondary" disabled>Download JSON</button></div></aside><div class="results-column"><section class="panel result-panel"><div class="panel-title-row"><h2>Run summary</h2><span id="runState" class="tag neutral">Waiting</span></div><div id="emptyState" class="empty-state"><h3>Configure a workload and run it</h3><p>The Python simulator executes in a background Web Worker and returns request-level virtual timestamps.</p></div><div id="resultContent" class="hidden"><div class="metric-grid"><div class="metric"><span>p95 TTFT</span><strong id="mTtft">N/A</strong></div><div class="metric"><span>p95 E2E</span><strong id="mE2e">N/A</strong></div><div class="metric"><span>Goodput</span><strong id="mGoodput">N/A</strong></div><div class="metric"><span>SLO attainment</span><strong id="mSlo">N/A</strong></div><div class="metric"><span>Throughput</span><strong id="mReq">N/A</strong></div><div class="metric"><span>Peak KV</span><strong id="mKv">N/A</strong></div></div><section class="diagnostic-card" id="diagnosticCard"><div class="diagnostic-head"><span>Simulator diagnosis</span><strong id="mBottleneck">N/A</strong></div><p id="mDiagnosis">Run a simulation to generate a bottleneck explanation.</p><p class="diagnostic-action" id="mRecommendation"></p><div class="evidence-row" id="mEvidence"></div></section><div class="chart-grid"><div class="chart-card" data-chart-card><div class="chart-head"><div class="chart-title">Latency percentiles</div><button class="chart-expand" type="button">Expand</button></div><div class="chart-body"><canvas id="latencyChart"></canvas></div></div><div class="chart-card" data-chart-card><div class="chart-head"><div class="chart-title">Queue, decode, and KV timeline</div><button class="chart-expand" type="button">Expand</button></div><div class="chart-body"><canvas id="timelineChart"></canvas></div></div></div><div class="chart-card full" data-chart-card><div class="chart-head"><div class="chart-title">Request TTFT vs prompt length</div><button class="chart-expand" type="button">Expand</button></div><div class="chart-body"><canvas id="scatterChart"></canvas></div></div><div id="warnings" class="warnings hidden"></div></div></section></div></div></section><section id="arena" class="tab-panel"><div class="panel wide-panel"><div class="panel-title-row arena-title-row"><div><div class="section-kicker">Same workload - same seed</div><h2>Scheduler Arena</h2><p class="muted">Run every scheduler against the current Serving Lab configuration and rank by SLO attainment, then goodput.</p></div><button id="arenaBtn" class="primary compact" disabled>Compare schedulers</button></div><div id="arenaEmpty" class="empty-state small"><h3>No comparison yet</h3><p>Your Serving Lab controls are reused automatically.</p></div><div id="arenaContent" class="hidden"><div class="chart-card full" data-chart-card><div class="chart-head"><div class="chart-title">Useful vs raw request throughput</div><button class="chart-expand" type="button">Expand</button></div><div class="chart-body large"><canvas id="arenaChart"></canvas></div></div><div class="table-toolbar"><span>Scheduler comparison</span><div><button id="arenaCopyBtn" class="mini-button" disabled>Copy table</button><button id="arenaCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Scheduler</th><th>Goodput</th><th>SLO attainment</th><th>p95 TTFT</th><th>p95 E2E</th><th>KV peak</th><th>Unfinished</th><th>Diagnosis</th></tr></thead><tbody id="arenaRows"></tbody></table></div></div></div></section><section id="planner" class="tab-panel"><div class="workspace planner-grid"><aside class="panel controls-panel"><div class="panel-title-row"><h2>Capacity search</h2><span class="tag">Robust binary search</span></div><p class="muted">Find the highest offered load where every repetition meets the SLO target and fully drains.</p><label>Required SLO attainment<input id="targetSlo" type="number" min="0.5" max="1" step="0.001" value="0.99" /></label><div class="field-grid two"><label>Minimum rate<input id="minRate" type="number" min="0.05" step="0.1" value="0.25" /><span class="unit">req/s</span></label><label>Maximum rate<input id="maxRate" type="number" min="0.1" step="1" value="20" /><span class="unit">req/s</span></label><label>Search iterations<input id="searchIter" type="number" min="2" max="12" value="7" /></label><label>Repetitions / rate<input id="repetitions" type="number" min="1" max="5" value="2" /></label></div><label>Safety headroom<input id="headroom" type="number" min="0" max="0.8" step="0.05" value="0.20" /><span class="unit">fraction</span></label><button id="capacityBtn" class="primary" disabled>Find sustainable capacity</button></aside><section class="panel result-panel"><div class="panel-title-row"><h2>Planner result</h2><span id="plannerState" class="tag neutral">Waiting</span></div><div id="plannerEmpty" class="empty-state"><h3>No search yet</h3><p>The planner repeatedly runs the simulator at different offered loads.</p></div><div id="plannerContent" class="hidden"><div class="metric-grid four"><div class="metric emphasis"><span>Estimated capacity</span><strong id="pCapacity">N/A</strong></div><div class="metric"><span>Recommended load</span><strong id="pRecommended">N/A</strong></div><div class="metric"><span>Safety headroom</span><strong id="pHeadroom">N/A</strong></div><div class="metric"><span>Status</span><strong id="pStatus">N/A</strong></div></div><div class="planner-note" id="plannerCriterion">A rate passes only if every repetition meets the target and drains all generated requests.</div><div class="chart-card full" data-chart-card><div class="chart-head"><div class="chart-title">SLO attainment across searched rates</div><button class="chart-expand" type="button">Expand</button></div><div class="chart-body large"><canvas id="capacityChart"></canvas></div></div><div class="table-toolbar"><span>Search trace</span><div><button id="capacityCopyBtn" class="mini-button" disabled>Copy table</button><button id="capacityCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Rate</th><th>Pass</th><th>Mean SLO</th><th>SLO range</th><th>Goodput</th><th>p95 TTFT</th><th>p95 E2E</th></tr></thead><tbody id="capacityRows"></tbody></table></div></div></section></div></section><section id="method" class="tab-panel"><div class="method-grid"><article class="panel prose"><div class="section-kicker">What is simulated?</div><h2>A serving loop, not CUDA kernels.</h2><p>InferScale advances virtual time through request arrivals, queueing, prefill, autoregressive decode, batch membership changes, KV allocation, and completion. A predicted 40 ms decode step becomes <code>simulated_time += 0.040</code>; the browser never waits 40 ms.</p><p>The latency backend is roofline-inspired and replaceable. v0.2 uses it to expose systems interactions, not to claim measured L4/A100 latency.</p></article><article class="panel prose"><div class="section-kicker">Why goodput?</div><h2>Throughput can reward overload.</h2><p>Goodput counts completed requests satisfying both TTFT and E2E SLOs per simulated second.</p><div class="formula">goodput = SLO-compliant completions / simulated time</div></article><article class="panel prose"><div class="section-kicker">v0.2 analysis</div><h2>Explain the limiting regime.</h2><p>Each run derives a simulator-side diagnosis from SLO failures, queue latency, busy fraction, unfinished work, and KV utilization. These labels explain simulated state, not hardware counters.</p><div class="formula">healthy | queue/prefill | decode/E2E | KV pressure | over-capacity</div></article><article class="panel prose"><div class="section-kicker">Capacity criterion</div><h2>Do not average away a bad repetition.</h2><p>A searched rate passes only when every configured repetition reaches the SLO target and fully drains. Mean, minimum, and maximum attainment remain visible in the trace.</p></article><article class="panel prose wide-method"><div class="section-kicker">Research lineage</div><h2>From Vidur to modern disaggregated simulators.</h2><div class="paper-grid"><div><strong>Vidur - 2024</strong><span>Predictive profiling and deployment search. Reported about 1 CPU-hour versus an estimated 42K GPU-hours (about $218K) for one LLaMA2-70B search.</span></div><div><strong>TokenSim - 2025</strong><span>Extensible hardware/software exploration with scheduler and memory-management modeling.</span></div><div><strong>Revati - 2026</strong><span>GPU-free time-warp emulation using serving control logic.</span></div><div><strong>LLMServingSim 2.0 - 2026</strong><span>Heterogeneous and disaggregated serving with runtime-driven batching, routing, memory, and power.</span></div><div><strong>Frontier - 2026</strong><span>Modern disaggregation, runtime optimizations, stateful workloads, and large-scale configuration exploration.</span></div></div></article></div></section></main><footer><span>InferScale-Sim v0.2.0</span><span>Simulation executes locally in your browser. Experiment data is not transmitted.</span></footer><div id="toast" class="toast" role="status" aria-live="polite"></div><script type="module" src="app.js"></script></body></html>10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727810 unmodified lines</head><body><header class="topbar" id="topbar"><div class="brand-wrap"><div><div class="brand">InferScale-Sim</div><div class="subtitle">interactive serving-systems research prototype</div></div></div><div class="runtime-pill" id="runtimePill"><span class="dot"></span><span id="runtimeText">Loading Python runtime...</span></div></header><main class="shell"><section class="intro"><div class="intro-copy"><div class="eyebrow">InferScale-Sim / v0.3.0</div><h1>Explore serving policies, cache reuse, and P/D disaggregation without provisioning a GPU.</h1><p>Generate workloads, compare schedulers, model KV pressure and prefix reuse, separate prefill from decode, and search the SLO-constrained design space. The simulator is Python running locally in a Pyodide Web Worker.</p></div><dl class="project-facts"><div><dt>Backend</dt><dd>None</dd></div><div><dt>Runtime</dt><dd>Python / WASM</dd></div><div><dt>Network data</dt><dd>None after load</dd></div><div><dt>Profiles</dt><dd>Analytical reference</dd></div></dl></section><div class="reference-note"><strong>Reference-profile mode.</strong> Absolute L4, A10G, and A100 latency values are analytical predictions, not measured GPU benchmarks. Queueing, scheduling, cache, transfer, and SLO behavior is simulated live.</div><nav class="tabs" aria-label="InferScale sections"><button class="tab active" data-tab="lab">Serving Lab</button><button class="tab" data-tab="arena">Scheduler Arena</button><button class="tab" data-tab="planner">Capacity Planner</button><button class="tab" data-tab="modern">Modern Serving</button><button class="tab" data-tab="design">Design Explorer</button><button class="tab" data-tab="method">Methodology</button></nav><section id="lab" class="tab-panel active"><div class="workspace"><aside class="panel controls-panel"><div class="panel-title-row"><h2>Experiment</h2><span class="tag">Deterministic seed</span></div><div class="field-grid two"><label>Model<select id="model"><option>Qwen2.5-3B</option><option>Llama-3.1-8B</option><option>Mistral-7B-v0.3</option></select></label><label>Weight precision<select id="quantization"><option value="fp16">FP16</option><option value="int8" selected>INT8 scenario</option><option value="int4">INT4 scenario</option></select></label></div><div class="field-grid two"><label>Topology<select id="topology"><option value="colocated">Colocated</option><option value="disaggregated_pd">P/D disaggregated</option></select></label><label id="colocatedAcceleratorLabel">Accelerator<select id="accelerator"><option value="L4">NVIDIA L4</option><option value="A10G">NVIDIA A10G</option><option value="A100-40GB">NVIDIA A100 40GB</option></select></label></div><div class="field-grid two"><label>Scheduler<select id="scheduler"><option value="continuous_fcfs">Continuous - FCFS</option><option value="continuous_sjf">Continuous - SJF</option><option value="continuous_slo">Continuous - SLO-aware</option><option value="chunked_slo">Chunked prefill - SLO-aware</option><option value="static_fcfs">Static batching - FCFS</option></select></label><label>Prefix reuse<select id="prefixCache"><option value="off">Off</option><option value="on">On</option></select></label></div><div id="prefixControls" class="subcontrols hidden"><div class="section-kicker">Shared-prefix scenario</div><div class="field-grid two"><label>Shared prefix<input id="sharedPrefix" type="number" min="0" step="32" value="256" /><span class="unit">tokens</span></label><label>Reuse fraction<input id="prefixReuse" type="number" min="0" max="1" step="0.05" value="0.60" /><span class="unit">fraction</span></label></div></div><div id="pdControls" class="subcontrols hidden"><div class="section-kicker">P/D topology</div><div class="field-grid two"><label>Prefill accelerator<select id="prefillAccelerator"><option value="L4">NVIDIA L4</option><option value="A10G">NVIDIA A10G</option><option value="A100-40GB">NVIDIA A100 40GB</option></select></label><label>Decode accelerator<select id="decodeAccelerator"><option value="L4">NVIDIA L4</option><option value="A10G">NVIDIA A10G</option><option value="A100-40GB">NVIDIA A100 40GB</option></select></label><label>Prefill workers<input id="prefillWorkers" type="number" min="1" max="8" step="1" value="1" /></label><label>Decode workers<input id="decodeWorkers" type="number" min="1" max="8" step="1" value="1" /></label><label>Interconnect<input id="interconnect" type="number" min="1" step="1" value="50" /><span class="unit">GB/s</span></label><label>Transfer base<input id="transferBase" type="number" min="0" step="0.05" value="0.20" /><span class="unit">ms</span></label></div></div><hr /><div class="section-kicker">Workload</div><div class="field-grid two"><label>Arrival process<select id="arrival"><option value="poisson">Poisson</option><option value="constant">Constant</option><option value="bursty">Bursty</option></select></label><label>Request rate<input id="rate" type="number" min="0.1" step="0.1" value="4" /><span class="unit">req/s</span></label><label>Duration<input id="duration" type="number" min="2" step="1" value="30" /><span class="unit">sim s</span></label><label>Seed<input id="seed" type="number" step="1" value="7" /></label></div><div id="burstControls" class="field-grid two hidden"><label>Burst multiplier<input id="burstMultiplier" type="number" min="1" step="0.25" value="3" /><span class="unit">x</span></label><label>Burst period<input id="burstPeriod" type="number" min="0.5" step="0.5" value="10" /><span class="unit">s</span></label></div><div class="field-grid two"><label>Prompt mean<input id="promptMean" type="number" min="16" value="512" /><span class="unit">tokens</span></label><label>Prompt CV<input id="promptCv" type="number" min="0" max="2" step="0.05" value="0.50" /></label><label>Output mean<input id="outputMean" type="number" min="1" value="64" /><span class="unit">tokens</span></label><label>Output CV<input id="outputCv" type="number" min="0" max="2" step="0.05" value="0.60" /></label></div><hr /><div class="section-kicker">Serving controls</div><div class="field-grid two"><label>Max batch size<input id="maxBatch" type="number" min="1" max="128" value="16" /></label><label>Max batch tokens<input id="maxBatchTokens" type="number" min="128" step="128" value="8192" /></label><label>Prefill chunk<input id="chunkSize" type="number" min="64" step="64" value="512" /><span class="unit">tokens</span></label><label>KV block<input id="kvBlock" type="number" min="1" value="16" /><span class="unit">tokens</span></label></div><hr /><div class="section-kicker">SLO</div><div class="field-grid two"><label>TTFT limit<input id="sloTtft" type="number" min="1" value="500" /><span class="unit">ms</span></label><label>E2E limit<input id="sloE2e" type="number" min="100" value="5000" /><span class="unit">ms</span></label></div><button id="runBtn" class="primary" disabled>Run simulation</button><div class="button-row"><button id="copyResultBtn" class="secondary" disabled>Copy JSON</button><button id="exportBtn" class="secondary" disabled>Download JSON</button></div></aside><div class="results-column"><section class="panel result-panel"><div class="panel-title-row"><h2>Run summary</h2><span id="runState" class="tag neutral">Waiting</span></div><div id="emptyState" class="empty-state"><h3>Configure a workload and run it</h3><p>The Python simulator executes in a background Web Worker and returns request-level virtual timestamps.</p></div><div id="resultContent" class="hidden"><div class="metric-grid"><div class="metric"><span>p95 TTFT</span><strong id="mTtft">N/A</strong></div><div class="metric"><span>p95 E2E</span><strong id="mE2e">N/A</strong></div><div class="metric"><span>Goodput</span><strong id="mGoodput">N/A</strong></div><div class="metric"><span>SLO attainment</span><strong id="mSlo">N/A</strong></div><div class="metric"><span>Throughput</span><strong id="mReq">N/A</strong></div><div class="metric"><span>Peak KV</span><strong id="mKv">N/A</strong></div></div><section class="diagnostic-card" id="diagnosticCard"><div class="diagnostic-head"><span>Simulator diagnosis</span><strong id="mBottleneck">N/A</strong></div><p id="mDiagnosis">Run a simulation to generate a bottleneck explanation.</p><p class="diagnostic-action" id="mRecommendation"></p><div class="evidence-row" id="mEvidence"></div></section><div class="chart-grid"><div class="chart-card" data-chart-card data-chart-name="latency-percentiles"><div class="chart-head"><div class="chart-title">Latency percentiles</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body"><canvas id="latencyChart"></canvas></div></div><div class="chart-card" data-chart-card data-chart-name="queue-decode-kv-timeline"><div class="chart-head"><div class="chart-title">Queue, decode, and KV timeline</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body"><canvas id="timelineChart"></canvas></div></div></div><div class="chart-card full" data-chart-card data-chart-name="ttft-vs-prompt-length"><div class="chart-head"><div class="chart-title">Request TTFT vs prompt length</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body"><canvas id="scatterChart"></canvas></div></div><div id="warnings" class="warnings hidden"></div></div></section></div></div></section><section id="arena" class="tab-panel"><div class="panel wide-panel"><div class="panel-title-row arena-title-row"><div><div class="section-kicker">Same workload - same seed</div><h2>Scheduler Arena</h2><p class="muted">Run every colocated v0.3 scheduler against the current Serving Lab workload and rank by SLO attainment, then goodput.</p></div><button id="arenaBtn" class="primary compact" disabled>Compare schedulers</button></div><div id="arenaEmpty" class="empty-state small"><h3>No comparison yet</h3><p>Your Serving Lab workload and model controls are reused automatically.</p></div><div id="arenaContent" class="hidden"><div class="chart-card full" data-chart-card data-chart-name="scheduler-throughput-comparison"><div class="chart-head"><div class="chart-title">Useful vs raw request throughput</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body large"><canvas id="arenaChart"></canvas></div></div><div class="table-toolbar"><span>Scheduler comparison</span><div><button id="arenaCopyBtn" class="mini-button" disabled>Copy table</button><button id="arenaCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Scheduler</th><th>Goodput</th><th>SLO attainment</th><th>p95 TTFT</th><th>p95 E2E</th><th>KV peak</th><th>Unfinished</th><th>Diagnosis</th></tr></thead><tbody id="arenaRows"></tbody></table></div></div></div></section><section id="planner" class="tab-panel"><div class="workspace planner-grid"><aside class="panel controls-panel"><div class="panel-title-row"><h2>Capacity search</h2><span class="tag">Robust binary search</span></div><p class="muted">Find the highest offered load where every repetition meets the SLO target and fully drains.</p><label>Required SLO attainment<input id="targetSlo" type="number" min="0.5" max="1" step="0.001" value="0.99" /></label><div class="field-grid two"><label>Minimum rate<input id="minRate" type="number" min="0.05" step="0.1" value="0.25" /><span class="unit">req/s</span></label><label>Maximum rate<input id="maxRate" type="number" min="0.1" step="1" value="20" /><span class="unit">req/s</span></label><label>Search iterations<input id="searchIter" type="number" min="2" max="12" value="7" /></label><label>Repetitions / rate<input id="repetitions" type="number" min="1" max="5" value="2" /></label></div><label>Safety headroom<input id="headroom" type="number" min="0" max="0.8" step="0.05" value="0.20" /><span class="unit">fraction</span></label><button id="capacityBtn" class="primary" disabled>Find sustainable capacity</button></aside><section class="panel result-panel"><div class="panel-title-row"><h2>Planner result</h2><span id="plannerState" class="tag neutral">Waiting</span></div><div id="plannerEmpty" class="empty-state"><h3>No search yet</h3><p>The planner repeatedly runs the simulator at different offered loads.</p></div><div id="plannerContent" class="hidden"><div class="metric-grid four"><div class="metric emphasis"><span>Estimated capacity</span><strong id="pCapacity">N/A</strong></div><div class="metric"><span>Recommended load</span><strong id="pRecommended">N/A</strong></div><div class="metric"><span>Safety headroom</span><strong id="pHeadroom">N/A</strong></div><div class="metric"><span>Status</span><strong id="pStatus">N/A</strong></div></div><div class="planner-note" id="plannerCriterion">A rate passes only if every repetition meets the target and drains all generated requests.</div><div class="chart-card full" data-chart-card data-chart-name="capacity-slo-curve"><div class="chart-head"><div class="chart-title">SLO attainment across searched rates</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body large"><canvas id="capacityChart"></canvas></div></div><div class="table-toolbar"><span>Search trace</span><div><button id="capacityCopyBtn" class="mini-button" disabled>Copy table</button><button id="capacityCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Rate</th><th>Pass</th><th>Mean SLO</th><th>Worst repetition</th><th>Target</th><th>SLO range</th><th>Goodput</th><th>p95 TTFT</th><th>p95 E2E</th></tr></thead><tbody id="capacityRows"></tbody></table></div></div></section></div></section><section id="modern" class="tab-panel"><div class="panel wide-panel"><div class="panel-title-row arena-title-row"><div><div class="section-kicker">P/D disaggregation + prefix reuse</div><h2>Modern Serving Lab</h2><p class="muted">Compare colocated and prefill/decode-disaggregated serving, each with and without the current shared-prefix reuse scenario. P/D worker counts and interconnect settings come from Serving Lab.</p></div><button id="topologyBtn" class="primary compact" disabled>Compare 4 scenarios</button></div><div id="topologyEmpty" class="empty-state small"><h3>No topology study yet</h3><p>Set shared-prefix and P/D parameters in Serving Lab, then run this controlled comparison.</p></div><div id="topologyContent" class="hidden"><div class="chart-card full" data-chart-card data-chart-name="topology-goodput-ttft"><div class="chart-head"><div class="chart-title">Goodput vs p95 TTFT</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body large"><canvas id="topologyChart"></canvas></div></div><div class="table-toolbar"><span>Topology and cache comparison</span><div><button id="topologyCopyBtn" class="mini-button" disabled>Copy table</button><button id="topologyCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Scenario</th><th>GPU instances</th><th>Goodput</th><th>Goodput / GPU</th><th>SLO attainment</th><th>p95 TTFT</th><th>p95 E2E</th><th>p95 KV transfer</th><th>Cache hit</th><th>Prefill saved</th><th>Diagnosis</th></tr></thead><tbody id="topologyRows"></tbody></table></div></div></div></section><section id="design" class="tab-panel"><div class="panel wide-panel"><div class="panel-title-row arena-title-row"><div><div class="section-kicker">Bounded what-if sweep</div><h2>Design Explorer</h2><p class="muted">Sweep 10 colocated candidates plus six P/D/cache variants, then identify the non-dominated goodput/TTFT frontier. This is an interactive design study, not an exhaustive optimizer.</p></div><div class="action-stack"><label class="checkline"><input id="includePd" type="checkbox" checked /> Include P/D candidates</label><button id="designBtn" class="primary compact" disabled>Explore design space</button></div></div><div id="designEmpty" class="empty-state small"><h3>No design sweep yet</h3><p>The current workload, model, SLO, and P/D parameters are reused from Serving Lab.</p></div><div id="designContent" class="hidden"><div class="metric-grid four"><div class="metric emphasis"><span>Candidates</span><strong id="dCandidates">N/A</strong></div><div class="metric"><span>Performance Pareto</span><strong id="dPareto">N/A</strong></div><div class="metric"><span>Efficiency Pareto</span><strong id="dEfficiencyPareto">N/A</strong></div><div class="metric"><span>Profile</span><strong class="metric-small">Analytical</strong></div></div><div class="chart-grid"><div class="chart-card" data-chart-card data-chart-name="design-performance-pareto-frontier"><div class="chart-head"><div class="chart-title">Raw goodput vs p95 TTFT</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body large"><canvas id="designChart"></canvas></div></div><div class="chart-card" data-chart-card data-chart-name="design-efficiency-pareto-frontier"><div class="chart-head"><div class="chart-title">Goodput per accelerator vs p95 TTFT</div><div class="chart-actions"><button class="chart-download" type="button">Download PNG</button><button class="chart-expand" type="button">Expand</button></div></div><div class="chart-body large"><canvas id="designEfficiencyChart"></canvas></div></div></div><div class="table-toolbar"><span>Candidate configurations</span><div><button id="designCopyBtn" class="mini-button" disabled>Copy table</button><button id="designCsvBtn" class="mini-button" disabled>Download CSV</button></div></div><div class="table-wrap"><table><thead><tr><th>Candidate</th><th>Perf Pareto</th><th>Efficiency Pareto</th><th>SLO pass</th><th>GPU instances</th><th>Goodput</th><th>Goodput / GPU</th><th>p95 TTFT</th><th>p95 E2E</th><th>KV peak</th><th>Diagnosis</th></tr></thead><tbody id="designRows"></tbody></table></div></div></div></section><section id="method" class="tab-panel"><div class="method-grid"><article class="panel prose"><div class="section-kicker">Simulation core</div><h2>What is actually simulated?</h2><p>Requests are generated from deterministic workload distributions and advanced through virtual time. Colocated runs model admission, prefill, paged KV allocation, dynamic decode batches, and completion. P/D runs use separate prefill and decode worker pools plus an explicit serialized KV-transfer link.</p><div class="formula">request -> queue -> prefill -> [KV transfer] -> decode -> completion</div></article><article class="panel prose"><div class="section-kicker">Prefix reuse</div><h2>Cache without pretending to implement a radix tree</h2><p>v0.3 models a single shared prompt prefix with configurable length and reuse fraction. Cache hits avoid redundant prefill work and share one persistent KV allocation. It is deliberately a controlled what-if abstraction, not a claim to reproduce SGLang's full RadixAttention policy.</p></article><article class="panel prose"><div class="section-kicker">P/D disaggregation</div><h2>Role-specific resources and transfer cost</h2><p>Prefill and decode have separate accelerator profiles and worker counts. Prompt KV state crosses a modeled interconnect before decode admission. The simulator reports role utilization, transfer latency, and transfer pressure so the benefit of isolation can be weighed against data-movement overhead.</p></article><article class="panel prose"><div class="section-kicker">Design search</div><h2>Pareto, not one magic configuration</h2><p>The Design Explorer reports both a raw-performance frontier and a resource-normalized frontier using goodput per accelerator. That prevents a multi-GPU P/D layout from looking unconditionally better merely because it uses more simulated hardware.</p></article><article class="panel prose wide-method"><div class="section-kicker">Research lineage</div><h2>Why these features are in v0.3</h2><p>Vidur established the value of simulation for avoiding expensive deployment sweeps. Recent systems have pushed toward heterogeneous and disaggregated serving, communication-aware modeling, runtime optimizations, and SLA-dependent design-space exploration. InferScale-Sim remains intentionally smaller and inspectable.</p><div class="paper-grid"><div><strong>Vidur / 2024</strong><span>Predictive profiling, workload-aware serving simulation, configuration search.</span></div><div><strong>TokenSim / 2025</strong><span>Extensible scheduling and memory-management simulation.</span></div><div><strong>Revati / 2026</strong><span>GPU-free time-warp emulation of serving control logic.</span></div><div><strong>LLMServingSim 2.0 / 2026</strong><span>Heterogeneous and disaggregated infrastructure, memory and communication.</span></div><div><strong>Frontier / May 2026</strong><span>P/D disaggregation, runtime optimizations, stateful workloads, Pareto exploration.</span></div><div><strong>HeteroPanacea / Aug 2026</strong><span>Heterogeneous stage specialization motivates resource-aware P/D comparison.</span></div><div><strong>SGLang / RadixAttention</strong><span>Automatic shared-prefix KV reuse motivates the controlled cache scenario.</span></div></div></article></div></section></main><div id="toast" class="toast" role="status"></div><script src="app.js"></script></body></html>
123456789101112131415from .api import execute, metadatafrom .models import SimulationConfigfrom .optimizer import capacity_search, compare_schedulersfrom .simulator import run_simulation__all__ = ["SimulationConfig","capacity_search","compare_schedulers","execute","metadata","run_simulation",]__version__ = "0.2.0"1234567891011121314151617from .api import execute, metadatafrom .models import SimulationConfigfrom .optimizer import capacity_search, compare_schedulers, compare_topologies, design_space_searchfrom .simulator import run_simulation__all__ = ["SimulationConfig","capacity_search","compare_schedulers","compare_topologies","design_space_search","execute","metadata","run_simulation",]__version__ = "0.3.0"
1234567891011121314151613 unmodified lines3031323334353637from __future__ import annotationsfrom .optimizer import capacity_search, compare_schedulersfrom .profiles import ACCELERATORS, MODELSfrom .simulator import SCHEDULERS, run_simulationdef metadata() -> dict:return {"version": "0.2.0","models": list(MODELS.keys()),"accelerators": list(ACCELERATORS.keys()),"schedulers": sorted(SCHEDULERS),"profile_type": "analytical-reference",}13 unmodified lines)if action == "compare":config = payload.get("config", payload)schedulers = payload.get("schedulers")return compare_schedulers(config, schedulers)if action == "metadata":return metadata()raise ValueError(f"Unknown action: {action}")123456789101112131415161713 unmodified lines31323334353637383940414243from __future__ import annotationsfrom .optimizer import capacity_search, compare_schedulers, compare_topologies, design_space_searchfrom .profiles import ACCELERATORS, MODELSfrom .simulator import SCHEDULERS, run_simulationdef metadata() -> dict:return {"version": "0.3.0","models": list(MODELS.keys()),"accelerators": list(ACCELERATORS.keys()),"schedulers": sorted(SCHEDULERS),"topologies": ["colocated", "disaggregated_pd"],"profile_type": "analytical-reference",}13 unmodified lines)if action == "compare":config = payload.get("config", payload)return compare_schedulers(config, payload.get("schedulers"))if action == "topology_compare":config = payload.get("config", payload)return compare_topologies(config)if action == "design_space":config = payload.get("config", payload)return design_space_search(config, bool(payload.get("include_disaggregated", True)))if action == "metadata":return metadata()raise ValueError(f"Unknown action: {action}")
5 unmodified lines67891011122 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line53545556575859606162636465669 unmodified lines7677787980815 unmodified linesdef diagnose_run(summary: dict[str, Any], latency: dict[str, Any], resource: dict[str, Any], cfg: SimulationConfig) -> dict[str, Any]:"""Explain the simulator's limiting regime from its own state."""target = cfg.slo_attainment_targetattainment = float(summary.get("slo_attainment", 0.0))ttft_attainment = float(summary.get("ttft_slo_attainment", 0.0))2 unmodified linesbusy = float(summary.get("busy_fraction", 0.0))kv_util = float(resource.get("peak_kv_utilization", 0.0))queue_p95 = float(latency.get("queue_ms", {}).get("p95", 0.0))code = "mixed_pressure"label = "Mixed SLO pressure"explanation = "Several constraints are active; inspect queueing, KV pressure, and tail latency together."recommendation = "Compare schedulers and run the capacity planner to isolate the limiting regime."if unfinished > 0 and kv_util >= 0.85:code, label = "kv_pressure", "KV memory pressure"explanation = "Requests remain unfinished while the simulated KV cache approaches its configured capacity."recommendation = "Reduce sequence pressure, lower offered load, use a smaller KV block, or choose a larger-memory profile."elif unfinished > 0 and busy >= 0.92:code, label = "over_capacity", "Offered load above capacity"explanation = "The virtual device remains busy while the workload fails to drain."recommendation = "Reduce offered load or use the capacity planner to find a sustainable operating point."elif unfinished > 0:code, label = "admission_stall", "Admission stall"explanation = "Some requests cannot be admitted or completed under the current serving constraints."recommendation = "Inspect batch-token and KV-cache limits, then compare a less restrictive scheduler configuration."elif attainment >= target:if busy >= 0.90:code, label = "healthy_near_saturation", "Healthy, little headroom"explanation = "The workload meets the configured SLO target, but simulated device busy time is already high."recommendation = "Run the capacity planner before increasing traffic; the current point is close to saturation."else:code, label = "healthy", "Healthy"explanation = "The workload drains and meets the configured SLO-attainment target with visible headroom."recommendation = "Use the capacity planner to quantify how much additional offered load the profile can absorb."elif kv_util >= 0.90:code, label = "kv_pressure", "KV memory pressure"explanation = "Peak simulated KV utilization is high enough to constrain admission and batching flexibility."recommendation = "Reduce sequence pressure, use smaller KV blocks, or select a larger-memory accelerator profile."elif ttft_attainment < target and queue_p95 >= max(25.0, cfg.slo_ttft_ms * 0.20):code, label = "queue_prefill_pressure", "Queue / prefill pressure"explanation = "TTFT misses coincide with substantial queueing before prefill begins."1 unmodified lineelif ttft_attainment < target:code, label = "ttft_pressure", "TTFT pressure"explanation = "First-token latency is the dominant SLO failure even though queueing is not the only contributor."recommendation = "Compare prefill-oriented schedulers and reduce prompt or offered-load pressure."elif e2e_attainment < target:code, label = "decode_pressure", "Decode / E2E pressure"explanation = "Most first tokens arrive within target, but end-to-end latency still misses the configured SLO."recommendation = "Reduce output-length pressure or offered load; larger decode batches may help when memory allows."elif busy >= 0.95:code, label = "compute_saturation", "Compute saturation"explanation = "The simulated device is effectively saturated even though no single SLO component dominates."recommendation = "Reduce load or switch to a higher-throughput accelerator profile."return {9 unmodified lines"peak_kv_utilization": kv_util,"queue_p95_ms": queue_p95,"unfinished_requests": unfinished,},"provenance": "heuristic-simulator-diagnosis",}5 unmodified lines67891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172731 unmodified line75767778798081828384858687889 unmodified lines98991001011021031041051065 unmodified linesdef diagnose_run(summary: dict[str, Any], latency: dict[str, Any], resource: dict[str, Any], cfg: SimulationConfig) -> dict[str, Any]:"""Explain the simulator's limiting regime from its own state.Diagnostics are heuristic labels over simulated telemetry; they are nothardware-counter measurements and must be interpreted with the profileprovenance attached to every run."""target = cfg.slo_attainment_targetattainment = float(summary.get("slo_attainment", 0.0))ttft_attainment = float(summary.get("ttft_slo_attainment", 0.0))2 unmodified linesbusy = float(summary.get("busy_fraction", 0.0))kv_util = float(resource.get("peak_kv_utilization", 0.0))queue_p95 = float(latency.get("queue_ms", {}).get("p95", 0.0))prefill_busy = float(resource.get("prefill_busy_fraction", 0.0))decode_busy = float(resource.get("decode_busy_fraction", 0.0))transfer_busy = float(resource.get("transfer_busy_fraction", 0.0))topology = str(resource.get("topology", cfg.topology))code = "mixed_pressure"label = "Mixed SLO pressure"explanation = "Several constraints are active; inspect queueing, KV pressure, and tail latency together."recommendation = "Compare schedulers and run the capacity planner to isolate the limiting regime."if topology == "disaggregated_pd" and transfer_busy >= 0.85 and attainment < target:code, label = "kv_transfer_pressure", "KV transfer pressure"explanation = "The simulated P/D interconnect is highly utilized and transfer time is contributing to first-token latency."recommendation = "Increase link bandwidth, reduce prompt pressure, or compare against colocated serving."elif topology == "disaggregated_pd" and prefill_busy >= 0.92 and prefill_busy > decode_busy + 0.08:code, label = "prefill_pool_pressure", "Prefill pool pressure"explanation = "Prefill workers are the hottest role in the disaggregated pipeline."recommendation = "Add prefill capacity, use prefix reuse, or reduce prompt-side pressure."elif topology == "disaggregated_pd" and decode_busy >= 0.92 and decode_busy > prefill_busy + 0.08:code, label = "decode_pool_pressure", "Decode pool pressure"explanation = "Decode workers are the hottest role in the disaggregated pipeline."recommendation = "Add decode capacity or reduce output-length / offered-load pressure."elif unfinished > 0 and kv_util >= 0.85:code, label = "kv_pressure", "KV memory pressure"explanation = "Requests remain unfinished while the simulated KV cache approaches its configured capacity."recommendation = "Reduce sequence pressure, lower offered load, use a smaller KV block, or choose a larger-memory profile."elif unfinished > 0 and busy >= 0.92:code, label = "over_capacity", "Offered load above capacity"explanation = "The virtual serving system remains busy while the workload fails to drain."recommendation = "Reduce offered load or use the capacity planner to find a sustainable operating point."elif unfinished > 0:code, label = "admission_stall", "Admission stall"explanation = "Some requests cannot be admitted or completed under the current serving constraints."recommendation = "Inspect batch-token and KV-cache limits, then compare a less restrictive configuration."elif attainment >= target:if busy >= 0.90:code, label = "healthy_near_saturation", "Healthy, little headroom"explanation = "The workload meets the configured SLO target, but simulated resource utilization is already high."recommendation = "Run the capacity planner before increasing traffic; the current point is close to saturation."else:code, label = "healthy", "Healthy"explanation = "The workload drains and meets the configured SLO-attainment target with visible headroom."recommendation = "Use the capacity planner or design explorer to quantify additional headroom."elif kv_util >= 0.90:code, label = "kv_pressure", "KV memory pressure"explanation = "Peak simulated KV utilization is high enough to constrain admission and batching flexibility."recommendation = "Reduce sequence pressure, use smaller KV blocks, enable reusable prefixes, or select a larger-memory profile."elif ttft_attainment < target and queue_p95 >= max(25.0, cfg.slo_ttft_ms * 0.20):code, label = "queue_prefill_pressure", "Queue / prefill pressure"explanation = "TTFT misses coincide with substantial queueing before prefill begins."1 unmodified lineelif ttft_attainment < target:code, label = "ttft_pressure", "TTFT pressure"explanation = "First-token latency is the dominant SLO failure even though queueing is not the only contributor."recommendation = "Compare prefill-oriented scheduling, prefix reuse, and P/D disaggregation scenarios."elif e2e_attainment < target:code, label = "decode_pressure", "Decode / E2E pressure"explanation = "Most first tokens arrive within target, but end-to-end latency still misses the configured SLO."recommendation = "Reduce output-length pressure or offered load; larger decode capacity may help when memory allows."elif busy >= 0.95:code, label = "compute_saturation", "Compute saturation"explanation = "The simulated serving resources are effectively saturated even though no single SLO component dominates."recommendation = "Reduce load or switch to a higher-throughput accelerator profile."return {9 unmodified lines"peak_kv_utilization": kv_util,"queue_p95_ms": queue_p95,"unfinished_requests": unfinished,"prefill_busy_fraction": prefill_busy,"decode_busy_fraction": decode_busy,"transfer_busy_fraction": transfer_busy,},"provenance": "heuristic-simulator-diagnosis",}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362from __future__ import annotations
import heapqfrom dataclasses import asdict, dataclass, fieldfrom itertools import count
from .diagnostics import diagnose_runfrom .kv_cache import KVCacheModelfrom .latency import AnalyticalLatencyModelfrom .metrics import percentile, summarizefrom .models import Request, SimulationConfig, SimulationResult, TimelinePointfrom .profiles import get_accelerator, get_modelfrom .workloads import generate_workload
@dataclassclass PrefillWorker: worker_id: int latency: AnalyticalLatencyModel kv: KVCacheModel busy: bool = False busy_time_s: float = 0.0
@dataclassclass DecodeWorker: worker_id: int latency: AnalyticalLatencyModel kv: KVCacheModel active: list[Request] = field(default_factory=list) busy: bool = False busy_time_s: float = 0.0 peak_kv_gb: float = 0.0
class DisaggregatedSimulator: """Two-stage prefill/decode discrete-event simulator.
v0.3 models role-specific worker pools plus a serialized analytical KV-transfer link. It is intentionally a systems abstraction, not a distributed-runtime emulator: transport, compute and memory timings remain reference-model predictions and carry explicit provenance in every result. """
def __init__(self, cfg: SimulationConfig): if cfg.prefill_workers < 1 or cfg.decode_workers < 1: raise ValueError("prefill_workers and decode_workers must be >= 1") if cfg.interconnect_gbps <= 0: raise ValueError("interconnect_gbps must be > 0")
self.cfg = cfg self.model = get_model(cfg.model) self.prefill_accelerator = get_accelerator(cfg.prefill_accelerator) self.decode_accelerator = get_accelerator(cfg.decode_accelerator) self.prefill_latency = AnalyticalLatencyModel(self.model, self.prefill_accelerator, cfg.quantization) self.decode_latency = AnalyticalLatencyModel(self.model, self.decode_accelerator, cfg.quantization)
self.prefill_workers = [ PrefillWorker(i, self.prefill_latency, KVCacheModel(self.prefill_latency, cfg)) for i in range(cfg.prefill_workers) ] self.decode_workers = [ DecodeWorker(i, self.decode_latency, KVCacheModel(self.decode_latency, cfg)) for i in range(cfg.decode_workers) ]
self.requests = generate_workload(cfg) self.prefill_waiting: list[Request] = [] self.decode_waiting: list[Request] = [] self.completed: list[Request] = [] self.events: list[tuple[float, int, str, object]] = [] self.seq = count() self.now = 0.0 self.transfer_busy_until = 0.0 self.transfer_busy_time_s = 0.0 self.transfer_gb = 0.0 self.transfer_latencies_ms: list[float] = [] self.transfer_pending = 0 self.timeline: list[TimelinePoint] = [] self.peak_total_kv_gb = 0.0 self.warnings: list[str] = []
for req in self.requests: self._push(req.arrival_time, "arrival", req)
def _push(self, time_s: float, kind: str, payload: object) -> None: heapq.heappush(self.events, (max(time_s, self.now), next(self.seq), kind, payload))
def _waiting_sorted(self, requests: list[Request]) -> list[Request]: if self.cfg.scheduler == "continuous_sjf": return sorted(requests, key=lambda r: (r.remaining_prefill + r.output_tokens, r.arrival_time)) if self.cfg.scheduler in {"continuous_slo", "chunked_slo"}: def slack(req: Request) -> tuple[float, float]: prefill = self.prefill_latency.prefill_seconds([max(req.remaining_prefill, 1)]) midpoint_context = req.prompt_tokens + max(req.output_tokens // 2, 1) decode = req.output_tokens * self.decode_latency.decode_step_seconds([midpoint_context]) return (req.deadline_time - self.now - prefill - decode, req.arrival_time)
return sorted(requests, key=slack) return sorted(requests, key=lambda r: r.arrival_time)
def _record_timeline(self, force: bool = False) -> None: target = max(self.cfg.timeline_points, 20) total_kv = sum(w.kv.used_gb(w.active) for w in self.decode_workers) total_capacity = sum(w.kv.capacity_gb for w in self.decode_workers) self.peak_total_kv_gb = max(self.peak_total_kv_gb, total_kv) for worker in self.decode_workers: worker.peak_kv_gb = max(worker.peak_kv_gb, worker.kv.used_gb(worker.active)) point = TimelinePoint( time_s=self.now, waiting=len(self.prefill_waiting), prefill_pending=sum(1 for w in self.prefill_workers if w.busy), decoding=sum(len(w.active) for w in self.decode_workers), completed=len(self.completed), kv_used_gb=total_kv, kv_capacity_gb=total_capacity, transfer_pending=self.transfer_pending, decode_ready=len(self.decode_waiting), prefill_active=sum(1 for w in self.prefill_workers if w.busy), ) if not self.timeline or force or self.now - self.timeline[-1].time_s >= max(self.cfg.duration_s / target, 0.05): self.timeline.append(point) if len(self.timeline) > target * 2: self.timeline = self.timeline[::2]
def _prefill_batch_for(self, worker: PrefillWorker) -> list[tuple[Request, int]]: if not self.prefill_waiting: return [] selected: list[tuple[Request, int]] = [] budget = self.cfg.max_batch_tokens virtual_selected: list[Request] = [] for req in self._waiting_sorted(self.prefill_waiting): if len(selected) >= self.cfg.max_batch_size or budget <= 0: break chunk = req.remaining_prefill if self.cfg.scheduler == "chunked_slo": chunk = min(chunk, self.cfg.chunk_size) chunk = min(chunk, budget) if chunk <= 0: continue if not worker.kv.can_admit(req, [], virtual_selected): continue selected.append((req, chunk)) virtual_selected.append(req) budget -= chunk return selected
def _try_start_prefill(self) -> None: for worker in self.prefill_workers: if worker.busy: continue batch = self._prefill_batch_for(worker) if not batch: continue selected_ids = {r.request_id for r, _ in batch} self.prefill_waiting = [r for r in self.prefill_waiting if r.request_id not in selected_ids] for req, _ in batch: if req.first_prefill_time is None: req.first_prefill_time = self.now delta = worker.latency.prefill_seconds([chunk for _, chunk in batch]) worker.busy = True worker.busy_time_s += delta self._push(self.now + delta, "prefill_done", (worker.worker_id, batch))
def _schedule_transfer(self, req: Request) -> None: # Cached shared-prefix KV is assumed resident in both role pools. Only # newly computed prompt state must cross the P/D boundary. bytes_to_transfer = req.uncached_prompt_tokens * self.prefill_latency.kv_bytes_per_token() gb = bytes_to_transfer / 1e9 start = max(self.now, self.transfer_busy_until) duration = self.cfg.transfer_base_ms / 1000.0 + bytes_to_transfer / (self.cfg.interconnect_gbps * 1e9) end = start + duration self.transfer_busy_until = end self.transfer_busy_time_s += duration self.transfer_gb += gb self.transfer_latencies_ms.append(duration * 1000.0) self.transfer_pending += 1 req.transfer_start_time = start req.transfer_end_time = end self._push(end, "transfer_done", req)
def _decode_order(self) -> list[Request]: return self._waiting_sorted(self.decode_waiting)
def _try_schedule_decode(self) -> None: # Admissions occur only between iterations. A worker marked busy has a # decode step already in flight and cannot accept work until it completes. for worker in self.decode_workers: if worker.busy: continue slots = self.cfg.max_batch_size - len(worker.active) if slots > 0 and self.decode_waiting: for req in list(self._decode_order()): if slots <= 0: break if worker.kv.can_admit(req, worker.active): self.decode_waiting.remove(req) req.decode_worker_id = worker.worker_id worker.active.append(req) slots -= 1 if not worker.active: continue contexts = [r.context_tokens for r in worker.active] delta = worker.latency.decode_step_seconds(contexts) worker.busy = True worker.busy_time_s += delta self._push(self.now + delta, "decode_done", worker.worker_id)
def _handle_event(self, kind: str, payload: object) -> None: if kind == "arrival": self.prefill_waiting.append(payload) # type: ignore[arg-type] self._try_start_prefill() return
if kind == "prefill_done": worker_id, batch = payload # type: ignore[misc] worker = self.prefill_workers[worker_id] worker.busy = False for req, chunk in batch: req.remaining_prefill = max(0, req.remaining_prefill - chunk) if req.remaining_prefill > 0: self.prefill_waiting.append(req) else: req.prefill_complete_time = self.now self._schedule_transfer(req) self._try_start_prefill() return
if kind == "transfer_done": req = payload # type: ignore[assignment] self.transfer_pending = max(0, self.transfer_pending - 1) self.decode_waiting.append(req) self._try_schedule_decode() return
if kind == "decode_done": worker = self.decode_workers[int(payload)] worker.busy = False for req in worker.active: req.generated_tokens += 1 if req.first_token_time is None: req.first_token_time = self.now done = [r for r in worker.active if r.complete] for req in done: req.completion_time = self.now self.completed.append(req) if done: done_ids = {r.request_id for r in done} worker.active = [r for r in worker.active if r.request_id not in done_ids] self._try_schedule_decode() return
raise RuntimeError(f"Unknown event kind: {kind}")
def run(self) -> SimulationResult: if self.cfg.scheduler == "static_fcfs": self.warnings.append("Static FCFS is not defined for P/D disaggregation; using continuous FCFS semantics.") self._record_timeline(force=True) processed = 0 max_events = max(10000, len(self.requests) * max(self.cfg.output_tokens_mean, 1) * 20)
while self.events and len(self.completed) < len(self.requests): time_s, _, kind, payload = heapq.heappop(self.events) self.now = max(self.now, time_s) self._handle_event(kind, payload) self._record_timeline() processed += 1 if processed > max_events: self.warnings.append("Simulation stopped at the event safety limit.") break
# If queued work remains with no events, the configuration is memory- or # admission-constrained rather than silently considered complete. if len(self.completed) < len(self.requests) and not self.events: self.warnings.append("Disaggregated pipeline stalled before all requests completed.")
self._record_timeline(force=True) makespan = max(self.now, self.cfg.duration_s if self.requests else 0.0) prefill_util = sum(w.busy_time_s for w in self.prefill_workers) / max(makespan * len(self.prefill_workers), 1e-9) decode_util = sum(w.busy_time_s for w in self.decode_workers) / max(makespan * len(self.decode_workers), 1e-9) transfer_util = self.transfer_busy_time_s / max(makespan, 1e-9) hottest = min(1.0, max(prefill_util, decode_util, transfer_util)) summary, latency = summarize(self.completed, self.cfg, makespan, hottest * makespan) summary["requests_generated"] = len(self.requests) summary["requests_unfinished"] = len(self.requests) - len(self.completed)
total_kv_capacity = sum(w.kv.capacity_gb for w in self.decode_workers) peak_kv_gb = self.peak_total_kv_gb peak_worker_util = max( (w.peak_kv_gb / w.kv.capacity_gb if w.kv.capacity_gb > 0 else 0.0 for w in self.decode_workers), default=0.0, ) resource = { "topology": "disaggregated_pd", "model_weight_gb": self.decode_latency.model_weight_gb, "kv_capacity_gb": total_kv_capacity, "peak_kv_gb": peak_kv_gb, "peak_kv_utilization": peak_worker_util, "prefill_accelerator_vram_gb": self.prefill_accelerator.vram_gb, "decode_accelerator_vram_gb": self.decode_accelerator.vram_gb, "prefill_workers": len(self.prefill_workers), "decode_workers": len(self.decode_workers), "accelerator_instances": len(self.prefill_workers) + len(self.decode_workers), "prefill_busy_fraction": min(1.0, prefill_util), "decode_busy_fraction": min(1.0, decode_util), "transfer_busy_fraction": min(1.0, transfer_util), "kv_transfer_gb": self.transfer_gb, "mean_transfer_ms": sum(self.transfer_latencies_ms) / len(self.transfer_latencies_ms) if self.transfer_latencies_ms else 0.0, "p95_transfer_ms": percentile(self.transfer_latencies_ms, 0.95), "interconnect_gbps": self.cfg.interconnect_gbps, "prefix_cache_gb_per_decode_worker": self.decode_workers[0].kv.shared_prefix_gb if self.decode_workers else 0.0, "prefix_cache_hits": sum(1 for r in self.requests if r.prefix_cache_hit), "prefix_cache_hit_rate": (sum(1 for r in self.requests if r.prefix_cache_hit) / len(self.requests)) if self.requests else 0.0, "prefill_tokens_saved": sum(r.cached_prefix_tokens for r in self.requests), }
request_rows = [] for req in self.completed[:2000]: transfer_ms = 0.0 if req.transfer_start_time is not None and req.transfer_end_time is not None: transfer_ms = (req.transfer_end_time - req.transfer_start_time) * 1000.0 request_rows.append( { "request_id": req.request_id, "arrival_time": req.arrival_time, "prompt_tokens": req.prompt_tokens, "output_tokens": req.output_tokens, "cached_prefix_tokens": req.cached_prefix_tokens, "decode_worker_id": req.decode_worker_id, "transfer_ms": transfer_ms, "ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None, "e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None, } )
diagnostics = diagnose_run(summary, latency, resource, self.cfg) provenance = { "simulator": "InferScale-Sim", "version": "0.3.0", "latency_profile_type": "analytical-reference", "profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.", "model_profile_source": self.model.source, "prefill_accelerator_profile_source": self.prefill_accelerator.source, "decode_accelerator_profile_source": self.decode_accelerator.source, "topology": "disaggregated_pd", "transfer_model": "serialized-reference-link", } return SimulationResult( config=self.cfg.to_dict(), provenance=provenance, summary=summary, latency=latency, resource=resource, diagnostics=diagnostics, requests=request_rows, timeline=[asdict(p) for p in self.timeline], warnings=self.warnings, )
def run_disaggregated(config: dict) -> dict: return DisaggregatedSimulator(SimulationConfig.from_dict(config)).run().to_dict()11 unmodified lines1213141516171819202122232425262728293 unmodified lines3334353637383911 unmodified linesself.cfg = cfgself.model_weight_gb = latency_model.model_weight_gbtotal_vram = latency_model.accelerator.vram_gb# Reserve non-KV space for runtime workspace and weights.remaining = max(0.0, total_vram - self.model_weight_gb - 1.2)self.capacity_gb = remaining * cfg.kv_memory_fractiondef _allocated_tokens(self, req: Request, include_output_reservation: bool = False) -> int:live_tokens = req.prompt_tokens + req.generated_tokensif self.cfg.scheduler == "static_fcfs" or include_output_reservation:# Static baseline reserves the full sequence, illustrating memory# fragmentation / over-reservation versus paged allocation.return req.prompt_tokens + req.output_tokensblock = max(self.cfg.kv_block_tokens, 1)return int(math.ceil(live_tokens / block) * block)def request_gb(self, req: Request, include_output_reservation: bool = False) -> float:tokens = self._allocated_tokens(req, include_output_reservation)3 unmodified linesrequests = list(active)if prefill_pending:requests.extend(prefill_pending)return sum(self.request_gb(r) for r in requests)def can_admit(self, req: Request, active: list[Request], prefill_pending: list[Request] | None = None) -> bool:return self.used_gb(active, prefill_pending) + self.request_gb(req) <= self.capacity_gb + 1e-1211 unmodified lines12131415161718192021222324252627282930313 unmodified lines3536373839404111 unmodified linesself.cfg = cfgself.model_weight_gb = latency_model.model_weight_gbtotal_vram = latency_model.accelerator.vram_gbremaining = max(0.0, total_vram - self.model_weight_gb - 1.2)self.capacity_gb = remaining * cfg.kv_memory_fractionself.shared_prefix_gb = 0.0if cfg.prefix_cache_enabled and cfg.shared_prefix_tokens > 0 and cfg.prefix_reuse_fraction > 0:self.shared_prefix_gb = cfg.shared_prefix_tokens * latency_model.kv_bytes_per_token() / 1e9def _allocated_tokens(self, req: Request, include_output_reservation: bool = False) -> int:# Cached prefix state is represented once by shared_prefix_gb. Per-request# allocation therefore contains only the uncached suffix + generated state.live_tokens = req.uncached_prompt_tokens + req.generated_tokensif self.cfg.scheduler == "static_fcfs" or include_output_reservation:return req.uncached_prompt_tokens + req.output_tokensblock = max(self.cfg.kv_block_tokens, 1)return int(math.ceil(max(live_tokens, 0) / block) * block)def request_gb(self, req: Request, include_output_reservation: bool = False) -> float:tokens = self._allocated_tokens(req, include_output_reservation)3 unmodified linesrequests = list(active)if prefill_pending:requests.extend(prefill_pending)return self.shared_prefix_gb + sum(self.request_gb(r) for r in requests)def can_admit(self, req: Request, active: list[Request], prefill_pending: list[Request] | None = None) -> bool:return self.used_gb(active, prefill_pending) + self.request_gb(req) <= self.capacity_gb + 1e-12
28 unmodified lines2930313233343528 unmodified linesreturn self.model.params_b * self.weight_bytes_per_paramdef kv_bytes_per_token(self) -> float:# K + V, all layers, KV heads only. KV state is assumed fp16 in v0.2.return (2* self.model.layers28 unmodified lines2930313233343528 unmodified linesreturn self.model.params_b * self.weight_bytes_per_paramdef kv_bytes_per_token(self) -> float:# K + V, all layers, KV heads only. KV state is assumed fp16 in v0.3.return (2* self.model.layers
35 unmodified lines36373839404115 unmodified lines57585960616211 unmodified lines7475767778798081828384858687888923 unmodified lines11311411511611711835 unmodified linesmodel: str = "Llama-3.1-8B"accelerator: str = "L4"scheduler: str = "continuous_fcfs"arrival_process: str = "poisson"request_rate_rps: float = 4.0duration_s: float = 60.015 unmodified linesburst_period_s: float = 10.0timeline_points: int = 300@classmethoddef from_dict(cls, data: dict[str, Any]) -> "SimulationConfig":allowed = cls.__dataclass_fields__.keys()11 unmodified linesoutput_tokens: intdeadline_time: floatremaining_prefill: intgenerated_tokens: int = 0first_prefill_time: float | None = Nonefirst_token_time: float | None = Nonecompletion_time: float | None = Nonepriority: int = 0@propertydef context_tokens(self) -> int:return self.prompt_tokens + self.generated_tokens@propertydef complete(self) -> bool:return self.generated_tokens >= self.output_tokens23 unmodified linescompleted: intkv_used_gb: floatkv_capacity_gb: float@dataclass35 unmodified lines3637383940414215 unmodified lines58596061626364656667686970717273747576777811 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711823 unmodified lines14214314414514614714814915035 unmodified linesmodel: str = "Llama-3.1-8B"accelerator: str = "L4"scheduler: str = "continuous_fcfs"topology: str = "colocated"arrival_process: str = "poisson"request_rate_rps: float = 4.0duration_s: float = 60.015 unmodified linesburst_period_s: float = 10.0timeline_points: int = 300# Prefix-cache scenario. v0.3 intentionally models one reusable shared# prefix rather than a full radix tree. Hits share one persistent KV entry.prefix_cache_enabled: bool = Falseshared_prefix_tokens: int = 256prefix_reuse_fraction: float = 0.0# Prefill/decode disaggregation scenario. These fields are ignored for the# colocated topology. Interconnect bandwidth is expressed in GB/s.prefill_accelerator: str = "L4"decode_accelerator: str = "L4"prefill_workers: int = 1decode_workers: int = 1interconnect_gbps: float = 50.0transfer_base_ms: float = 0.20@classmethoddef from_dict(cls, data: dict[str, Any]) -> "SimulationConfig":allowed = cls.__dataclass_fields__.keys()11 unmodified linesoutput_tokens: intdeadline_time: floatremaining_prefill: intcached_prefix_tokens: int = 0generated_tokens: int = 0first_prefill_time: float | None = Noneprefill_complete_time: float | None = Nonetransfer_start_time: float | None = Nonetransfer_end_time: float | None = Nonefirst_token_time: float | None = Nonecompletion_time: float | None = Nonedecode_worker_id: int | None = Nonepriority: int = 0@propertydef context_tokens(self) -> int:return self.prompt_tokens + self.generated_tokens@propertydef uncached_prompt_tokens(self) -> int:return max(0, self.prompt_tokens - self.cached_prefix_tokens)@propertydef prefix_cache_hit(self) -> bool:return self.cached_prefix_tokens > 0@propertydef complete(self) -> bool:return self.generated_tokens >= self.output_tokens23 unmodified linescompleted: intkv_used_gb: floatkv_capacity_gb: floattransfer_pending: int = 0decode_ready: int = 0prefill_active: int = 0@dataclass
39 unmodified lines40414243444564 unmodified lines11011111211311411514 unmodified lines13013113239 unmodified lines"max_unfinished": max(unfinished_values),"repetitions": repetitions,"criterion": "all-repetitions-meet-target-and-drain",}64 unmodified lines"chunked_slo",]base = SimulationConfig.from_dict(config)rows = []for scheduler in schedulers:cfg = deepcopy(base)14 unmodified lines)rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}39 unmodified lines4041424344454664 unmodified lines11111211311411511611714 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327439 unmodified lines"max_unfinished": max(unfinished_values),"repetitions": repetitions,"criterion": "all-repetitions-meet-target-and-drain","target": base.slo_attainment_target,}64 unmodified lines"chunked_slo",]base = SimulationConfig.from_dict(config)base.topology = "colocated"rows = []for scheduler in schedulers:cfg = deepcopy(base)14 unmodified lines)rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}def compare_topologies(config: dict) -> dict:"""Compare colocated and P/D-disaggregated serving on one deterministic trace."""base = SimulationConfig.from_dict(config)rows = []scenarios = [("colocated", False),("colocated", True),("disaggregated_pd", False),("disaggregated_pd", True),]for topology, cache_enabled in scenarios:cfg = deepcopy(base)cfg.topology = topologycfg.prefix_cache_enabled = cache_enabledif topology == "disaggregated_pd" and cfg.scheduler == "static_fcfs":cfg.scheduler = "continuous_fcfs"result = run_simulation(cfg.to_dict())resource = result["resource"]accelerator_instances = int(resource.get("accelerator_instances", 1))goodput_rps = result["summary"]["goodput_rps"]rows.append({"scenario": f"{topology}{'_cache' if cache_enabled else ''}","topology": topology,"prefix_cache": cache_enabled,"accelerator_instances": accelerator_instances,"goodput_rps": goodput_rps,"goodput_per_accelerator": goodput_rps / max(accelerator_instances, 1),"request_throughput_rps": result["summary"]["request_throughput_rps"],"slo_attainment": result["summary"]["slo_attainment"],"p95_ttft_ms": result["latency"]["ttft_ms"]["p95"],"p95_e2e_ms": result["latency"]["e2e_ms"]["p95"],"peak_kv_utilization": resource.get("peak_kv_utilization", 0.0),"prefix_hit_rate": resource.get("prefix_cache_hit_rate", 0.0),"prefill_tokens_saved": resource.get("prefill_tokens_saved", 0),"p95_transfer_ms": resource.get("p95_transfer_ms", 0.0),"prefill_busy_fraction": resource.get("prefill_busy_fraction", 0.0),"decode_busy_fraction": resource.get("decode_busy_fraction", result["summary"].get("busy_fraction", 0.0)),"transfer_busy_fraction": resource.get("transfer_busy_fraction", 0.0),"bottleneck": result["diagnostics"]["label"],})rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}def _is_dominated(candidate: dict, rows: list[dict], throughput_key: str = "goodput_rps") -> bool:for other in rows:if other is candidate:continueno_worse = (other[throughput_key] >= candidate[throughput_key]and other["p95_ttft_ms"] <= candidate["p95_ttft_ms"])strictly_better = (other[throughput_key] > candidate[throughput_key]or other["p95_ttft_ms"] < candidate["p95_ttft_ms"])if no_worse and strictly_better:return Truereturn Falsedef design_space_search(config: dict, include_disaggregated: bool = True) -> dict:"""Small browser-safe design-space sweep with a goodput/TTFT Pareto frontier.The sweep is intentionally bounded: its purpose is to expose configurationinteractions interactively, not to claim exhaustive optimization."""base = SimulationConfig.from_dict(config)rows: list[dict] = []colocated_candidates = []for scheduler in ["continuous_fcfs", "continuous_slo", "chunked_slo"]:for batch in [8, 16, 32]:colocated_candidates.append((scheduler, batch, False))# Prefix reuse is added as a separate systems dimension for the SLO-aware# scheduler at the user's current batch size.colocated_candidates.append(("continuous_slo", base.max_batch_size, True))for scheduler, batch, cache in colocated_candidates:cfg = deepcopy(base)cfg.topology = "colocated"cfg.scheduler = schedulercfg.max_batch_size = batchcfg.prefix_cache_enabled = cacheresult = run_simulation(cfg.to_dict())rows.append(_design_row(result, cfg, f"colocated / {scheduler} / batch {batch}{' / cache' if cache else ''}"))if include_disaggregated:for prefill_workers, decode_workers in [(1, 1), (1, 2), (2, 1)]:for cache in [False, True]:cfg = deepcopy(base)cfg.topology = "disaggregated_pd"cfg.scheduler = "continuous_slo"cfg.prefill_workers = prefill_workerscfg.decode_workers = decode_workerscfg.prefix_cache_enabled = cacheresult = run_simulation(cfg.to_dict())label = f"P/D {prefill_workers}P:{decode_workers}D{' / cache' if cache else ''}"rows.append(_design_row(result, cfg, label))for row in rows:row["pareto"] = not _is_dominated(row, rows, "goodput_rps")row["efficiency_pareto"] = not _is_dominated(row, rows, "goodput_per_accelerator")rows.sort(key=lambda r: (not r["pareto"], not r["slo_pass"], -r["goodput_rps"], r["p95_ttft_ms"]))return {"rows": rows,"pareto_count": sum(1 for r in rows if r["pareto"]),"efficiency_pareto_count": sum(1 for r in rows if r["efficiency_pareto"]),"candidate_count": len(rows),"objectives": ["performance: maximize goodput / minimize p95 TTFT","efficiency: maximize goodput per accelerator / minimize p95 TTFT",],}def _design_row(result: dict, cfg: SimulationConfig, label: str) -> dict:resource = result["resource"]accelerator_instances = int(resource.get("accelerator_instances", 1))goodput_rps = result["summary"]["goodput_rps"]return {"label": label,"topology": cfg.topology,"scheduler": cfg.scheduler,"max_batch_size": cfg.max_batch_size,"prefix_cache": cfg.prefix_cache_enabled,"accelerator_instances": accelerator_instances,"goodput_rps": goodput_rps,"goodput_per_accelerator": goodput_rps / max(accelerator_instances, 1),"slo_attainment": result["summary"]["slo_attainment"],"slo_pass": result["summary"]["slo_attainment"] >= cfg.slo_attainment_target and result["summary"]["requests_unfinished"] == 0,"p95_ttft_ms": result["latency"]["ttft_ms"]["p95"],"p95_e2e_ms": result["latency"]["e2e_ms"]["p95"],"peak_kv_utilization": resource.get("peak_kv_utilization", 0.0),"bottleneck": result["diagnostics"]["label"],}
120 unmodified lines1211221231241251261271281291301311322 unmodified lines13513613713813914014135 unmodified lines17717817918018118218333 unmodified lines21721821922022122222358 unmodified lines2822832842852862875 unmodified lines2932942952962972982 unmodified lines30130230330430530630730830931031110 unmodified lines322323324325120 unmodified linesfor req in self._waiting_sorted():if len(selected) >= slots:breakif selected and total_tokens + req.prompt_tokens > self.cfg.max_batch_tokens:continueif not self.kv.can_admit(req, self.active, selected):continueselected.append(req)total_tokens += req.prompt_tokensif not selected:return False2 unmodified linesfor req in selected:if req.first_prefill_time is None:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.prompt_tokens for r in selected]))for req in selected:req.remaining_prefill = 0self.active.append(req)35 unmodified lines# One prefill chunk. Decode is serviced on the next loop iteration,# producing the intended prefill/decode interleaving.self._advance(self.latency.prefill_seconds(chunks))for req, chunk in zip(selected, chunks):req.remaining_prefill -= chunkif req.remaining_prefill <= 0:self.prefill_pending.remove(req)33 unmodified linesself.waiting = [r for r in self.waiting if r.request_id not in ids]for req in admitted:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.prompt_tokens for r in admitted]))for req in admitted:req.remaining_prefill = 0self.active.append(req)58 unmodified lines"peak_kv_gb": self.peak_kv_gb,"peak_kv_utilization": self.peak_kv_gb / self.kv.capacity_gb if self.kv.capacity_gb > 0 else 0.0,"accelerator_vram_gb": self.accelerator.vram_gb,}request_rows = []5 unmodified lines"arrival_time": req.arrival_time,"prompt_tokens": req.prompt_tokens,"output_tokens": req.output_tokens,"ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None,"e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None,})2 unmodified linesprovenance = {"simulator": "InferScale-Sim","version": "0.2.0","latency_profile_type": "analytical-reference","profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.","model_profile_source": self.model.source,"accelerator_profile_source": self.accelerator.source,}return SimulationResult(10 unmodified linesdef run_simulation(config: dict) -> dict:return Simulator(SimulationConfig.from_dict(config)).run().to_dict()120 unmodified lines1211221231241251261271281291301311322 unmodified lines13513613713813914014135 unmodified lines17717817918018118218333 unmodified lines21721821922022122222358 unmodified lines2822832842852862872882892902912922935 unmodified lines2993003013023033043052 unmodified lines30830931031131231331431531631731831910 unmodified lines330331332333334335336337338339340120 unmodified linesfor req in self._waiting_sorted():if len(selected) >= slots:breakif selected and total_tokens + req.remaining_prefill > self.cfg.max_batch_tokens:continueif not self.kv.can_admit(req, self.active, selected):continueselected.append(req)total_tokens += req.remaining_prefillif not selected:return False2 unmodified linesfor req in selected:if req.first_prefill_time is None:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.remaining_prefill for r in selected]))for req in selected:req.remaining_prefill = 0self.active.append(req)35 unmodified lines# One prefill chunk. Decode is serviced on the next loop iteration,# producing the intended prefill/decode interleaving.self._advance(self.latency.prefill_seconds(chunks))for req, chunk in zip(selected, chunks, strict=True):req.remaining_prefill -= chunkif req.remaining_prefill <= 0:self.prefill_pending.remove(req)33 unmodified linesself.waiting = [r for r in self.waiting if r.request_id not in ids]for req in admitted:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.remaining_prefill for r in admitted]))for req in admitted:req.remaining_prefill = 0self.active.append(req)58 unmodified lines"peak_kv_gb": self.peak_kv_gb,"peak_kv_utilization": self.peak_kv_gb / self.kv.capacity_gb if self.kv.capacity_gb > 0 else 0.0,"accelerator_vram_gb": self.accelerator.vram_gb,"topology": "colocated","accelerator_instances": 1,"prefix_cache_gb": self.kv.shared_prefix_gb,"prefix_cache_hits": sum(1 for r in self.requests if r.prefix_cache_hit),"prefix_cache_hit_rate": (sum(1 for r in self.requests if r.prefix_cache_hit) / len(self.requests)) if self.requests else 0.0,"prefill_tokens_saved": sum(r.cached_prefix_tokens for r in self.requests),}request_rows = []5 unmodified lines"arrival_time": req.arrival_time,"prompt_tokens": req.prompt_tokens,"output_tokens": req.output_tokens,"cached_prefix_tokens": req.cached_prefix_tokens,"ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None,"e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None,})2 unmodified linesprovenance = {"simulator": "InferScale-Sim","version": "0.3.0","latency_profile_type": "analytical-reference","profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.","model_profile_source": self.model.source,"accelerator_profile_source": self.accelerator.source,"topology": "colocated",}return SimulationResult(10 unmodified linesdef run_simulation(config: dict) -> dict:cfg = SimulationConfig.from_dict(config)if cfg.topology == "disaggregated_pd":from .disaggregated import DisaggregatedSimulatorreturn DisaggregatedSimulator(cfg).run().to_dict()if cfg.topology != "colocated":raise ValueError(f"Unsupported topology: {cfg.topology}")return Simulator(cfg).run().to_dict()
28 unmodified lines29303132333435363714 unmodified lines525354555657585960611 unmodified line6364656667686928 unmodified linesreturn arrivalsif cfg.arrival_process == "bursty":# Alternating baseline/high-load windows. The mean offered load is not# forced to equal request_rate_rps; the UI labels this clearly as a burst# stress test rather than an average-rate generator.while t < cfg.duration_s:phase = int(t // max(cfg.burst_period_s, 0.1)) % 2local_rate = rate * (cfg.burst_multiplier if phase else 0.55)14 unmodified linesdef generate_workload(cfg: SimulationConfig) -> list[Request]:rng = random.Random(cfg.seed)requests: list[Request] = []for idx, arrival in enumerate(_arrival_times(cfg, rng)):prompt = _sample_lognormal(cfg.prompt_tokens_mean, cfg.prompt_tokens_cv, rng)output = _sample_lognormal(cfg.output_tokens_mean, cfg.output_tokens_cv, rng)requests.append(Request(request_id=idx,1 unmodified lineprompt_tokens=prompt,output_tokens=output,deadline_time=arrival + cfg.slo_e2e_ms / 1000.0,remaining_prefill=prompt,))return requests28 unmodified lines29303132333414 unmodified lines4950515253545556575859606162631 unmodified line656667686970717228 unmodified linesreturn arrivalsif cfg.arrival_process == "bursty":while t < cfg.duration_s:phase = int(t // max(cfg.burst_period_s, 0.1)) % 2local_rate = rate * (cfg.burst_multiplier if phase else 0.55)14 unmodified linesdef generate_workload(cfg: SimulationConfig) -> list[Request]:rng = random.Random(cfg.seed)cache_rng = random.Random(cfg.seed ^ 0x5A17CACE)requests: list[Request] = []for idx, arrival in enumerate(_arrival_times(cfg, rng)):prompt = _sample_lognormal(cfg.prompt_tokens_mean, cfg.prompt_tokens_cv, rng)output = _sample_lognormal(cfg.output_tokens_mean, cfg.output_tokens_cv, rng)cached = 0if cfg.prefix_cache_enabled and cfg.shared_prefix_tokens > 0 and cfg.prefix_reuse_fraction > 0:if cache_rng.random() < min(max(cfg.prefix_reuse_fraction, 0.0), 1.0):cached = min(cfg.shared_prefix_tokens, max(prompt - 1, 0))requests.append(Request(request_id=idx,1 unmodified lineprompt_tokens=prompt,output_tokens=output,deadline_time=arrival + cfg.slo_e2e_ms / 1000.0,remaining_prefill=max(0, prompt - cached),cached_prefix_tokens=cached,))return requests
3 unmodified lines456789103 unmodified lines[project]name = "inferscale-sim"version = "0.2.0"description = "Interactive LLM serving simulator and SLO capacity planner"readme = "README.md"requires-python = ">=3.10"3 unmodified lines456789103 unmodified lines[project]name = "inferscale-sim"version = "0.3.0"description = "Interactive LLM serving simulator and SLO capacity planner"readme = "README.md"requires-python = ">=3.10"
123453 unmodified lines91011121314158 unmodified lines242526272829303115 unmodified lines47484950515210 unmodified lines63646566676869707172735 unmodified lines798081828384from __future__ import annotationsimport reimport sysfrom pathlib import Path3 unmodified linesSRC = ROOT / "src"sys.path.insert(0, str(SRC))from inferscale import __version__, run_simulation # noqa: E402errors: list[str] = []8 unmodified linesif "sdk: static" not in README:errors.append("README metadata must use sdk: static")if __version__ != "0.2.0":errors.append(f"package version is {__version__}; expected 0.2.0")src_files = sorted((ROOT / "src" / "inferscale").glob("*.py"))web_files = sorted((ROOT / "py" / "inferscale").glob("*.py"))15 unmodified linesexcept UnicodeEncodeError:errors.append(f"{ui_file.name} contains non-ASCII UI glyphs; use text labels for reliable rendering")smoke_cfg = {"model": "Qwen2.5-3B","accelerator": "L4",10 unmodified linesif smoke["provenance"]["latency_profile_type"] != "analytical-reference":errors.append("profile provenance guard is missing")if smoke["diagnostics"].get("provenance") != "heuristic-simulator-diagnosis":errors.append("v0.2 diagnosis provenance missing")if "ttft_slo_attainment" not in smoke["summary"] or "e2e_slo_attainment" not in smoke["summary"]:errors.append("component SLO metrics missing")except Exception as exc: # pragma: no cover - release diagnosticerrors.append(f"simulation smoke test raised: {exc}")if errors:print("InferScale release check: FAIL")5 unmodified linesprint(f"Version: {__version__}")print(f"HF short_description: {len(short)}/60 characters")print(f"Python modules mirrored: {len(src_files)}")print(f"Smoke requests completed: {smoke['summary']['requests_completed']}")print(f"Profile provenance: {smoke['provenance']['latency_profile_type']}")print(f"Diagnosis: {smoke['diagnostics']['label']}")1234563 unmodified lines101112131415161718198 unmodified lines282930313233343515 unmodified lines51525354555657585960616263646510 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121135 unmodified lines119120121122123124125126127128from __future__ import annotationsimport importlibimport reimport sysfrom pathlib import Path3 unmodified linesSRC = ROOT / "src"sys.path.insert(0, str(SRC))inferscale = importlib.import_module("inferscale")__version__ = inferscale.__version__design_space_search = inferscale.design_space_searchrun_simulation = inferscale.run_simulationerrors: list[str] = []8 unmodified linesif "sdk: static" not in README:errors.append("README metadata must use sdk: static")if __version__ != "0.3.0":errors.append(f"package version is {__version__}; expected 0.3.0")src_files = sorted((ROOT / "src" / "inferscale").glob("*.py"))web_files = sorted((ROOT / "py" / "inferscale").glob("*.py"))15 unmodified linesexcept UnicodeEncodeError:errors.append(f"{ui_file.name} contains non-ASCII UI glyphs; use text labels for reliable rendering")index = (ROOT / "index.html").read_text()app = (ROOT / "app.js").read_text()if "<footer" in index.lower():errors.append("v0.3 UI should not include the old product-style footer")if "Download PNG" not in index or ".chart-download" not in app:errors.append("chart PNG export controls are missing")if "Worst repetition" not in index or "Target" not in index:errors.append("capacity evidence columns are missing")smoke_cfg = {"model": "Qwen2.5-3B","accelerator": "L4",10 unmodified linesif smoke["provenance"]["latency_profile_type"] != "analytical-reference":errors.append("profile provenance guard is missing")if smoke["diagnostics"].get("provenance") != "heuristic-simulator-diagnosis":errors.append("diagnosis provenance missing")if "prefix_cache_hit_rate" not in smoke["resource"]:errors.append("prefix-cache telemetry missing")except Exception as exc: # pragma: no covererrors.append(f"colocated smoke test raised: {exc}")try:pd = run_simulation(smoke_cfg | {"topology": "disaggregated_pd","scheduler": "continuous_slo","prefill_accelerator": "L4","decode_accelerator": "L4","interconnect_gbps": 50,})if pd["provenance"].get("topology") != "disaggregated_pd":errors.append("P/D provenance missing")if pd["resource"].get("p95_transfer_ms", 0) <= 0:errors.append("P/D transfer telemetry missing")except Exception as exc: # pragma: no covererrors.append(f"P/D smoke test raised: {exc}")try:design = design_space_search(smoke_cfg | {"shared_prefix_tokens": 64,"prefix_reuse_fraction": 0.5,"prefill_accelerator": "L4","decode_accelerator": "L4",}, include_disaggregated=False)if design["candidate_count"] != 10 or design["pareto_count"] < 1 or design["efficiency_pareto_count"] < 1:errors.append("design-space smoke test did not return both expected Pareto frontiers")except Exception as exc: # pragma: no covererrors.append(f"design-space smoke test raised: {exc}")if errors:print("InferScale release check: FAIL")5 unmodified linesprint(f"Version: {__version__}")print(f"HF short_description: {len(short)}/60 characters")print(f"Python modules mirrored: {len(src_files)}")print(f"Colocated smoke requests: {smoke['summary']['requests_completed']}")print(f"P/D transfer p95: {pd['resource']['p95_transfer_ms']:.3f} ms")print(f"Design candidates: {design['candidate_count']} "f"({design['pareto_count']} performance Pareto, {design['efficiency_pareto_count']} efficiency Pareto)")print(f"Profile provenance: {smoke['provenance']['latency_profile_type']}")
123456789101112131415from .api import execute, metadatafrom .models import SimulationConfigfrom .optimizer import capacity_search, compare_schedulersfrom .simulator import run_simulation__all__ = ["SimulationConfig","capacity_search","compare_schedulers","execute","metadata","run_simulation",]__version__ = "0.2.0"1234567891011121314151617from .api import execute, metadatafrom .models import SimulationConfigfrom .optimizer import capacity_search, compare_schedulers, compare_topologies, design_space_searchfrom .simulator import run_simulation__all__ = ["SimulationConfig","capacity_search","compare_schedulers","compare_topologies","design_space_search","execute","metadata","run_simulation",]__version__ = "0.3.0"
1234567891011121314151613 unmodified lines3031323334353637from __future__ import annotationsfrom .optimizer import capacity_search, compare_schedulersfrom .profiles import ACCELERATORS, MODELSfrom .simulator import SCHEDULERS, run_simulationdef metadata() -> dict:return {"version": "0.2.0","models": list(MODELS.keys()),"accelerators": list(ACCELERATORS.keys()),"schedulers": sorted(SCHEDULERS),"profile_type": "analytical-reference",}13 unmodified lines)if action == "compare":config = payload.get("config", payload)schedulers = payload.get("schedulers")return compare_schedulers(config, schedulers)if action == "metadata":return metadata()raise ValueError(f"Unknown action: {action}")123456789101112131415161713 unmodified lines31323334353637383940414243from __future__ import annotationsfrom .optimizer import capacity_search, compare_schedulers, compare_topologies, design_space_searchfrom .profiles import ACCELERATORS, MODELSfrom .simulator import SCHEDULERS, run_simulationdef metadata() -> dict:return {"version": "0.3.0","models": list(MODELS.keys()),"accelerators": list(ACCELERATORS.keys()),"schedulers": sorted(SCHEDULERS),"topologies": ["colocated", "disaggregated_pd"],"profile_type": "analytical-reference",}13 unmodified lines)if action == "compare":config = payload.get("config", payload)return compare_schedulers(config, payload.get("schedulers"))if action == "topology_compare":config = payload.get("config", payload)return compare_topologies(config)if action == "design_space":config = payload.get("config", payload)return design_space_search(config, bool(payload.get("include_disaggregated", True)))if action == "metadata":return metadata()raise ValueError(f"Unknown action: {action}")
5 unmodified lines67891011122 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line53545556575859606162636465669 unmodified lines7677787980815 unmodified linesdef diagnose_run(summary: dict[str, Any], latency: dict[str, Any], resource: dict[str, Any], cfg: SimulationConfig) -> dict[str, Any]:"""Explain the simulator's limiting regime from its own state."""target = cfg.slo_attainment_targetattainment = float(summary.get("slo_attainment", 0.0))ttft_attainment = float(summary.get("ttft_slo_attainment", 0.0))2 unmodified linesbusy = float(summary.get("busy_fraction", 0.0))kv_util = float(resource.get("peak_kv_utilization", 0.0))queue_p95 = float(latency.get("queue_ms", {}).get("p95", 0.0))code = "mixed_pressure"label = "Mixed SLO pressure"explanation = "Several constraints are active; inspect queueing, KV pressure, and tail latency together."recommendation = "Compare schedulers and run the capacity planner to isolate the limiting regime."if unfinished > 0 and kv_util >= 0.85:code, label = "kv_pressure", "KV memory pressure"explanation = "Requests remain unfinished while the simulated KV cache approaches its configured capacity."recommendation = "Reduce sequence pressure, lower offered load, use a smaller KV block, or choose a larger-memory profile."elif unfinished > 0 and busy >= 0.92:code, label = "over_capacity", "Offered load above capacity"explanation = "The virtual device remains busy while the workload fails to drain."recommendation = "Reduce offered load or use the capacity planner to find a sustainable operating point."elif unfinished > 0:code, label = "admission_stall", "Admission stall"explanation = "Some requests cannot be admitted or completed under the current serving constraints."recommendation = "Inspect batch-token and KV-cache limits, then compare a less restrictive scheduler configuration."elif attainment >= target:if busy >= 0.90:code, label = "healthy_near_saturation", "Healthy, little headroom"explanation = "The workload meets the configured SLO target, but simulated device busy time is already high."recommendation = "Run the capacity planner before increasing traffic; the current point is close to saturation."else:code, label = "healthy", "Healthy"explanation = "The workload drains and meets the configured SLO-attainment target with visible headroom."recommendation = "Use the capacity planner to quantify how much additional offered load the profile can absorb."elif kv_util >= 0.90:code, label = "kv_pressure", "KV memory pressure"explanation = "Peak simulated KV utilization is high enough to constrain admission and batching flexibility."recommendation = "Reduce sequence pressure, use smaller KV blocks, or select a larger-memory accelerator profile."elif ttft_attainment < target and queue_p95 >= max(25.0, cfg.slo_ttft_ms * 0.20):code, label = "queue_prefill_pressure", "Queue / prefill pressure"explanation = "TTFT misses coincide with substantial queueing before prefill begins."1 unmodified lineelif ttft_attainment < target:code, label = "ttft_pressure", "TTFT pressure"explanation = "First-token latency is the dominant SLO failure even though queueing is not the only contributor."recommendation = "Compare prefill-oriented schedulers and reduce prompt or offered-load pressure."elif e2e_attainment < target:code, label = "decode_pressure", "Decode / E2E pressure"explanation = "Most first tokens arrive within target, but end-to-end latency still misses the configured SLO."recommendation = "Reduce output-length pressure or offered load; larger decode batches may help when memory allows."elif busy >= 0.95:code, label = "compute_saturation", "Compute saturation"explanation = "The simulated device is effectively saturated even though no single SLO component dominates."recommendation = "Reduce load or switch to a higher-throughput accelerator profile."return {9 unmodified lines"peak_kv_utilization": kv_util,"queue_p95_ms": queue_p95,"unfinished_requests": unfinished,},"provenance": "heuristic-simulator-diagnosis",}5 unmodified lines67891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172731 unmodified line75767778798081828384858687889 unmodified lines98991001011021031041051065 unmodified linesdef diagnose_run(summary: dict[str, Any], latency: dict[str, Any], resource: dict[str, Any], cfg: SimulationConfig) -> dict[str, Any]:"""Explain the simulator's limiting regime from its own state.Diagnostics are heuristic labels over simulated telemetry; they are nothardware-counter measurements and must be interpreted with the profileprovenance attached to every run."""target = cfg.slo_attainment_targetattainment = float(summary.get("slo_attainment", 0.0))ttft_attainment = float(summary.get("ttft_slo_attainment", 0.0))2 unmodified linesbusy = float(summary.get("busy_fraction", 0.0))kv_util = float(resource.get("peak_kv_utilization", 0.0))queue_p95 = float(latency.get("queue_ms", {}).get("p95", 0.0))prefill_busy = float(resource.get("prefill_busy_fraction", 0.0))decode_busy = float(resource.get("decode_busy_fraction", 0.0))transfer_busy = float(resource.get("transfer_busy_fraction", 0.0))topology = str(resource.get("topology", cfg.topology))code = "mixed_pressure"label = "Mixed SLO pressure"explanation = "Several constraints are active; inspect queueing, KV pressure, and tail latency together."recommendation = "Compare schedulers and run the capacity planner to isolate the limiting regime."if topology == "disaggregated_pd" and transfer_busy >= 0.85 and attainment < target:code, label = "kv_transfer_pressure", "KV transfer pressure"explanation = "The simulated P/D interconnect is highly utilized and transfer time is contributing to first-token latency."recommendation = "Increase link bandwidth, reduce prompt pressure, or compare against colocated serving."elif topology == "disaggregated_pd" and prefill_busy >= 0.92 and prefill_busy > decode_busy + 0.08:code, label = "prefill_pool_pressure", "Prefill pool pressure"explanation = "Prefill workers are the hottest role in the disaggregated pipeline."recommendation = "Add prefill capacity, use prefix reuse, or reduce prompt-side pressure."elif topology == "disaggregated_pd" and decode_busy >= 0.92 and decode_busy > prefill_busy + 0.08:code, label = "decode_pool_pressure", "Decode pool pressure"explanation = "Decode workers are the hottest role in the disaggregated pipeline."recommendation = "Add decode capacity or reduce output-length / offered-load pressure."elif unfinished > 0 and kv_util >= 0.85:code, label = "kv_pressure", "KV memory pressure"explanation = "Requests remain unfinished while the simulated KV cache approaches its configured capacity."recommendation = "Reduce sequence pressure, lower offered load, use a smaller KV block, or choose a larger-memory profile."elif unfinished > 0 and busy >= 0.92:code, label = "over_capacity", "Offered load above capacity"explanation = "The virtual serving system remains busy while the workload fails to drain."recommendation = "Reduce offered load or use the capacity planner to find a sustainable operating point."elif unfinished > 0:code, label = "admission_stall", "Admission stall"explanation = "Some requests cannot be admitted or completed under the current serving constraints."recommendation = "Inspect batch-token and KV-cache limits, then compare a less restrictive configuration."elif attainment >= target:if busy >= 0.90:code, label = "healthy_near_saturation", "Healthy, little headroom"explanation = "The workload meets the configured SLO target, but simulated resource utilization is already high."recommendation = "Run the capacity planner before increasing traffic; the current point is close to saturation."else:code, label = "healthy", "Healthy"explanation = "The workload drains and meets the configured SLO-attainment target with visible headroom."recommendation = "Use the capacity planner or design explorer to quantify additional headroom."elif kv_util >= 0.90:code, label = "kv_pressure", "KV memory pressure"explanation = "Peak simulated KV utilization is high enough to constrain admission and batching flexibility."recommendation = "Reduce sequence pressure, use smaller KV blocks, enable reusable prefixes, or select a larger-memory profile."elif ttft_attainment < target and queue_p95 >= max(25.0, cfg.slo_ttft_ms * 0.20):code, label = "queue_prefill_pressure", "Queue / prefill pressure"explanation = "TTFT misses coincide with substantial queueing before prefill begins."1 unmodified lineelif ttft_attainment < target:code, label = "ttft_pressure", "TTFT pressure"explanation = "First-token latency is the dominant SLO failure even though queueing is not the only contributor."recommendation = "Compare prefill-oriented scheduling, prefix reuse, and P/D disaggregation scenarios."elif e2e_attainment < target:code, label = "decode_pressure", "Decode / E2E pressure"explanation = "Most first tokens arrive within target, but end-to-end latency still misses the configured SLO."recommendation = "Reduce output-length pressure or offered load; larger decode capacity may help when memory allows."elif busy >= 0.95:code, label = "compute_saturation", "Compute saturation"explanation = "The simulated serving resources are effectively saturated even though no single SLO component dominates."recommendation = "Reduce load or switch to a higher-throughput accelerator profile."return {9 unmodified lines"peak_kv_utilization": kv_util,"queue_p95_ms": queue_p95,"unfinished_requests": unfinished,"prefill_busy_fraction": prefill_busy,"decode_busy_fraction": decode_busy,"transfer_busy_fraction": transfer_busy,},"provenance": "heuristic-simulator-diagnosis",}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362from __future__ import annotations
import heapqfrom dataclasses import asdict, dataclass, fieldfrom itertools import count
from .diagnostics import diagnose_runfrom .kv_cache import KVCacheModelfrom .latency import AnalyticalLatencyModelfrom .metrics import percentile, summarizefrom .models import Request, SimulationConfig, SimulationResult, TimelinePointfrom .profiles import get_accelerator, get_modelfrom .workloads import generate_workload
@dataclassclass PrefillWorker: worker_id: int latency: AnalyticalLatencyModel kv: KVCacheModel busy: bool = False busy_time_s: float = 0.0
@dataclassclass DecodeWorker: worker_id: int latency: AnalyticalLatencyModel kv: KVCacheModel active: list[Request] = field(default_factory=list) busy: bool = False busy_time_s: float = 0.0 peak_kv_gb: float = 0.0
class DisaggregatedSimulator: """Two-stage prefill/decode discrete-event simulator.
v0.3 models role-specific worker pools plus a serialized analytical KV-transfer link. It is intentionally a systems abstraction, not a distributed-runtime emulator: transport, compute and memory timings remain reference-model predictions and carry explicit provenance in every result. """
def __init__(self, cfg: SimulationConfig): if cfg.prefill_workers < 1 or cfg.decode_workers < 1: raise ValueError("prefill_workers and decode_workers must be >= 1") if cfg.interconnect_gbps <= 0: raise ValueError("interconnect_gbps must be > 0")
self.cfg = cfg self.model = get_model(cfg.model) self.prefill_accelerator = get_accelerator(cfg.prefill_accelerator) self.decode_accelerator = get_accelerator(cfg.decode_accelerator) self.prefill_latency = AnalyticalLatencyModel(self.model, self.prefill_accelerator, cfg.quantization) self.decode_latency = AnalyticalLatencyModel(self.model, self.decode_accelerator, cfg.quantization)
self.prefill_workers = [ PrefillWorker(i, self.prefill_latency, KVCacheModel(self.prefill_latency, cfg)) for i in range(cfg.prefill_workers) ] self.decode_workers = [ DecodeWorker(i, self.decode_latency, KVCacheModel(self.decode_latency, cfg)) for i in range(cfg.decode_workers) ]
self.requests = generate_workload(cfg) self.prefill_waiting: list[Request] = [] self.decode_waiting: list[Request] = [] self.completed: list[Request] = [] self.events: list[tuple[float, int, str, object]] = [] self.seq = count() self.now = 0.0 self.transfer_busy_until = 0.0 self.transfer_busy_time_s = 0.0 self.transfer_gb = 0.0 self.transfer_latencies_ms: list[float] = [] self.transfer_pending = 0 self.timeline: list[TimelinePoint] = [] self.peak_total_kv_gb = 0.0 self.warnings: list[str] = []
for req in self.requests: self._push(req.arrival_time, "arrival", req)
def _push(self, time_s: float, kind: str, payload: object) -> None: heapq.heappush(self.events, (max(time_s, self.now), next(self.seq), kind, payload))
def _waiting_sorted(self, requests: list[Request]) -> list[Request]: if self.cfg.scheduler == "continuous_sjf": return sorted(requests, key=lambda r: (r.remaining_prefill + r.output_tokens, r.arrival_time)) if self.cfg.scheduler in {"continuous_slo", "chunked_slo"}: def slack(req: Request) -> tuple[float, float]: prefill = self.prefill_latency.prefill_seconds([max(req.remaining_prefill, 1)]) midpoint_context = req.prompt_tokens + max(req.output_tokens // 2, 1) decode = req.output_tokens * self.decode_latency.decode_step_seconds([midpoint_context]) return (req.deadline_time - self.now - prefill - decode, req.arrival_time)
return sorted(requests, key=slack) return sorted(requests, key=lambda r: r.arrival_time)
def _record_timeline(self, force: bool = False) -> None: target = max(self.cfg.timeline_points, 20) total_kv = sum(w.kv.used_gb(w.active) for w in self.decode_workers) total_capacity = sum(w.kv.capacity_gb for w in self.decode_workers) self.peak_total_kv_gb = max(self.peak_total_kv_gb, total_kv) for worker in self.decode_workers: worker.peak_kv_gb = max(worker.peak_kv_gb, worker.kv.used_gb(worker.active)) point = TimelinePoint( time_s=self.now, waiting=len(self.prefill_waiting), prefill_pending=sum(1 for w in self.prefill_workers if w.busy), decoding=sum(len(w.active) for w in self.decode_workers), completed=len(self.completed), kv_used_gb=total_kv, kv_capacity_gb=total_capacity, transfer_pending=self.transfer_pending, decode_ready=len(self.decode_waiting), prefill_active=sum(1 for w in self.prefill_workers if w.busy), ) if not self.timeline or force or self.now - self.timeline[-1].time_s >= max(self.cfg.duration_s / target, 0.05): self.timeline.append(point) if len(self.timeline) > target * 2: self.timeline = self.timeline[::2]
def _prefill_batch_for(self, worker: PrefillWorker) -> list[tuple[Request, int]]: if not self.prefill_waiting: return [] selected: list[tuple[Request, int]] = [] budget = self.cfg.max_batch_tokens virtual_selected: list[Request] = [] for req in self._waiting_sorted(self.prefill_waiting): if len(selected) >= self.cfg.max_batch_size or budget <= 0: break chunk = req.remaining_prefill if self.cfg.scheduler == "chunked_slo": chunk = min(chunk, self.cfg.chunk_size) chunk = min(chunk, budget) if chunk <= 0: continue if not worker.kv.can_admit(req, [], virtual_selected): continue selected.append((req, chunk)) virtual_selected.append(req) budget -= chunk return selected
def _try_start_prefill(self) -> None: for worker in self.prefill_workers: if worker.busy: continue batch = self._prefill_batch_for(worker) if not batch: continue selected_ids = {r.request_id for r, _ in batch} self.prefill_waiting = [r for r in self.prefill_waiting if r.request_id not in selected_ids] for req, _ in batch: if req.first_prefill_time is None: req.first_prefill_time = self.now delta = worker.latency.prefill_seconds([chunk for _, chunk in batch]) worker.busy = True worker.busy_time_s += delta self._push(self.now + delta, "prefill_done", (worker.worker_id, batch))
def _schedule_transfer(self, req: Request) -> None: # Cached shared-prefix KV is assumed resident in both role pools. Only # newly computed prompt state must cross the P/D boundary. bytes_to_transfer = req.uncached_prompt_tokens * self.prefill_latency.kv_bytes_per_token() gb = bytes_to_transfer / 1e9 start = max(self.now, self.transfer_busy_until) duration = self.cfg.transfer_base_ms / 1000.0 + bytes_to_transfer / (self.cfg.interconnect_gbps * 1e9) end = start + duration self.transfer_busy_until = end self.transfer_busy_time_s += duration self.transfer_gb += gb self.transfer_latencies_ms.append(duration * 1000.0) self.transfer_pending += 1 req.transfer_start_time = start req.transfer_end_time = end self._push(end, "transfer_done", req)
def _decode_order(self) -> list[Request]: return self._waiting_sorted(self.decode_waiting)
def _try_schedule_decode(self) -> None: # Admissions occur only between iterations. A worker marked busy has a # decode step already in flight and cannot accept work until it completes. for worker in self.decode_workers: if worker.busy: continue slots = self.cfg.max_batch_size - len(worker.active) if slots > 0 and self.decode_waiting: for req in list(self._decode_order()): if slots <= 0: break if worker.kv.can_admit(req, worker.active): self.decode_waiting.remove(req) req.decode_worker_id = worker.worker_id worker.active.append(req) slots -= 1 if not worker.active: continue contexts = [r.context_tokens for r in worker.active] delta = worker.latency.decode_step_seconds(contexts) worker.busy = True worker.busy_time_s += delta self._push(self.now + delta, "decode_done", worker.worker_id)
def _handle_event(self, kind: str, payload: object) -> None: if kind == "arrival": self.prefill_waiting.append(payload) # type: ignore[arg-type] self._try_start_prefill() return
if kind == "prefill_done": worker_id, batch = payload # type: ignore[misc] worker = self.prefill_workers[worker_id] worker.busy = False for req, chunk in batch: req.remaining_prefill = max(0, req.remaining_prefill - chunk) if req.remaining_prefill > 0: self.prefill_waiting.append(req) else: req.prefill_complete_time = self.now self._schedule_transfer(req) self._try_start_prefill() return
if kind == "transfer_done": req = payload # type: ignore[assignment] self.transfer_pending = max(0, self.transfer_pending - 1) self.decode_waiting.append(req) self._try_schedule_decode() return
if kind == "decode_done": worker = self.decode_workers[int(payload)] worker.busy = False for req in worker.active: req.generated_tokens += 1 if req.first_token_time is None: req.first_token_time = self.now done = [r for r in worker.active if r.complete] for req in done: req.completion_time = self.now self.completed.append(req) if done: done_ids = {r.request_id for r in done} worker.active = [r for r in worker.active if r.request_id not in done_ids] self._try_schedule_decode() return
raise RuntimeError(f"Unknown event kind: {kind}")
def run(self) -> SimulationResult: if self.cfg.scheduler == "static_fcfs": self.warnings.append("Static FCFS is not defined for P/D disaggregation; using continuous FCFS semantics.") self._record_timeline(force=True) processed = 0 max_events = max(10000, len(self.requests) * max(self.cfg.output_tokens_mean, 1) * 20)
while self.events and len(self.completed) < len(self.requests): time_s, _, kind, payload = heapq.heappop(self.events) self.now = max(self.now, time_s) self._handle_event(kind, payload) self._record_timeline() processed += 1 if processed > max_events: self.warnings.append("Simulation stopped at the event safety limit.") break
# If queued work remains with no events, the configuration is memory- or # admission-constrained rather than silently considered complete. if len(self.completed) < len(self.requests) and not self.events: self.warnings.append("Disaggregated pipeline stalled before all requests completed.")
self._record_timeline(force=True) makespan = max(self.now, self.cfg.duration_s if self.requests else 0.0) prefill_util = sum(w.busy_time_s for w in self.prefill_workers) / max(makespan * len(self.prefill_workers), 1e-9) decode_util = sum(w.busy_time_s for w in self.decode_workers) / max(makespan * len(self.decode_workers), 1e-9) transfer_util = self.transfer_busy_time_s / max(makespan, 1e-9) hottest = min(1.0, max(prefill_util, decode_util, transfer_util)) summary, latency = summarize(self.completed, self.cfg, makespan, hottest * makespan) summary["requests_generated"] = len(self.requests) summary["requests_unfinished"] = len(self.requests) - len(self.completed)
total_kv_capacity = sum(w.kv.capacity_gb for w in self.decode_workers) peak_kv_gb = self.peak_total_kv_gb peak_worker_util = max( (w.peak_kv_gb / w.kv.capacity_gb if w.kv.capacity_gb > 0 else 0.0 for w in self.decode_workers), default=0.0, ) resource = { "topology": "disaggregated_pd", "model_weight_gb": self.decode_latency.model_weight_gb, "kv_capacity_gb": total_kv_capacity, "peak_kv_gb": peak_kv_gb, "peak_kv_utilization": peak_worker_util, "prefill_accelerator_vram_gb": self.prefill_accelerator.vram_gb, "decode_accelerator_vram_gb": self.decode_accelerator.vram_gb, "prefill_workers": len(self.prefill_workers), "decode_workers": len(self.decode_workers), "accelerator_instances": len(self.prefill_workers) + len(self.decode_workers), "prefill_busy_fraction": min(1.0, prefill_util), "decode_busy_fraction": min(1.0, decode_util), "transfer_busy_fraction": min(1.0, transfer_util), "kv_transfer_gb": self.transfer_gb, "mean_transfer_ms": sum(self.transfer_latencies_ms) / len(self.transfer_latencies_ms) if self.transfer_latencies_ms else 0.0, "p95_transfer_ms": percentile(self.transfer_latencies_ms, 0.95), "interconnect_gbps": self.cfg.interconnect_gbps, "prefix_cache_gb_per_decode_worker": self.decode_workers[0].kv.shared_prefix_gb if self.decode_workers else 0.0, "prefix_cache_hits": sum(1 for r in self.requests if r.prefix_cache_hit), "prefix_cache_hit_rate": (sum(1 for r in self.requests if r.prefix_cache_hit) / len(self.requests)) if self.requests else 0.0, "prefill_tokens_saved": sum(r.cached_prefix_tokens for r in self.requests), }
request_rows = [] for req in self.completed[:2000]: transfer_ms = 0.0 if req.transfer_start_time is not None and req.transfer_end_time is not None: transfer_ms = (req.transfer_end_time - req.transfer_start_time) * 1000.0 request_rows.append( { "request_id": req.request_id, "arrival_time": req.arrival_time, "prompt_tokens": req.prompt_tokens, "output_tokens": req.output_tokens, "cached_prefix_tokens": req.cached_prefix_tokens, "decode_worker_id": req.decode_worker_id, "transfer_ms": transfer_ms, "ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None, "e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None, } )
diagnostics = diagnose_run(summary, latency, resource, self.cfg) provenance = { "simulator": "InferScale-Sim", "version": "0.3.0", "latency_profile_type": "analytical-reference", "profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.", "model_profile_source": self.model.source, "prefill_accelerator_profile_source": self.prefill_accelerator.source, "decode_accelerator_profile_source": self.decode_accelerator.source, "topology": "disaggregated_pd", "transfer_model": "serialized-reference-link", } return SimulationResult( config=self.cfg.to_dict(), provenance=provenance, summary=summary, latency=latency, resource=resource, diagnostics=diagnostics, requests=request_rows, timeline=[asdict(p) for p in self.timeline], warnings=self.warnings, )
def run_disaggregated(config: dict) -> dict: return DisaggregatedSimulator(SimulationConfig.from_dict(config)).run().to_dict()11 unmodified lines1213141516171819202122232425262728293 unmodified lines3334353637383911 unmodified linesself.cfg = cfgself.model_weight_gb = latency_model.model_weight_gbtotal_vram = latency_model.accelerator.vram_gb# Reserve non-KV space for runtime workspace and weights.remaining = max(0.0, total_vram - self.model_weight_gb - 1.2)self.capacity_gb = remaining * cfg.kv_memory_fractiondef _allocated_tokens(self, req: Request, include_output_reservation: bool = False) -> int:live_tokens = req.prompt_tokens + req.generated_tokensif self.cfg.scheduler == "static_fcfs" or include_output_reservation:# Static baseline reserves the full sequence, illustrating memory# fragmentation / over-reservation versus paged allocation.return req.prompt_tokens + req.output_tokensblock = max(self.cfg.kv_block_tokens, 1)return int(math.ceil(live_tokens / block) * block)def request_gb(self, req: Request, include_output_reservation: bool = False) -> float:tokens = self._allocated_tokens(req, include_output_reservation)3 unmodified linesrequests = list(active)if prefill_pending:requests.extend(prefill_pending)return sum(self.request_gb(r) for r in requests)def can_admit(self, req: Request, active: list[Request], prefill_pending: list[Request] | None = None) -> bool:return self.used_gb(active, prefill_pending) + self.request_gb(req) <= self.capacity_gb + 1e-1211 unmodified lines12131415161718192021222324252627282930313 unmodified lines3536373839404111 unmodified linesself.cfg = cfgself.model_weight_gb = latency_model.model_weight_gbtotal_vram = latency_model.accelerator.vram_gbremaining = max(0.0, total_vram - self.model_weight_gb - 1.2)self.capacity_gb = remaining * cfg.kv_memory_fractionself.shared_prefix_gb = 0.0if cfg.prefix_cache_enabled and cfg.shared_prefix_tokens > 0 and cfg.prefix_reuse_fraction > 0:self.shared_prefix_gb = cfg.shared_prefix_tokens * latency_model.kv_bytes_per_token() / 1e9def _allocated_tokens(self, req: Request, include_output_reservation: bool = False) -> int:# Cached prefix state is represented once by shared_prefix_gb. Per-request# allocation therefore contains only the uncached suffix + generated state.live_tokens = req.uncached_prompt_tokens + req.generated_tokensif self.cfg.scheduler == "static_fcfs" or include_output_reservation:return req.uncached_prompt_tokens + req.output_tokensblock = max(self.cfg.kv_block_tokens, 1)return int(math.ceil(max(live_tokens, 0) / block) * block)def request_gb(self, req: Request, include_output_reservation: bool = False) -> float:tokens = self._allocated_tokens(req, include_output_reservation)3 unmodified linesrequests = list(active)if prefill_pending:requests.extend(prefill_pending)return self.shared_prefix_gb + sum(self.request_gb(r) for r in requests)def can_admit(self, req: Request, active: list[Request], prefill_pending: list[Request] | None = None) -> bool:return self.used_gb(active, prefill_pending) + self.request_gb(req) <= self.capacity_gb + 1e-12
28 unmodified lines2930313233343528 unmodified linesreturn self.model.params_b * self.weight_bytes_per_paramdef kv_bytes_per_token(self) -> float:# K + V, all layers, KV heads only. KV state is assumed fp16 in v0.2.return (2* self.model.layers28 unmodified lines2930313233343528 unmodified linesreturn self.model.params_b * self.weight_bytes_per_paramdef kv_bytes_per_token(self) -> float:# K + V, all layers, KV heads only. KV state is assumed fp16 in v0.3.return (2* self.model.layers
35 unmodified lines36373839404115 unmodified lines57585960616211 unmodified lines7475767778798081828384858687888923 unmodified lines11311411511611711835 unmodified linesmodel: str = "Llama-3.1-8B"accelerator: str = "L4"scheduler: str = "continuous_fcfs"arrival_process: str = "poisson"request_rate_rps: float = 4.0duration_s: float = 60.015 unmodified linesburst_period_s: float = 10.0timeline_points: int = 300@classmethoddef from_dict(cls, data: dict[str, Any]) -> "SimulationConfig":allowed = cls.__dataclass_fields__.keys()11 unmodified linesoutput_tokens: intdeadline_time: floatremaining_prefill: intgenerated_tokens: int = 0first_prefill_time: float | None = Nonefirst_token_time: float | None = Nonecompletion_time: float | None = Nonepriority: int = 0@propertydef context_tokens(self) -> int:return self.prompt_tokens + self.generated_tokens@propertydef complete(self) -> bool:return self.generated_tokens >= self.output_tokens23 unmodified linescompleted: intkv_used_gb: floatkv_capacity_gb: float@dataclass35 unmodified lines3637383940414215 unmodified lines58596061626364656667686970717273747576777811 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711823 unmodified lines14214314414514614714814915035 unmodified linesmodel: str = "Llama-3.1-8B"accelerator: str = "L4"scheduler: str = "continuous_fcfs"topology: str = "colocated"arrival_process: str = "poisson"request_rate_rps: float = 4.0duration_s: float = 60.015 unmodified linesburst_period_s: float = 10.0timeline_points: int = 300# Prefix-cache scenario. v0.3 intentionally models one reusable shared# prefix rather than a full radix tree. Hits share one persistent KV entry.prefix_cache_enabled: bool = Falseshared_prefix_tokens: int = 256prefix_reuse_fraction: float = 0.0# Prefill/decode disaggregation scenario. These fields are ignored for the# colocated topology. Interconnect bandwidth is expressed in GB/s.prefill_accelerator: str = "L4"decode_accelerator: str = "L4"prefill_workers: int = 1decode_workers: int = 1interconnect_gbps: float = 50.0transfer_base_ms: float = 0.20@classmethoddef from_dict(cls, data: dict[str, Any]) -> "SimulationConfig":allowed = cls.__dataclass_fields__.keys()11 unmodified linesoutput_tokens: intdeadline_time: floatremaining_prefill: intcached_prefix_tokens: int = 0generated_tokens: int = 0first_prefill_time: float | None = Noneprefill_complete_time: float | None = Nonetransfer_start_time: float | None = Nonetransfer_end_time: float | None = Nonefirst_token_time: float | None = Nonecompletion_time: float | None = Nonedecode_worker_id: int | None = Nonepriority: int = 0@propertydef context_tokens(self) -> int:return self.prompt_tokens + self.generated_tokens@propertydef uncached_prompt_tokens(self) -> int:return max(0, self.prompt_tokens - self.cached_prefix_tokens)@propertydef prefix_cache_hit(self) -> bool:return self.cached_prefix_tokens > 0@propertydef complete(self) -> bool:return self.generated_tokens >= self.output_tokens23 unmodified linescompleted: intkv_used_gb: floatkv_capacity_gb: floattransfer_pending: int = 0decode_ready: int = 0prefill_active: int = 0@dataclass
39 unmodified lines40414243444564 unmodified lines11011111211311411514 unmodified lines13013113239 unmodified lines"max_unfinished": max(unfinished_values),"repetitions": repetitions,"criterion": "all-repetitions-meet-target-and-drain",}64 unmodified lines"chunked_slo",]base = SimulationConfig.from_dict(config)rows = []for scheduler in schedulers:cfg = deepcopy(base)14 unmodified lines)rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}39 unmodified lines4041424344454664 unmodified lines11111211311411511611714 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327439 unmodified lines"max_unfinished": max(unfinished_values),"repetitions": repetitions,"criterion": "all-repetitions-meet-target-and-drain","target": base.slo_attainment_target,}64 unmodified lines"chunked_slo",]base = SimulationConfig.from_dict(config)base.topology = "colocated"rows = []for scheduler in schedulers:cfg = deepcopy(base)14 unmodified lines)rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}def compare_topologies(config: dict) -> dict:"""Compare colocated and P/D-disaggregated serving on one deterministic trace."""base = SimulationConfig.from_dict(config)rows = []scenarios = [("colocated", False),("colocated", True),("disaggregated_pd", False),("disaggregated_pd", True),]for topology, cache_enabled in scenarios:cfg = deepcopy(base)cfg.topology = topologycfg.prefix_cache_enabled = cache_enabledif topology == "disaggregated_pd" and cfg.scheduler == "static_fcfs":cfg.scheduler = "continuous_fcfs"result = run_simulation(cfg.to_dict())resource = result["resource"]accelerator_instances = int(resource.get("accelerator_instances", 1))goodput_rps = result["summary"]["goodput_rps"]rows.append({"scenario": f"{topology}{'_cache' if cache_enabled else ''}","topology": topology,"prefix_cache": cache_enabled,"accelerator_instances": accelerator_instances,"goodput_rps": goodput_rps,"goodput_per_accelerator": goodput_rps / max(accelerator_instances, 1),"request_throughput_rps": result["summary"]["request_throughput_rps"],"slo_attainment": result["summary"]["slo_attainment"],"p95_ttft_ms": result["latency"]["ttft_ms"]["p95"],"p95_e2e_ms": result["latency"]["e2e_ms"]["p95"],"peak_kv_utilization": resource.get("peak_kv_utilization", 0.0),"prefix_hit_rate": resource.get("prefix_cache_hit_rate", 0.0),"prefill_tokens_saved": resource.get("prefill_tokens_saved", 0),"p95_transfer_ms": resource.get("p95_transfer_ms", 0.0),"prefill_busy_fraction": resource.get("prefill_busy_fraction", 0.0),"decode_busy_fraction": resource.get("decode_busy_fraction", result["summary"].get("busy_fraction", 0.0)),"transfer_busy_fraction": resource.get("transfer_busy_fraction", 0.0),"bottleneck": result["diagnostics"]["label"],})rows.sort(key=lambda row: (row["slo_attainment"], row["goodput_rps"]), reverse=True)return {"rows": rows}def _is_dominated(candidate: dict, rows: list[dict], throughput_key: str = "goodput_rps") -> bool:for other in rows:if other is candidate:continueno_worse = (other[throughput_key] >= candidate[throughput_key]and other["p95_ttft_ms"] <= candidate["p95_ttft_ms"])strictly_better = (other[throughput_key] > candidate[throughput_key]or other["p95_ttft_ms"] < candidate["p95_ttft_ms"])if no_worse and strictly_better:return Truereturn Falsedef design_space_search(config: dict, include_disaggregated: bool = True) -> dict:"""Small browser-safe design-space sweep with a goodput/TTFT Pareto frontier.The sweep is intentionally bounded: its purpose is to expose configurationinteractions interactively, not to claim exhaustive optimization."""base = SimulationConfig.from_dict(config)rows: list[dict] = []colocated_candidates = []for scheduler in ["continuous_fcfs", "continuous_slo", "chunked_slo"]:for batch in [8, 16, 32]:colocated_candidates.append((scheduler, batch, False))# Prefix reuse is added as a separate systems dimension for the SLO-aware# scheduler at the user's current batch size.colocated_candidates.append(("continuous_slo", base.max_batch_size, True))for scheduler, batch, cache in colocated_candidates:cfg = deepcopy(base)cfg.topology = "colocated"cfg.scheduler = schedulercfg.max_batch_size = batchcfg.prefix_cache_enabled = cacheresult = run_simulation(cfg.to_dict())rows.append(_design_row(result, cfg, f"colocated / {scheduler} / batch {batch}{' / cache' if cache else ''}"))if include_disaggregated:for prefill_workers, decode_workers in [(1, 1), (1, 2), (2, 1)]:for cache in [False, True]:cfg = deepcopy(base)cfg.topology = "disaggregated_pd"cfg.scheduler = "continuous_slo"cfg.prefill_workers = prefill_workerscfg.decode_workers = decode_workerscfg.prefix_cache_enabled = cacheresult = run_simulation(cfg.to_dict())label = f"P/D {prefill_workers}P:{decode_workers}D{' / cache' if cache else ''}"rows.append(_design_row(result, cfg, label))for row in rows:row["pareto"] = not _is_dominated(row, rows, "goodput_rps")row["efficiency_pareto"] = not _is_dominated(row, rows, "goodput_per_accelerator")rows.sort(key=lambda r: (not r["pareto"], not r["slo_pass"], -r["goodput_rps"], r["p95_ttft_ms"]))return {"rows": rows,"pareto_count": sum(1 for r in rows if r["pareto"]),"efficiency_pareto_count": sum(1 for r in rows if r["efficiency_pareto"]),"candidate_count": len(rows),"objectives": ["performance: maximize goodput / minimize p95 TTFT","efficiency: maximize goodput per accelerator / minimize p95 TTFT",],}def _design_row(result: dict, cfg: SimulationConfig, label: str) -> dict:resource = result["resource"]accelerator_instances = int(resource.get("accelerator_instances", 1))goodput_rps = result["summary"]["goodput_rps"]return {"label": label,"topology": cfg.topology,"scheduler": cfg.scheduler,"max_batch_size": cfg.max_batch_size,"prefix_cache": cfg.prefix_cache_enabled,"accelerator_instances": accelerator_instances,"goodput_rps": goodput_rps,"goodput_per_accelerator": goodput_rps / max(accelerator_instances, 1),"slo_attainment": result["summary"]["slo_attainment"],"slo_pass": result["summary"]["slo_attainment"] >= cfg.slo_attainment_target and result["summary"]["requests_unfinished"] == 0,"p95_ttft_ms": result["latency"]["ttft_ms"]["p95"],"p95_e2e_ms": result["latency"]["e2e_ms"]["p95"],"peak_kv_utilization": resource.get("peak_kv_utilization", 0.0),"bottleneck": result["diagnostics"]["label"],}
120 unmodified lines1211221231241251261271281291301311322 unmodified lines13513613713813914014135 unmodified lines17717817918018118218333 unmodified lines21721821922022122222358 unmodified lines2822832842852862875 unmodified lines2932942952962972982 unmodified lines30130230330430530630730830931031110 unmodified lines322323324325120 unmodified linesfor req in self._waiting_sorted():if len(selected) >= slots:breakif selected and total_tokens + req.prompt_tokens > self.cfg.max_batch_tokens:continueif not self.kv.can_admit(req, self.active, selected):continueselected.append(req)total_tokens += req.prompt_tokensif not selected:return False2 unmodified linesfor req in selected:if req.first_prefill_time is None:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.prompt_tokens for r in selected]))for req in selected:req.remaining_prefill = 0self.active.append(req)35 unmodified lines# One prefill chunk. Decode is serviced on the next loop iteration,# producing the intended prefill/decode interleaving.self._advance(self.latency.prefill_seconds(chunks))for req, chunk in zip(selected, chunks):req.remaining_prefill -= chunkif req.remaining_prefill <= 0:self.prefill_pending.remove(req)33 unmodified linesself.waiting = [r for r in self.waiting if r.request_id not in ids]for req in admitted:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.prompt_tokens for r in admitted]))for req in admitted:req.remaining_prefill = 0self.active.append(req)58 unmodified lines"peak_kv_gb": self.peak_kv_gb,"peak_kv_utilization": self.peak_kv_gb / self.kv.capacity_gb if self.kv.capacity_gb > 0 else 0.0,"accelerator_vram_gb": self.accelerator.vram_gb,}request_rows = []5 unmodified lines"arrival_time": req.arrival_time,"prompt_tokens": req.prompt_tokens,"output_tokens": req.output_tokens,"ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None,"e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None,})2 unmodified linesprovenance = {"simulator": "InferScale-Sim","version": "0.2.0","latency_profile_type": "analytical-reference","profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.","model_profile_source": self.model.source,"accelerator_profile_source": self.accelerator.source,}return SimulationResult(10 unmodified linesdef run_simulation(config: dict) -> dict:return Simulator(SimulationConfig.from_dict(config)).run().to_dict()120 unmodified lines1211221231241251261271281291301311322 unmodified lines13513613713813914014135 unmodified lines17717817918018118218333 unmodified lines21721821922022122222358 unmodified lines2822832842852862872882892902912922935 unmodified lines2993003013023033043052 unmodified lines30830931031131231331431531631731831910 unmodified lines330331332333334335336337338339340120 unmodified linesfor req in self._waiting_sorted():if len(selected) >= slots:breakif selected and total_tokens + req.remaining_prefill > self.cfg.max_batch_tokens:continueif not self.kv.can_admit(req, self.active, selected):continueselected.append(req)total_tokens += req.remaining_prefillif not selected:return False2 unmodified linesfor req in selected:if req.first_prefill_time is None:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.remaining_prefill for r in selected]))for req in selected:req.remaining_prefill = 0self.active.append(req)35 unmodified lines# One prefill chunk. Decode is serviced on the next loop iteration,# producing the intended prefill/decode interleaving.self._advance(self.latency.prefill_seconds(chunks))for req, chunk in zip(selected, chunks, strict=True):req.remaining_prefill -= chunkif req.remaining_prefill <= 0:self.prefill_pending.remove(req)33 unmodified linesself.waiting = [r for r in self.waiting if r.request_id not in ids]for req in admitted:req.first_prefill_time = self.nowself._advance(self.latency.prefill_seconds([r.remaining_prefill for r in admitted]))for req in admitted:req.remaining_prefill = 0self.active.append(req)58 unmodified lines"peak_kv_gb": self.peak_kv_gb,"peak_kv_utilization": self.peak_kv_gb / self.kv.capacity_gb if self.kv.capacity_gb > 0 else 0.0,"accelerator_vram_gb": self.accelerator.vram_gb,"topology": "colocated","accelerator_instances": 1,"prefix_cache_gb": self.kv.shared_prefix_gb,"prefix_cache_hits": sum(1 for r in self.requests if r.prefix_cache_hit),"prefix_cache_hit_rate": (sum(1 for r in self.requests if r.prefix_cache_hit) / len(self.requests)) if self.requests else 0.0,"prefill_tokens_saved": sum(r.cached_prefix_tokens for r in self.requests),}request_rows = []5 unmodified lines"arrival_time": req.arrival_time,"prompt_tokens": req.prompt_tokens,"output_tokens": req.output_tokens,"cached_prefix_tokens": req.cached_prefix_tokens,"ttft_ms": (req.first_token_time - req.arrival_time) * 1000.0 if req.first_token_time is not None else None,"e2e_ms": (req.completion_time - req.arrival_time) * 1000.0 if req.completion_time is not None else None,})2 unmodified linesprovenance = {"simulator": "InferScale-Sim","version": "0.3.0","latency_profile_type": "analytical-reference","profile_warning": "Reference profiles are analytical proxies, not measured hardware benchmarks.","model_profile_source": self.model.source,"accelerator_profile_source": self.accelerator.source,"topology": "colocated",}return SimulationResult(10 unmodified linesdef run_simulation(config: dict) -> dict:cfg = SimulationConfig.from_dict(config)if cfg.topology == "disaggregated_pd":from .disaggregated import DisaggregatedSimulatorreturn DisaggregatedSimulator(cfg).run().to_dict()if cfg.topology != "colocated":raise ValueError(f"Unsupported topology: {cfg.topology}")return Simulator(cfg).run().to_dict()
28 unmodified lines29303132333435363714 unmodified lines525354555657585960611 unmodified line6364656667686928 unmodified linesreturn arrivalsif cfg.arrival_process == "bursty":# Alternating baseline/high-load windows. The mean offered load is not# forced to equal request_rate_rps; the UI labels this clearly as a burst# stress test rather than an average-rate generator.while t < cfg.duration_s:phase = int(t // max(cfg.burst_period_s, 0.1)) % 2local_rate = rate * (cfg.burst_multiplier if phase else 0.55)14 unmodified linesdef generate_workload(cfg: SimulationConfig) -> list[Request]:rng = random.Random(cfg.seed)requests: list[Request] = []for idx, arrival in enumerate(_arrival_times(cfg, rng)):prompt = _sample_lognormal(cfg.prompt_tokens_mean, cfg.prompt_tokens_cv, rng)output = _sample_lognormal(cfg.output_tokens_mean, cfg.output_tokens_cv, rng)requests.append(Request(request_id=idx,1 unmodified lineprompt_tokens=prompt,output_tokens=output,deadline_time=arrival + cfg.slo_e2e_ms / 1000.0,remaining_prefill=prompt,))return requests28 unmodified lines29303132333414 unmodified lines4950515253545556575859606162631 unmodified line656667686970717228 unmodified linesreturn arrivalsif cfg.arrival_process == "bursty":while t < cfg.duration_s:phase = int(t // max(cfg.burst_period_s, 0.1)) % 2local_rate = rate * (cfg.burst_multiplier if phase else 0.55)14 unmodified linesdef generate_workload(cfg: SimulationConfig) -> list[Request]:rng = random.Random(cfg.seed)cache_rng = random.Random(cfg.seed ^ 0x5A17CACE)requests: list[Request] = []for idx, arrival in enumerate(_arrival_times(cfg, rng)):prompt = _sample_lognormal(cfg.prompt_tokens_mean, cfg.prompt_tokens_cv, rng)output = _sample_lognormal(cfg.output_tokens_mean, cfg.output_tokens_cv, rng)cached = 0if cfg.prefix_cache_enabled and cfg.shared_prefix_tokens > 0 and cfg.prefix_reuse_fraction > 0:if cache_rng.random() < min(max(cfg.prefix_reuse_fraction, 0.0), 1.0):cached = min(cfg.shared_prefix_tokens, max(prompt - 1, 0))requests.append(Request(request_id=idx,1 unmodified lineprompt_tokens=prompt,output_tokens=output,deadline_time=arrival + cfg.slo_e2e_ms / 1000.0,remaining_prefill=max(0, prompt - cached),cached_prefix_tokens=cached,))return requests
123456789101112:root{--bg:#0b0e13;--surface:#11161e;--surface2:#0d1219;--line:#29313d;--line2:#202732;--text:#e8edf3;--muted:#929dab;--faint:#66717f;--accent:#79a7ff;--good:#69c99a;--warn:#dfb966;--danger:#e47e87}*{box-sizing:border-box}html{background:var(--bg);color-scheme:dark}body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--text);background:var(--bg);font-size:14px}button,input,select{font:inherit}.topbar{height:68px;padding:0 28px;border-bottom:1px solid var(--line2);display:flex;align-items:center;justify-content:space-between;position:fixed;top:0;left:0;right:0;z-index:50;background:#0c1016;transition:transform .22s ease}body.runtime-ready .topbar{transform:translateY(calc(-100% + 6px))}body.runtime-ready .topbar:hover,body.runtime-ready .topbar:focus-within{transform:translateY(0)}.brand-wrap{display:flex;align-items:center;gap:11px}.logo{width:34px;height:34px;display:grid;place-items:center;border:1px solid #455164;border-radius:6px;color:#d9e2ee;font:700 12px/1 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.brand{font-weight:700;letter-spacing:-.015em}.subtitle{color:var(--muted);font-size:11px;margin-top:2px}.runtime-pill{display:flex;gap:8px;align-items:center;padding:7px 10px;border:1px solid var(--line);border-radius:6px;color:var(--muted);font:11px/1.2 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:var(--surface2)}.dot{width:7px;height:7px;border-radius:50%;background:var(--warn)}.runtime-pill.ready .dot{background:var(--good)}.runtime-pill.error .dot{background:var(--danger)}.shell{width:min(1460px,calc(100% - 40px));margin:0 auto;padding:100px 0 56px;transition:padding-top .22s ease}body.runtime-ready .shell{padding-top:30px}.intro{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(380px,.55fr);gap:48px;align-items:end;padding:20px 2px 26px}.eyebrow,.section-kicker{font:700 10px/1.2 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8ea6c7}h1{font-size:clamp(32px,3.2vw,48px);line-height:1.06;letter-spacing:-.035em;max-width:900px;margin:10px 0 14px;font-weight:720}.intro p{max-width:840px;color:var(--muted);line-height:1.65;margin:0;font-size:15px}.project-facts{margin:0;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.project-facts div{display:grid;grid-template-columns:130px 1fr;gap:14px;padding:9px 0;border-bottom:1px solid var(--line2)}.project-facts div:last-child{border-bottom:0}.project-facts dt{color:var(--faint);font-size:11px}.project-facts dd{margin:0;color:#cbd4df;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.reference-note{border-left:3px solid #8b7445;background:#12151a;color:#bcb5a5;padding:11px 13px;font-size:12px;line-height:1.5}.tabs{display:flex;gap:2px;padding:22px 0 12px;overflow:auto;border-bottom:1px solid var(--line2);margin-bottom:14px}.tab{border:0;border-bottom:2px solid transparent;color:var(--muted);background:transparent;padding:9px 12px;cursor:pointer;font-weight:650}.tab:hover{color:var(--text)}.tab.active{color:var(--text);border-bottom-color:var(--accent)}.tab-panel{display:none}.tab-panel.active{display:block}.workspace{display:grid;grid-template-columns:390px minmax(0,1fr);gap:14px;align-items:start}.panel{background:var(--surface);border:1px solid var(--line);border-radius:8px}.controls-panel{padding:18px;position:sticky;top:18px}.result-panel,.wide-panel{padding:20px}.panel-title-row{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:16px}.panel-title-row h2{margin:0;font-size:17px;letter-spacing:-.02em}.panel-title-row p{margin:6px 0 0}.tag{display:inline-flex;align-items:center;border:1px solid var(--line);background:var(--surface2);color:var(--muted);border-radius:5px;padding:5px 7px;font-size:10px;white-space:nowrap}.tag.good{color:var(--good);border-color:#315e4a}.tag.bad{color:var(--danger);border-color:#643943}label{display:block;color:#b5bfcb;font-size:11px;font-weight:650;position:relative}select,input{width:100%;margin-top:7px;height:37px;border:1px solid var(--line);background:#0b1016;color:var(--text);border-radius:5px;padding:0 9px;outline:none}select:focus,input:focus{border-color:#5475a8;box-shadow:0 0 0 2px rgba(84,117,168,.17)}.unit{position:absolute;right:9px;bottom:11px;color:#697687;font-size:9px;pointer-events:none}.field-grid{display:grid;gap:10px;margin-bottom:10px}.field-grid.two{grid-template-columns:1fr 1fr}hr{border:0;border-top:1px solid var(--line2);margin:17px 0}.section-kicker{margin-bottom:10px}button.primary,button.secondary{height:40px;border-radius:5px;font-weight:700;cursor:pointer;transition:.13s ease}button.primary{width:100%;border:1px solid #668fd5;background:#4f7fce;color:white;margin-top:11px}button.primary:hover:not(:disabled){background:#5b8bd8}button.secondary{border:1px solid var(--line);background:#0d1219;color:#c4ccd7}button.secondary:hover:not(:disabled),.mini-button:hover:not(:disabled),.chart-expand:hover{border-color:#536174;background:#151b24}button:disabled{opacity:.42;cursor:not-allowed}.compact{width:auto!important;min-width:178px;padding:0 17px;margin-top:0!important}.button-row{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px}.empty-state{min-height:380px;display:grid;place-content:center;text-align:center;color:var(--muted);padding:30px}.empty-state.small{min-height:240px}.empty-state h3{color:#ccd4de;margin:0 0 6px;font-size:15px}.empty-state p{max-width:500px;margin:0;line-height:1.55;font-size:12px}.hidden{display:none!important}.metric-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;margin-bottom:12px}.metric-grid.four{grid-template-columns:repeat(4,1fr)}.metric{min-height:82px;padding:13px;border:1px solid var(--line2);background:var(--surface2)}.metric span{display:block;color:var(--muted);font-size:10px;margin-bottom:9px}.metric strong{font-size:18px;letter-spacing:-.025em}.metric.emphasis{border-color:#486da4;background:#101824}.diagnostic-card{margin-bottom:12px;border:1px solid var(--line);background:#0e131a;padding:14px}.diagnostic-head{display:flex;align-items:baseline;justify-content:space-between;gap:16px}.diagnostic-head span{color:var(--muted);font-size:10px;text-transform:uppercase;letter-spacing:.06em}.diagnostic-head strong{font-size:14px}.diagnostic-card p{margin:8px 0 0;color:#b8c1cd;font-size:12px;line-height:1.55}.diagnostic-card .diagnostic-action{color:var(--muted)}.evidence-row{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.evidence-row span{border:1px solid var(--line2);background:#0a0f15;padding:4px 6px;color:#8390a0;font:10px/1.2 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.chart-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.chart-card{border:1px solid var(--line);background:var(--surface2);min-height:300px;position:relative}.chart-card.full{margin-top:10px}.chart-head{height:42px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:0 12px;border-bottom:1px solid var(--line2)}.chart-title{color:#c7d0db;font-size:11px;font-weight:700}.chart-expand,.mini-button{border:1px solid var(--line);background:#0b1016;color:var(--muted);border-radius:4px;cursor:pointer;height:28px;padding:0 9px;font-size:10px}.chart-body{height:260px;padding:10px 12px 12px}.chart-body.large{height:340px}.chart-card.chart-expanded{position:fixed;inset:18px;z-index:100;background:#0b1016;border-color:#4c596b;box-shadow:0 0 0 9999px rgba(0,0,0,.72);min-height:0;margin:0}.chart-card.chart-expanded .chart-body{height:calc(100vh - 84px)}body.chart-open{overflow:hidden}canvas{width:100%!important;height:100%!important;max-height:none}.warnings{margin-top:10px;border-left:3px solid #7b6840;padding:9px 11px;background:#15140f;color:#c4bca9;font-size:11px;line-height:1.5}.muted{color:var(--muted);font-size:12px;line-height:1.55}.table-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:14px;color:#aab4c1;font-size:11px}.table-toolbar>div{display:flex;gap:6px}.table-wrap{overflow:auto;margin-top:7px;border:1px solid var(--line)}table{width:100%;border-collapse:collapse;font-size:12px;min-width:900px}th,td{padding:10px 11px;text-align:right;border-bottom:1px solid var(--line2);white-space:nowrap}th:first-child,td:first-child{text-align:left}th{color:#7f8b9b;font-size:9px;text-transform:uppercase;letter-spacing:.06em;background:#0a0f15;position:sticky;top:0}td{color:#c7d0db}tbody tr:last-child td{border-bottom:0}tbody tr:hover td{background:#121821}.pass{color:var(--good)}.fail{color:var(--danger)}.best-label{display:inline-block;margin-left:7px;border:1px solid #4a6386;color:#9ab8df;padding:2px 5px;border-radius:3px;font-size:9px;text-transform:uppercase}.planner-grid{grid-template-columns:360px minmax(0,1fr)}.planner-note{color:var(--muted);border-left:2px solid #445a77;padding:7px 9px;margin-bottom:2px;font-size:11px;line-height:1.5}.method-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.prose{padding:22px}.prose h2{font-size:20px;margin:8px 0 11px}.prose p{color:var(--muted);line-height:1.7;font-size:13px}.prose code{color:#a8bfe4}.formula{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:#b7c3d2;padding:10px;border:1px solid var(--line);background:#0b1016;font-size:11px}.wide-method{grid-column:1/-1}.paper-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-top:18px}.paper-grid>div{padding:12px;border:1px solid var(--line2);background:#0d1219}.paper-grid strong{display:block;font-size:11px;margin-bottom:7px}.paper-grid span{color:var(--muted);font-size:10px;line-height:1.55;display:block}footer{width:min(1460px,calc(100% - 40px));margin:0 auto;padding:20px 0 34px;border-top:1px solid var(--line2);display:flex;justify-content:space-between;gap:20px;color:var(--faint);font-size:10px}.toast{position:fixed;right:20px;bottom:20px;z-index:130;background:#17202b;border:1px solid #465467;color:#d5dce5;padding:9px 12px;border-radius:5px;font-size:11px;opacity:0;transform:translateY(8px);pointer-events:none;transition:.16s ease}.toast.show{opacity:1;transform:translateY(0)}@media(max-width:1100px){.intro{grid-template-columns:1fr;gap:24px}.workspace,.planner-grid{grid-template-columns:1fr}.controls-panel{position:static}.metric-grid{grid-template-columns:repeat(3,1fr)}.paper-grid{grid-template-columns:1fr 1fr}}@media(max-width:720px){.topbar{padding:0 15px}.subtitle{display:none}.runtime-pill{max-width:170px}.shell{width:calc(100% - 20px);padding-top:88px}body.runtime-ready .shell{padding-top:20px}.intro{padding-top:10px}.project-facts div{grid-template-columns:100px 1fr}.field-grid.two,.chart-grid,.method-grid{grid-template-columns:1fr}.metric-grid,.metric-grid.four{grid-template-columns:1fr 1fr}.paper-grid{grid-template-columns:1fr}.panel-title-row{flex-direction:column}.arena-title-row .compact{width:100%!important}.wide-method{grid-column:auto}footer{width:calc(100% - 20px);flex-direction:column}.chart-card.chart-expanded{inset:6px}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288:root {--bg: #090d12;--surface: #0d1219;--surface-2: #0a0f15;--surface-3: #111822;--line: #26313f;--line-soft: #1b2430;--text: #e4e9ef;--muted: #929dab;--faint: #697586;--accent: #6f9fe8;--accent-2: #9ab8df;--good: #6fd0a0;--danger: #ee7f8d;--amber: #d8b96e;}* { box-sizing: border-box; }html { color-scheme: dark; }body {margin: 0;background: var(--bg);color: var(--text);font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;font-size: 14px;}.topbar {position: fixed;inset: 0 0 auto 0;z-index: 80;height: 64px;padding: 0 24px;display: flex;align-items: center;justify-content: space-between;gap: 16px;background: #090d12;border-bottom: 1px solid var(--line);transition: transform .18s ease;}body.runtime-ready .topbar { transform: translateY(-58px); }body.runtime-ready .topbar:hover,body.runtime-ready .topbar:focus-within { transform: translateY(0); }.brand-wrap { display: flex; align-items: center; min-width: 0; }.brand { font-size: 14px; font-weight: 760; letter-spacing: -.01em; }.subtitle { margin-top: 2px; color: var(--faint); font-size: 10px; }.runtime-pill {display: inline-flex;align-items: center;gap: 7px;color: var(--muted);border: 1px solid var(--line);background: var(--surface-2);border-radius: 4px;padding: 6px 9px;font-size: 10px;white-space: nowrap;}.runtime-pill .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--amber); }.runtime-pill.ready .dot { background: var(--good); }.runtime-pill.error .dot { background: var(--danger); }.shell {width: min(1460px, calc(100% - 40px));margin: 0 auto;padding: 94px 0 44px;transition: padding-top .18s ease;}body.runtime-ready .shell { padding-top: 34px; }.intro {display: grid;grid-template-columns: minmax(0, 1.4fr) minmax(320px, .6fr);gap: 46px;align-items: end;padding: 16px 0 18px;}.eyebrow, .section-kicker {color: var(--accent-2);font-size: 9px;line-height: 1.2;text-transform: uppercase;letter-spacing: .1em;font-weight: 760;}.intro h1 {max-width: 900px;margin: 8px 0 9px;color: #edf1f5;font-size: clamp(28px, 3vw, 43px);line-height: 1.06;letter-spacing: -.038em;font-weight: 720;}.intro p { max-width: 920px; margin: 0; color: var(--muted); font-size: 13px; line-height: 1.65; }.project-facts { margin: 0; border-top: 1px solid var(--line); }.project-facts div { display: grid; grid-template-columns: 120px 1fr; gap: 14px; padding: 9px 0; border-bottom: 1px solid var(--line-soft); }.project-facts dt { color: var(--faint); font-size: 10px; }.project-facts dd { margin: 0; color: #bdc7d2; font-size: 11px; }.reference-note {border-left: 2px solid #6c6041;background: #11120f;color: #bcb5a5;padding: 10px 12px;font-size: 11px;line-height: 1.55;}.tabs {display: flex;gap: 2px;padding: 22px 0 10px;overflow-x: auto;border-bottom: 1px solid var(--line-soft);margin-bottom: 14px;}.tab {border: 0;border-bottom: 2px solid transparent;color: var(--muted);background: transparent;padding: 9px 11px;cursor: pointer;font-weight: 650;white-space: nowrap;}.tab:hover { color: var(--text); }.tab.active { color: var(--text); border-bottom-color: var(--accent); }.tab-panel { display: none; }.tab-panel.active { display: block; }.workspace { display: grid; grid-template-columns: 405px minmax(0, 1fr); gap: 14px; align-items: start; }.planner-grid { grid-template-columns: 360px minmax(0, 1fr); }.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 6px; }.controls-panel { padding: 18px; position: sticky; top: 16px; }.result-panel, .wide-panel { padding: 20px; }.panel-title-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; margin-bottom: 16px; }.panel-title-row h2 { margin: 0; font-size: 17px; letter-spacing: -.02em; }.panel-title-row p { margin: 6px 0 0; }.tag {display: inline-flex;align-items: center;border: 1px solid var(--line);background: var(--surface-2);color: var(--muted);border-radius: 4px;padding: 5px 7px;font-size: 10px;white-space: nowrap;}.tag.good { color: var(--good); border-color: #315e4a; }.tag.bad { color: var(--danger); border-color: #643943; }label { display: block; color: #b5bfcb; font-size: 11px; font-weight: 650; position: relative; }select, input[type="number"] {width: 100%;margin-top: 7px;height: 37px;border: 1px solid var(--line);background: #0a0f15;color: var(--text);border-radius: 4px;padding: 0 9px;outline: none;}select:focus, input[type="number"]:focus { border-color: #5475a8; box-shadow: 0 0 0 2px rgba(84,117,168,.16); }.unit { position: absolute; right: 9px; bottom: 11px; color: #697687; font-size: 9px; pointer-events: none; }.field-grid { display: grid; gap: 10px; margin-bottom: 10px; }.field-grid.two { grid-template-columns: 1fr 1fr; }.subcontrols { margin: 12px 0 4px; padding: 12px; border: 1px solid var(--line-soft); background: #0a0f15; }.subcontrols .section-kicker { margin-bottom: 10px; }hr { border: 0; border-top: 1px solid var(--line-soft); margin: 17px 0; }.section-kicker { margin-bottom: 10px; }.hidden { display: none !important; }button.primary, button.secondary {height: 40px;border-radius: 4px;font-weight: 700;cursor: pointer;transition: .12s ease;}button.primary { width: 100%; border: 1px solid #668fd5; background: #4f7fce; color: white; margin-top: 11px; }button.primary:hover:not(:disabled) { background: #5b8bd8; }button.secondary { border: 1px solid var(--line); background: #0b1016; color: #c4ccd7; }button.secondary:hover:not(:disabled),.mini-button:hover:not(:disabled),.chart-expand:hover,.chart-download:hover { border-color: #536174; background: #151b24; color: #d9e0e8; }button:disabled { opacity: .42; cursor: not-allowed; }.compact { width: auto !important; min-width: 178px; padding: 0 17px; margin-top: 0 !important; }.button-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }.action-stack { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; }.checkline { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 10px; font-weight: 600; }.checkline input { accent-color: var(--accent); }.empty-state { min-height: 380px; display: grid; place-content: center; text-align: center; color: var(--muted); padding: 30px; }.empty-state.small { min-height: 240px; }.empty-state h3 { color: #ccd4de; margin: 0 0 6px; font-size: 15px; }.empty-state p { max-width: 560px; margin: 0; line-height: 1.55; font-size: 12px; }.metric-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 8px; margin-bottom: 12px; }.metric-grid.four { grid-template-columns: repeat(4, 1fr); }.metric { min-height: 82px; padding: 13px; border: 1px solid var(--line-soft); background: var(--surface-2); }.metric span { display: block; color: var(--muted); font-size: 10px; margin-bottom: 9px; }.metric strong { font-size: 18px; letter-spacing: -.025em; }.metric strong.metric-small { font-size: 13px; line-height: 1.35; }.metric.emphasis { border-color: #486da4; background: #101824; }.diagnostic-card { margin-bottom: 12px; border: 1px solid var(--line); background: #0d131b; padding: 14px; }.diagnostic-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }.diagnostic-head span { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .06em; }.diagnostic-head strong { font-size: 14px; }.diagnostic-card p { margin: 8px 0 0; color: #b8c1cd; font-size: 12px; line-height: 1.55; }.diagnostic-card .diagnostic-action { color: var(--muted); }.evidence-row { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }.evidence-row span { border: 1px solid var(--line-soft); background: #090e14; padding: 4px 6px; color: #8390a0; font: 10px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }.chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }.chart-card { border: 1px solid var(--line); background: var(--surface-2); min-height: 300px; position: relative; }.chart-card.full { margin-top: 10px; }.chart-head { height: 42px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 0 12px; border-bottom: 1px solid var(--line-soft); }.chart-title { color: #c7d0db; font-size: 11px; font-weight: 700; }.chart-actions { display: flex; gap: 6px; }.chart-expand, .chart-download, .mini-button { border: 1px solid var(--line); background: #0a0f15; color: var(--muted); border-radius: 3px; cursor: pointer; height: 28px; padding: 0 9px; font-size: 10px; }.chart-body { height: 260px; padding: 10px 12px 12px; }.chart-body.large { height: 350px; }.chart-card.chart-expanded { position: fixed; inset: 16px; z-index: 100; background: #0a0f15; border-color: #4c596b; box-shadow: 0 0 0 9999px rgba(0,0,0,.76); min-height: 0; margin: 0; }.chart-card.chart-expanded .chart-body { height: calc(100vh - 80px); }body.chart-open { overflow: hidden; }canvas { width: 100% !important; height: 100% !important; max-height: none; }.warnings { margin-top: 10px; border-left: 3px solid #7b6840; padding: 9px 11px; background: #15140f; color: #c4bca9; font-size: 11px; line-height: 1.5; }.muted { color: var(--muted); font-size: 12px; line-height: 1.55; }.table-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; color: #aab4c1; font-size: 11px; }.table-toolbar > div { display: flex; gap: 6px; }.table-wrap { overflow: auto; margin-top: 7px; border: 1px solid var(--line); }table { width: 100%; border-collapse: collapse; font-size: 12px; min-width: 900px; }th, td { padding: 10px 11px; text-align: right; border-bottom: 1px solid var(--line-soft); white-space: nowrap; }th:first-child, td:first-child { text-align: left; }th { color: #7f8b9b; font-size: 9px; text-transform: uppercase; letter-spacing: .06em; background: #090e14; position: sticky; top: 0; }td { color: #c7d0db; }tbody tr:last-child td { border-bottom: 0; }tbody tr:hover td { background: #111821; }.pass { color: var(--good); }.fail { color: var(--danger); }.best-label, .pareto-label { display: inline-block; margin-left: 7px; border: 1px solid #4a6386; color: #9ab8df; padding: 2px 5px; border-radius: 2px; font-size: 9px; text-transform: uppercase; }.planner-note { color: var(--muted); border-left: 2px solid #445a77; padding: 7px 9px; margin-bottom: 2px; font-size: 11px; line-height: 1.5; }.method-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }.prose { padding: 22px; }.prose h2 { font-size: 20px; margin: 8px 0 11px; }.prose p { color: var(--muted); line-height: 1.7; font-size: 13px; }.prose code { color: #a8bfe4; }.formula { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: #b7c3d2; padding: 10px; border: 1px solid var(--line); background: #0a0f15; font-size: 11px; }.wide-method { grid-column: 1 / -1; }.paper-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-top: 18px; }.paper-grid > div { padding: 12px; border: 1px solid var(--line-soft); background: #0c1219; }.paper-grid strong { display: block; font-size: 11px; margin-bottom: 7px; }.paper-grid span { color: var(--muted); font-size: 10px; line-height: 1.55; display: block; }.toast { position: fixed; right: 20px; bottom: 20px; z-index: 130; background: #17202b; border: 1px solid #465467; color: #d5dce5; padding: 9px 12px; border-radius: 4px; font-size: 11px; opacity: 0; transform: translateY(8px); pointer-events: none; transition: .16s ease; }.toast.show { opacity: 1; transform: translateY(0); }@media (max-width: 1100px) {.intro { grid-template-columns: 1fr; gap: 24px; }.workspace, .planner-grid { grid-template-columns: 1fr; }.controls-panel { position: static; }.metric-grid { grid-template-columns: repeat(3, 1fr); }.paper-grid { grid-template-columns: 1fr 1fr; }}@media (max-width: 720px) {.topbar { padding: 0 15px; }.subtitle { display: none; }.runtime-pill { max-width: 170px; }.shell { width: calc(100% - 20px); padding-top: 88px; }body.runtime-ready .shell { padding-top: 20px; }.intro { padding-top: 10px; }.project-facts div { grid-template-columns: 100px 1fr; }.field-grid.two, .chart-grid, .method-grid { grid-template-columns: 1fr; }.metric-grid, .metric-grid.four { grid-template-columns: 1fr 1fr; }.paper-grid { grid-template-columns: 1fr; }.panel-title-row { flex-direction: column; }.arena-title-row .compact { width: 100% !important; }.action-stack { width: 100%; align-items: stretch; }.wide-method { grid-column: auto; }.chart-card.chart-expanded { inset: 6px; }}
1234567891011121314151617181920212223242526272829303132333435363738394041from inferscale import compare_topologies, design_space_search
def test_topology_comparison_has_four_scenarios(): result = compare_topologies({ "model": "Qwen2.5-3B", "accelerator": "L4", "prefill_accelerator": "L4", "decode_accelerator": "L4", "quantization": "int8", "duration_s": 3, "request_rate_rps": 1, "prompt_tokens_mean": 64, "output_tokens_mean": 4, "prefix_reuse_fraction": 0.5, "shared_prefix_tokens": 32, }) assert len(result["rows"]) == 4 assert {row["topology"] for row in result["rows"]} == {"colocated", "disaggregated_pd"} assert all(row["goodput_per_accelerator"] >= 0 for row in result["rows"])
def test_design_space_marks_pareto_candidates(): result = design_space_search({ "model": "Qwen2.5-3B", "accelerator": "L4", "prefill_accelerator": "L4", "decode_accelerator": "L4", "quantization": "int8", "duration_s": 2, "request_rate_rps": 0.8, "prompt_tokens_mean": 64, "output_tokens_mean": 4, "shared_prefix_tokens": 32, "prefix_reuse_fraction": 0.5, }, include_disaggregated=False) assert result["candidate_count"] == 10 assert result["pareto_count"] >= 1 assert result["efficiency_pareto_count"] >= 1 assert any(row["pareto"] for row in result["rows"]) assert any(row["efficiency_pareto"] for row in result["rows"])123456789101112131415161718192021222324252627282930313233343536373839from inferscale import run_simulation
def base_config(): return { "model": "Qwen2.5-3B", "accelerator": "L4", "prefill_accelerator": "L4", "decode_accelerator": "L4", "quantization": "int8", "scheduler": "continuous_slo", "topology": "disaggregated_pd", "duration_s": 5, "request_rate_rps": 1.5, "prompt_tokens_mean": 128, "prompt_tokens_cv": 0.1, "output_tokens_mean": 8, "output_tokens_cv": 0.1, "seed": 4, "slo_ttft_ms": 2000, "slo_e2e_ms": 10000, }
def test_disaggregated_pipeline_completes_and_reports_transfer(): result = run_simulation(base_config()) assert result["provenance"]["topology"] == "disaggregated_pd" assert result["summary"]["requests_completed"] > 0 assert result["resource"]["kv_transfer_gb"] > 0 assert result["resource"]["accelerator_instances"] == 2 assert result["resource"]["p95_transfer_ms"] > 0
def test_more_decode_workers_are_modelled(): cfg = base_config() cfg["decode_workers"] = 2 result = run_simulation(cfg) assert result["resource"]["decode_workers"] == 2 assert result["resource"]["accelerator_instances"] == 312345678910111213141516171819202122232425262728from inferscale import run_simulation
def cfg(cache: bool): return { "model": "Qwen2.5-3B", "accelerator": "L4", "quantization": "int8", "scheduler": "continuous_fcfs", "duration_s": 6, "request_rate_rps": 2, "prompt_tokens_mean": 512, "prompt_tokens_cv": 0, "output_tokens_mean": 8, "output_tokens_cv": 0, "seed": 2, "prefix_cache_enabled": cache, "shared_prefix_tokens": 256, "prefix_reuse_fraction": 1.0, }
def test_prefix_cache_reduces_prefill_work_and_is_reported(): uncached = run_simulation(cfg(False)) cached = run_simulation(cfg(True)) assert cached["resource"]["prefix_cache_hit_rate"] == 1.0 assert cached["resource"]["prefill_tokens_saved"] > 0 assert cached["latency"]["ttft_ms"]["p50"] < uncached["latency"]["ttft_ms"]["p50"]3 unmodified lines4567893 unmodified lines"__init__.py","api.py","diagnostics.py","kv_cache.py","latency.py","metrics.py",3 unmodified lines456789103 unmodified lines"__init__.py","api.py","diagnostics.py","disaggregated.py","kv_cache.py","latency.py","metrics.py",
CHANGELOG.md+33-2
README.md+158-97
app.js+613-59
docs/architecture.md+34-13
docs/methodology.md+75-31
docs/research.md+43-13
docs/validation.md+34-18
index.html+256-39
py/inferscale/__init__.py+4-2
py/inferscale/api.py+10-4
py/inferscale/diagnostics.py+35-10
py/inferscale/disaggregated.pyAdded+362
py/inferscale/kv_cache.py+9-7
py/inferscale/latency.py+1-1
py/inferscale/models.py+32
py/inferscale/optimizer.py+142
py/inferscale/simulator.py+22-7
py/inferscale/workloads.py+7-4
pyproject.toml+1-1
scripts/release_check.py+54-10
src/inferscale/__init__.py+4-2
src/inferscale/api.py+10-4
src/inferscale/diagnostics.py+35-10
src/inferscale/disaggregated.pyAdded+362
src/inferscale/kv_cache.py+9-7
src/inferscale/latency.py+1-1
src/inferscale/models.py+32
src/inferscale/optimizer.py+142
src/inferscale/simulator.py+22-7
src/inferscale/workloads.py+7-4
styles.css+288-12
tests/test_design_space.pyAdded+41
tests/test_disaggregated.pyAdded+39
tests/test_prefix_cache.pyAdded+28
worker.mjs+1