model-rs 0.1.0

A Rust CLI tool for downloading HuggingFace models and running local LLM inference
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
//! MLX backend for Apple Silicon GPU acceleration
//!
//! This module provides support for running LLM inference using Apple's MLX
//! framework, which offers optimized performance on Apple Silicon via unified
//! memory and Metal GPU acceleration.
//!
//! Currently supports Llama-family models with safetensors weights.
//! Enable with `--features mlx` (CPU+Accelerate) or `--features mlx-metal` (Metal GPU).

use crate::error::{ModelError, Result};
use crate::local::LocalModelConfig;
use std::path::Path;
use tracing::info;

#[cfg(feature = "mlx")]
use mlx_rs::{transforms::eval, Array};

#[cfg(feature = "mlx")]
mod inner {
    use mlx_rs::{
        error::Exception,
        macros::{ModuleParameters, Quantizable},
        module::{Module, ModuleParametersExt},
        nn,
        quantization::MaybeQuantized,
        Array,
    };
    use serde::Deserialize;
    use std::collections::HashMap;

    #[derive(Debug, Clone, Deserialize)]
    pub struct ModelArgs {
        pub model_type: String,
        pub hidden_size: i32,
        pub num_hidden_layers: i32,
        pub intermediate_size: i32,
        pub num_attention_heads: i32,
        pub rms_norm_eps: f32,
        pub vocab_size: i32,
        pub num_key_value_heads: i32,
        pub max_position_embeddings: i32,
        pub rope_theta: f32,
        #[serde(default)]
        pub head_dim: i32,
        #[serde(default = "default_true")]
        pub tie_word_embeddings: bool,
        #[serde(default)]
        pub attention_bias: bool,
        #[serde(default)]
        pub mlp_bias: bool,
        pub rope_scaling: Option<HashMap<String, serde_json::Value>>,
    }

    fn default_true() -> bool {
        true
    }

    #[derive(Debug, Clone, ModuleParameters, Quantizable)]
    pub struct Attention {
        pub n_heads: i32,
        pub n_kv_heads: i32,
        pub head_dim: i32,
        pub scale: f32,

        #[quantizable]
        #[param]
        pub q_proj: MaybeQuantized<nn::Linear>,
        #[quantizable]
        #[param]
        pub k_proj: MaybeQuantized<nn::Linear>,
        #[quantizable]
        #[param]
        pub v_proj: MaybeQuantized<nn::Linear>,
        #[quantizable]
        #[param]
        pub o_proj: MaybeQuantized<nn::Linear>,
        #[param]
        pub rope: nn::Rope,
    }

    impl Attention {
        pub fn new(args: &ModelArgs) -> Result<Self, Exception> {
            let dim = args.hidden_size;
            let n_heads = args.num_attention_heads;
            let n_kv_heads = args.num_key_value_heads;
            let head_dim = if args.head_dim > 0 {
                args.head_dim
            } else {
                dim / n_heads
            };
            let scale = 1.0 / (head_dim as f32).sqrt();

            let q_proj = nn::Linear::new(dim, n_heads * head_dim, args.attention_bias)?;
            let k_proj = nn::Linear::new(dim, n_kv_heads * head_dim, args.attention_bias)?;
            let v_proj = nn::Linear::new(dim, n_kv_heads * head_dim, args.attention_bias)?;
            let o_proj = nn::Linear::new(n_heads * head_dim, dim, args.attention_bias)?;

            let rope = nn::Rope::new(head_dim, false, args.rope_theta as f64)?;

            Ok(Self {
                n_heads,
                n_kv_heads,
                head_dim,
                scale,
                q_proj: MaybeQuantized::Original(q_proj),
                k_proj: MaybeQuantized::Original(k_proj),
                v_proj: MaybeQuantized::Original(v_proj),
                o_proj: MaybeQuantized::Original(o_proj),
                rope,
            })
        }
    }

    pub trait MlxKvCache {
        fn offset(&self) -> i32;
        fn update_and_fetch(
            &mut self,
            keys: Array,
            values: Array,
        ) -> Result<(Array, Array), Exception>;
    }

    pub struct ConcatCache {
        keys: Option<Array>,
        values: Option<Array>,
        offset: i32,
    }

    impl Default for ConcatCache {
        fn default() -> Self {
            Self {
                keys: None,
                values: None,
                offset: 0,
            }
        }
    }

    impl MlxKvCache for ConcatCache {
        fn offset(&self) -> i32 {
            self.offset
        }

        fn update_and_fetch(
            &mut self,
            keys: Array,
            values: Array,
        ) -> Result<(Array, Array), Exception> {
            self.offset += keys.shape()[2] as i32;
            let (nk, nv) = match (&self.keys, &self.values) {
                (Some(pk), Some(pv)) => {
                    let k = mlx_rs::ops::concat(&[pk, &keys], 2)?;
                    let v = mlx_rs::ops::concat(&[pv, &values], 2)?;
                    (k, v)
                }
                _ => (keys.clone(), values.clone()),
            };
            self.keys = Some(nk.clone());
            self.values = Some(nv.clone());
            Ok((nk, nv))
        }
    }

    pub fn sdpa(
        queries: &Array,
        keys: &Array,
        values: &Array,
        scale: f32,
    ) -> Result<Array, Exception> {
        let scores = queries
            .matmul(&keys.transpose_axes(&[0, 1, 3, 2])?)?
            .multiply(&mlx_rs::array!(scale))?;
        let weights = mlx_rs::nn::softmax(&scores, -1, None)?;
        weights.matmul(values)
    }

    impl Attention {
        pub fn forward_with_cache(
            &mut self,
            x: &Array,
            mask: Option<&Array>,
            cache: Option<&mut dyn MlxKvCache>,
        ) -> Result<Array, Exception> {
            use mlx_rs::ops::indexing::NewAxis;
            let shape = x.shape();
            let b = shape[0];
            let l = shape[1];

            let mut q = self
                .q_proj
                .forward(x)?
                .reshape(&[b, l, self.n_heads, -1])?
                .transpose_axes(&[0, 2, 1, 3])?;
            let mut k = self
                .k_proj
                .forward(x)?
                .reshape(&[b, l, self.n_kv_heads, -1])?
                .transpose_axes(&[0, 2, 1, 3])?;
            let mut v = self
                .v_proj
                .forward(x)?
                .reshape(&[b, l, self.n_kv_heads, -1])?
                .transpose_axes(&[0, 2, 1, 3])?;

            if let Some(cache) = cache {
                let qi = nn::RopeInput::new_with_offset(&q, cache.offset());
                q = self.rope.forward(qi)?;
                let ki = nn::RopeInput::new_with_offset(&k, cache.offset());
                k = self.rope.forward(ki)?;
                (k, v) = cache.update_and_fetch(k, v)?;
            } else {
                q = self.rope.forward(nn::RopeInput::new(&q))?;
                k = self.rope.forward(nn::RopeInput::new(&k))?;
            }

            let mut output = sdpa(&q, &k, &v, self.scale)?;
            if let Some(m) = mask {
                output = output.add(m)?;
            }
            output = output.transpose_axes(&[0, 2, 1, 3])?.reshape(&[b, l, -1])?;
            self.o_proj.forward(&output)
        }
    }

    #[derive(Debug, Clone, ModuleParameters, Quantizable)]
    pub struct Mlp {
        #[quantizable]
        #[param]
        pub gate_proj: MaybeQuantized<nn::Linear>,
        #[quantizable]
        #[param]
        pub down_proj: MaybeQuantized<nn::Linear>,
        #[quantizable]
        #[param]
        pub up_proj: MaybeQuantized<nn::Linear>,
    }

    impl Mlp {
        pub fn new(dim: i32, hidden_dim: i32, bias: bool) -> Result<Self, Exception> {
            Ok(Self {
                gate_proj: MaybeQuantized::Original(nn::Linear::new(dim, hidden_dim, bias)?),
                down_proj: MaybeQuantized::Original(nn::Linear::new(hidden_dim, dim, bias)?),
                up_proj: MaybeQuantized::Original(nn::Linear::new(dim, hidden_dim, bias)?),
            })
        }

        pub fn forward(&mut self, x: &Array) -> Result<Array, Exception> {
            let gate = self.gate_proj.forward(x)?;
            let up = self.up_proj.forward(x)?;
            self.down_proj.forward(&nn::silu(gate)?.multiply(&up)?)
        }
    }

    #[derive(Debug, Clone, ModuleParameters, Quantizable)]
    pub struct TransformerBlock {
        #[quantizable]
        #[param]
        pub self_attn: Attention,
        #[quantizable]
        #[param]
        pub mlp: Mlp,
        #[param]
        pub input_layernorm: nn::RmsNorm,
        #[param]
        pub post_attention_layernorm: nn::RmsNorm,
    }

    impl TransformerBlock {
        pub fn new(args: &ModelArgs) -> Result<Self, Exception> {
            Ok(Self {
                self_attn: Attention::new(args)?,
                mlp: Mlp::new(args.hidden_size, args.intermediate_size, args.mlp_bias)?,
                input_layernorm: nn::RmsNorm::new(args.hidden_size, args.rms_norm_eps)?,
                post_attention_layernorm: nn::RmsNorm::new(args.hidden_size, args.rms_norm_eps)?,
            })
        }

        pub fn forward_with_cache(
            &mut self,
            x: &Array,
            mask: Option<&Array>,
            cache: Option<&mut dyn MlxKvCache>,
        ) -> Result<Array, Exception> {
            let r = self.self_attn.forward_with_cache(
                &self.input_layernorm.forward(x)?,
                mask,
                cache,
            )?;
            let h = x.add(&r)?;
            let r2 = self
                .mlp
                .forward(&self.post_attention_layernorm.forward(&h)?)?;
            h.add(&r2)
        }
    }

    #[derive(Debug, Clone, ModuleParameters, Quantizable)]
    pub struct LlamaModel {
        pub vocab_size: i32,
        pub n_layers: i32,
        #[quantizable]
        #[param]
        pub embed_tokens: MaybeQuantized<nn::Embedding>,
        #[quantizable]
        #[param]
        pub layers: Vec<TransformerBlock>,
        #[param]
        pub norm: nn::RmsNorm,
    }

    impl LlamaModel {
        pub fn new(args: &ModelArgs) -> Result<Self, Exception> {
            Ok(Self {
                vocab_size: args.vocab_size,
                n_layers: args.num_hidden_layers,
                embed_tokens: MaybeQuantized::Original(nn::Embedding::new(
                    args.vocab_size,
                    args.hidden_size,
                )?),
                layers: (0..args.num_hidden_layers)
                    .map(|_| TransformerBlock::new(args))
                    .collect::<Result<Vec<_>, _>>()?,
                norm: nn::RmsNorm::new(args.hidden_size, args.rms_norm_eps)?,
            })
        }

        pub fn forward_with_caches(
            &mut self,
            input_ids: &Array,
            caches: &mut Vec<Option<ConcatCache>>,
        ) -> Result<Array, Exception> {
            let mut h = self.embed_tokens.forward(input_ids)?;

            let mask = if h.shape()[1] > 1 {
                let m = nn::MultiHeadAttention::create_additive_causal_mask::<f32>(h.shape()[1])?;
                Some(m.as_dtype(h.dtype())?)
            } else {
                None
            };

            if caches.is_empty() {
                *caches = (0..self.layers.len())
                    .map(|_| Some(ConcatCache::default()))
                    .collect();
            }

            for (layer, c) in self.layers.iter_mut().zip(caches.iter_mut()) {
                h = layer.forward_with_cache(&h, mask.as_ref(), c.as_mut())?;
            }

            self.norm.forward(&h)
        }
    }

    #[derive(Debug, Clone, ModuleParameters, Quantizable)]
    pub struct Model {
        pub args: ModelArgs,
        #[quantizable]
        #[param]
        pub model: LlamaModel,
        #[quantizable]
        #[param]
        pub lm_head: Option<MaybeQuantized<nn::Linear>>,
    }

    impl Model {
        pub fn new(args: ModelArgs) -> Result<Self, Exception> {
            let model = LlamaModel::new(&args)?;
            let lm_head = if !args.tie_word_embeddings {
                Some(MaybeQuantized::Original(nn::Linear::new(
                    args.hidden_size,
                    args.vocab_size,
                    false,
                )?))
            } else {
                None
            };
            Ok(Self {
                args,
                model,
                lm_head,
            })
        }

        pub fn forward_with_caches(
            &mut self,
            input_ids: &Array,
            caches: &mut Vec<Option<ConcatCache>>,
        ) -> Result<Array, Exception> {
            let out = self.model.forward_with_caches(input_ids, caches)?;
            match self.lm_head.as_mut() {
                Some(head) => head.forward(&out),
                None => match &mut self.model.embed_tokens {
                    MaybeQuantized::Original(e) => e.as_linear(&out),
                    MaybeQuantized::Quantized(q) => q.as_linear(&out),
                },
            }
        }
    }
}

#[cfg(feature = "mlx")]
pub struct MlxBackend {
    model: inner::Model,
}

#[cfg(not(feature = "mlx"))]
pub struct MlxBackend {
    _private: (),
}

#[cfg(feature = "mlx")]
impl MlxBackend {
    pub fn load(config: &LocalModelConfig) -> Result<Self> {
        let model_path = &config.model_path;
        let config_path = model_path.join("config.json");
        if !config_path.exists() {
            return Err(ModelError::LocalModelError(format!(
                "config.json not found in {}\n\nHint: Ensure the model directory contains all required files.",
                model_path.display()
            )));
        }

        let config_content = std::fs::read_to_string(&config_path)?;
        let mut args: inner::ModelArgs = serde_json::from_str(&config_content).map_err(|e| {
            ModelError::LocalModelError(format!("Failed to parse config.json: {}", e))
        })?;

        if args.head_dim == 0 {
            args.head_dim = args.hidden_size / args.num_attention_heads;
        }

        info!(
            "MLX config: vocab={}, hidden={}, layers={}, heads={}",
            args.vocab_size, args.hidden_size, args.num_hidden_layers, args.num_attention_heads
        );

        let mut model = inner::Model::new(args).map_err(|e| {
            ModelError::LocalModelError(format!("Failed to create MLX model: {}", e))
        })?;

        let weight_files = find_weight_files(model_path);
        if weight_files.is_empty() {
            return Err(ModelError::LocalModelError(format!(
                "No .safetensors files found in {}",
                model_path.display()
            )));
        }

        info!("Loading {} MLX weight file(s)...", weight_files.len());
        for wf in &weight_files {
            model.load_safetensors(wf).map_err(|e| {
                ModelError::LocalModelError(format!("Failed to load MLX weights: {}", e))
            })?;
        }

        Ok(Self { model })
    }

    pub fn generate_text(
        &mut self,
        input_ids: &[u32],
        max_tokens: usize,
        temperature: f32,
        top_p: f32,
        top_k: Option<usize>,
        eos_token: Option<u32>,
    ) -> Result<Vec<u32>> {
        use mlx_rs::ops::indexing::{IndexOp, NewAxis};

        let prompt = Array::from(input_ids).index(NewAxis);
        let mut caches = Vec::new();

        let logits = self
            .model
            .forward_with_caches(&prompt, &mut caches)
            .map_err(|e| ModelError::LocalModelError(format!("MLX prefill failed: {}", e)))?;

        let last = logits.index((.., -1, ..));
        let mut y = sample_token(&last, temperature)?;
        eval([&y]).map_err(|e| ModelError::LocalModelError(format!("MLX eval failed: {}", e)))?;

        let mut generated = vec![y.item::<u32>()];

        for _ in 1..max_tokens {
            if let Some(eos) = eos_token {
                if generated.last() == Some(&eos) {
                    break;
                }
            }

            let inp = y.index((.., NewAxis));
            let logits = self
                .model
                .forward_with_caches(&inp, &mut caches)
                .map_err(|e| ModelError::LocalModelError(format!("MLX decode failed: {}", e)))?;
            y = sample_token(&logits, temperature)?;
            eval([&y])
                .map_err(|e| ModelError::LocalModelError(format!("MLX eval failed: {}", e)))?;
            generated.push(y.item::<u32>());
        }

        Ok(generated)
    }

    pub fn generate_text_stream<F>(
        &mut self,
        input_ids: &[u32],
        max_tokens: usize,
        temperature: f32,
        top_p: f32,
        top_k: Option<usize>,
        eos_token: Option<u32>,
        mut emit: F,
        tokenizer: &tokenizers::Tokenizer,
    ) -> Result<()>
    where
        F: FnMut(String) -> Result<()>,
    {
        use crate::local::tokenization::stream_piece;
        use mlx_rs::ops::indexing::{IndexOp, NewAxis};

        let prompt = Array::from(input_ids).index(NewAxis);
        let mut caches = Vec::new();
        let mut started = false;

        let logits = self
            .model
            .forward_with_caches(&prompt, &mut caches)
            .map_err(|e| ModelError::LocalModelError(format!("MLX prefill failed: {}", e)))?;

        let last = logits.index((.., -1, ..));
        let mut y = sample_token(&last, temperature)?;
        eval([&y]).map_err(|e| ModelError::LocalModelError(format!("MLX eval failed: {}", e)))?;
        let mut tid = y.item::<u32>();

        if let Some(piece) = stream_piece(tokenizer, tid, &mut started)? {
            emit(piece)?;
        }

        for _ in 1..max_tokens {
            if let Some(eos) = eos_token {
                if tid == eos {
                    break;
                }
            }

            let inp = y.index((.., NewAxis));
            let logits = self
                .model
                .forward_with_caches(&inp, &mut caches)
                .map_err(|e| ModelError::LocalModelError(format!("MLX decode failed: {}", e)))?;
            y = sample_token(&logits, temperature)?;
            eval([&y])
                .map_err(|e| ModelError::LocalModelError(format!("MLX eval failed: {}", e)))?;
            tid = y.item::<u32>();

            if let Some(piece) = stream_piece(tokenizer, tid, &mut started)? {
                emit(piece)?;
            }
        }

        Ok(())
    }

    pub fn model_type(&self) -> &str {
        &self.model.args.model_type
    }
}

#[cfg(feature = "mlx")]
fn sample_token(logits: &Array, temperature: f32) -> Result<Array> {
    if temperature == 0.0 {
        mlx_rs::ops::indexing::ArgMaxAxis::new(logits, -1, None)
            .run()
            .map_err(|e| ModelError::LocalModelError(format!("MLX argmax: {}", e)))
    } else {
        let scaled = logits
            .multiply(&mlx_rs::array!(1.0f32 / temperature))
            .map_err(|e| ModelError::LocalModelError(format!("MLX scale: {}", e)))?;
        mlx_rs::random::categorical(&scaled, None, None, None)
            .map_err(|e| ModelError::LocalModelError(format!("MLX sample: {}", e)))
    }
}

fn find_weight_files(model_path: &Path) -> Vec<std::path::PathBuf> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(model_path) {
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.ends_with(".safetensors") {
                    files.push(path);
                }
            }
        }
    }
    files.sort();
    files
}

#[cfg(not(feature = "mlx"))]
impl MlxBackend {
    pub fn load(_config: &LocalModelConfig) -> Result<Self> {
        Err(ModelError::InvalidConfig(
            "MLX support not enabled. Build with --features mlx".to_string(),
        ))
    }
}

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

    #[test]
    #[cfg(not(feature = "mlx"))]
    fn test_mlx_disabled() {
        let config = LocalModelConfig::default();
        let result = MlxBackend::load(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("MLX support not enabled"));
    }
}