Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/mistral_rs_technical_notes.md # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / mistral_rs_technical_notes.md` 402 lines · 19792 bytes Raw Blame History Rendered 1 # mistral.rs Technical Research Notes for MojoLlama 2 3 ## 1. GGUF File Loading and Parsing 4 5 ### Directory: `mistralrs-core/src/gguf/` 6 7 **Architecture enum** (`mod.rs`): 8 - `GGUFArchitecture` maps string names (from `general.architecture` metadata key) to Rust enum variants: Llama, Mpt, Gptneox, Falcon, Qwen2, Phi3, etc. 9 - Uses `strum::EnumString` with case-insensitive matching via `from_value()`. 10 - Model loading pipeline checks this to determine which model struct to construct. 11 12 **Content struct** (`content.rs`): 13 - `Content<'a, R>` is the central GGUF file abstraction. It wraps: 14 - `contents: Vec` — parsed GGUF metadata + tensor info from Candle's `gguf_file` 15 - `readers: &'a mut [&'a mut R]` — paired file readers (supports sharding) 16 - `arch: GGUFArchitecture` — the detected architecture 17 - `all_metadata: HashMap` — merged metadata across all shards 18 - **Construction**: `Content::from_readers(readers)` calls `gguf_file::Content::read(reader)` on each reader, collects TensorInfos, validates shard consistency via `split.count` metadata. 19 - **Tensor access**: 20 - `tensor_info(name)` — searches across shards (no I/O) 21 - `tensor(name, device)` — reads tensor data from the correct shard via `tensor_info.read(reader, data_offset, device)`, returns a `QTensor` (Candle's quantized tensor type) 22 - `has_tensor(name)` — existence check across shards 23 - **Key insight for Mojo**: The GGUF format is fundamentally a key-value metadata store + a flat array of tensor data with offsets. A Mojo equivalent would memmap the file, parse the header once, and use pointer arithmetic + dtype-specific strides to read values. No need for a full parser — just a header reader. 24 25 **Known DTypes** (from Candle's `GgmlDType`): 26 F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, Q2K, Q3K, Q4K, Q5K, Q6K, Q8K. 27 28 **Tokenizer conversion** (`gguf_tokenizer.rs`): Converts GGUF tokenizer data → HuggingFace tokenizer JSON format. Not directly relevant to Mojo. 29 30 **Loading pipeline** (`pipeline/gguf.rs`): 31 - The GGUF pipeline loader reads `Content` metadata to populate model config (hidden_size, n_layers, vocab_size, etc.) 32 - Maps `GGUFArchitecture` -> specific `ModelParams` struct 33 - Builds individual layer tensors by name pattern: `model.layers.{i}.attention.wq.weight` 34 - Uses Candle's `VarBuilder` path system (`.pp("sub")`) to match PyTorch naming 35 36 ### Mojo Translation Patterns: 37 1. GGUF header parsing can be a simple struct-deserialize from bytes (magic + version + metadata_kv_count + tensor_count) 38 2. Tensor metadata is (name, shape, dtype, offset) — just read the header and build a lookup table 39 3. Sharding means multiple files — maintain a list of `(file_handle, tensor_infos)` pairs 40 4. The `general.architecture` string drives model dispatch — Mojo can use a match or dictionary 41 42 --- 43 44 ## 2. Candle Tensor Operations (ops.rs) 45 46 ### File: `mistralrs-core/src/ops.rs` (857 lines) 47 48 **Design pattern**: Extend `Tensor` with trait-based custom ops. 49 50 **Kernel dispatch architecture**: 51 1. **Trait pattern**: Define a trait (e.g., `TopKLastDimOp`), implement on `Tensor`, with `#[cfg(feature = "cuda")]` gates for CUDA fast paths. 52 2. **Fallback chain**: CUDA → CPU fallback (full sort, then narrow). 53 3. **CustomOp1 / CustomOp2 interface**: Candle's mechanism for user-defined operations that get JIT-compiled on CUDA. 54 55 **Example — TopK dispatch**: 56 ```rust 57 impl TopKLastDimOp for Tensor { 58 fn topk(&self, topk: usize) -> Result { 59 #[cfg(feature = "cuda")] 60 if self.device().is_cuda() { 61 return cuda_topk(self, topk); // Custom CUDA kernel 62 } 63 // Fallback: full sort then narrow 64 let (values, sorted_indices) = self.sort_last_dim(false)?; 65 // ... 66 } 67 } 68 ``` 69 70 **CUDA kernel integration pattern** (from `cuda_topk`): 71 ```rust 72 fn cuda_topk(input: &Tensor, k: usize) -> Result { 73 let input = input.contiguous()?; 74 let (storage, _layout) = input.storage_and_layout(); 75 let storage = match &*storage { Storage::Cuda(s) => s, _ => bail!() }; 76 let stream = dev.cuda_stream().cu_stream() as i64; 77 let (src_ptr, _src_guard) = match &storage.slice { 78 CudaStorageSlice::F32(inp) => inp.device_ptr(inp.stream()), 79 // ... 80 }; 81 // Allocate output on device 82 let values_dst = unsafe { dev.alloc::(out_elem_count) }?; 83 // Call the C function 84 unsafe { ffi::topk_f32(src_ptr, values_ptr, indices_ptr, nrows, ncols, k, stream); } 85 // Wrap device pointers back into Tensor 86 let storage = CudaStorage { slice: CudaStorageSlice::F32(values_dst), device: dev.clone() }; 87 Tensor::from((Storage::Cuda(storage), Shape::from_dims(&out_dims))) 88 } 89 ``` 90 91 **Key patterns**: 92 - `device_ptr()` gets the raw CUDA pointer from a `CudaSlice` 93 - `ffi::` module contains `extern "C"` declarations for CUDA kernel launchers 94 - Stream management via `dev.cuda_stream().cu_stream()` 95 - Dtype dispatch via match on `DType` enum (BF16, F16, F32, etc.) 96 - Two-phase: extract slice pointers → call kernel → wrap results back into tensors 97 98 **Fused Operations**: 99 - `cuda_topk_softmax` — single kernel that does topk + softmax in one pass (eliminates intermediate allocation) 100 - `mul_and_act` — fused gated activation for FFN (SiLU, GELU, ReLU) with dispatch to `mistralrs_quant::fused_glu` 101 102 **CustomOp1 for `ArgSort`**: 103 ```rust 104 impl candle_core::CustomOp1 for ArgSort { 105 fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout) -> Result<...> { panic!("not impl") } 106 fn cuda_fwd(&self, storage: &CudaStorage, layout: &Layout) -> Result<...> { 107 // Extract pointers from CudaStorage, call ffi::asort_asc_f32 etc. 108 } 109 } 110 // Used via: tensor.apply_op1_no_bwd(&ArgSort { ... }) 111 ``` 112 113 ### Mojo Translation: 114 1. Use `trait` pattern for ops extensions — exactly like Candle/Rust 115 2. In MAX/accelerator kernels, the dispatch is implicit (no `#[cfg]` needed — `@parameter` if/elif handles it) 116 3. The "get device pointers → call kernel → wrap result" pattern maps to MAX's `Buffer` API 117 4. Fused ops (topk+softmax, mul+act) are natural in Mojo with `fn` parameterization 118 119 --- 120 121 ## 3. Quantized MatMul Dispatch 122 123 ### File: `mistralrs-quant/src/gguf/mod.rs` (GGUF matmul wrapper) 124 ### File: `mistralrs-quant/src/gguf/fast_mmvq.rs` (small-batch CUDA path) 125 ### File: `mistralrs-quant/src/gguf/fast_mmq.rs` (large-batch CUDA path) 126 ### File: `mistralrs-quant/src/gguf/cuda.rs` (indexed MoE) 127 ### File: `mistralrs-quant/src/gguf/cpu.rs` (CPU fallback) 128 129 **Architecture**: `QuantMethod` trait is the central abstraction: 130 131 ```rust 132 pub trait QuantMethod: Send + Sync + Debug + QuantizedSerde { 133 fn forward_raw(&self, a: &Tensor) -> Result; // matmul 134 fn gather_forward_raw(&self, a: &Tensor, indices: &Tensor) -> Result; // MoE 135 fn quantized_act_type(&self) -> Option; // activation casting hint 136 fn get_qtensor(&self) -> Option<&QTensor>; // for direct kernel access 137 // ... 138 } 139 ``` 140 141 **GgufMatMul** (`mistralrs-quant/src/gguf/mod.rs`): 142 - Wraps `QMatMul` (Candle's quantized weight container) + optional bias 143 - `forward_raw` implements the **dispatch decision tree**: 144 1. Try fast path: `try_fast_forward()` (CUDA only) 145 2. Fallback: Cast to F32 → `self.w.forward()` (Candle's generic quant matmul) → cast back 146 147 **Fast path selection** (batch-size dependent): 148 ```rust 149 fn try_fast_forward(&self, a: &Tensor) -> Result> { 150 // Batch 1-8: use MMVQ (decode kernel - optimized for single tokens) 151 if (1..=MMVQ_MAX_BATCH).contains(&flat_batch) { 152 return fast_mmvq::plain(q, a); 153 } 154 // Batch > 8: use MMQ (prompt kernel - tiled matmul) 155 if flat_batch > MMVQ_MAX_BATCH { 156 return fast_mmq::plain(q, a); 157 } 158 } 159 ``` 160 161 **CUDA Kernel Naming Convention** (from FFI): 162 - `launch_mmvq_gguf_{Q4_0|Q4_1|Q5_0|Q5_1|Q8_0|Q2K|Q3K|Q4K|Q5K|Q6K}_{bf16|f16|f32}_plain` 163 - `launch_mmvq_gguf_quantize_q8_1_{bf16|f16|f32}` (quantize activation to Q8_1) 164 - `launch_mmq_gguf_{quant_type}` with fixup/SM params for tiled kernel 165 - `launch_indexed_moe_forward_{qtype}_q8_1` for MoE 166 167 ### How the fast MMVQ works (decode path): 168 169 1. **Two-phase approach**: 170 - Phase 1: Quantize activation to Q8_1 (using `launch_mmvq_gguf_quantize_q8_1_*`) 171 - Phase 2: Compute matmul with quantized weights using Q8_1 launchers 172 173 2. **Scratch buffer management**: Uses `OnceLock>>` for caching device-side buffers across calls. 174 175 3. **Output dtype matches input dtype** (BF16→BF16, F16→F16, F32→F32). 176 177 ### How the fast MMQ works (prefill path): 178 179 1. **More complex**: Needs device properties (SM count, compute capability, shared memory per block, warp size) 180 2. Also two-phase: quantize activations to `block_q8_1_mmq` format, then tiled matmul 181 3. Different `DsLayout` per quant type: D4, DS4, D2S6 (affects how intermediate sums are structured) 182 4. Uses "Stream-K" decomposition for load balancing across SMs 183 184 ### CPU Indexed MoE (`mistralrs-quant/src/gguf/cpu.rs`): 185 186 Simple fallback: dequantize all weights → create `UnquantLinear` → use its `gather_forward`. 187 188 ### CUDA Indexed MoE (`mistralrs-quant/src/gguf/cuda.rs`): 189 190 1. Quantize input to Q8_1 191 2. Dispatch to dtype-specific CUDA kernel (`launch_indexed_moe_forward_*`) 192 3. Each kernel handles the dequant-interleaved matmul on-the-fly 193 4. Supports Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, Q2K, Q3K, Q4K, Q5K, Q6K 194 195 ### Mojo Translation: 196 197 1. The `QuantMethod` trait maps directly to a Mojo trait (or struct with function pointer fields for dynamic dispatch) 198 2. The batch-size-aware dispatch (MMVQ vs MMQ) is critical — decode vs prefill need different kernels 199 3. The Q8_1 quantize-then-matmul pattern works well with Mojo's SIMD: 200 - Activations continuously quantized to Q8_1 201 - Weights stored in quantized block format 202 - Dot product dequantizes on the fly 203 4. Mojo's `@parameter` if/elif replaces Rust's `#[cfg(feature = "cuda")]` gates 204 5. The workspace allocation cache pattern (`OnceLock>>`) is a must for performance 205 206 --- 207 208 ## 4. K-Quant Dequantization Kernels 209 210 ### The GGUF K-Quant Family: Q2_K, Q3_K, Q4_K, Q5_K, Q6_K 211 212 These are "importance-tuned" block quantization formats from llama.cpp: 213 214 **Common structure (256-element blocks)**: 215 - `Q2_K`: 2-bit + scales (super-block + sub-block) 216 - `Q3_K`: 3-bit + scales 217 - `Q4_K`: 4-bit + scales 218 - `Q5_K`: 5-bit + scales 219 - `Q6_K`: 6-bit + scales (no sub-block scales) 220 221 **Key characteristics**: 222 - Block size = 256 (vs Q4_0/Q8_0 which are 32) 223 - Two-level hierarchy: super-block scale (f16 or f32) + sub-block scales (6-bit or 8-bit) 224 - The "K" prefix indicates importance-based bit allocation 225 - CUDA kernels for these have `Q2K`, `Q3K`, `Q4K`, `Q5K`, `Q6K` in their names 226 227 **FFI pattern** (from `ffi.rs`): 228 - Each K-quant type has its own kernel launcher (e.g., `launch_mmq_gguf_q2_k`) 229 - The kernels are in `*.cu` files compiled with nvcc, linked as `extern "C"` functions 230 - Signature varies: 231 - MMVQ: `(weight_ptr, scratch_ptr, out_ptr, k, nrows, stride_col_y, stride_col_dst, b_size, stream)` 232 - MMQ: `(fixup_ptr, weight_ptr, scratch_ptr, out_ptr, ncols_x, nrows_x, ncols_y, stride_row_x, stride_col_dst, cc, nsm, smpbo, warp_size, stream)` 233 234 ### What the CUDA Kernel Actually Does (dequant + compute): 235 236 Conceptually (from llama.cpp's kernel patterns): 237 ```cuda 238 // For each block of 256 weight elements: 239 float block_scale = super_block_scale[block_idx]; 240 // For each sub-block of 16 elements: 241 float sub_scale = sub_block_scales[sub_block_idx]; 242 // Dequantize elements: x[i] = (quant_value - midpoint) * sub_scale * block_scale 243 // Compute dot product with Q8_1 quantized activation 244 ``` 245 246 The key insight for Mojo: **Dequantization is interleaved with computation** — you never fully dequantize, you just load quant values, scales, and compute on the fly. This maps perfectly to Mojo's SIMD vectors. 247 248 ### Mojo Translation for K-Quant: 249 250 1. **Block layout**: Each K-quant type is a SIMD-friendly data structure 251 - Q8_1 activation: (16 int8 values + half-scale) × 2 252 - Q4_0 weight: (32 int4 values + half-scale) 253 - Q4_K weight: 256 values in 4-bit + super-scale + 8 sub-block scales (6-bit each) 254 255 2. **Dequantize-and-dot pattern**: 256 ```mojo 257 fn dot_product_k_quant[type: DType, simd_width: Int](weight_ptr, act_ptr) -> F32: 258 # Load block of quantized weights 259 # Load block of Q8_1 activations 260 # Dequantize weights on the fly using SIMD 261 # Compute fused multiply-add, accumulate in F32 262 # Return sum 263 ``` 264 265 3. **Block-size dimension**: 64-256 elements per block for K-quant (must handle in SIMD loops) 266 267 --- 268 269 ## 5. Paged Attention 270 271 ### Directory: `mistralrs-paged-attn/src/cuda/` 272 273 **Architecture**: 274 - Uses vLLM's attention template heavily adapted 275 - Supports V1 (single-iteration) and V2 (split across two kernel launches for softmax) paged attention 276 - Separate .cu files per dtype: `pagedattention_v1_{bf16,f16,f32}.cu`, same for v2 277 - FlashInfer-based MLA decode kernels for Multi-Latent Attention (deepseek-style) 278 279 **Kernel dispatch** (from `paged_attention.rs` backend): 280 ```rust 281 fn cuda_fwd_t(&self, q: &CudaStorage, q_l: &Layout) -> Result<(CudaStorage, Shape)> { 282 // Check cache dtype (F16=0, BF16=1, F32=2, FP8=3) 283 // Extract: key_cache, value_cache, block_tables, context_lens 284 // Dispatch to: paged_attention_v1_{f32|f16|bf16}(...) 285 // or: paged_attention_v2_{f32|f16|bf16}(...) 286 } 287 ``` 288 289 **Key structure** (from the `.cuh` template): 290 ```cpp 291 template 292 __global__ void paged_attention_v1_kernel(...) { 293 // Warp-level: each warp handles one head 294 // Q tile in registers 295 // K/V tiles from block tables (page table indirection) 296 // Online softmax (safe softmax with max tracking) 297 // Final output: each warp writes its head's results 298 } 299 ``` 300 301 **Online softmax** (vital pattern for Mojo): 302 - Keeps running max `m` and sum `s` 303 - For each new element: `m_new = max(m_old, s_val)`, renormalize previous, add new 304 - `m * s * v` update pattern 305 - This is the exact same pattern used in CPU flash attention in `cpu.rs` 306 307 **CPU Flash Attention** (`mistralrs-core/src/attention/backends/cpu.rs`): 308 - Pure Rust implementation with Rayon parallelism 309 - Uses `vec_dot_f32` — manually unrolled 4-element dot product 310 - Ping-pong prefetch via `_mm_prefetch` (x86) and `prfm` (ARM) 311 - Online softmax (same v1.0/v2.0 scalar kernel formulation) 312 - Tile-based with `TILE_KV = 16` 313 - Thread QoS hint on macOS via `pthread_set_qos_class_self_np` 314 315 ### Mojo Translation: 316 317 1. **Page table indirection**: KV cache access uses block table (logical → physical block mapping). In Mojo/MAX, this is a simple index indirection: `block_tables[batch_pos, head_pos]` gives the physical block number. 318 319 2. **Warp-level decomposition**: Each warp handles one attention head. In Mojo/Max, this maps to `@parameter` groups executing in SIMT fashion. 320 321 3. **Online softmax**: The scalar formulation (m/s/v) is the same. In Mojo, this composes cleanly with SIMD reductions. 322 323 4. **F32 accumulation**: All CUDA attention variants accumulate in F32 regardless of input dtype — matches Mojo's `simd[DType.f32]` pattern. 324 325 --- 326 327 ## 6. Relationship Between Candle's Kernel Approach and Mojo SIMD 328 329 ### Candle's Architecture: 330 331 1. **Trait-based tensor ops**: CustomOp1/CustomOp2 for extendable operations 332 2. **Device-specific implementations**: CPU (Rayon), CUDA (cudarc), Metal (objc2-metal) 333 3. **Staged dispatch**: 334 - Feature gates (`#[cfg(feature = "cuda")]`) 335 - Runtime checks (`if device.is_cuda()`) 336 - Fallback: trait method with default implementation 337 4. **CUDA integration**: `extern "C"` FFI → compiled .cu files → launches 338 339 ### Mojo Equivalent (from MojoLlama perspective): 340 341 1. **`@parameter` if/elif**: Replaces both compile-time feature gates AND runtime device checks — the compiler specializes for each path 342 2. **`simd[DType, width]`**: Replaces vector types and half precision handling 343 3. **`Buffer`/`NDBuffer`**: Replaces Candle's `Storage` + `Layout` + `Tensor` separation 344 4. **`@always_inline`**: Replaces C++ template inlining in CUDA kernels 345 5. **MAX accelerator**: Backend-agnostic — same Mojo code compiles to CPU SIMD, GPU kernels, or metal without separate .cu files 346 347 ### Key Learnings for MojoLlama: 348 349 | Candle/Rust Pattern | Mojo Equivalent | 350 |---|---| 351 | `CustomOp1` trait + `cpu_fwd`/`cuda_fwd` | `fn` with `@parameter` if/elif for backend dispatch | 352 | `Storage::Cuda(s)`, `Storage::Cpu(s)` | `Buffer` abstractions in MAX | 353 | `Tensor` + `Layout` + `Shape` | `NDBuffer[DType, shape]` | 354 | `ffi::launch_*` CUDA calls | MAX compiler handles accelerator kernel generation | 355 | `Q8_1` quantize for activation | Same pattern, but using `simd` ops | 356 | Workspace cache (OnceLock+HashMap) | `@staticmethod` with per-device cache | 357 | Batch-size dispatch (MMVQ vs MMQ) | `@parameter` branch on batch dimension at compile time | 358 | Online softmax (m/s/v) | Same scalar formulation, vectorized | 359 | GgmlDType enum for 20+ quant types | `DType` parameter with per-type block struct | 360 | `extern "C"` FFI for CUDA | No FFI — MAX compiles Mojo directly to PTX | 361 362 ### The Two-Phase Compute Pattern (Critically Important for Mojo): 363 364 The entire quantized matmul infrastructure relies on a **two-phase approach** that Mojo should replicate: 365 366 1. **Phase 1 (Quantize)**: Convert activation (F32/BF16/F16) → Q8_1 block format 367 - Each block of 32 floats → 32 int8 values + 2 half-precision scales 368 - This is trivially SIMD-friendly: find max, scale to [-127, 127] 369 370 2. **Phase 2 (Matmul)**: Block-level dot product between Q8_1 activation and quantized weight (any format) 371 - Weight types: Q4_0, Q4_1, Q5_0, Q5_1, Q8_0 (block_size=32) or Q2K..Q6K (block_size=256) 372 - Each block's scale(s) dequantized and multiplied with Q8_1 scales 373 - Dot product accumulates in F32 374 375 This means MojoLlama only needs: 376 - One Q8_1 quantize kernel (can be generic over input dtype) 377 - One dequantize-dot kernel per weight type (all Q8_1 input → various weight formats) 378 379 --- 380 381 ## Summary of Files Analyzed 382 383 | File | Lines | Key Content | 384 |------|-------|-------------| 385 | `mistralrs-core/src/gguf/mod.rs` | 44 | GGUFArchitecture enum + from_value | 386 | `mistralrs-core/src/gguf/content.rs` | 257 | Content struct, multi-file reader, tensor access | 387 | `mistralrs-core/src/ops.rs` | 857 | TopK, topk_softmax, ArgSort, SplitOp, mul_and_act | 388 | `mistralrs-core/src/layers.rs` | 3077 | LayerNorm, RmsNorm, QLinear, RotaryEmbedding, Mlp | 389 | `mistralrs-quant/src/lib.rs` | 1319 | QuantMethod trait, QuantMethodConfig, MatMul wrapper | 390 | `mistralrs-quant/src/gguf/mod.rs` | 556 | GgufMatMul, forward dispatch, serde, ISQ pipeline | 391 | `mistralrs-quant/src/gguf/fast_mmvq.rs` | 333 | MMVQ decode path: quantize + matmul launcher | 392 | `mistralrs-quant/src/gguf/fast_mmq.rs` | 385 | MMQ prefill path: tiled quantized matmul | 393 | `mistralrs-quant/src/gguf/cuda.rs` | 810 | Indexed MoE CUDA forward | 394 | `mistralrs-quant/src/gguf/cpu.rs` | 60 | CPU fallback (dequantize + matmul) | 395 | `mistralrs-quant/src/gguf/ffi.rs` | 1292 | All extern "C" CUDA kernel declarations | 396 | `mistralrs-core/src/cuda/ffi.rs` | — | CUDA topk, sort FFI declarations | 397 | `mistralrs-core/src/attention/mod.rs` | — | Sdpa, AttentionMask, dispatch, chunked_attention | 398 | `mistralrs-core/src/attention/backends/naive.rs` | — | Naive SDPA (softmax(QK^T)V) | 399 | `mistralrs-core/src/attention/backends/cpu.rs` | — | CPU flash attention (online softmax, Rayon, TILE_KV=16) | 400 | `mistralrs-paged-attn/src/cuda/backend/paged_attention.rs` | — | Paged attention CUDA backend dispatch | 401 | `mistralrs-paged-attn/src/cuda/attention/attention_generic.cuh` | — | vLLM-derived attention template, Vec<> types, dot product | 402 | `mistralrs-paged-attn/src/cuda/pagedattention.cuh` | — | Block sum, fast_tanh, warp reduction helpers |