MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / mistral_serving_isq_mgpu.md
| 1 | # mistral.rs Deep Research: Serving Layer, ISQ, Multi-GPU, & Auto-Tuning |
| 2 | |
| 3 | > Research conducted: May 18, 2026 |
| 4 | > Source: github.com/EricLBuehler/mistral.rs @ 0ed6f6c |
| 5 | |
| 6 | --- |
| 7 | |
| 8 | ## Area 1: HTTP Serving Layer (OpenAI API) |
| 9 | |
| 10 | ### Architecture Overview |
| 11 | |
| 12 | The serving layer lives in `mistralrs-server-core/` and is built on **axum** (Tokio-based async HTTP framework). It exposes OpenAI-compatible endpoints for chat completions, completions, embeddings, image generation, speech, files, and responses. |
| 13 | |
| 14 | The architecture follows a **channel-based request/response** pattern: |
| 15 | |
| 16 | ``` |
| 17 | Client HTTP Request |
| 18 | -> axum Router (MistralRsServerRouterBuilder) |
| 19 | -> Endpoint Handler |
| 20 | -> create_response_channel() -> (Sender, Receiver) |
| 21 | -> parse_request() converts OpenAI JSON -> Request |
| 22 | -> send_request() dispatches via MPSC to engine |
| 23 | -> Engine processes, sends Response via Receiver |
| 24 | -> Handler converts Response to HTTP response (JSON or SSE) |
| 25 | ``` |
| 26 | |
| 27 | ### Router Construction (mistralrs_server_router_builder.rs) |
| 28 | |
| 29 | Core pattern: Builder pattern that wraps axum `Router::new()`. |
| 30 | |
| 31 | Routes registered: |
| 32 | - POST /v1/chat/completions |
| 33 | - POST /v1/completions |
| 34 | - POST /v1/embeddings |
| 35 | - GET /v1/models |
| 36 | - POST /v1/models/unload, /v1/models/reload, /v1/models/status, /v1/models/tune |
| 37 | - GET /v1/system/info |
| 38 | - POST /v1/system/doctor |
| 39 | - GET /health |
| 40 | - POST /re_isq |
| 41 | - POST /v1/images/generations |
| 42 | - GET /v1/files, GET/DELETE /v1/files/{id}, GET /v1/files/{id}/content |
| 43 | - POST /v1/audio/speech |
| 44 | - POST /v1/responses, GET/DELETE /v1/responses/{response_id} |
| 45 | - POST /v1/responses/{response_id}/cancel |
| 46 | - GET/PUT/DELETE /v1/sessions/{session_id} |
| 47 | |
| 48 | Middleware chain: |
| 49 | 1. CORS layer (configurable origins, methods GET/POST/PUT/DELETE, headers Content-Type/Authorization) |
| 50 | 2. DefaultBodyLimit (50 MB, configurable via builder) |
| 51 | 3. Extension injector for AgenticDefaults (max_tool_rounds, tool_dispatch_url) |
| 52 | 4. Shared state via Arc<MistralRs> |
| 53 | |
| 54 | Multi-model routing: model field selects sender via state.get_sender(model_id). If model == "default", primary model is used. |
| 55 | |
| 56 | ### Request/Response Channel Pattern (handler_core.rs) |
| 57 | |
| 58 | Core dispatch creates buffered channel (default 10_000), parses OpenAI JSON to internal Request, sends via MPSC, processes response as SSE or JSON. |
| 59 | |
| 60 | Error handling via ErrorToResponse trait (Serializes to JSON with HTTP status code). |
| 61 | |
| 62 | BaseCompletionResponder<R, S> enum: |
| 63 | - Sse(Sse<S>) - streaming SSE |
| 64 | - Json(R) - complete JSON |
| 65 | - ModelError(String, R) - partial error with data |
| 66 | - InternalError(Box<dyn Error>) - server error |
| 67 | - ValidationError(Box<dyn Error>) - 422 |
| 68 | |
| 69 | ### Streaming Implementation (streaming.rs, chat_completion.rs) |
| 70 | |
| 71 | SSE via axum Sse::new(stream) with KeepAlive. BaseStreamer<R, C, D> implements futures::Stream. |
| 72 | |
| 73 | State machine: Running -> SendingDone (emits [DONE]) -> Done (fires on_done). |
| 74 | |
| 75 | Callback hooks: on_chunk (Fn(R) -> R), on_done (Fn(&[R])). |
| 76 | Keep-alive: KEEP_ALIVE_INTERVAL env var (default 10s). |
| 77 | |
| 78 | ### Applicability to MojoLlama (Mojo/MAX Terms) |
| 79 | |
| 80 | 1. Channel-based request/response for async serving |
| 81 | 2. Builder pattern for router construction and middleware composition |
| 82 | 3. SSE streaming with KeepAlive as Mojo Stream iterator |
| 83 | 4. Error-as-response-variant enum for composable error handling |
| 84 | 5. Callback hooks for middleware/injection (logging, metrics, content filtering) |
| 85 | 6. Multi-model dispatch via string-keyed pipeline lookup |
| 86 | |
| 87 | --- |
| 88 | |
| 89 | ## Area 2: ISQ (In-Situ Quantization) Pipeline |
| 90 | |
| 91 | ### Architecture Overview |
| 92 | |
| 93 | ISQ converts weights from FP16/BF16/F32 to quantized formats after loading. Operates at layer level through QuantMethod trait. |
| 94 | |
| 95 | Flow: |
| 96 | - Model weights loaded |
| 97 | - IsqModel::get_layers() returns all quantizable layers |
| 98 | - For each layer: layer.apply_isq(dtype, device, n_quantized, imatrix_weight, guard) |
| 99 | - UQFF file written for fast reload |
| 100 | |
| 101 | ### Core Types |
| 102 | |
| 103 | IsqType enum: Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, Q2K-Q8K, HQQ4, HQQ8, F8E4M3, AFQ2-AFQ8, F8Q8, MXFP4. |
| 104 | |
| 105 | IsqBits: numeric shorthand (2-8). Platform-adaptive resolution: |
| 106 | - Metal: Two->AFQ2, Three->AFQ3, Four->AFQ4, Six->AFQ6, Eight->AFQ8 |
| 107 | - CUDA/CPU: Two->Q2K, Three->Q3K, Four->Q4K, Six->Q6K, Eight->Q8_0 |
| 108 | |
| 109 | QuantMethod trait: apply_isq(), forward(), dequantize_w(), quantized_act_type(), add_delta_w(), gather_forward(), is_distributed(). |
| 110 | |
| 111 | ### ISQ Pipeline Flow (mistralrs-core/src/pipeline/isq.rs) |
| 112 | |
| 113 | IsqModel::quantize(): load imatrix, get_layers(), apply_isq() per layer, parallel via rayon (GPU serialized by QuantizeOntoGuard), write UQFF artifacts. |
| 114 | |
| 115 | IsqOrganization: Default (all layers) or MoeExpertsOnly (MoQE). |
| 116 | |
| 117 | ### Immediate ISQ (mistralrs-quant/src/utils/isq.rs) |
| 118 | |
| 119 | ISQ during loading via thread-local ENGINE_IMMEDIATE_ISQ RefCell. Supports: |
| 120 | - Parallel path (spawn on pool, return PendingIsqLayer wrapper) |
| 121 | - Sync path (Metal/integrated GPU) |
| 122 | - Backpressure system (prevents OOM on MoE models) |
| 123 | - Per-layer overrides (regex-based ty/device) |
| 124 | |
| 125 | ### UQFF Binary Format |
| 126 | |
| 127 | [UQFF_VERSION: u32 LE] [QuantizedSerdeType: u8] [data_length: u32 LE] [has_bias: u8] [dtype: u32 LE] [n_dims: u32 LE] [dims...: u32 LE] [tensor_data: u8[]] [optional bias tensor] |
| 128 | |
| 129 | 10GB shard limit; files named {name}-{N}.uqff. |
| 130 | |
| 131 | ### Applicability to MojoLlama |
| 132 | |
| 133 | 1. Trait-based quantization dispatch via QuantMethod analogue |
| 134 | 2. Platform-adaptive quantization (detect backend, select optimal format) |
| 135 | 3. Immediate ISQ during loading with thread pool + backpressure |
| 136 | 4. Importance matrix (imatrix) support for quality preservation |
| 137 | 5. UQFF-style format with residuals for fast reload |
| 138 | 6. Backpressure for memory-constrained MoE environments |
| 139 | |
| 140 | --- |
| 141 | |
| 142 | ## Area 3: Multi-GPU and Device Mapping |
| 143 | |
| 144 | ### Architecture Overview |
| 145 | |
| 146 | Three strategies: |
| 147 | 1. Layer-pipeline parallelism (per-layer device) |
| 148 | 2. NCCL tensor parallelism (per-weight sharding + all-reduce) |
| 149 | 3. Ring-based distributed (TCP multi-node) |
| 150 | |
| 151 | ### Device Map System (device_map.rs) |
| 152 | |
| 153 | DeviceMapSetting: Map (manual/auto layers), Auto (compute optimal), DummyNccl, Nccl (real NCCL). |
| 154 | |
| 155 | DeviceMapper trait: |
| 156 | - map(input, layer) - runtime tensor move |
| 157 | - set_device(layer, vb, isq) - load-time varbuilder assignment |
| 158 | - device_for(layer, isq) - query device |
| 159 | - get_unique_devices() - all distinct devices |
| 160 | - cast_nm_device(x, isq) - non-mapped layers (embed, lm_head) |
| 161 | - get_comm_for(layer_idx) - communicator for TP |
| 162 | - num_device_mapping_layers() |
| 163 | |
| 164 | LayerDeviceMapper: Vec<Device>, one per layer. Forward: .to_device(&mappings[layer]). |
| 165 | |
| 166 | Auto device map: layer_sizes_in_bytes(), non_mapped_size_in_bytes(), MemoryUsage::query(). Round-robin until memory fills, then CPU. |
| 167 | |
| 168 | ### Tensor Parallelism (distributed/layers.rs) |
| 169 | |
| 170 | ColumnParallelLayer: shards weight along output dim. No all-reduce. |
| 171 | |
| 172 | RowParallelLayer: shards weight along input dim. All-reduce sum. |
| 173 | |
| 174 | KV head replication: compute_kv_shard() when world_size > num_kv_heads. |
| 175 | |
| 176 | ### Distributed Setup (distributed.rs) |
| 177 | |
| 178 | prepare_distributed_mapper(): world sizes, NCCL communicator via IPC or ring, spawn workers, load shards, multi-node via env vars. |
| 179 | |
| 180 | IPC: Unix socket, daemon flag, NCCL unique ID broadcast. |
| 181 | |
| 182 | ### MoE Expert Sharding |
| 183 | |
| 184 | PackedExperts/FusedExperts: stacked (single tensor) and per-expert formats. Only UnquantLinear and BlockwiseFP8Linear support gather_forward(). |
| 185 | |
| 186 | ### Applicability to MojoLlama |
| 187 | |
| 188 | 1. Layer-pipeline parallelism with per-layer device assignment |
| 189 | 2. Tensor parallelism via row/column sharding + all-reduce |
| 190 | 3. KV head replication for GQA models |
| 191 | 4. Comm abstraction wrapping MAX collectives |
| 192 | 5. Auto device mapping algorithm |
| 193 | 6. Pre-computed device-mapped masks |
| 194 | |
| 195 | --- |
| 196 | |
| 197 | ## Area 4: Hardware Auto-Tuning |
| 198 | |
| 199 | ### Architecture Overview |
| 200 | |
| 201 | AutoTuneRequest -> load config -> detect backend -> find GPUs -> for each ISQ candidate (estimate size via pack_factor, compute device layers, determine fit, calculate max context from remaining VRAM) -> pick best -> emit AutoTuneResult. |
| 202 | |
| 203 | ### Profiles |
| 204 | |
| 205 | TuneProfile: Quality (Q8_0..Q2K or AFQ equivalents on Metal), Balanced (Q6K..Q3K), Fast (Q4K..Q2K). |
| 206 | |
| 207 | ### Candidate Evaluation |
| 208 | |
| 209 | For each IsqType: pack_factor, layer_sizes_in_bytes(), get_device_layers_for_loader(), max context from remaining VRAM (kv_cache_elements_per_token * dtype_size * num_layers). |
| 210 | |
| 211 | Fit: Fits (all GPU), Hybrid (GPU+CPU), TooLarge. |
| 212 | |
| 213 | CLI: mistralrs tune outputs table, JSON (--json), config (--emit-config). |
| 214 | |
| 215 | ### Applicability to MojoLlama |
| 216 | |
| 217 | 1. Size estimation via pack_factor |
| 218 | 2. Layer-by-layer memory budgeting |
| 219 | 3. KV cache sizing via ModelConfigLike |
| 220 | 4. Profile-guided recommendation (Quality/Balanced/Fast) |
| 221 | 5. Hybrid CPU-GPU offloading |
| 222 | |
| 223 | --- |
| 224 | |
| 225 | ## Cross-Cutting Patterns |
| 226 | |
| 227 | 1. Trait-Based Abstraction Layers: QuantMethod, DeviceMapper, IsqModel, QuantizedSerde |
| 228 | 2. Thread-Local + Thread Pool Async (immediate ISQ config propagation) |
| 229 | 3. Channel-Based Decoupling (serving, engine, distributed workers) |
| 230 | 4. Builder Pattern for all major components |
| 231 | |
| 232 | ## File References |
| 233 | |
| 234 | Area 1 (Serving Layer): |
| 235 | - mistralrs-server-core/src/lib.rs |
| 236 | - mistralrs-server-core/src/mistralrs_server_router_builder.rs |
| 237 | - mistralrs-server-core/src/handler_core.rs |
| 238 | - mistralrs-server-core/src/streaming.rs |
| 239 | - mistralrs-server-core/src/chat_completion.rs |
| 240 | - mistralrs-server-core/src/completions.rs |
| 241 | - mistralrs-server-core/src/completion_core.rs |
| 242 | - mistralrs-server-core/src/types.rs |
| 243 | - mistralrs-server-core/src/openai.rs |
| 244 | |
| 245 | Area 2 (ISQ): |
| 246 | - mistralrs-core/src/pipeline/isq.rs |
| 247 | - mistralrs-quant/src/lib.rs |
| 248 | - mistralrs-quant/src/utils/isq.rs |
| 249 | - mistralrs-quant/src/gguf/mod.rs |
| 250 | - mistralrs-quant/src/gguf/cpu.rs |
| 251 | - mistralrs-quant/src/unquantized/mod.rs |
| 252 | |
| 253 | Area 3 (Multi-GPU): |
| 254 | - mistralrs-core/src/device_map.rs |
| 255 | - mistralrs-core/src/distributed.rs |
| 256 | - mistralrs-quant/src/distributed/layers.rs |
| 257 | - mistralrs-quant/src/distributed/mod.rs |
| 258 | - mistralrs-quant/src/distributed/socket.rs |
| 259 | |
| 260 | Area 4 (Tuning): |
| 261 | - mistralrs-core/src/tuning.rs |
| 262 | - mistralrs-cli/src/main.rs |