MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / mistral_concurrency_notes.md
| 1 | # mistral.rs Concurrency & Throughput Architecture — MojoLlama Applicable Patterns |
| 2 | |
| 3 | ## 1. Server Concurrency Model |
| 4 | |
| 5 | ### axum + tokio HTTP Layer |
| 6 | - Each HTTP request spawns a tokio task. |
| 7 | - Per-request `mpsc::channel(10_000)` created. `Sender` attached to `NormalRequest.response`. |
| 8 | - Axum router built by `MistralRsServerRouterBuilder`. |
| 9 | |
| 10 | ### Multi-Model Management |
| 11 | - `MistralRs` struct owns `HashMap<String, EngineInstance>` — one per model. |
| 12 | - Each model gets a **dedicated OS thread** with its own `tokio::runtime::Runtime`. |
| 13 | - Each runtime runs a single `Engine::run()` async task. |
| 14 | - `get_sender(model_id)` resolves model aliases, auto-reloads unloaded models. |
| 15 | |
| 16 | ### Model Loading Flow |
| 17 | ```rust |
| 18 | // Load a model: spawns a thread, creates engine, channels everything |
| 19 | fn load_model_from_config(config: ModelConfig) -> Result<Arc<MistralRs>> { |
| 20 | // 1. Build pipeline (model architecture) |
| 21 | // 2. Create scheduler + KV cache manager |
| 22 | // 3. Spawn OS thread: `std::thread::spawn(move || { runtime.block_on(engine.run()) })` |
| 23 | // 4. Return Arc<MistralRs> with sender channel stored |
| 24 | } |
| 25 | ``` |
| 26 | |
| 27 | **Threading model:** |
| 28 | ``` |
| 29 | Client 1 ──HTTP──┐ |
| 30 | Client 2 ──HTTP──┤ |
| 31 | Client 3 ──HTTP──┤ axum router (tokio tasks) |
| 32 | │ |
| 33 | ▼ |
| 34 | mpsc::channel (per-request Sender) |
| 35 | │ |
| 36 | ▼ |
| 37 | ┌──────────────────┐ |
| 38 | │ Engine::run() │ ← Single OS thread per model |
| 39 | │ (event loop) │ |
| 40 | └──────────────────┘ |
| 41 | │ |
| 42 | ▼ |
| 43 | Scheduler → Pipeline::step() → forward → sample → respond |
| 44 | ``` |
| 45 | |
| 46 | ### MojoLlama Pattern: |
| 47 | ```mojo |
| 48 | # Per-model event loop in its own thread |
| 49 | struct EngineInstance: |
| 50 | var model_id: String |
| 51 | var request_rx: Channel[Request] |
| 52 | var scheduler: Scheduler |
| 53 | var pipeline: Pipeline |
| 54 | |
| 55 | fn run(out self): |
| 56 | while self.running: |
| 57 | # Drain channel |
| 58 | while var req = self.request_rx.try_recv(): |
| 59 | if req.type == REQUEST_TERMINATE: |
| 60 | self.running = False |
| 61 | break |
| 62 | self.scheduler.add_request(req) |
| 63 | |
| 64 | # Schedule and step |
| 65 | if var batch = self.scheduler.schedule(): |
| 66 | self.pipeline.step(batch) |
| 67 | |
| 68 | # Respond to completed sequences |
| 69 | self.dispatch_responses() |
| 70 | |
| 71 | # Idle wait |
| 72 | if nothing_to_do: |
| 73 | self.request_rx.wait() |
| 74 | ``` |
| 75 | |
| 76 | **Key insight:** One OS thread per model with async channels is simpler and more predictable than a thread-per-request model. Mojo's `@parameter` + threading can replicate this cleanly. |
| 77 | |
| 78 | --- |
| 79 | |
| 80 | ## 2. The Engine Event Loop |
| 81 | |
| 82 | From `mistralrs-core/src/engine/mod.rs`: |
| 83 | |
| 84 | ```rust |
| 85 | pub async fn run(&mut self) { |
| 86 | loop { |
| 87 | // 1. Drain channel: collect all pending requests |
| 88 | while let Ok(normal_or_terminate) = self.rx.try_recv() { |
| 89 | match normal_or_terminate { |
| 90 | Request::Normal(req) => { |
| 91 | if let Err(e) = self.add_request(req).await { ... } |
| 92 | } |
| 93 | Request::Terminate => { ... break; } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // 2. Schedule: form a batch from waiting + running sequences |
| 98 | if self.scheduler.schedule()? { |
| 99 | let batch = self.scheduler.get_batch()?; |
| 100 | // 3. Step: forward pass + sampling |
| 101 | let result = self.pipeline.step(self.scheduler, batch).await; |
| 102 | // 4. Handle output: stream to channels, mark done |
| 103 | self.process_step_output(result); |
| 104 | } |
| 105 | |
| 106 | // 5. Cleanup: remove finished sequences |
| 107 | self.scheduler.remove_done_seqs(); |
| 108 | |
| 109 | // 6. Wait if idle |
| 110 | if is_idle { |
| 111 | select! { |
| 112 | _ = self.rx.recv() => {}, |
| 113 | _ = self.pending_notify.notified() => {}, |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | ``` |
| 119 | |
| 120 | **Key design decisions:** |
| 121 | - **Single-threaded event loop** — no contention, no locks in hot path |
| 122 | - **Drain-then-process** — all pending requests collected before scheduling |
| 123 | - **Synchronous step** — `Pipeline::step()` is blocking (GPU kernel launch), no async in hot path |
| 124 | - **`pending_notify`** — scheduler wakes the engine when a sequence becomes ready (e.g., after waiting for preempted sequence) |
| 125 | |
| 126 | ### MojoLlama Pattern: |
| 127 | ```mojo |
| 128 | fn engine_loop(out self): |
| 129 | while self.active: |
| 130 | # Step 1: Drain incoming requests |
| 131 | for request in self.request_queue.drain_all(): |
| 132 | self.handle_request(request) |
| 133 | |
| 134 | # Step 2: Try to schedule a batch |
| 135 | if var batch = self.scheduler.schedule(): |
| 136 | # Step 3: Run inference (blocking, SIMD/MAX kernel) |
| 137 | var outputs = self.pipeline.step(batch) |
| 138 | |
| 139 | # Step 4: Dispatch per-sequence responses |
| 140 | for output in outputs: |
| 141 | if output.completed: |
| 142 | self.respond(output) # Send via mpsc channel |
| 143 | else: |
| 144 | self.scheduler.requeue(output.sequence) |
| 145 | |
| 146 | # Step 5: Cleanup |
| 147 | self.scheduler.purge_completed() |
| 148 | |
| 149 | # Step 6: Backpressure — yield if nothing to do |
| 150 | if self.request_queue.empty() and self.scheduler.idle(): |
| 151 | self.request_queue.wait_for_request() |
| 152 | ``` |
| 153 | |
| 154 | --- |
| 155 | |
| 156 | ## 3. DefaultScheduler (Fixed-Slot, Normal KV Cache) |
| 157 | |
| 158 | From `mistralrs-core/src/scheduler/default_scheduler.rs`: |
| 159 | |
| 160 | ### Data Structures |
| 161 | ```rust |
| 162 | pub struct DefaultScheduler { |
| 163 | waiting: VecDeque<Sequence>, // Not yet admitted |
| 164 | running: Vec<Sequence>, // Currently active (decode loop) |
| 165 | method: DefaultSchedulerMethod, // Fixed(N) or MaxThroughput |
| 166 | n_grace: f32, // Grace period for preempted sequences |
| 167 | } |
| 168 | ``` |
| 169 | |
| 170 | ### Admission Policy |
| 171 | - `DefaultSchedulerMethod::Fixed(N)`: At most `N` sequences in `running` at any time |
| 172 | - A waiting sequence is admitted when `running.len() < max_seqs` |
| 173 | - No KV memory admission check (assumes fits) |
| 174 | |
| 175 | ### Scheduling Algorithm (called every engine loop iteration) |
| 176 | |
| 177 | ```rust |
| 178 | fn schedule(&mut self) -> bool { |
| 179 | // 1. Remove completed sequences from running |
| 180 | self.running.retain(|s| !s.is_done()); |
| 181 | |
| 182 | // 2. Try to admit waiting sequences |
| 183 | while self.running.len() < self.max_seqs && !self.waiting.is_empty() { |
| 184 | let seq = self.waiting.pop_front().unwrap(); |
| 185 | self.running.push(seq); |
| 186 | } |
| 187 | |
| 188 | // 3. If no running sequences, nothing to do |
| 189 | if self.running.is_empty() { |
| 190 | return Ok(false); |
| 191 | } |
| 192 | |
| 193 | // 4. Length-based bucketing: group by (seq_len, has_images, token_offset) |
| 194 | let buckets = self.bucket_sequences(&self.running); |
| 195 | |
| 196 | // 5. Pick the bucket with the shortest sequence length |
| 197 | let chosen = self.select_bucket(&buckets); |
| 198 | |
| 199 | // 6. Preempt all sequences NOT in the chosen bucket |
| 200 | // (with urgency boost to prevent starvation) |
| 201 | for seq in &mut self.running { |
| 202 | if !chosen.contains(seq.id()) { |
| 203 | seq.preempt_with_urgency_boost(); |
| 204 | self.waiting.push_front(seq); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // 7. Build batch from chosen bucket |
| 209 | self.current_batch = Some(Batch::from(chosen)); |
| 210 | Ok(true) |
| 211 | } |
| 212 | ``` |
| 213 | |
| 214 | ### Bucket Selection |
| 215 | ```rust |
| 216 | fn bucket_sequences(&self, seqs: &[Sequence]) -> Vec<Bucket> { |
| 217 | // Group by (padded_length, has_images && is_prompt, token_offset) |
| 218 | // padded_length = ceil(log2(seq_len)) (power-of-2 padding) |
| 219 | let mut buckets: HashMap<(usize, bool, usize), Vec<Sequence>> = HashMap::new(); |
| 220 | for seq in seqs { |
| 221 | let key = ( |
| 222 | seq.padded_length(), |
| 223 | seq.has_images() && seq.is_prompt(), |
| 224 | seq.token_offset(), |
| 225 | ); |
| 226 | buckets.entry(key).or_default().push(seq.clone()); |
| 227 | } |
| 228 | buckets.into_values().map(Bucket).collect() |
| 229 | } |
| 230 | |
| 231 | fn select_bucket(&self, buckets: &[Bucket]) -> &Bucket { |
| 232 | // Pick the bucket with the minimum sequence length |
| 233 | // (shortest sequences run first — maximizes throughput) |
| 234 | buckets.iter().min_by_key(|b| b.min_length()).unwrap() |
| 235 | } |
| 236 | ``` |
| 237 | |
| 238 | **Why length-based bucketing?** Padding all sequences to the same length wastes computation. By grouping same-length sequences together, the padding overhead is eliminated. The shortest bucket runs first (fastest to finish, frees slots). |
| 239 | |
| 240 | ### Preemption with Urgency Boost |
| 241 | ```rust |
| 242 | fn preempt(&mut self, seq: &mut Sequence) { |
| 243 | seq.waiting_count += 1; // Starvation counter |
| 244 | self.waiting.push_front(seq.clone()); |
| 245 | } |
| 246 | ``` |
| 247 | |
| 248 | Each time a sequence is preempted, its `waiting_count` increases. The selection algorithm biases toward high-count sequences. After `MAX_PREEMPTIONS` (64), a running sequence is forcibly evicted. |
| 249 | |
| 250 | ### MojoLlama Pattern: |
| 251 | ```mojo |
| 252 | struct DefaultScheduler: |
| 253 | var waiting: List[Sequence] |
| 254 | var running: List[Sequence] |
| 255 | var max_seqs: Int |
| 256 | var current_batch: Batch |
| 257 | |
| 258 | fn schedule(out self) -> Bool: |
| 259 | # 1. Remove done sequences |
| 260 | self.running = self.running.filter(not done) |
| 261 | |
| 262 | # 2. Admit waiting up to capacity |
| 263 | while self.running.size() < self.max_seqs: |
| 264 | if var seq = self.waiting.pop_front(): |
| 265 | self.running.append(seq) |
| 266 | else: break |
| 267 | |
| 268 | # 3. Bucket by sequence length (power-of-2 groups) |
| 269 | var buckets = self.bucket_sequences(self.running) |
| 270 | if buckets.size() == 0: return False |
| 271 | |
| 272 | # 4. Pick shortest bucket (maximize throughput) |
| 273 | var chosen = self.select_shortest_bucket(buckets) |
| 274 | |
| 275 | # 5. Preempt others with starvation awareness |
| 276 | for seq in self.running: |
| 277 | if not chosen.contains(seq): |
| 278 | seq.starvation_counter += 1 |
| 279 | self.waiting.push_front(seq) |
| 280 | |
| 281 | self.running = chosen.to_list() |
| 282 | self.current_batch = Batch(self.running) |
| 283 | return True |
| 284 | |
| 285 | fn bucket_sequences(self, seqs: List[Sequence]) -> List[Bucket]: |
| 286 | # Group by (log2_padded_length, is_prefill) |
| 287 | var buckets = Dict[(Int, Bool), Bucket]() |
| 288 | for seq in seqs: |
| 289 | var key = (seq.padded_length_log2(), seq.is_prefill) |
| 290 | buckets[key].append(seq) |
| 291 | return buckets.values() |
| 292 | ``` |
| 293 | |
| 294 | --- |
| 295 | |
| 296 | ## 4. PagedAttentionScheduler (Block-Level KV Cache) |
| 297 | |
| 298 | From `mistralrs-core/src/paged_attention/scheduler.rs`: |
| 299 | |
| 300 | ### Block-Level Admission Control |
| 301 | ```rust |
| 302 | fn schedule_block_level(...) -> bool { |
| 303 | // 1. Compute which KV cache blocks each running sequence needs |
| 304 | // 2. Check if blocks are available in the cache pool |
| 305 | |
| 306 | // For each sequence in running, ensure it has enough allocated blocks |
| 307 | // If not enough blocks, preempt the lowest-urgency sequence |
| 308 | |
| 309 | // For each sequence in waiting, check if we can allocate its first block |
| 310 | // Blocks are allocated on-demand, not upfront |
| 311 | } |
| 312 | ``` |
| 313 | |
| 314 | ### KV Cache Allocation |
| 315 | ```rust |
| 316 | fn allocate_slots(&mut self, seq: &mut Sequence, n_tokens: usize) -> bool { |
| 317 | let blocks_needed = ceil_div(seq.seq_len + n_tokens, BLOCK_SIZE) - seq.num_blocks; |
| 318 | // Check pool; if insufficient, try LRU eviction from inactive sequences |
| 319 | // If still insufficient, return false (sequence not admitted) |
| 320 | } |
| 321 | ``` |
| 322 | |
| 323 | ### Prefix Caching |
| 324 | ```rust |
| 325 | // Each block has a content hash |
| 326 | // On admission, check if any existing block has the same hash |
| 327 | // If so, reuse it (increment reference count) |
| 328 | fn get_computed_blocks(&self, seq: &Sequence) -> Vec<BlockId> { |
| 329 | let mut blocks = Vec::new(); |
| 330 | for token in seq.tokens.iter_chunks(BLOCK_SIZE) { |
| 331 | let hash = compute_hash(token); |
| 332 | if let Some(block) = self.block_hashtable.get(&hash) { |
| 333 | blocks.push(block.id); |
| 334 | } else { |
| 335 | break; // Prefix match only |
| 336 | } |
| 337 | } |
| 338 | blocks |
| 339 | } |
| 340 | ``` |
| 341 | |
| 342 | ### Starvation Prevention |
| 343 | ```rust |
| 344 | // After 64 scheduling passes without being picked for inference, |
| 345 | // the waiting sequence forces a running sequence to be preempted |
| 346 | const MAX_STARVATION_PASSES: u32 = 64; |
| 347 | |
| 348 | fn check_starvation(&mut self) { |
| 349 | for seq in &self.waiting { |
| 350 | seq.passes_without_inference += 1; |
| 351 | if seq.passes_without_inference > MAX_STARVATION_PASSES { |
| 352 | // Force-preempt the lowest-urgency running sequence |
| 353 | let victim = self.running.iter().min_by_key(|s| s.urgency()).unwrap(); |
| 354 | self.preempt(victim); |
| 355 | break; |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | ``` |
| 360 | |
| 361 | ### MojoLlama Pattern: |
| 362 | ```mojo |
| 363 | struct PagedAttentionScheduler: |
| 364 | var block_pool: BlockPool # Physical KV cache blocks |
| 365 | var block_table: Dict[Int, List[Int]] # Logical → physical mapping per sequence |
| 366 | var waiting: List[Sequence] |
| 367 | var running: List[Sequence] |
| 368 | |
| 369 | fn allocate_kv_blocks(inout self, seq: Sequence, n_tokens: Int) -> Bool: |
| 370 | var needed = (seq.seq_len + n_tokens + BLOCK_SIZE - 1) // BLOCK_SIZE |
| 371 | var current = self.block_table[seq.id].size() |
| 372 | var allocate = needed - current |
| 373 | |
| 374 | for _ in range(allocate): |
| 375 | if var block = self.block_pool.allocate(): |
| 376 | self.block_table[seq.id].append(block) |
| 377 | else: |
| 378 | # Try evicting LRU from completed sequences |
| 379 | self.evict_lru() |
| 380 | if var block = self.block_pool.allocate(): |
| 381 | self.block_table[seq.id].append(block) |
| 382 | else: |
| 383 | return False # Out of memory |
| 384 | return True |
| 385 | |
| 386 | fn schedule(out self) -> Bool: |
| 387 | # 1. Check starvation |
| 388 | self.check_starvation() |
| 389 | |
| 390 | # 2. Try admitting waiting sequences |
| 391 | for seq in self.waiting: |
| 392 | if self.allocate_kv_blocks(seq, 0): |
| 393 | self.running.append(seq) |
| 394 | # else: stays in waiting, retried next iteration |
| 395 | |
| 396 | # 3. Build batch from all running sequences |
| 397 | # (PagedAttention can handle variable-length sequences) |
| 398 | if self.running.size() > 0: |
| 399 | self.current_batch = Batch(self.running) |
| 400 | return True |
| 401 | return False |
| 402 | ``` |
| 403 | |
| 404 | --- |
| 405 | |
| 406 | ## 5. Pipeline::step() — The Core Inference Step |
| 407 | |
| 408 | From `mistralrs-core/src/pipeline/mod.rs` and `mistralrs-core/src/pipeline/normal.rs`: |
| 409 | |
| 410 | ```rust |
| 411 | async fn step(&mut self, scheduler: &mut Box<dyn Scheduler>, batch: Batch) -> Result<()> { |
| 412 | // ---- Phase 1: Cache Pre-Op ---- |
| 413 | // For each sequence in batch, ensure KV cache is contiguous |
| 414 | // (clone cache tensors or reset for new sequences) |
| 415 | for seq in batch.iter() { |
| 416 | self.cache_manager.clone_in_cache(seq)?; |
| 417 | } |
| 418 | |
| 419 | // ---- Phase 2: Input Processing ---- |
| 420 | // Tokenize + multimodal processing |
| 421 | let input = self.process_inputs(&batch).await?; |
| 422 | // input.input_ids: Tensor [batch_size, seq_len] |
| 423 | // input.position_ids: Tensor [batch_size, seq_len] |
| 424 | |
| 425 | // ---- Phase 3: Forward Pass ---- |
| 426 | // Model forward (blocking GPU call) |
| 427 | let logits = self.model.forward( |
| 428 | input.input_ids, |
| 429 | input.position_ids, |
| 430 | input.cache_input, |
| 431 | )?; |
| 432 | |
| 433 | // ---- Phase 4: Output Splitting ---- |
| 434 | // Split the [batch, seq_len, vocab] logits per sequence |
| 435 | let per_seq_logits = self.split_logits(logits, &batch); |
| 436 | |
| 437 | // ---- Phase 5: Cache Post-Op ---- |
| 438 | // Copy KV cache from scratch space to sequence storage |
| 439 | for seq in batch.iter() { |
| 440 | self.cache_manager.clone_out_cache(seq)?; |
| 441 | } |
| 442 | |
| 443 | // ---- Phase 6: Sampling ---- |
| 444 | // For each sequence: sample token, check stop, stream response |
| 445 | for (seq, logits) in batch.iter().zip(per_seq_logits) { |
| 446 | let token = self.sample(logits, seq.sampling_params)?; |
| 447 | let done = seq.append_token(token); |
| 448 | if done { |
| 449 | self.send_response(seq, Response::Done(last_token)); |
| 450 | } else { |
| 451 | self.send_response(seq, Response::Chunk(token)); |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | Ok(()) |
| 456 | } |
| 457 | ``` |
| 458 | |
| 459 | ### Prefill-then-Decode Ordering |
| 460 | |
| 461 | From the scheduler's `schedule()` method, completions have priority: |
| 462 | 1. **Completions first** (decode): sequences already in `running` that are generating tokens |
| 463 | 2. **Prompts second** (prefill): newly admitted sequences that need their first forward pass |
| 464 | |
| 465 | This ensures prefilling a long prompt doesn't block ongoing generation. |
| 466 | |
| 467 | ### MojoLlama Pattern: |
| 468 | ```mojo |
| 469 | struct Pipeline: |
| 470 | var model: LlamaModel |
| 471 | var cache_manager: CacheManager |
| 472 | var sampler: Sampler |
| 473 | |
| 474 | fn step(inout self, batch: Batch) -> List[StepOutput]: |
| 475 | # Phase 1: Prepare KV cache |
| 476 | for seq in batch: |
| 477 | self.cache_manager.prepare(seq) |
| 478 | |
| 479 | # Phase 2: Process inputs |
| 480 | var input_ids = self.prepare_inputs(batch) |
| 481 | |
| 482 | # Phase 3: Forward |
| 483 | var logits = self.model.forward( |
| 484 | input_ids, |
| 485 | self.cache_manager.get_kv_cache(batch) |
| 486 | ) |
| 487 | |
| 488 | # Phase 4: Split per-sequence logits |
| 489 | var per_seq = self.split_logits(logits, batch) |
| 490 | |
| 491 | # Phase 5: Commit KV cache |
| 492 | for seq in batch: |
| 493 | self.cache_manager.commit(seq) |
| 494 | |
| 495 | # Phase 6: Sample and stream |
| 496 | var outputs = List[StepOutput]() |
| 497 | for i in range(batch.size()): |
| 498 | var token = self.sampler.sample(per_seq[i], batch[i].params) |
| 499 | var done = batch[i].append(token) |
| 500 | outputs.append(StepOutput(batch[i].id, token, done)) |
| 501 | |
| 502 | return outputs |
| 503 | ``` |
| 504 | |
| 505 | --- |
| 506 | |
| 507 | ## 6. Streaming Architecture |
| 508 | |
| 509 | From `mistralrs-server-core/src/streaming.rs` and `chat_completion.rs`: |
| 510 | |
| 511 | ### Per-Request Channel |
| 512 | ```rust |
| 513 | // When a request arrives: |
| 514 | let (tx, rx) = mpsc::channel::<Response>(10_000); |
| 515 | let request = NormalRequest { |
| 516 | response: RequestResponse(tx), // Sender embedded in request |
| 517 | ... |
| 518 | }; |
| 519 | |
| 520 | // Engine sends responses through this channel: |
| 521 | let _ = request.response.0.send(Response::Chunk(token)); |
| 522 | |
| 523 | // Server reads from the channel and formats as SSE: |
| 524 | pub struct BaseStreamer { |
| 525 | receiver: tokio::sync::mpsc::Receiver<Response>, |
| 526 | state: DoneState, |
| 527 | } |
| 528 | ``` |
| 529 | |
| 530 | ### SSE Format |
| 531 | ``` |
| 532 | data: {"choices":[{"delta":{"content":"Hello"},"index":0}]} |
| 533 | |
| 534 | data: {"choices":[{"delta":{"content":" world"},"index":0}]} |
| 535 | |
| 536 | data: [DONE] |
| 537 | ``` |
| 538 | |
| 539 | ### Keep-Alive |
| 540 | - Every 10 seconds of no data, a keep-alive comment is sent. |
| 541 | - Implemented with `tokio::time::interval` in the streamer. |
| 542 | |
| 543 | ### SequenceGroup for Multi-Choice |
| 544 | - A `SequenceGroup` contains `n_choices` sequences. |
| 545 | - Chunk is sent to the client only when ALL choices have output ready. |
| 546 | - When all choices are done, `Done` is sent. |
| 547 | |
| 548 | ### MojoLlama Pattern: |
| 549 | ```mojo |
| 550 | # Per-request response channel |
| 551 | struct Request: |
| 552 | var prompt: String |
| 553 | var params: SamplingParams |
| 554 | var response_tx: MPSCSender[StepOutput] # Channel back to HTTP handler |
| 555 | var id: Int |
| 556 | |
| 557 | # HTTP handler — SSE streaming |
| 558 | fn handle_chat_completion(request: ChatRequest) -> Response: |
| 559 | var (tx, rx) = MPSCChannel[StepOutput](10_000) |
| 560 | engine.send_request(Request(prompt, params, tx)) |
| 561 | |
| 562 | # Stream response as SSE |
| 563 | response_stream = rx.to_stream().map(|output| |
| 564 | SSE(data=output.to_json()) |
| 565 | ) |
| 566 | |
| 567 | return Response( |
| 568 | content_type="text/event-stream", |
| 569 | body=response_stream.chain(SSE("[DONE]")) |
| 570 | ) |
| 571 | ``` |
| 572 | |
| 573 | --- |
| 574 | |
| 575 | ## 7. KV Cache Management |
| 576 | |
| 577 | ### Normal Cache (DefaultScheduler) |
| 578 | - Per-layer `SingleCache`: grows in 512-token increments |
| 579 | - Batching via `Tensor::cat` (concat) and `Tensor::chunk` (split) |
| 580 | - Simple but wastes padding space |
| 581 | |
| 582 | ### PagedAttention Cache (PagedAttentionScheduler) |
| 583 | - Block pool with configurable GPU memory limit (`--cache-free-memory`) |
| 584 | - Blocks allocated on demand, reference-counted |
| 585 | - LRU eviction to CPU when GPU memory runs low |
| 586 | - Prefix caching via content hashing |
| 587 | |
| 588 | ### Hybrid Cache |
| 589 | - For MoE/recurrent models: attention layers use KV cache, recurrent layers use state pool |
| 590 | - State pool: index-based gather/scatter |
| 591 | |
| 592 | ### MojoLlama Pattern: |
| 593 | ```mojo |
| 594 | # Block-based KV cache (PagedAttention-style) |
| 595 | struct BlockPool: |
| 596 | var blocks: NDBuffer # [num_blocks, block_size, num_heads, head_dim] |
| 597 | var free_list: List[Int] |
| 598 | var lru_queue: List[Int] |
| 599 | |
| 600 | fn allocate(out self) -> Option[Int]: |
| 601 | if self.free_list.size() > 0: |
| 602 | return self.free_list.pop() |
| 603 | # Evict LRU |
| 604 | if self.lru_queue.size() > 0: |
| 605 | var victim = self.lru_queue.pop_front() |
| 606 | self.evict_to_cpu(victim) |
| 607 | return victim |
| 608 | return None |
| 609 | |
| 610 | fn evict_to_cpu(self, block_id: Int): |
| 611 | # Copy block from GPU to CPU swap |
| 612 | self.cpu_swap.store(self.blocks[block_id, :, :, :]) |
| 613 | |
| 614 | # Cache manager with prefix caching |
| 615 | struct CacheManager: |
| 616 | var pool: BlockPool |
| 617 | var block_tables: Dict[Int, List[Int]] # seq_id → [physical_block_ids] |
| 618 | var content_hashes: Dict[Int, Int] # hash → physical_block_id |
| 619 | |
| 620 | fn compute_prefix_blocks(self, tokens: List[Int]) -> List[Int]: |
| 621 | var result = List[Int]() |
| 622 | for chunk in tokens.chunks(BLOCK_SIZE): |
| 623 | var h = hash(chunk) |
| 624 | if self.content_hashes.contains(h): |
| 625 | result.append(self.content_hashes[h]) |
| 626 | else: break |
| 627 | return result |
| 628 | ``` |
| 629 | |
| 630 | --- |
| 631 | |
| 632 | ## 8. Request Flow Summary |
| 633 | |
| 634 | ``` |
| 635 | HTTP Request |
| 636 | │ |
| 637 | ▼ |
| 638 | axum route handler |
| 639 | │ |
| 640 | ├─ NormalRequest { messages, sampling_params, response_tx } |
| 641 | │ |
| 642 | ▼ |
| 643 | mpsc::channel[10000] |
| 644 | │ |
| 645 | ▼ |
| 646 | ┌────────────────────────────────────────┐ |
| 647 | │ Engine::run() [single OS thread] │ |
| 648 | │ │ |
| 649 | │ Loop: │ |
| 650 | │ drain channel │ |
| 651 | │ scheduler.schedule() → batch │ |
| 652 | │ pipeline.step(batch) → outputs │ |
| 653 | │ ├─ model.forward() │ |
| 654 | │ │ ├─ input_ids, cache │ |
| 655 | │ │ └─ logits │ |
| 656 | │ └─ sampler.sample() → tokens │ |
| 657 | │ ├─ Response::Chunk(tx) → SSE │ |
| 658 | │ └─ Response::Done(tx) → [DONE]│ |
| 659 | │ scheduler.remove_done() │ |
| 660 | └────────────────────────────────────────┘ |
| 661 | │ |
| 662 | ▼ |
| 663 | SSE stream to HTTP client |
| 664 | ``` |
| 665 | |
| 666 | --- |
| 667 | |
| 668 | ## 9. Benchmarking Concurrency |
| 669 | |
| 670 | ```bash |
| 671 | # Single request throughput |
| 672 | mistralrs bench -m Qwen/Qwen3-4B --isq Q4_0 |
| 673 | |
| 674 | # Concurrent requests (server mode) |
| 675 | mistralrs serve -m Qwen/Qwen3-4B --isq Q4_0 |
| 676 | |
| 677 | # Then bench with something like: |
| 678 | # oha -c 4 -n 100 http://localhost:1234/v1/chat/completions -m POST ... |
| 679 | |
| 680 | # Key metrics to measure on MojoLlama: |
| 681 | # - tok/s at batch_size=1 (decode latency) |
| 682 | # - tok/s at batch_size=4,8,16 (continuous batching throughput) |
| 683 | # - p50/p95 TTFT (time to first token) |
| 684 | # - Max concurrent sequences before OOM |
| 685 | # - Token throughput decay as context grows |
| 686 | ``` |
| 687 | |
| 688 | ## 10. 10 Design Patterns MojoLlama Should Adopt (Ranked) |
| 689 | |
| 690 | | Priority | Pattern | Why | Mojo Impl | |
| 691 | |----------|---------|-----|-----------| |
| 692 | | P0 | **Single-threaded engine per model** | No locking in hot path, deterministic scheduling | `@parameter` + dedicated OS thread per model | |
| 693 | | P0 | **Continuous batching** | Max GPU utilization during decode | Batch formed every `step()`, sequences exit when done | |
| 694 | | P0 | **mpsc channel dispatching** | Decoupled HTTP and inference, backpressure | `MPSCChannel[Request]` between server and engine | |
| 695 | | P0 | **Prefill-then-decode ordering** | Decode never blocked by long prompts | Sort batch: decodes first, prefills second | |
| 696 | | P0 | **PagedAttention block KV cache** | Memory proportional to active tokens, not max context | Block pool + page table + LRU eviction | |
| 697 | | P1 | **Length-based bucketing** | Minimizes padding waste | Group sequences by `ceil(log2(seq_len))` | |
| 698 | | P1 | **SSE streaming via per-request channel** | Low-latency token delivery | `MPSCChannel[StepOutput]` per request | |
| 699 | | P1 | **Prefix caching with content hashing** | Reuse KV blocks across requests | Hash-based block dedup in page table | |
| 700 | | P2 | **Starvation-aware scheduling** | Fairness under load | Urgency counter + forced preemption after N passes | |
| 701 | | P2 | **SequenceGroup for multi-choice** | Coordinate parallel sampled responses | Group `n` sequences, dispatch only when all ready | |