abaddon 0.2.0-rc.1

Blazingly fast LLM inference engine - The Destroyer renders judgment
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Model architecture definitions and configurations.
//!
//! Supports multiple transformer architectures with a unified interface.

use std::path::Path;

use super::InferenceError;

/// Supported model architectures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModelArch {
    /// Llama 1/2/3 and CodeLlama.
    Llama,
    /// Mistral and Mixtral (MoE).
    Mistral,
    /// Qwen and Qwen2.
    Qwen,
    /// Microsoft Phi-2/3.
    Phi,
    /// Google Gemma.
    Gemma,
    /// Falcon.
    Falcon,
    /// GPT-NeoX / Pythia.
    GptNeoX,
    /// StarCoder.
    StarCoder,
}

impl ModelArch {
    /// Detect architecture from config.json or model files.
    pub fn detect(model_dir: &Path) -> Result<Self, InferenceError> {
        let config_path = model_dir.join("config.json");

        if config_path.exists() {
            let config_str = std::fs::read_to_string(&config_path)
                .map_err(|e| InferenceError::ModelLoad(e.to_string()))?;

            return Self::from_config_json(&config_str);
        }

        // Try to detect from file naming patterns
        let dir_name = model_dir
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_lowercase();

        if dir_name.contains("llama") || dir_name.contains("codellama") {
            Ok(ModelArch::Llama)
        } else if dir_name.contains("mistral") || dir_name.contains("mixtral") {
            Ok(ModelArch::Mistral)
        } else if dir_name.contains("qwen") {
            Ok(ModelArch::Qwen)
        } else if dir_name.contains("phi") {
            Ok(ModelArch::Phi)
        } else if dir_name.contains("gemma") {
            Ok(ModelArch::Gemma)
        } else {
            // Default to Llama-style (most common)
            Ok(ModelArch::Llama)
        }
    }

    /// Parse architecture from HuggingFace config.json.
    pub fn from_config_json(config: &str) -> Result<Self, InferenceError> {
        let json: serde_json::Value = serde_json::from_str(config)
            .map_err(|e| InferenceError::ModelLoad(format!("Invalid config.json: {}", e)))?;

        // Check architectures field
        if let Some(archs) = json.get("architectures").and_then(|v| v.as_array()) {
            for arch in archs {
                if let Some(arch_str) = arch.as_str() {
                    let arch_lower = arch_str.to_lowercase();

                    if arch_lower.contains("llama") {
                        return Ok(ModelArch::Llama);
                    } else if arch_lower.contains("mistral") || arch_lower.contains("mixtral") {
                        return Ok(ModelArch::Mistral);
                    } else if arch_lower.contains("qwen") {
                        return Ok(ModelArch::Qwen);
                    } else if arch_lower.contains("phi") {
                        return Ok(ModelArch::Phi);
                    } else if arch_lower.contains("gemma") {
                        return Ok(ModelArch::Gemma);
                    } else if arch_lower.contains("falcon") {
                        return Ok(ModelArch::Falcon);
                    } else if arch_lower.contains("neox") || arch_lower.contains("pythia") {
                        return Ok(ModelArch::GptNeoX);
                    } else if arch_lower.contains("starcoder") {
                        return Ok(ModelArch::StarCoder);
                    }
                }
            }
        }

        // Check model_type field
        if let Some(model_type) = json.get("model_type").and_then(|v| v.as_str()) {
            let model_lower = model_type.to_lowercase();

            if model_lower == "llama" {
                return Ok(ModelArch::Llama);
            } else if model_lower == "mistral" {
                return Ok(ModelArch::Mistral);
            } else if model_lower == "qwen" || model_lower == "qwen2" {
                return Ok(ModelArch::Qwen);
            } else if model_lower == "phi" || model_lower == "phi3" {
                return Ok(ModelArch::Phi);
            } else if model_lower == "gemma" || model_lower == "gemma2" {
                return Ok(ModelArch::Gemma);
            }
        }

        // Default to Llama
        Ok(ModelArch::Llama)
    }

    /// Get default weight name mappings for this architecture.
    pub fn weight_map(&self) -> WeightNameMap {
        match self {
            ModelArch::Llama | ModelArch::Mistral | ModelArch::Qwen => WeightNameMap::llama_style(),
            ModelArch::Phi => WeightNameMap::phi_style(),
            ModelArch::Gemma => WeightNameMap::gemma_style(),
            ModelArch::Falcon => WeightNameMap::falcon_style(),
            ModelArch::GptNeoX | ModelArch::StarCoder => WeightNameMap::gpt_neox_style(),
        }
    }
}

/// Model configuration parameters.
#[derive(Debug, Clone)]
pub struct ModelConfig {
    /// Model architecture.
    pub arch: ModelArch,

    /// Hidden dimension size.
    pub hidden_size: usize,

    /// Intermediate (MLP) dimension size.
    pub intermediate_size: usize,

    /// Number of transformer layers.
    pub num_layers: usize,

    /// Number of attention heads.
    pub num_attention_heads: usize,

    /// Number of key-value heads (for GQA/MQA).
    pub num_kv_heads: usize,

    /// Dimension per attention head.
    pub head_dim: usize,

    /// Vocabulary size.
    pub vocab_size: usize,

    /// Maximum sequence length.
    pub max_seq_len: usize,

    /// RMS norm epsilon.
    pub rms_norm_eps: f32,

    /// RoPE theta (base frequency).
    pub rope_theta: f32,

    /// RoPE scaling factor (for extended context).
    pub rope_scaling: Option<RopeScaling>,

    /// Whether to use bias in attention.
    pub attention_bias: bool,

    /// Whether to use bias in MLP.
    pub mlp_bias: bool,

    /// Activation function for MLP.
    pub hidden_act: Activation,

    /// Whether embeddings are tied to LM head.
    pub tie_word_embeddings: bool,

    /// Sliding window attention size (Mistral/Mixtral).
    /// If Some, attention is limited to this window size.
    pub sliding_window: Option<usize>,

    /// BOS token ID.
    pub bos_token_id: u32,

    /// EOS token ID.
    pub eos_token_id: u32,

    /// Padding token ID.
    pub pad_token_id: Option<u32>,
}

impl ModelConfig {
    /// Load config from HuggingFace config.json.
    pub fn from_json(config: &str, arch: ModelArch) -> Result<Self, InferenceError> {
        let json: serde_json::Value = serde_json::from_str(config)
            .map_err(|e| InferenceError::ModelLoad(format!("Invalid config: {}", e)))?;

        let get_usize = |key: &str, default: usize| -> usize {
            json.get(key)
                .and_then(|v| v.as_u64())
                .map(|v| v as usize)
                .unwrap_or(default)
        };

        let get_f32 = |key: &str, default: f32| -> f32 {
            json.get(key)
                .and_then(|v| v.as_f64())
                .map(|v| v as f32)
                .unwrap_or(default)
        };

        let get_bool = |key: &str, default: bool| -> bool {
            json.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
        };

        let hidden_size = get_usize("hidden_size", 4096);
        let num_attention_heads = get_usize("num_attention_heads", 32);

        // Handle different naming conventions
        let num_kv_heads = json
            .get("num_key_value_heads")
            .or_else(|| json.get("num_kv_heads"))
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or(num_attention_heads);

        let head_dim = json
            .get("head_dim")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or(hidden_size / num_attention_heads);

        let hidden_act = json
            .get("hidden_act")
            .and_then(|v| v.as_str())
            .map(Activation::from_str)
            .unwrap_or(Activation::SiLU);

        let rope_scaling = json.get("rope_scaling").and_then(|v| {
            let scale_type = v.get("type").and_then(|t| t.as_str())?;
            let factor = v.get("factor").and_then(|f| f.as_f64())? as f32;
            Some(RopeScaling::from_type(scale_type, factor))
        });

        // Sliding window attention (Mistral/Mixtral feature)
        let sliding_window = json
            .get("sliding_window")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize);

        Ok(Self {
            arch,
            hidden_size,
            intermediate_size: get_usize("intermediate_size", hidden_size * 4),
            num_layers: get_usize("num_hidden_layers", 32),
            num_attention_heads,
            num_kv_heads,
            head_dim,
            vocab_size: get_usize("vocab_size", 32000),
            max_seq_len: get_usize("max_position_embeddings", 4096),
            rms_norm_eps: get_f32("rms_norm_eps", 1e-6),
            rope_theta: get_f32("rope_theta", 10000.0),
            rope_scaling,
            attention_bias: get_bool("attention_bias", false),
            mlp_bias: get_bool("mlp_bias", false),
            hidden_act,
            tie_word_embeddings: get_bool("tie_word_embeddings", false),
            sliding_window,
            bos_token_id: get_usize("bos_token_id", 1) as u32,
            eos_token_id: get_usize("eos_token_id", 2) as u32,
            pad_token_id: json
                .get("pad_token_id")
                .and_then(|v| v.as_u64())
                .map(|v| v as u32),
        })
    }

    /// Create config with default values for an architecture.
    pub fn default_for_arch(arch: ModelArch, hidden_size: usize, num_layers: usize) -> Self {
        let num_attention_heads = match hidden_size {
            h if h <= 1024 => 8,
            h if h <= 2048 => 16,
            h if h <= 4096 => 32,
            _ => 64,
        };

        // Mistral uses sliding window attention by default
        let sliding_window = match arch {
            ModelArch::Mistral => Some(4096),
            _ => None,
        };

        Self {
            arch,
            hidden_size,
            intermediate_size: hidden_size * 4,
            num_layers,
            num_attention_heads,
            num_kv_heads: num_attention_heads,
            head_dim: hidden_size / num_attention_heads,
            vocab_size: 32000,
            max_seq_len: 4096,
            rms_norm_eps: 1e-6,
            rope_theta: 10000.0,
            rope_scaling: None,
            attention_bias: false,
            mlp_bias: false,
            hidden_act: Activation::SiLU,
            tie_word_embeddings: false,
            sliding_window,
            bos_token_id: 1,
            eos_token_id: 2,
            pad_token_id: None,
        }
    }

    /// Total number of parameters (approximate).
    pub fn num_params(&self) -> usize {
        let embed_params = self.vocab_size * self.hidden_size;

        let attn_params = self.num_layers * (self.hidden_size * self.hidden_size * 4); // Q, K, V, O

        let mlp_params = self.num_layers * (self.hidden_size * self.intermediate_size * 3); // gate, up, down

        let norm_params = self.num_layers * self.hidden_size * 2 + self.hidden_size;

        let lm_head = if self.tie_word_embeddings {
            0
        } else {
            self.vocab_size * self.hidden_size
        };

        embed_params + attn_params + mlp_params + norm_params + lm_head
    }
}

/// RoPE scaling configuration.
#[derive(Debug, Clone, Copy)]
pub enum RopeScaling {
    /// Linear scaling.
    Linear(f32),
    /// Dynamic NTK scaling.
    Dynamic(f32),
    /// YaRN scaling.
    Yarn {
        /// Scaling factor.
        factor: f32,
        /// Original maximum sequence length before scaling.
        original_max_len: usize,
    },
}

impl RopeScaling {
    fn from_type(scale_type: &str, factor: f32) -> Self {
        match scale_type.to_lowercase().as_str() {
            "linear" => RopeScaling::Linear(factor),
            "dynamic" => RopeScaling::Dynamic(factor),
            "yarn" => RopeScaling::Yarn {
                factor,
                original_max_len: 4096,
            },
            _ => RopeScaling::Linear(factor),
        }
    }
}

/// Activation functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Activation {
    /// Sigmoid Linear Unit (Llama, Mistral).
    SiLU,
    /// Gaussian Error Linear Unit.
    GELU,
    /// Approximate GELU (GPT-2 style).
    GELUApprox,
    /// ReLU.
    ReLU,
    /// Squared ReLU (Phi).
    ReLU2,
}

impl Activation {
    fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "silu" | "swish" => Activation::SiLU,
            "gelu" => Activation::GELU,
            "gelu_new" | "gelu_fast" | "gelu_pytorch_tanh" => Activation::GELUApprox,
            "relu" => Activation::ReLU,
            "relu2" | "squared_relu" => Activation::ReLU2,
            _ => Activation::SiLU,
        }
    }
}

/// Mapping of weight names from HuggingFace format to our internal names.
#[derive(Debug, Clone)]
pub struct WeightNameMap {
    /// Pattern mappings: (hf_pattern, internal_name).
    mappings: Vec<(String, String)>,
}

impl WeightNameMap {
    /// Create Llama-style weight mappings.
    pub fn llama_style() -> Self {
        Self {
            mappings: vec![
                // Embeddings
                ("model.embed_tokens.weight".into(), "embed_tokens".into()),
                ("lm_head.weight".into(), "lm_head".into()),
                ("model.norm.weight".into(), "final_norm".into()),
                // Per-layer patterns (use {layer} as placeholder)
                (
                    "model.layers.{layer}.input_layernorm.weight".into(),
                    "layers.{layer}.input_norm".into(),
                ),
                (
                    "model.layers.{layer}.post_attention_layernorm.weight".into(),
                    "layers.{layer}.post_attn_norm".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.q_proj.weight".into(),
                    "layers.{layer}.q_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.k_proj.weight".into(),
                    "layers.{layer}.k_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.v_proj.weight".into(),
                    "layers.{layer}.v_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.o_proj.weight".into(),
                    "layers.{layer}.o_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.gate_proj.weight".into(),
                    "layers.{layer}.gate_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.up_proj.weight".into(),
                    "layers.{layer}.up_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.down_proj.weight".into(),
                    "layers.{layer}.down_proj".into(),
                ),
            ],
        }
    }

    /// Create Phi-style weight mappings.
    pub fn phi_style() -> Self {
        Self {
            mappings: vec![
                ("model.embed_tokens.weight".into(), "embed_tokens".into()),
                ("lm_head.weight".into(), "lm_head".into()),
                ("model.final_layernorm.weight".into(), "final_norm".into()),
                (
                    "model.layers.{layer}.input_layernorm.weight".into(),
                    "layers.{layer}.input_norm".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.q_proj.weight".into(),
                    "layers.{layer}.q_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.k_proj.weight".into(),
                    "layers.{layer}.k_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.v_proj.weight".into(),
                    "layers.{layer}.v_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.dense.weight".into(),
                    "layers.{layer}.o_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.fc1.weight".into(),
                    "layers.{layer}.gate_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.fc2.weight".into(),
                    "layers.{layer}.down_proj".into(),
                ),
            ],
        }
    }

    /// Create Gemma-style weight mappings.
    pub fn gemma_style() -> Self {
        Self {
            mappings: vec![
                ("model.embed_tokens.weight".into(), "embed_tokens".into()),
                ("model.norm.weight".into(), "final_norm".into()),
                (
                    "model.layers.{layer}.input_layernorm.weight".into(),
                    "layers.{layer}.input_norm".into(),
                ),
                (
                    "model.layers.{layer}.post_attention_layernorm.weight".into(),
                    "layers.{layer}.post_attn_norm".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.q_proj.weight".into(),
                    "layers.{layer}.q_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.k_proj.weight".into(),
                    "layers.{layer}.k_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.v_proj.weight".into(),
                    "layers.{layer}.v_proj".into(),
                ),
                (
                    "model.layers.{layer}.self_attn.o_proj.weight".into(),
                    "layers.{layer}.o_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.gate_proj.weight".into(),
                    "layers.{layer}.gate_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.up_proj.weight".into(),
                    "layers.{layer}.up_proj".into(),
                ),
                (
                    "model.layers.{layer}.mlp.down_proj.weight".into(),
                    "layers.{layer}.down_proj".into(),
                ),
            ],
        }
    }

    /// Create Falcon-style weight mappings.
    pub fn falcon_style() -> Self {
        Self {
            mappings: vec![
                (
                    "transformer.word_embeddings.weight".into(),
                    "embed_tokens".into(),
                ),
                ("lm_head.weight".into(), "lm_head".into()),
                ("transformer.ln_f.weight".into(), "final_norm".into()),
                (
                    "transformer.h.{layer}.input_layernorm.weight".into(),
                    "layers.{layer}.input_norm".into(),
                ),
                (
                    "transformer.h.{layer}.self_attention.query_key_value.weight".into(),
                    "layers.{layer}.qkv_proj".into(),
                ),
                (
                    "transformer.h.{layer}.self_attention.dense.weight".into(),
                    "layers.{layer}.o_proj".into(),
                ),
                (
                    "transformer.h.{layer}.mlp.dense_h_to_4h.weight".into(),
                    "layers.{layer}.gate_proj".into(),
                ),
                (
                    "transformer.h.{layer}.mlp.dense_4h_to_h.weight".into(),
                    "layers.{layer}.down_proj".into(),
                ),
            ],
        }
    }

    /// Create GPT-NeoX style weight mappings.
    pub fn gpt_neox_style() -> Self {
        Self {
            mappings: vec![
                ("gpt_neox.embed_in.weight".into(), "embed_tokens".into()),
                ("embed_out.weight".into(), "lm_head".into()),
                (
                    "gpt_neox.final_layer_norm.weight".into(),
                    "final_norm".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.input_layernorm.weight".into(),
                    "layers.{layer}.input_norm".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.post_attention_layernorm.weight".into(),
                    "layers.{layer}.post_attn_norm".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.attention.query_key_value.weight".into(),
                    "layers.{layer}.qkv_proj".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.attention.dense.weight".into(),
                    "layers.{layer}.o_proj".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.mlp.dense_h_to_4h.weight".into(),
                    "layers.{layer}.gate_proj".into(),
                ),
                (
                    "gpt_neox.layers.{layer}.mlp.dense_4h_to_h.weight".into(),
                    "layers.{layer}.down_proj".into(),
                ),
            ],
        }
    }

    /// Map a HuggingFace weight name to internal name.
    pub fn map_name(&self, hf_name: &str) -> Option<String> {
        // Try to extract layer number if present
        let layer_num = extract_layer_number(hf_name);

        for (pattern, internal) in &self.mappings {
            if let Some(layer) = layer_num {
                let expanded_pattern = pattern.replace("{layer}", &layer.to_string());
                if hf_name == expanded_pattern {
                    return Some(internal.replace("{layer}", &layer.to_string()));
                }
            } else if !pattern.contains("{layer}") && hf_name == pattern {
                return Some(internal.clone());
            }
        }

        None
    }
}

/// Extract layer number from weight name like "model.layers.5.self_attn.q_proj.weight".
fn extract_layer_number(name: &str) -> Option<usize> {
    let parts: Vec<&str> = name.split('.').collect();
    for (i, part) in parts.iter().enumerate() {
        if *part == "layers" || *part == "h" {
            if let Some(num_str) = parts.get(i + 1) {
                if let Ok(num) = num_str.parse::<usize>() {
                    return Some(num);
                }
            }
        }
    }
    None
}

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

    #[test]
    fn test_weight_name_mapping() {
        let map = WeightNameMap::llama_style();

        assert_eq!(
            map.map_name("model.embed_tokens.weight"),
            Some("embed_tokens".to_string())
        );

        assert_eq!(
            map.map_name("model.layers.5.self_attn.q_proj.weight"),
            Some("layers.5.q_proj".to_string())
        );

        assert_eq!(
            map.map_name("model.layers.31.mlp.down_proj.weight"),
            Some("layers.31.down_proj".to_string())
        );
    }

    #[test]
    fn test_extract_layer_number() {
        assert_eq!(
            extract_layer_number("model.layers.5.self_attn.q_proj.weight"),
            Some(5)
        );
        assert_eq!(
            extract_layer_number("transformer.h.12.mlp.weight"),
            Some(12)
        );
        assert_eq!(extract_layer_number("model.embed_tokens.weight"), None);
    }
}