Ypeng12 commited on
Commit
db080b7
ยท
1 Parent(s): 02445d7

docs: restore rich and premium README structure with formulas, diagrams, and code snippets

Browse files
Files changed (1) hide show
  1. README.md +159 -35
README.md CHANGED
@@ -7,47 +7,168 @@
7
  <img src="https://img.shields.io/badge/PRs-Welcome-goldenrod.svg" alt="PRs Welcome">
8
  </p>
9
 
10
- > ๐ŸŒ **Interactive Academic Hub & Cascade Simulator**: **[https://ypeng12.github.io/InferRoute/](https://ypeng12.github.io/InferRoute/)**
11
- > Go here to explore detailed mathematical derivations, request lifecycle sequence charts, paper downloads, and run the sequential cascade simulation.
12
 
13
  ---
14
 
15
- ## ๐Ÿ“– Overview
16
 
17
- **InferRoute** is a lightweight, production-grade LLM inference gateway and reliability proxy. Sitting between your client applications/AI agents and model backends (local Ollama/vLLM instances and cloud APIs like OpenAI/Gemini), it dynamically routes queries to optimize for **cost, latency, and quality** in real-time.
18
 
19
- By incorporating optimization techniques from Stanford's **FrugalGPT** and Martian's **RouterBench**, InferRoute helps developers reduce API operational costs by over **60%** while respecting latency and formatting SLAs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  ---
22
 
23
- ## โšก Key Features
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- * **๐Ÿ”„ Streaming Request Coalescing**: Uses a Redis-backed lock to merge concurrent duplicate prompts. Only the first request calls the upstream LLM, broadcasting stream token chunks to all callers via Redis Pub/Sub, preventing cache stampedes.
26
- * **๐ŸŒณ Radix Trie prefix KV-Cache Affinity**: Hashes and stores prompt system instruction prefixes in a Prefix Tree. Directs requests to local GPU backends holding warm KV caches, reducing TTFT (Time-to-First-Token) by up to 80%.
27
- * **๐Ÿ›ก๏ธ Vegas Adaptive Concurrency Control**: Tracks active RTT queues dynamically using a TCP Vegas congestion control loop to protect local GPUs from OOM failures under sudden traffic spikes.
28
- * **๐Ÿ”€ Speculative Fallback Cascades**: Buffers stream output from cheap local endpoints, running real-time loop and validation checks. Automatically and transparently escalates requests to premium cloud endpoints mid-stream if quality checks fail.
29
- * **๐Ÿง  Learned Predictive Routers**: Supports content-aware KNN and MLP scoring models, optimizing the cost-quality trade-off dynamically.
30
- * **๐Ÿ’ณ Multi-Tenant Billing Gateway**: Validates tenant keys and credit balances against an asynchronous PostgreSQL audit ledger, enforcing a resilient fail-open policy.
 
 
 
 
 
 
 
 
31
 
32
  ---
33
 
34
- ## ๐Ÿš€ Quick Start (Simulation Mode)
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- You can run InferRoute completely offline with zero API keys using our built-in mock simulation mode:
 
 
 
 
 
 
 
37
 
38
- ### 1. Installation
39
  ```bash
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  git clone https://github.com/ypeng12/InferRoute.git
41
  cd InferRoute
42
 
43
- # Set up virtual environment
44
  python -m venv .venv
45
  source .venv/bin/activate # On Windows: .venv\Scripts\activate
 
 
46
  pip install -r requirements.txt
47
  ```
48
 
49
- ### 2. Configure Environment
50
- Create a `.env` file in the root:
51
  ```env
52
  DATABASE_URL=sqlite+aiosqlite:///inferroute.db
53
  MOCK_OPENAI=true
@@ -56,29 +177,31 @@ MOCK_VLLM=true
56
  MOCK_OLLAMA=true
57
  ```
58
 
59
- ### 3. Start Gateway
60
  ```bash
61
  python -m uvicorn inferroute.main:app --host 127.0.0.1 --port 8080 --reload
62
  ```
63
- Open **[http://127.0.0.1:8080](http://127.0.0.1:8080)** to interact with the Live Playground and Chaos panel.
64
 
65
  ---
66
 
67
- ## ๐Ÿ› ๏ธ Integration Example (OpenAI Client)
68
 
69
- InferRoute exposes a fully OpenAI-compatible chat completions interface. Switch your existing application client in one line:
70
 
71
  ```python
72
  import openai
73
 
74
  client = openai.OpenAI(
75
  base_url="http://localhost:8080/v1",
76
- api_key="sk-inferroute-demo" # Tenant API key
77
  )
78
 
79
  response = client.chat.completions.create(
80
- model="edge/auto", # Dynamic auto-routing policy
81
- messages=[{"role": "user", "content": "Write a quicksort in Python."}],
 
 
82
  stream=True
83
  )
84
 
@@ -90,24 +213,25 @@ for chunk in response:
90
 
91
  ---
92
 
93
- ## ๐Ÿ“š Technical Documentation
94
 
95
- For deeper engineering writeups, check our documentation guides:
96
- * **[Academic Foundations & Theory](docs/academic_foundations.md)**: Stanford FrugalGPT and RouterBench cost-quality derivations.
97
- * **[Performance & Cost Benchmarks](docs/benchmark.md)**: Pareto Sweeps, latency comparisons, and metrics.
98
- * **[Gateway Request Lifecycle](docs/architecture.md)**: Interceptors, concurrency queues, and fallback sequence diagrams.
99
- * **[Resilience & Failure Injection](docs/failure-injection.md)**: Self-healing circuit breakers and Vegas metrics.
100
 
101
  ---
102
 
103
- ## ๐Ÿ“Š Containerized Production Stack
104
 
105
- In production, run the Docker Compose stack to enable the full observability pipeline:
106
  ```bash
 
107
  docker compose up -d
108
  ```
109
- * **Grafana Dashboard (Performance & Latency)**: [http://localhost:3000](http://localhost:3000) (Admin/Admin)
110
- * **Jaeger UI (Microservice Trace Tracking)**: [http://localhost:16686](http://localhost:16686)
111
 
112
  ---
113
 
 
7
  <img src="https://img.shields.io/badge/PRs-Welcome-goldenrod.svg" alt="PRs Welcome">
8
  </p>
9
 
10
+ > ๐Ÿš€ **Live Technical Hub & Interactive Cascade Simulator**: **[https://ypeng12.github.io/InferRoute/](https://ypeng12.github.io/InferRoute/)**
11
+ > Visit the hosted page to interact with the live sequence charts, LaTeX formula guides, original paper previews, and the FrugalGPT sequential cascade simulator!
12
 
13
  ---
14
 
15
+ ## ๐Ÿ“– Introduction
16
 
17
+ **InferRoute** is a lightweight, high-performance LLM inference gateway and reliability proxy. Sitting between client applications/AI agents and model backends (local Ollama/vLLM engines and commercial APIs like OpenAI/Gemini), it dynamically routes queries to optimize for **cost, latency, and quality** in real-time.
18
 
19
+ Rather than statically pinning your application to a single expensive cloud endpoint, InferRoute dynamically routes prompts based on **real-time quality validation, cost constraints, latency tracking, and prefix KV-cache affinity**, demonstrating **over 60% in API cost savings** in benchmark sweeps while guaranteeing strict latency and formatting SLAs.
20
+
21
+ <p align="center">
22
+ <img src="docs/cost_quality_frontier.png" alt="Cost Quality Pareto Frontier Sweep" width="650" style="border-radius: 12px; border: 1px solid rgba(0,0,0,0.08); box-shadow: 0 10px 30px rgba(0,0,0,0.05);" />
23
+ </p>
24
+
25
+ ---
26
+
27
+ ## โšก Key Technical Highlights
28
+
29
+ * **๐Ÿ”„ Distributed Streaming Deduplication**: Implements a Redis lock for duplicate concurrent prompts. The first request invokes the LLM while subsequent callers subscribe to the stream via **Redis Pub/Sub**, broadcasting token chunks simultaneously to avoid duplicate API fees.
30
+ * **๐ŸŒณ Radix Trie prefix KV-Cache Affinity**: Hashes prompt prefixes in a Prefix Tree to route requests to local GPU nodes holding warm KV caches, reducing Time-to-First-Token (TTFT) by up to 80%.
31
+ * **๐Ÿ›ก๏ธ Vegas Adaptive Concurrency Control**: Scales gateway concurrency slots dynamically based on active queue size tracking via a TCP Vegas congestion control loop to protect local GPUs from OOM failures.
32
+ * **๐Ÿ”€ Speculative Fallback Cascades**: Buffers response stream tokens, cancels degraded local streams speculatively (on loop or gibberish detection), and escalates to premium cloud nodes mid-stream to avoid service disruptions.
33
+ * **๐Ÿ’ณ Multi-Tenant Billing Gateway**: Validates tenant credentials and credits against an asynchronous PostgreSQL audit ledger, enforcing a resilient fail-open policy if the database is unreachable.
34
+
35
+ ---
36
+
37
+ ## ๐Ÿ—๏ธ Gateway Request Lifecycle
38
+
39
+ The diagram below outlines how the gateway intercepts client requests, checks caches, scales concurrency, and handles fallback cascades:
40
+
41
+ ```mermaid
42
+ graph TD
43
+ Client[Client App / SDK] -->|POST /v1/chat/completions| Gateway[InferRoute Gateway]
44
+
45
+ Gateway --> Auth{Auth Gate & Balance Check}
46
+ Auth -->|Low Balance| Block[402 Payment Required]
47
+ Auth -->|Valid Wallet| Cache{Redis Exact & Trie Cache}
48
+
49
+ Cache -->|Cache Hit| StreamCache[Stream response from Redis] --> Client
50
+ Cache -->|Cache Miss| Limiter{Vegas Adaptive Limiter}
51
+
52
+ Limiter -->|Queue Overload| Failover[Fallback to Cloud Node]
53
+ Limiter -->|Slot Acquired| Router[Routing Engine]
54
+
55
+ Router -->|Prefill Cache Affinity| Primary[Local vLLM / Ollama]
56
+ Router -->|Speculative Cost-Saver| Primary
57
+
58
+ Primary --> StreamBuf[Stream Buffer Validation]
59
+ StreamBuf -->|Repeated Loops / Fail| Cascade[Speculative Cancel & Fallback to Cloud]
60
+ StreamBuf -->|Quality Passed| StreamClient[Stream Response to Client] --> Client
61
+
62
+ StreamBuf --> BackgroundLog[Async Log & Wallet Deduction] --> PostgreSQL[(PostgreSQL Audit & Ledger)]
63
+ ```
64
 
65
  ---
66
 
67
+ ## ๐Ÿง  RouterBench Integration & Theoretical Foundations
68
+
69
+ > [!TIP]
70
+ > For a detailed breakdown of routing algorithms, mathematical proofs, and model mapping logic, see our dedicated **[Academic Foundations Guide](docs/academic_foundations.md)**.
71
+
72
+ InferRoute integrates the core routing methodologies and trade-off evaluation principles from the research paper:
73
+ > **ROUTERBENCH: A Benchmark for Multi-LLM Routing System** (by Martian / [withmartian/routerbench](https://github.com/withmartian/routerbench)).
74
+ > ๐Ÿ“„ **[Read RouterBench Paper PDF](docs/article/A_Benchmark_for_Multi_LLM_Routing_System.pdf)**
75
+
76
+ ### 1. Mathematical Scoring & Optimization
77
+ Predictive routing is formulated as choosing a backend $m$ that maximizes the utility score for a prompt $x$:
78
+ $$\text{Score}(m) = \lambda \cdot \text{Quality}_{\text{pred}}(m) - \text{Cost}(m)$$
79
+
80
+ Where:
81
+ * **$\lambda$ (lambda)**: User's willingness to pay. A high $\lambda$ (e.g. 5.0) prioritizes output quality (routing to GPT-4o-mini or Gemini-Flash). A low $\lambda$ (e.g. 0.1) prioritizes cost savings (routing to local vLLM/Ollama).
82
+ * **$\text{Quality}_{\text{pred}}(m)$**: Predicted quality score of model $m$ on prompt $x$ (ranging from $0.0$ to $1.0$).
83
+ * **$\text{Cost}(m)$**: The estimated economic API fee to process the request on backend $m$.
84
 
85
+ ### 2. Supported Routing Policies
86
+ InferRoute supports six distinct routing strategies aligned with the paper's framework:
87
+ 1. **๐ŸŽฒ Zero Router Baseline (`zero`)**: Non-content-aware routing. Randomly routes requests to Cloud/Expensive vs. Local/Cheap backends based on a target cloud mixture ratio $p$. Sweeping $p \in [0, 1]$ constructs the baseline cost-quality curve.
88
+ 2. **๐Ÿ“‹ Rule-Based Router (`rule`)**: Content-aware heuristics. Evaluates prompt keywords to route tasks (e.g., routing math tasks to GPT/Gemini, coding tasks to vLLM, simple greetings to Ollama).
89
+ 3. **๐Ÿง  KNN-Based Router (`knn`)**: Retrieves the $K$ most textually similar prompts (using Jaccard similarity) from historical benchmark outcomes. Computes the average historical quality per backend and optimizes via $\lambda \cdot \text{Quality} - \text{Cost}$.
90
+ 4. **๐Ÿ•ธ๏ธ MLP-Based Router (`mlp`)**: A fast logistic regression classifier that extracts prompt features (`is_code`, `is_math`, `is_json`, `is_long`) to predict success probability as predicted quality, then optimizes using the cost-quality formula.
91
+ 5. **๐Ÿ”ฎ Oracle Router Offline Upper Bound (`oracle`)**: A theoretical upper bound that has advance knowledge of whether each model will answer correctly. It selects the cheapest model that achieves a quality score $\ge 0.8$.
92
+ 6. **๐Ÿ”„ Cascade Router (FrugalGPT) (`cascade`)**: Server-side model cascade. Executes the cascade chain (cheap local models up to premium cloud models) until the reliability judge score meets the acceptance threshold $\tau$.
93
+
94
+ ### 3. Metric: AIQ (Area Under the Curve)
95
+ To measure a router's overall efficiency across all budgets, we compute the **AIQ (Area under the cost-quality curve)** using the Trapezoidal Rule over swept parameter values ($\lambda$ or $p$):
96
+ $$\text{AIQ} = \int_{c_{\min}}^{c_{\max}} Q(c) \, dc \approx \sum_{i=0}^{n-1} \frac{q_i + q_{i+1}}{2} \cdot (c_{i+1} - c_i)$$
97
+
98
+ A smart, content-aware learned router (MLP/KNN) will push the Pareto frontier towards the top-left, achieving a **significantly higher AIQ** than the Zero Router baseline.
99
 
100
  ---
101
 
102
+ ## ๐Ÿ”„ FrugalGPT Cascading Inference (LLM Cascade)
103
+
104
+ InferRoute integrates the cost-performance optimization concepts from the paper:
105
+ > **FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance** (by Stanford University / arXiv:2305.05196).
106
+ > ๐Ÿ“„ **[Read FrugalGPT Paper PDF](docs/article/How_to_Use_Large_Language_Models.pdf)** | ๐Ÿ“„ **[Read Hybrid LLM Routing Paper PDF](docs/article/cost_efficiency.pdf)**
107
+
108
+ FrugalGPT identifies three main classes of cost-saving methods:
109
+ 1. **Prompt Adaptation**: Reduces input tokens dynamically. In InferRoute, when routing to cheap local backends (Ollama/vLLM), the **Prompt Adapter** (`prompt_adapter.py`) automatically compresses prompt sizes by pruning few-shot examples, restoring full prompts when upgrading to premium models.
110
+ 2. **LLM Approximation (Completion Cache)**: Caches full answers. Handled by InferRoute's exact completions caching layer in Redis.
111
+ 3. **LLM Cascade**: Sequential invocation of backends (e.g., `ollama` โž” `vllm` โž” `gemini` โž” `openai`). The request starts with the cheapest backend, passes through a **Reliability Judge** (syntactic check, schema validation, loop penalty), and only escalates to a more expensive tier if the quality score is below the acceptance threshold $\tau$.
112
+
113
+ ### 1. Cascade Configuration
114
+ Select `Cascade Router (FrugalGPT Style)` in the routing options, and adjust the acceptance threshold $\tau \in [0.0, 1.0]$. The gateway executes the cascade loop entirely server-side, accumulating tokens and fees across all tried models to log in the PostgreSQL database correctly.
115
 
116
+ ### 2. Streaming Cascade Buffer
117
+ To prevent leaking low-quality responses to clients during streaming requests, the gateway buffers stream chunks internally, executes quality grading, and only pumps the SSE stream to the client once the output is officially accepted.
118
+
119
+ ---
120
+
121
+ ## ๐Ÿ“Š Reproducible Evaluation Harness
122
+
123
+ InferRoute includes a standardized pipeline to test and compare multiple routing strategies under realistic workloads, sweeping ratios and lambdas to trace Pareto frontiers:
124
 
 
125
  ```bash
126
+ # 1. Run the evaluation orchestrator (sweeps Zero Router p-ratios and KNN/MLP lambda values)
127
+ python benchmarks/run_router_eval.py
128
+
129
+ # 2. Compile stats, compute AIQ values, and generate visual Pareto curves
130
+ python benchmarks/plot_results.py
131
+ ```
132
+ This runs the dataset prompts across all scenarios and sweeps, and outputs cost, quality, latencies, SLO compliance, and AIQ comparisons to `benchmarks/results/`.
133
+
134
+ ---
135
+
136
+ ## ๐ŸŽจ Interactive Playground & Chaos Simulator
137
+
138
+ InferRoute includes a built-in interactive control center panel served at the root (`/`) path:
139
+ * **Live Cost Dashboard**: Displays money saved ($ USD), tokens saved, TTFT latency, and Redis cache hit rate.
140
+ * **Request Pipeline Visualizer**: Renders a vertical stepper showing step-by-step processing of the query (Cache checking, Limiter checking, Node executing, and Cascades).
141
+ * **Simulated Wallet & Recharge**: Top-right wallet indicator showing current credits (e.g., `$5.00` trial credit) with a simulated `+ $10` recharge button.
142
+ * **Chaos Engineering & Failure Injection**: A panel to manually kill or throttle model nodes, observing the circuit-breaker turning Red and routing self-healing in real-time.
143
+
144
+ For detailed performance, concurrency, and cost reports under heavy loads, check out the **[Benchmark Report](docs/benchmark.md)**.
145
+
146
+ ---
147
+
148
+ ## ๐Ÿš€ Quick Start (Running Offline in 10 Seconds)
149
+
150
+ InferRoute features a built-in **Simulation Mode** (using SQLite and Mock adapters) allowing you to boot and explore the gateway **completely for free, offline, with zero real API keys**!
151
+
152
+ ### 1. Requirements
153
+ * Python 3.12 or 3.13
154
+ * Docker & Docker Compose (Optional, for production Postgres/Redis/Grafana observability)
155
+
156
+ ### 2. Installation
157
+ ```bash
158
+ # Clone the repository
159
  git clone https://github.com/ypeng12/InferRoute.git
160
  cd InferRoute
161
 
162
+ # Initialize virtual environment
163
  python -m venv .venv
164
  source .venv/bin/activate # On Windows: .venv\Scripts\activate
165
+
166
+ # Install dependencies
167
  pip install -r requirements.txt
168
  ```
169
 
170
+ ### 3. Create Local Config File
171
+ Create a `.env` file in the root directory:
172
  ```env
173
  DATABASE_URL=sqlite+aiosqlite:///inferroute.db
174
  MOCK_OPENAI=true
 
177
  MOCK_OLLAMA=true
178
  ```
179
 
180
+ ### 4. Start the Gateway
181
  ```bash
182
  python -m uvicorn inferroute.main:app --host 127.0.0.1 --port 8080 --reload
183
  ```
184
+ Open **[http://127.0.0.1:8080](http://127.0.0.1:8080)** in your browser to interact with the dashboard immediately!
185
 
186
  ---
187
 
188
+ ## ๐Ÿ› ๏ธ Unified Integration (OpenAI Drop-In)
189
 
190
+ InferRoute is compatible with the standard OpenAI API chat completions format. You can switch your existing codebases to run through InferRoute in just one line:
191
 
192
  ```python
193
  import openai
194
 
195
  client = openai.OpenAI(
196
  base_url="http://localhost:8080/v1",
197
+ api_key="sk-inferroute-demo" # Custom tenant auth key
198
  )
199
 
200
  response = client.chat.completions.create(
201
+ model="edge/auto", # Dynamic auto-routing
202
+ messages=[
203
+ {"role": "user", "content": "Write a quicksort in Python."}
204
+ ],
205
  stream=True
206
  )
207
 
 
213
 
214
  ---
215
 
216
+ ## ๐Ÿ“š Project Documentation
217
 
218
+ Explore the following detailed guides for in-depth engineering breakdowns:
219
+ * **[Academic Research & Mathematical Foundations](docs/academic_foundations.md)**: Details of how FrugalGPT and RouterBench optimization theories map to our gateway components.
220
+ * **[Performance & Cost Benchmarks](docs/benchmark.md)**: Concrete metrics, cache stampede statistics, and reproduction logs.
221
+ * **[Inference Gateway Architecture](docs/architecture.md)**: Sequence diagrams of the request lifecycle and core sub-components.
222
+ * **[Failure Injection & High Availability](docs/failure-injection.md)**: Details on fail-open mechanisms and circuit breaker status thresholds.
223
 
224
  ---
225
 
226
+ ## ๐Ÿ“Š Observability Stack (Production Environment)
227
 
228
+ In a production environment, spin up the containerized observability stack to monitor traffic, metrics, and traces:
229
  ```bash
230
+ # Boot Postgres, Redis, OTtel Collector, Jaeger, Prometheus, Grafana
231
  docker compose up -d
232
  ```
233
+ * **Grafana Dashboard (Performance Metrics)**: [http://localhost:3000](http://localhost:3000) (Admin/Admin)
234
+ * **Jaeger UI (Microservices Traces)**: [http://localhost:16686](http://localhost:16686)
235
 
236
  ---
237