ruvllm 2.2.0

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Model Weight Initialization from GGUF
//!
//! This module provides the actual wiring from GGUF tensors to model layer weights
//! for inference. It handles:
//!
//! - Architecture-specific weight mapping (Llama, Mistral, Phi, Gemma, Qwen)
//! - Quantized weight handling for efficient inference
//! - Layer-by-layer weight initialization
//! - Integration with the serving engine
//!
//! ## Supported Architectures
//!
//! | Architecture | Status | Notes |
//! |--------------|--------|-------|
//! | Llama | Full | Llama 1/2/3, CodeLlama |
//! | Mistral | Full | Mistral 7B, Codestral |
//! | Phi | Full | Phi-1, Phi-2, Phi-3 |
//! | Gemma | Full | Gemma, Gemma-2 |
//! | Qwen | Full | Qwen, Qwen2 |
//!
//! ## Example
//!
//! ```rust,ignore
//! use ruvllm::gguf::{GgufLoader, LoadConfig, ModelInitializer};
//! use std::path::Path;
//!
//! // Load GGUF file
//! let loader = GgufLoader::new(Path::new("model.gguf"), LoadConfig::default())?;
//! let weights = loader.load_weights()?;
//!
//! // Initialize model from weights
//! let initializer = ModelInitializer::new(weights)?;
//! let model = initializer.build_model()?;
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use super::{
    GgufQuantType, LoadedTensor, LoadedWeights, ModelConfig, QuantizedTensor, TensorCategory,
};
use crate::backends::ModelArchitecture;
use crate::error::{Result, RuvLLMError};

// ============================================================================
// Model Layer Weights
// ============================================================================

/// Weights for a single transformer layer.
#[derive(Clone)]
pub struct LayerWeights {
    /// Layer index
    pub layer_idx: usize,
    /// Query projection (Wq)
    pub q_proj: WeightTensor,
    /// Key projection (Wk)
    pub k_proj: WeightTensor,
    /// Value projection (Wv)
    pub v_proj: WeightTensor,
    /// Output projection (Wo)
    pub o_proj: WeightTensor,
    /// Attention layer normalization
    pub attn_norm: Option<WeightTensor>,
    /// FFN gate projection (gate_proj / w1)
    pub gate_proj: WeightTensor,
    /// FFN up projection (up_proj / w3)
    pub up_proj: WeightTensor,
    /// FFN down projection (down_proj / w2)
    pub down_proj: WeightTensor,
    /// FFN layer normalization
    pub ffn_norm: Option<WeightTensor>,
}

/// Full model weights container.
#[derive(Clone)]
pub struct ModelWeights {
    /// Model architecture
    pub architecture: ModelArchitecture,
    /// Model configuration
    pub config: ModelConfig,
    /// Token embedding weights
    pub embed_tokens: WeightTensor,
    /// Per-layer weights
    pub layers: Vec<LayerWeights>,
    /// Final layer normalization
    pub final_norm: Option<WeightTensor>,
    /// Output/LM head weights (may be tied to embed_tokens)
    pub lm_head: Option<WeightTensor>,
    /// Total memory usage
    pub memory_bytes: usize,
}

/// A weight tensor that can be either quantized or F32.
#[derive(Clone)]
pub enum WeightTensor {
    /// Full precision F32 weights
    F32(Arc<Vec<f32>>, Vec<usize>),
    /// Quantized weights
    Quantized(Arc<QuantizedWeight>),
}

/// Quantized weight data for efficient inference.
#[derive(Clone)]
pub struct QuantizedWeight {
    /// Raw quantized data
    pub data: Vec<u8>,
    /// Quantization type
    pub quant_type: GgufQuantType,
    /// Tensor shape
    pub shape: Vec<usize>,
    /// Number of elements
    pub num_elements: usize,
}

impl WeightTensor {
    /// Get tensor shape.
    pub fn shape(&self) -> &[usize] {
        match self {
            WeightTensor::F32(_, shape) => shape,
            WeightTensor::Quantized(q) => &q.shape,
        }
    }

    /// Check if quantized.
    pub fn is_quantized(&self) -> bool {
        matches!(self, WeightTensor::Quantized(_))
    }

    /// Get F32 data (dequantizing if necessary).
    pub fn to_f32(&self) -> Result<Vec<f32>> {
        match self {
            WeightTensor::F32(data, _) => Ok((**data).clone()),
            WeightTensor::Quantized(q) => {
                super::quantization::dequantize_tensor(&q.data, q.quant_type, q.num_elements)
            }
        }
    }

    /// Get memory size in bytes.
    pub fn memory_bytes(&self) -> usize {
        match self {
            WeightTensor::F32(data, _) => data.len() * 4,
            WeightTensor::Quantized(q) => q.data.len(),
        }
    }

    /// Create from loaded tensor.
    pub fn from_loaded(tensor: &LoadedTensor) -> Result<Self> {
        if let Some(ref data) = tensor.data_f32 {
            Ok(WeightTensor::F32(
                Arc::new(data.clone()),
                tensor.shape.clone(),
            ))
        } else if let Some(ref quantized) = tensor.data_quantized {
            Ok(WeightTensor::Quantized(Arc::new(QuantizedWeight {
                data: quantized.data.clone(),
                quant_type: quantized.dtype,
                shape: quantized.shape.clone(),
                num_elements: quantized.num_elements,
            })))
        } else {
            Err(RuvLLMError::Model("Tensor has no data".to_string()))
        }
    }
}

// ============================================================================
// Model Initializer
// ============================================================================

/// Initializes model weights from loaded GGUF data.
///
/// This struct handles the mapping of GGUF tensor names to the appropriate
/// model layer weights based on the detected architecture.
pub struct ModelInitializer {
    /// Loaded weights
    weights: LoadedWeights,
    /// Architecture
    architecture: ModelArchitecture,
    /// Tensor name mappings for the architecture
    tensor_map: TensorNameMap,
}

/// Architecture-specific tensor name mappings.
struct TensorNameMap {
    /// Embedding tensor name pattern
    embed_tokens: &'static str,
    /// Query projection pattern
    q_proj: &'static str,
    /// Key projection pattern
    k_proj: &'static str,
    /// Value projection pattern
    v_proj: &'static str,
    /// Output projection pattern
    o_proj: &'static str,
    /// Attention norm pattern
    attn_norm: &'static str,
    /// Gate projection pattern
    gate_proj: &'static str,
    /// Up projection pattern
    up_proj: &'static str,
    /// Down projection pattern
    down_proj: &'static str,
    /// FFN norm pattern
    ffn_norm: &'static str,
    /// Final norm pattern
    final_norm: &'static str,
    /// LM head pattern
    lm_head: &'static str,
}

impl TensorNameMap {
    /// Get tensor name maps for Llama architecture.
    fn llama() -> Self {
        Self {
            embed_tokens: "model.embed_tokens.weight",
            q_proj: "model.layers.{}.self_attn.q_proj.weight",
            k_proj: "model.layers.{}.self_attn.k_proj.weight",
            v_proj: "model.layers.{}.self_attn.v_proj.weight",
            o_proj: "model.layers.{}.self_attn.o_proj.weight",
            attn_norm: "model.layers.{}.input_layernorm.weight",
            gate_proj: "model.layers.{}.mlp.gate_proj.weight",
            up_proj: "model.layers.{}.mlp.up_proj.weight",
            down_proj: "model.layers.{}.mlp.down_proj.weight",
            ffn_norm: "model.layers.{}.post_attention_layernorm.weight",
            final_norm: "model.norm.weight",
            lm_head: "lm_head.weight",
        }
    }

    /// Get tensor name maps for Mistral architecture.
    fn mistral() -> Self {
        // Mistral uses same naming as Llama
        Self::llama()
    }

    /// Get tensor name maps for Phi architecture.
    fn phi() -> Self {
        Self {
            embed_tokens: "transformer.embd.wte.weight",
            q_proj: "transformer.h.{}.mixer.Wqkv.weight", // Combined QKV
            k_proj: "transformer.h.{}.mixer.Wqkv.weight",
            v_proj: "transformer.h.{}.mixer.Wqkv.weight",
            o_proj: "transformer.h.{}.mixer.out_proj.weight",
            attn_norm: "transformer.h.{}.ln.weight",
            gate_proj: "transformer.h.{}.mlp.fc1.weight",
            up_proj: "transformer.h.{}.mlp.fc1.weight", // Combined with gate
            down_proj: "transformer.h.{}.mlp.fc2.weight",
            ffn_norm: "transformer.h.{}.ln.weight", // Same as attn_norm for Phi
            final_norm: "transformer.ln_f.weight",
            lm_head: "lm_head.weight",
        }
    }

    /// Get tensor name maps for Phi-3 architecture.
    fn phi3() -> Self {
        Self {
            embed_tokens: "model.embed_tokens.weight",
            q_proj: "model.layers.{}.self_attn.qkv_proj.weight",
            k_proj: "model.layers.{}.self_attn.qkv_proj.weight",
            v_proj: "model.layers.{}.self_attn.qkv_proj.weight",
            o_proj: "model.layers.{}.self_attn.o_proj.weight",
            attn_norm: "model.layers.{}.input_layernorm.weight",
            gate_proj: "model.layers.{}.mlp.gate_up_proj.weight",
            up_proj: "model.layers.{}.mlp.gate_up_proj.weight",
            down_proj: "model.layers.{}.mlp.down_proj.weight",
            ffn_norm: "model.layers.{}.post_attention_layernorm.weight",
            final_norm: "model.norm.weight",
            lm_head: "lm_head.weight",
        }
    }

    /// Get tensor name maps for Gemma architecture.
    fn gemma() -> Self {
        Self {
            embed_tokens: "model.embed_tokens.weight",
            q_proj: "model.layers.{}.self_attn.q_proj.weight",
            k_proj: "model.layers.{}.self_attn.k_proj.weight",
            v_proj: "model.layers.{}.self_attn.v_proj.weight",
            o_proj: "model.layers.{}.self_attn.o_proj.weight",
            attn_norm: "model.layers.{}.input_layernorm.weight",
            gate_proj: "model.layers.{}.mlp.gate_proj.weight",
            up_proj: "model.layers.{}.mlp.up_proj.weight",
            down_proj: "model.layers.{}.mlp.down_proj.weight",
            ffn_norm: "model.layers.{}.post_attention_layernorm.weight",
            final_norm: "model.norm.weight",
            lm_head: "model.embed_tokens.weight", // Tied embeddings
        }
    }

    /// Get tensor name maps for Qwen architecture.
    fn qwen() -> Self {
        Self {
            embed_tokens: "transformer.wte.weight",
            q_proj: "transformer.h.{}.attn.c_attn.weight",
            k_proj: "transformer.h.{}.attn.c_attn.weight",
            v_proj: "transformer.h.{}.attn.c_attn.weight",
            o_proj: "transformer.h.{}.attn.c_proj.weight",
            attn_norm: "transformer.h.{}.ln_1.weight",
            gate_proj: "transformer.h.{}.mlp.w1.weight",
            up_proj: "transformer.h.{}.mlp.w2.weight",
            down_proj: "transformer.h.{}.mlp.c_proj.weight",
            ffn_norm: "transformer.h.{}.ln_2.weight",
            final_norm: "transformer.ln_f.weight",
            lm_head: "lm_head.weight",
        }
    }

    /// Get tensor name with layer index substituted.
    fn layer_tensor(&self, pattern: &str, layer: usize) -> String {
        pattern.replace("{}", &layer.to_string())
    }
}

impl ModelInitializer {
    /// Create a new model initializer from loaded weights.
    pub fn new(weights: LoadedWeights) -> Result<Self> {
        let architecture = weights
            .architecture()
            .ok_or_else(|| RuvLLMError::Model("Cannot determine model architecture".to_string()))?;

        let tensor_map = match architecture {
            ModelArchitecture::Llama => TensorNameMap::llama(),
            ModelArchitecture::Mistral => TensorNameMap::mistral(),
            ModelArchitecture::Phi => TensorNameMap::phi(),
            ModelArchitecture::Phi3 => TensorNameMap::phi3(),
            ModelArchitecture::Gemma | ModelArchitecture::Gemma2 => TensorNameMap::gemma(),
            ModelArchitecture::Qwen => TensorNameMap::qwen(),
        };

        Ok(Self {
            weights,
            architecture,
            tensor_map,
        })
    }

    /// Build the model weights structure.
    pub fn build_weights(&self) -> Result<ModelWeights> {
        let config = self.weights.config().clone();
        let num_layers = config.layer_count.unwrap_or(0);

        // Load embedding
        let embed_tokens = self.load_tensor(&self.tensor_map.embed_tokens)?;

        // Load layers
        let mut layers = Vec::with_capacity(num_layers);
        for layer_idx in 0..num_layers {
            let layer = self.load_layer(layer_idx)?;
            layers.push(layer);
        }

        // Load final norm
        let final_norm = self.try_load_tensor(&self.tensor_map.final_norm);

        // Load LM head (may be tied to embeddings)
        let lm_head = self.try_load_tensor(&self.tensor_map.lm_head);

        // Calculate memory
        let mut memory_bytes = embed_tokens.memory_bytes();
        for layer in &layers {
            memory_bytes += layer.q_proj.memory_bytes();
            memory_bytes += layer.k_proj.memory_bytes();
            memory_bytes += layer.v_proj.memory_bytes();
            memory_bytes += layer.o_proj.memory_bytes();
            memory_bytes += layer.gate_proj.memory_bytes();
            memory_bytes += layer.up_proj.memory_bytes();
            memory_bytes += layer.down_proj.memory_bytes();
            if let Some(ref norm) = layer.attn_norm {
                memory_bytes += norm.memory_bytes();
            }
            if let Some(ref norm) = layer.ffn_norm {
                memory_bytes += norm.memory_bytes();
            }
        }
        if let Some(ref norm) = final_norm {
            memory_bytes += norm.memory_bytes();
        }
        if let Some(ref head) = lm_head {
            memory_bytes += head.memory_bytes();
        }

        Ok(ModelWeights {
            architecture: self.architecture,
            config,
            embed_tokens,
            layers,
            final_norm,
            lm_head,
            memory_bytes,
        })
    }

    /// Load a single layer's weights.
    fn load_layer(&self, layer_idx: usize) -> Result<LayerWeights> {
        let q_proj = self.load_layer_tensor(&self.tensor_map.q_proj, layer_idx)?;
        let k_proj = self.load_layer_tensor(&self.tensor_map.k_proj, layer_idx)?;
        let v_proj = self.load_layer_tensor(&self.tensor_map.v_proj, layer_idx)?;
        let o_proj = self.load_layer_tensor(&self.tensor_map.o_proj, layer_idx)?;
        let gate_proj = self.load_layer_tensor(&self.tensor_map.gate_proj, layer_idx)?;
        let up_proj = self.load_layer_tensor(&self.tensor_map.up_proj, layer_idx)?;
        let down_proj = self.load_layer_tensor(&self.tensor_map.down_proj, layer_idx)?;

        let attn_norm = self.try_load_layer_tensor(&self.tensor_map.attn_norm, layer_idx);
        let ffn_norm = self.try_load_layer_tensor(&self.tensor_map.ffn_norm, layer_idx);

        Ok(LayerWeights {
            layer_idx,
            q_proj,
            k_proj,
            v_proj,
            o_proj,
            attn_norm,
            gate_proj,
            up_proj,
            down_proj,
            ffn_norm,
        })
    }

    /// Load a tensor by name.
    fn load_tensor(&self, name: &str) -> Result<WeightTensor> {
        // Try to find the tensor with exact name first
        if let Some(tensor) = self.weights.get(name) {
            return WeightTensor::from_loaded(tensor);
        }

        // Try normalized name
        let normalized = self.normalize_name(name);
        if let Some(tensor) = self.weights.get(&normalized) {
            return WeightTensor::from_loaded(tensor);
        }

        // Try to find by fuzzy matching
        for tensor_name in self.weights.tensor_names() {
            if tensor_name.contains(&self.extract_key_part(name)) {
                if let Some(tensor) = self.weights.get(tensor_name) {
                    return WeightTensor::from_loaded(tensor);
                }
            }
        }

        Err(RuvLLMError::NotFound(format!("Tensor not found: {}", name)))
    }

    /// Try to load a tensor, returning None if not found.
    fn try_load_tensor(&self, name: &str) -> Option<WeightTensor> {
        self.load_tensor(name).ok()
    }

    /// Load a layer-specific tensor.
    fn load_layer_tensor(&self, pattern: &str, layer: usize) -> Result<WeightTensor> {
        let name = self.tensor_map.layer_tensor(pattern, layer);
        self.load_tensor(&name)
    }

    /// Try to load a layer-specific tensor.
    fn try_load_layer_tensor(&self, pattern: &str, layer: usize) -> Option<WeightTensor> {
        let name = self.tensor_map.layer_tensor(pattern, layer);
        self.try_load_tensor(&name)
    }

    /// Normalize tensor name for lookup.
    fn normalize_name(&self, name: &str) -> String {
        name.replace("model.", "")
            .replace("transformer.", "")
            .replace("h.", "layers.")
    }

    /// Extract the key identifying part of a tensor name.
    fn extract_key_part(&self, name: &str) -> String {
        // Extract the last meaningful part of the name
        name.split('.').last().unwrap_or(name).to_string()
    }
}

// ============================================================================
// Progress-Aware Model Building
// ============================================================================

/// Builder for constructing models with progress callbacks.
pub struct ProgressModelBuilder {
    weights: LoadedWeights,
    progress_callback: Option<Box<dyn Fn(&str, usize, usize) + Send + Sync>>,
}

impl ProgressModelBuilder {
    /// Create a new builder.
    pub fn new(weights: LoadedWeights) -> Self {
        Self {
            weights,
            progress_callback: None,
        }
    }

    /// Set progress callback.
    ///
    /// Callback receives: (stage_name, current_step, total_steps)
    pub fn with_progress<F>(mut self, callback: F) -> Self
    where
        F: Fn(&str, usize, usize) + Send + Sync + 'static,
    {
        self.progress_callback = Some(Box::new(callback));
        self
    }

    /// Build the model weights.
    pub fn build(self) -> Result<ModelWeights> {
        let initializer = ModelInitializer::new(self.weights)?;

        if let Some(ref callback) = self.progress_callback {
            callback("Initializing model", 0, 3);
        }

        let weights = initializer.build_weights()?;

        if let Some(ref callback) = self.progress_callback {
            callback("Model ready", 3, 3);
        }

        Ok(weights)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tensor_name_map_llama() {
        let map = TensorNameMap::llama();
        assert_eq!(
            map.layer_tensor(map.q_proj, 0),
            "model.layers.0.self_attn.q_proj.weight"
        );
        assert_eq!(
            map.layer_tensor(map.gate_proj, 5),
            "model.layers.5.mlp.gate_proj.weight"
        );
    }

    #[test]
    fn test_tensor_name_map_phi() {
        let map = TensorNameMap::phi();
        assert_eq!(
            map.layer_tensor(map.o_proj, 2),
            "transformer.h.2.mixer.out_proj.weight"
        );
    }

    #[test]
    fn test_weight_tensor_f32() {
        let data = vec![1.0f32, 2.0, 3.0, 4.0];
        let shape = vec![2, 2];
        let tensor = WeightTensor::F32(Arc::new(data.clone()), shape.clone());

        assert!(!tensor.is_quantized());
        assert_eq!(tensor.shape(), &[2, 2]);
        assert_eq!(tensor.memory_bytes(), 16); // 4 floats * 4 bytes
        assert_eq!(tensor.to_f32().unwrap(), data);
    }

    #[test]
    fn test_weight_tensor_quantized() {
        let data = vec![0u8; 18]; // One Q4_0 block
        let tensor = WeightTensor::Quantized(Arc::new(QuantizedWeight {
            data: data.clone(),
            quant_type: GgufQuantType::Q4_0,
            shape: vec![32],
            num_elements: 32,
        }));

        assert!(tensor.is_quantized());
        assert_eq!(tensor.shape(), &[32]);
        assert_eq!(tensor.memory_bytes(), 18);
    }
}