mistral.rs Documentation

repository·master·Indexed 27 days ago

https://github.com/ericlbuehler/mistral.rs

A high-performance LLM inference engine written in Rust providing zero-config inference for Hugging Face models. It supports multimodality (text, vision, video, audio), advanced quantization (GGUF, GPTQ, AWQ, HQQ, FP8, Bnb), and agentic capabilities including code and shell execution. The ecosystem includes crates for core model implementation (mistralrs-core), audio processing (mistralrs-audio), FlashAttention-2 CUDA kernels (mistralrs-flash-attn), and a Model Context Protocol client (mistralrs-mcp). It offers a CLI for interactive chat and API serving, a Python SDK, and hardware acceleration for CUDA, Metal, and MKL.

Tokens
113.7K
Snippets
240
Records
596
Agent score
90%

What's inside mistral.rs

  1. Understand the multimodal pipeline request shape

    master
    Multimodal requests in mistral.rs allow interleaving non-text content parts (image_url, audio, video) with text. The engine preserves the order of content parts in the request body, ensuring that text surrounding a media element appears correctly on either side of the media tokens in the final uniform token stream processed by the transformer.
  2. Supported Model Capabilities and Builders

    master

    The mistralrs engine supports a wide variety of model types, each accessible via a specific builder pattern:

    • Any model (auto-detect): ModelBuilder
    • Text generation: TextModelBuilder
    • Multimodal (image+text): MultimodalModelBuilder
    • GGUF quantized models: GgufModelBuilder
    • Image generation: DiffusionModelBuilder
    • Speech synthesis: SpeechModelBuilder
    • Embeddings: EmbeddingModelBuilder
    • Structured output: Use Model::generate_structured
    • Tool calling: Use Tool and ToolChoice
    • Agents: AgentBuilder
    • LoRA / X-LoRA: LoraModelBuilder or XLoraModelBuilder
    • AnyMoE: AnyMoeModelBuilder
    • MCP client: McpClientConfig
  3. Understand engine threading and concurrency

    master

    Concurrency in mistral.rs is managed at the engine thread level:

    • Engine Threads: One engine thread is spawned per loaded model during startup. This thread drives the loop that converts requests into token generation.
    • Concurrency Unit: The engine thread is the unit of concurrency.
    • Batching: Concurrent requests sent to the same model share a single queue and are batched by the scheduler.
    • Independent Execution: Requests sent to different models are handled by different engine threads and run independently.
  4. Explore the mistralrs Python API reference

    master

    The mistralrs Python package provides access to the core inference engine. The API is organized into several functional areas:

    • Runner: The main entry point for loading models and sending requests.
    • Requests & Responses: Dataclasses for passing requests to the Runner and handling response/streaming types.
    • Model Selection (Which): Variants for selecting specific model types to load.
    • Tooling & Execution: Configuration for web-search, Python/shell code execution, and MCP (Model Context Protocol) clients.
    • Agentic Features: Types for AnyMoE experts, agent action approvals, and file handling (input/output files).
    • Configuration: Enums for architecture and dtypes, auto-mapping for device placement, and search tool configurations.
  5. Use mistralrs-audio for audio processing utilities

    master
    The mistralrs-audio crate provides audio utilities for the mistral.rs ecosystem. It is designed to handle audio-related tasks such as reading audio files, resampling, managing audio channels, and computing mel spectrogram features. It functions similarly to mistralrs-vision but for audio data.
  6. Understand calibration data options

    master

    The project provides two versions of calibration data sourced from a GitHub Gist. Choosing between them involves a trade-off between accuracy and processing time:

    • calibration_datav3.txt: The full original dataset containing 64,181 tokens. Use this for the most accurate calibration, though it will take the longest to process.
    • calibration_datav3_small.txt: A subset containing up to line 1241 of the original data (30,173 tokens). Use this for faster calibration if full accuracy is not the primary concern.
  7. Understand Agentic Session Memory

    master

    Agentic sessions in mistral.rs manage state for tool-calls, tool responses, and multimodal payloads (images, videos). This state is stored in memory and reconciled with incoming requests to maintain context across turns.

    Session Storage Constraints

    • Capacity: The store is bounded to 128 sessions; once exceeded, the least-recently-used (LRU) session is evicted.
    • TTL: Sessions have a 30-minute idle Time-To-Live (TTL).
    • Persistence: Sessions are stored in process memory only. They do not survive server restarts unless explicitly exported and imported.

    Session Matching Logic

    Requests match an existing session via:

    1. Explicit session_id: A direct lookup using the provided ID.
    2. Content matching: If no session_id is provided, the engine scans stored sessions and returns the first one where the user-visible message prefix matches the incoming messages. Note that if multiple sessions match, the returned one is arbitrary (not necessarily the longest match).

    Splicing and Merging

    When a session is matched, the engine performs 'splicing' to merge stored history with the new request:

    • Preservation: Tool-role entries and assistant-with-tool-calls entries from stored history are kept.
    • Precedence: User and assistant messages from the incoming request take precedence over stored versions.
    • Divergence: If incoming messages differ from stored ones, the engine stops consuming stored history at the point of divergence and appends the new messages.
    • Multimodal Upgrade: Images and videos from the session are automatically re-attached to the request, upgrading plain-text requests to multimodal shape.
  8. Understand the mistral.rs architecture layers

    master

    The mistral.rs architecture is organized into three distinct layers to separate concerns between networking, orchestration, and hardware-specific execution:

    1. Server layer: Handles HTTP endpoints, MCP (Model Context Protocol) endpoints, CORS, body limits, and routing. It manages OpenAI wire formats but is agnostic of model internals.
    2. Engine layer: Manages the request queue, scheduler, tool loop, and session store. It drives inference pipelines without needing to know specific model architectures.
    3. Pipeline layer: Contains model implementations, tokenization, quantization, and attention kernels. Each model type uses one pipeline that conforms to a shared trait.

    To extend the project:

    • Implement new model architectures in the pipeline layer.
    • Implement new API surfaces in the server layer.
  9. Use the mistral.rs Python SDK

    master

    The mistralrs Python package allows you to run the mistral.rs inference engine in-process directly from Python. This enables high-performance LLM inference within your Python applications without needing to manage a separate server process.

    To begin using the SDK, follow these steps:

    1. Getting Started: Follow the initial setup and configuration guide.
    2. Streaming: Learn how to implement streaming responses for real-time text generation.
    3. API Reference: Consult the full Python API reference for detailed method signatures and parameter definitions.
  10. Understand the UQFF quantized model file format

    master

    UQFF is the native mistral.rs quantized file format. A UQFF export is a self-contained directory that must be distributed as a single unit. A single .uqff shard file is not loadable on its own; it requires the accompanying residual tensors and model assets located in the same directory.

    Required Directory Contents:

    • Shards: One or more <stem>-<shard>.uqff files containing quantized layers.
    • Residuals: residual.safetensors for unquantized tensors (e.g., norms, dense embeddings).
    • Model Assets: Configuration and tokenizer files copied from the source (e.g., config.json, tokenizer.json, tokenizer_config.json, generation_config.json, modules.json, chat_template.jinja, processor_config.json, preprocessor_config.json).

    Loading Mechanism: A loader is pointed at one or more shard files using from_uqff. The loader automatically locates the residual.safetensors and JSON assets via sibling-path lookup.