shimmy 2.0.0

Lightweight Ollama-compatible inference server with native SafeTensors support. No Python dependencies, cross-platform WebGPU acceleration via Airframe.
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
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use std::path::Path;
use std::process::Command;
use tokio::process::Command as TokioCommand;

use super::{GenOptions, ModelBackend, UniversalEngine, UniversalModel, UniversalModelSpec};

#[derive(Debug)]
pub struct HuggingFaceEngine {
    python_path: String,
}

impl Default for HuggingFaceEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl HuggingFaceEngine {
    pub fn new() -> Self {
        // Use the verified Python path from CLAUDE.md
        Self {
            python_path: "C:/Python311/python.exe".to_string(),
        }
    }
}

#[async_trait]
impl UniversalEngine for HuggingFaceEngine {
    async fn load(&self, spec: &UniversalModelSpec) -> Result<Box<dyn UniversalModel>> {
        match &spec.backend {
            ModelBackend::HuggingFace {
                base_model_id,
                peft_path,
                use_local,
            } => {
                let model = HuggingFaceModel::load(
                    &self.python_path,
                    base_model_id,
                    peft_path.as_deref(),
                    *use_local,
                    &spec.device,
                )
                .await?;
                Ok(Box::new(model))
            }
            _ => Err(anyhow!(
                "HuggingFaceEngine only supports HuggingFace backend"
            )),
        }
    }
}

struct HuggingFaceModel {
    python_path: String,
    base_model_id: String,
    peft_path: Option<String>,
    device: String,
}

impl HuggingFaceModel {
    async fn load(
        python_path: &str,
        base_model_id: &str,
        peft_path: Option<&Path>,
        _use_local: bool,
        device: &str,
    ) -> Result<Self> {
        // Verify Python and transformers availability
        let output = Command::new(python_path)
            .args(["-c", "import torch, transformers, peft; print('OK')"])
            .output()?;

        if !output.status.success() {
            return Err(anyhow!(
                "Python dependencies missing. Install: pip install torch transformers peft\nError: {}",
                String::from_utf8_lossy(&output.stderr)
            ));
        }

        // Verify model can be loaded (quick check)
        let verify_cmd = vec![
            "-c".to_string(),
            format!(
                r#"
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import sys

try:
    print("Loading base model...", file=sys.stderr)
    model = AutoModelForCausalLM.from_pretrained('{}', torch_dtype=torch.float16)

    {}

    print("SUCCESS: Model loaded", file=sys.stderr)
    print("OK")
except Exception as e:
    print(f"ERROR: {{e}}", file=sys.stderr)
    sys.exit(1)
"#,
                base_model_id,
                if let Some(peft_path) = peft_path {
                    format!(
                        r#"print("Loading PEFT adapter...", file=sys.stderr)
    model = PeftModel.from_pretrained(model, '{}')
    print("PEFT adapter loaded", file=sys.stderr)"#,
                        peft_path.display()
                    )
                } else {
                    "".to_string()
                }
            ),
        ];

        let verify_output = Command::new(python_path).args(&verify_cmd).output()?;

        if !verify_output.status.success() {
            return Err(anyhow!(
                "Failed to load HuggingFace model '{}': {}",
                base_model_id,
                String::from_utf8_lossy(&verify_output.stderr)
            ));
        }

        Ok(HuggingFaceModel {
            python_path: python_path.to_string(),
            base_model_id: base_model_id.to_string(),
            peft_path: peft_path.map(|p| p.to_string_lossy().to_string()),
            device: device.to_string(),
        })
    }
}

#[async_trait]
impl UniversalModel for HuggingFaceModel {
    async fn generate(
        &self,
        prompt: &str,
        opts: GenOptions,
        on_token: Option<Box<dyn FnMut(String) + Send>>,
    ) -> Result<String> {
        let generation_script = format!(
            r#"
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
from peft import PeftModel
import sys
import json

# Load model and tokenizer
print("Loading model...", file=sys.stderr)
tokenizer = AutoTokenizer.from_pretrained('{}')
model = AutoModelForCausalLM.from_pretrained(
    '{}',
    torch_dtype=torch.float16,
    device_map="auto" if '{}' == "cuda" else None
)

{}

# Set pad token if not present
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# Generate
print("Generating...", file=sys.stderr)
inputs = tokenizer('''{}''', return_tensors="pt")
if '{}' == "cuda":
    inputs = {{k: v.cuda() for k, v in inputs.items()}}

with torch.no_grad():
    outputs = model.generate(
        **inputs,
        max_new_tokens={},
        temperature={},
        top_p={},
        top_k={},
        repetition_penalty={},
        pad_token_id=tokenizer.pad_token_id,
        do_sample=True if {} > 0.0 else False,
        {}
    )

# Decode output
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Remove input prompt from output
input_text = '''{}'''
if generated_text.startswith(input_text):
    generated_text = generated_text[len(input_text):].strip()

print(generated_text)
"#,
            self.base_model_id,
            self.base_model_id,
            self.device,
            if let Some(peft_path) = &self.peft_path {
                format!(
                    r#"print("Loading PEFT adapter...", file=sys.stderr)
model = PeftModel.from_pretrained(model, '{}')"#,
                    peft_path
                )
            } else {
                "".to_string()
            },
            prompt.replace("'", r"\'"),
            self.device,
            opts.max_tokens,
            opts.temperature,
            opts.top_p,
            opts.top_k,
            opts.repeat_penalty,
            opts.temperature,
            if let Some(seed) = opts.seed {
                format!("use_cache=False,\n        torch.manual_seed({})", seed)
            } else {
                "use_cache=True".to_string()
            },
            prompt.replace("'", r"\'")
        );

        let mut cmd = TokioCommand::new(&self.python_path);
        cmd.args(["-c", &generation_script]);

        let output = cmd.output().await?;

        if !output.status.success() {
            return Err(anyhow!(
                "HuggingFace generation failed: {}",
                String::from_utf8_lossy(&output.stderr)
            ));
        }

        let result = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = result.lines().collect();

        // Find the actual generated text (after loading messages)
        let generated_text = lines
            .iter()
            .rev()
            .find(|line| !line.trim().is_empty())
            .unwrap_or(&"")
            .to_string();

        // Handle streaming callback if provided
        if let Some(mut callback) = on_token {
            for word in generated_text.split_whitespace() {
                callback(format!("{} ", word));
            }
        }

        Ok(generated_text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::{GenOptions, ModelBackend, UniversalModelSpec};

    #[test]
    fn test_default_creates_new_instance() {
        let engine = HuggingFaceEngine::default();
        assert_eq!(engine.python_path, "C:/Python311/python.exe");
    }

    #[test]
    fn test_new_creates_with_correct_python_path() {
        let engine = HuggingFaceEngine::new();
        assert_eq!(engine.python_path, "C:/Python311/python.exe");
    }

    #[tokio::test]
    async fn test_load_with_invalid_backend_returns_error() {
        let engine = HuggingFaceEngine::new();
        let spec = UniversalModelSpec {
            name: "test_model".to_string(),
            backend: ModelBackend::LlamaGGUF {
                base_path: std::path::PathBuf::from("test.gguf"),
                lora_path: None,
            },
            device: "cpu".to_string(),
            template: None,
            ctx_len: 2048,
            n_threads: None,
        };

        let result = engine.load(&spec).await;
        assert!(result.is_err());
        if let Err(e) = result {
            let error_str = format!("{}", e);
            assert!(error_str.contains("HuggingFaceEngine only supports HuggingFace backend"));
        }
    }

    #[tokio::test]
    async fn test_load_with_valid_backend_structure() {
        let engine = HuggingFaceEngine::new();
        let spec = UniversalModelSpec {
            name: "test_model".to_string(),
            backend: ModelBackend::HuggingFace {
                base_model_id: "microsoft/DialoGPT-medium".to_string(),
                peft_path: None,
                use_local: true,
            },
            device: "cpu".to_string(),
            template: None,
            ctx_len: 2048,
            n_threads: None,
        };

        // This will fail if Python isn't available, but tests the error path
        let result = engine.load(&spec).await;
        // Either succeeds or fails with Python dependency error or path not found error
        if let Err(e) = result {
            let error_msg = format!("{}", e);
            assert!(
                error_msg.contains("Python dependencies")
                    || error_msg.contains("Failed to load HuggingFace model")
                    || error_msg.contains("Failed to initialize")
                    || error_msg.contains("cannot find the path")
                    || error_msg.contains("os error 3")
                    || error_msg.contains("os error 2")  // No such file or directory
                    || error_msg.contains("No such file")
                    || error_msg.contains("not found")
                    || error_msg.contains("The system cannot find")
                    || error_msg.contains("command not found")
                    || error_msg.contains("Access is denied")
                    || error_msg.contains("Permission denied")
            );
        }
    }

    #[test]
    fn test_huggingface_model_struct_creation() {
        let model = HuggingFaceModel {
            python_path: "python".to_string(),
            base_model_id: "test_model".to_string(),
            peft_path: Some("/path/to/adapter".to_string()),
            device: "cuda".to_string(),
        };

        assert_eq!(model.python_path, "python");
        assert_eq!(model.base_model_id, "test_model");
        assert_eq!(model.peft_path, Some("/path/to/adapter".to_string()));
        assert_eq!(model.device, "cuda");
    }

    #[tokio::test]
    async fn test_huggingface_model_load_invalid_python_path() {
        let result = HuggingFaceModel::load(
            "/invalid/python/path",
            "microsoft/DialoGPT-medium",
            None,
            true,
            "cpu",
        )
        .await;

        assert!(result.is_err());
    }

    #[test]
    fn test_generate_options_handling() {
        // Test that GenOptions are properly structured for use
        let opts = GenOptions {
            max_tokens: 100,
            temperature: 0.7,
            top_p: 0.9,
            top_k: 40,
            repeat_penalty: 1.1,
            seed: Some(42),
            stream: false,
            stop_tokens: Vec::new(),
        };

        assert_eq!(opts.max_tokens, 100);
        assert_eq!(opts.temperature, 0.7);
        assert_eq!(opts.top_p, 0.9);
        assert_eq!(opts.top_k, 40);
        assert_eq!(opts.repeat_penalty, 1.1);
        assert_eq!(opts.seed, Some(42));
        assert!(!opts.stream);
    }

    // Integration test for error cases that would require actual Python/model access
    #[tokio::test]
    async fn test_full_workflow_error_cases() {
        let engine = HuggingFaceEngine::new();

        // Test 1: Unsupported backend
        let wrong_backend_spec = UniversalModelSpec {
            name: "test_model".to_string(),
            backend: ModelBackend::Candle {
                model_path: std::path::PathBuf::from("test.safetensors"),
                adapter_path: None,
            },
            device: "cpu".to_string(),
            template: None,
            ctx_len: 2048,
            n_threads: None,
        };

        let result = engine.load(&wrong_backend_spec).await;
        assert!(result.is_err());

        // Test 2: Valid backend structure but will fail on Python dependencies
        let valid_spec = UniversalModelSpec {
            name: "nonexistent_model".to_string(),
            backend: ModelBackend::HuggingFace {
                base_model_id: "nonexistent/model".to_string(),
                peft_path: None,
                use_local: true,
            },
            device: "cpu".to_string(),
            template: None,
            ctx_len: 2048,
            n_threads: None,
        };

        let result = engine.load(&valid_spec).await;
        // Should error due to missing Python deps or invalid model
        assert!(result.is_err());
    }
}