mistral.rs 통합
외부 서버나 API 키 없이 네이티브 Rust 추론으로 LLMs을 로컬에서 실행합니다.
mistral.rs란?
mistral.rs는 LLMs을 하드웨어에서 직접 실행하는 고성능 Rust 추론 엔진입니다. ADK-Rust은 adk-mistralrs crate를 통해 이를 통합하며, v0.8.0으로 고정되어 있고 Gemma 4를 지원합니다.
주요 특징:
- 🦀 네이티브 Rust - Python 및 외부 서버 불필요
- 🔒 완전한 오프라인 실행 - API 키나 인터넷 연결 불필요
- ⚡ 하드웨어 가속 - CUDA, Metal(3.1 bfloat16), CPU 최적화
- 📦 양자화 - 제한된 하드웨어에서 대규모 모델을 실행하기 위한 ISQ, MXFP4, GGUF, UQFF
- 🔧 LoRA 어댑터 - 미세 조정된 모델 지원 및 핫 스와핑
- 👁️ 멀티모달 - 비전, 오디오 및 비디오 이해(Gemma 4, Qwen 3 VL)
- 🎤 음성 - Voxtral 실시간 음성 인식
- 🎯 다중 모델 - 하나의 인스턴스에서 여러 모델 제공
1단계: 종속성 추가
adk-mistralrs은 workspace 멤버로 crates.io에 게시되어 있습니다. 표준 종속성으로 추가합니다.
[package]
name = "my-local-agent"
version = "0.1.0"
edition = "2024"
[dependencies]
adk-mistralrs = "2.1.0"
adk-agent = "2.1.0"
adk-rust = "2.1.0"
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
하드웨어 가속을 사용하려면 feature flags를 추가합니다.
# macOS with Apple Silicon
adk-mistralrs = { version = "2.1.0", features = ["metal"] }
# NVIDIA GPU (requires CUDA toolkit)
adk-mistralrs = { version = "2.1.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(In-Situ Quantization)를 사용하여 메모리 사용량을 줄입니다.
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 Hub(기본값)
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 — 멀티모달(텍스트, 이미지, 오디오, 동영상), 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.1.0", features = ["metal"] }
M1/M2/M3 Mac에서는 Metal 가속이 자동으로 활성화됩니다.
NVIDIA GPU
adk-mistralrs = { version = "2.1.0", features = ["cuda"] }
CUDA toolkit 11.8 이상이 필요합니다.
CPU 전용
필요한 기능이 없습니다. CPU가 기본값입니다.
Crate 검증
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 모델 ID가 올바른지 확인합니다.
- 처음 다운로드할 때 인터넷 연결이 되어 있는지 확인합니다.
관련 항목
이전: ← Ollama (로컬) | 다음: 함수 도구 →