mistral.rs 통합
LLMs를 외부 서버나 API 키 없이 네이티브 Rust 추론으로 로컬에서 실행하세요.
mistral.rs란 무엇인가요?
mistral.rs는 LLMs를 하드웨어에서 직접 실행하는 고성능 Rust 추론 엔진입니다. ADK-Rust는 Gemma 4 지원과 함께 v0.8.0에 고정된 adk-mistralrs crate를 통해 이를 통합합니다.
주요 특징:
- 🦀 네이티브 Rust - Python이나 외부 서버 없음
- 🔒 완전 오프라인 - API 키나 인터넷 필요 없음
- ⚡ 하드웨어 가속 - CUDA, Metal (3.1 bfloat16), CPU 최적화
- 📦 양자화 - 제한된 하드웨어에서 대규모 모델을 실행하기 위한 ISQ, MXFP4, GGUF, UQFF
- 🔧 LoRA 어댑터 - 핫 스와핑을 통한 미세 조정 모델 지원
- 👁️ 멀티모달 - 시각, 오디오, 비디오 이해 (Gemma 4, Qwen 3 VL)
- 🎤 음성 - Voxtral 실시간 음성 인식
- 🎯 멀티 모델 - 단일 인스턴스에서 여러 모델 제공
1단계: 의존성 추가
adk-mistralrs는 crates.io에 워크스페이스 멤버로 게시됩니다. 표준 의존성으로 추가하세요:
[package]
name = "my-local-agent"
version = "0.1.0"
edition = "2024"
[dependencies]
adk-mistralrs = "2.0.0"
adk-agent = "2.0.0"
adk-rust = "2.0.0"
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
하드웨어 가속을 위해 피처 플래그를 추가하세요:
# macOS with Apple Silicon
adk-mistralrs = { version = "2.0.0", features = ["metal"] }
# NVIDIA GPU (requires CUDA toolkit)
adk-mistralrs = { version = "2.0.0", features = ["cuda"] }
2단계: 기본 예제
HuggingFace에서 모델을 로드하여 로컬에서 실행합니다:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsModel, ModelSource};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load model from HuggingFace (downloads on first run)
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.build();
println!("Loading model (this may take a while on first run)...");
let model = MistralRsModel::new(config).await?;
println!("Model loaded: {}", model.name());
// Create agent
let agent = LlmAgentBuilder::new("local_assistant")
.description("Local AI assistant powered by mistral.rs")
.instruction("You are a helpful assistant running locally. Be concise.")
.model(Arc::new(model))
.build()?;
// Run interactive chat
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
어떤 일이 발생하나요:
- 첫 실행 시 HuggingFace에서 모델을 다운로드합니다 (모델에 따라 ~2-8GB).
- 모델은
~/.cache/huggingface/에 로컬로 캐시됩니다. - 이후 실행 시 캐시에서 즉시 로드됩니다.
3단계: 양자화를 통한 메모리 절감
대규모 모델은 많은 RAM을 필요로 합니다. ISQ (현장 양자화)를 사용하여 메모리를 절감하세요:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsModel, ModelSource, QuantizationLevel};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load model with 4-bit quantization for reduced memory
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.isq(QuantizationLevel::Q4_0) // 4-bit quantization
.paged_attention(true) // Memory-efficient attention
.build();
println!("Loading quantized model...");
let model = MistralRsModel::new(config).await?;
println!("Model loaded: {}", model.name());
let agent = LlmAgentBuilder::new("quantized_assistant")
.instruction("You are a helpful assistant. Be concise.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
양자화 수준:
| 수준 | 메모리 감소 | 품질 | 최적 사용처 |
|---|---|---|---|
Q4_0 | ~75% | 양호 | 제한된 RAM (8GB) |
Q4_1 | ~70% | 더 좋음 | 균형 잡힘 |
Q8_0 | 약 50% | 높음 | 품질 중심 |
Q8_1 | ~50% | 최고 | 최고 품질 |
4단계: LoRA 어댑터 (미세 조정된 모델)
전문화된 작업을 위해 LoRA 어댑터를 사용하여 모델을 로드합니다:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{AdapterConfig, Llm, MistralRsAdapterModel, MistralRsConfig, ModelSource};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load base model with LoRA adapter
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("meta-llama/Llama-3.2-3B-Instruct"))
.adapter(AdapterConfig::lora("username/my-lora-adapter"))
.build();
println!("Loading model with LoRA adapter...");
let model = MistralRsAdapterModel::new(config).await?;
println!("Model loaded: {}", model.name());
println!("Available adapters: {:?}", model.available_adapters());
let agent = LlmAgentBuilder::new("lora_assistant")
.instruction("You are a helpful assistant with specialized knowledge.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
런타임에 어댑터 핫스왑:
model.swap_adapter("another-adapter").await?;
5단계: 비전 모델 (이미지 이해)
비전-언어 모델로 이미지를 처리합니다:
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsVisionModel, ModelSource};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-vision-instruct"))
.build();
println!("Loading vision model...");
let model = MistralRsVisionModel::new(config).await?;
println!("Model loaded: {}", model.name());
// Analyze an image
let image = image::open("photo.jpg")?;
let response = model.generate_with_image("Describe this image.", vec![image]).await?;
Ok(())
}
6단계: 다중 모델 서빙
단일 인스턴스에서 여러 모델을 서빙합니다:
use adk_mistralrs::{MistralRsConfig, MistralRsMultiModel, ModelSource};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let multi = MistralRsMultiModel::new();
// Add models
let phi_config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.build();
multi.add_model("phi", phi_config).await?;
let gemma_config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("google/gemma-2-2b-it"))
.build();
multi.add_model("gemma", gemma_config).await?;
// Set default and route requests
multi.set_default("phi").await?;
println!("Available models: {:?}", multi.model_names().await);
// Route to specific model
// multi.generate_with_model(Some("gemma"), request, false).await?;
Ok(())
}
모델 소스
HuggingFace 허브 (기본값)
ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct")
로컬 디렉터리
ModelSource::local("/path/to/model")
사전 양자화된 GGUF
ModelSource::gguf("/path/to/model.Q4_K_M.gguf")
권장 모델
| 모델 | 크기 | RAM 필요 | 최적 용도 |
|---|---|---|---|
google/gemma-4-4b-it | 4B | 8GB | Gemma 4 — multimodal (text, image, audio, video), Apache 2.0 |
google/gemma-4-12b-it | 12B | 24GB | Gemma 4 — 고품질 멀티모달 추론 |
microsoft/Phi-3.5-mini-instruct | 3.8B | 8GB | 빠르고 범용적 |
microsoft/Phi-3.5-vision-instruct | 4.2B | 10GB | 비전 + 텍스트 |
Qwen/Qwen3-4B | 4B | 8GB | 다국어, 코딩, 추론 |
Qwen/Qwen3.5-7B-Instruct | 7B | 16GB | 강력한 추론 능력을 갖춘 최신 Qwen |
google/gemma-2-2b-it | 2B | 4GB | 경량 |
mistralai/Mistral-7B-Instruct-v0.3 | 7B | 16GB | 고품질 |
하드웨어 가속
macOS (Apple Silicon)
adk-mistralrs = { version = "2.0.0", features = ["metal"] }
M1/M2/M3 Mac에서는 Metal 가속이 자동으로 이루어집니다.
NVIDIA GPU
adk-mistralrs = { version = "2.0.0", features = ["cuda"] }
CUDA toolkit 11.8 이상이 필요합니다.
CPU 전용
별도의 기능이 필요하지 않습니다 - CPU가 기본값입니다.
크레이트 유효성 검사
cargo build -p adk-mistralrs
cargo build -p adk-mistralrs --features metal
문제 해결
메모리 부족
// Enable quantization
.isq(QuantizationLevel::Q4_0)
// Enable paged attention
.paged_attention(true)
느린 첫 로드
- 첫 실행 시 모델을 다운로드합니다 (~2-8GB)
- 이후 실행 시 캐시된 모델을 사용합니다
모델을 찾을 수 없음
- HuggingFace model ID가 올바른지 확인하세요
- 첫 다운로드를 위해 인터넷 연결을 확인하세요
관련 항목
이전: ← Ollama (로컬) | 다음: Function Tools →