mistral.rs 통합
외부 서버나 API 키 없이, 네이티브 Rust 추론으로 LLM을 로컬에서 실행하세요.
mistral.rs란 무엇인가요?
mistral.rs는 LLM을 하드웨어에서 직접 실행하는 고성능 Rust 추론 엔진입니다. adk-rust는 adk-mistralrs 크레이트를 통해 이를 통합합니다.
주요 특징:
- 🦀 네이티브 Rust - Python이나 외부 서버 불필요
- 🔒 완전 오프라인 - API 키나 인터넷 불필요
- ⚡ 하드웨어 가속 - CUDA, Metal, CPU 최적화
- 📦 양자화 - 제한된 하드웨어에서 대규모 모델 실행
- 🔧 LoRA adapters - 핫 스와핑을 통한 미세 조정 모델 지원
- 👁️ Vision models - 이미지 이해 기능
- 🎯 다중 모델 - 하나의 인스턴스에서 여러 모델 제공
1단계: 의존성 추가
adk-mistralrs는 git 저장소에 의존하므로 crates.io에 게시될 수 없습니다. git을 통해 추가하세요:
[package]
name = "my-local-agent"
version = "0.1.0"
edition = "2024"
[dependencies]
adk-mistralrs = { git = "https://github.com/zavora-ai/adk-rust" }
adk-agent = { git = "https://github.com/zavora-ai/adk-rust" }
adk-rust = { git = "https://github.com/zavora-ai/adk-rust" }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
하드웨어 가속을 위해서는 다음 기능 플래그를 추가하세요:
# macOS with Apple Silicon
adk-mistralrs = { git = "https://github.com/zavora-ai/adk-rust", features = ["metal"] }
# NVIDIA GPU (requires CUDA toolkit)
adk-mistralrs = { git = "https://github.com/zavora-ai/adk-rust", 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단계: Vision 모델 (이미지 이해)
비전-언어 모델로 이미지를 처리합니다:
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")
권장 모델
| Model | Size | RAM Needed | Best For |
|---|---|---|---|
microsoft/Phi-3.5-mini-instruct | 3.8B | 8GB | 빠르고 범용적 |
microsoft/Phi-3.5-vision-instruct | 4.2B | 10GB | 비전 + 텍스트 |
Qwen/Qwen2.5-3B-Instruct | 3B | 6GB | 다국어, 코딩 |
google/gemma-2-2b-it | 2B | 4GB | 경량 |
mistralai/Mistral-7B-Instruct-v0.3 | 7B | 16GB | 고품질 |
하드웨어 가속
macOS (Apple Silicon)
adk-mistralrs = { git = "https://github.com/zavora-ai/adk-rust", features = ["metal"] }
M1/M2/M3 Mac에서는 Metal 가속이 자동으로 이루어집니다.
NVIDIA GPU
adk-mistralrs = { git = "https://github.com/zavora-ai/adk-rust", features = ["cuda"] }
CUDA toolkit 11.8+가 필요합니다.
CPU 전용
별도의 기능이 필요 없습니다 - CPU가 기본값입니다.
예제 실행
# 기본 사용법
cargo run --bin basic
# 양자화 사용
cargo run --bin quantized
# LoRA 어댑터
cargo run --bin lora
# 다중 모델 설정
cargo run --bin multimodel
# 비전 모델
cargo run --bin vision
문제 해결
메모리 부족
// 양자화 활성화
.isq(QuantizationLevel::Q4_0)
// 페이지드 어텐션 활성화
.paged_attention(true)
첫 로딩 속도 저하
- 첫 실행 시 모델 다운로드 (~2-8GB)
- 이후 실행 시 캐시된 모델 사용
모델을 찾을 수 없음
- HuggingFace 모델 ID가 올바른지 확인하세요
- 첫 다운로드를 위해 인터넷 연결을 확인하세요
관련 항목
- Model Providers - 클라우드 LLM 제공업체
- Ollama - 대체 로컬 모델 서버
- LlmAgent - 에이전트와 함께 모델 사용
이전: ← Ollama (로컬) | 다음: Function Tools →