> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inferless.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy the Voxtral-Mini-3B model using Inferless

> An audio-language model fine-tuned for transcription, summarization, Q&A and voice-triggered function calls, deployable compactly on consumer GPUs with rich structured outputs.

## Introduction

[`mistralai/Voxtral-Mini-3B-2507`](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507) is an open-source, 3B-parameter audio-language model released under Apache 2.0, optimized for speech transcription, summarization, Q\&A, language detection, and voice-triggered workflows. It retains high performance on text prompts while offering multimodal audio understanding in a compact format, ideal for on-device or edge deployment.

It supports extended context windows upto 32k tokens, allowing processing of audios as long as \~30 minutes for transcription or \~40 minutes for audio reasoning.  It automatically detects language across many languages (English, Hindi, French, Portuguese, German, Dutch, Italian, Spanish and more), transcribes, summarizes, answers questions, and even triggers backend functions based on spoken commands.

## Defining Dependencies

We are using the [transformers](https://github.com/huggingface/transformers) to serve the model on a single A10.

## Constructing the GitHub/GitLab Template

Now quickly construct the GitHub/GitLab template, this process is mandatory and make sure you don't add any file named `model.py`.

```
voxtral-mini-3b/
├── app.py
├── inferless-runtime-config.yaml
└── inferless.yaml
```

You can also add other files to this directory.

## Create the Input Schema with Pydantic

Using the `inferless` Python client and Pydantic, you can define structured schemas directly in your code for input and output, eliminating the need for external file.

### Input Schema

When defining an input schema with Pydantic, you need to annotate your class attributes with the appropriate types, such as `str`, `float`, `int`, `bool` etc.
These type annotations specifys what type of data each field should contain.
The `default` value serves as the example input for testing with the `infer` function.

```python theme={null}
@inferless.request
class RequestObjects(BaseModel):
    audio_path: str = Field(default="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3")
    text_prompt: str = Field(default="What can you tell me about the audio?")
    max_new_tokens: Optional[int] = 500
    temperature: Optional[float] = 1.0
    do_sample: Optional[bool] = True
    top_p: Optional[float] = 0.9
    top_k: Optional[int] = 50
```

### Output Schema

The `@inferless.response` decorator helps you define structured output schemas.

```python theme={null}
@inferless.response
class ResponseObjects(BaseModel):
    generated_text: str = Field(default="Test Output")
```

### Usage in the `infer` Function

Once you have annotated the objects you can expect the infer function to receive `RequestObjects` as input,
and returns a `ResponseObjects` instance as output, ensuring the results adhere to a defined structure.

```python theme={null}
class InferlessPythonModel:
    def infer(self, request: RequestObjects) -> ResponseObjects:
        
        return ResponseObject(**return_result)
```

## Create the class for inference

In the [app.py](https://github.com/inferless/voxtral-mini-3b/blob/main/app.py) we will define the class and import all the required functions

1. `def initialize`: In this function, you will initialize your model and define any `variable` that you want to use during inference.

2. `def infer`: This function gets called for every request that you send. Here you can define all the steps that are required for the inference.

3. `def finalize`: This function cleans up all the allocated memory.

```python theme={null}
from transformers import VoxtralForConditionalGeneration, AutoProcessor
import torch
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
import inferless
import os

os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = '1'

@inferless.request
class RequestObjects(BaseModel):
    audio_path: str = Field(default="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3")
    text_prompt: str = Field(default="What can you tell me about the audio?")
    max_new_tokens: Optional[int] = 500
    temperature: Optional[float] = 1.0
    do_sample: Optional[bool] = True
    top_p: Optional[float] = 0.9
    top_k: Optional[int] = 50

@inferless.response
class ResponseObjects(BaseModel):
    generated_text: str = Field(default="Test Output")

class InferlessPythonModel:
    def initialize(self):
        self.repo_id = "mistralai/Voxtral-Mini-3B-2507"
        self.processor = AutoProcessor.from_pretrained(self.repo_id)
        self.model = VoxtralForConditionalGeneration.from_pretrained(
            self.repo_id, 
            torch_dtype=torch.bfloat16, 
            device_map="cuda"
        )

    def _create_conversation(self, audio_path: str, text_prompt: str) -> List[Dict[str, Any]]:
        """Create conversation format for the model"""
        content = []
        
        # Add audio file
        content.append({
                "type": "audio",
                "path": audio_path
            })
        
        # Add text prompt
        content.append({
            "type": "text", 
            "text": text_prompt
        })
        
        conversation = [
            {
                "role": "user",
                "content": content
            }
        ]
        
        return conversation

    def infer(self, inputs: RequestObjects) -> ResponseObjects:
        # Create conversation format
        conversation = self._create_conversation(inputs.audio_path, inputs.text_prompt)
        
        
        # Apply chat template
        model_inputs = self.processor.apply_chat_template(conversation)
        model_inputs = model_inputs.to("cuda", dtype=torch.bfloat16)
        
        # Generate response
        generation_kwargs = {
            "max_new_tokens": inputs.max_new_tokens,
            "do_sample": inputs.do_sample,
            "temperature": inputs.temperature,
            "top_p": inputs.top_p,
            "top_k": inputs.top_k,
        }
        with torch.no_grad():
            outputs = self.model.generate(**model_inputs, **generation_kwargs)
        
        # Decode the generated tokens
        decoded_outputs = self.processor.batch_decode(
            outputs[:, model_inputs.input_ids.shape[1]:], 
            skip_special_tokens=True
        )
        
        generated_text = decoded_outputs[0].strip()
        
        return ResponseObjects(
            generated_text=generated_text
        )

    def finalize(self):
        self.model = None
```

## Creating the Custom Runtime

This is a mandatory step where we allow the users to upload their custom runtime through [inferless-runtime-config.yaml](https://github.com/inferless/voxtral-mini-3b/blob/main/inferless-runtime-config.yaml).

```python theme={null}
build:
  cuda_version: "12.1.1"
  python_packages:
    - torch==2.7.1
    - mistral_common==1.8.1
    - accelerate==1.9.0
    - librosa==0.11.0
    - hf-transfer==0.1.9
    - huggingface-hub==0.34.0
    - pydantic==2.11.7
    - inferless==0.2.15
    - transformers==4.54.1
```

## Test your model with Remote Run

You can use the `inferless remote-run`([installation guide here](https://docs.inferless.com/model-import/cli-import#cli-import)) command to test your model or any custom Python script in a remote GPU environment directly from your local machine. Make sure that you use `Python3.10` for seamless experience.

### Step 1: Add the Decorators and local entry point

To enable **Remote Run**, simply do the following:

1. Import the `inferless` library and initialize `Cls(gpu="A10")`. The available GPU options are `T4`, `A10` and `A100`.
2. Decorated the `initialize` and `infer` functions with `@app.load` and `@app.infer` respectively.
3. Create the Local Entry Point by decorating a function (for example, `my_local_entry`) with `@inferless.local_entry_point`.
   Within this function, instantiate your model class, convert any incoming parameters into a `RequestObjects` object, and invoke the model's `infer` method.

```python theme={null}
from transformers import VoxtralForConditionalGeneration, AutoProcessor
import torch
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
import inferless
import os

os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = '1'

app = inferless.Cls(gpu="A10")

@inferless.request
class RequestObjects(BaseModel):
    audio_path: str = Field(default="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3")
    text_prompt: str = Field(default="What can you tell me about the audio?")
    max_new_tokens: Optional[int] = 500
    temperature: Optional[float] = 1.0
    do_sample: Optional[bool] = True
    top_p: Optional[float] = 0.9
    top_k: Optional[int] = 50

@inferless.response
class ResponseObjects(BaseModel):
    generated_text: str = Field(default="Test Output")

class InferlessPythonModel:
    @app.load
    def initialize(self):
        self.repo_id = "mistralai/Voxtral-Mini-3B-2507"
        self.processor = AutoProcessor.from_pretrained(self.repo_id)
        self.model = VoxtralForConditionalGeneration.from_pretrained(
            self.repo_id, 
            torch_dtype=torch.bfloat16, 
            device_map="cuda"
        )

    def _create_conversation(self, audio_path: str, text_prompt: str) -> List[Dict[str, Any]]:
        """Create conversation format for the model"""
        content = []
        
        # Add audio file
        content.append({
                "type": "audio",
                "path": audio_path
            })
        
        # Add text prompt
        content.append({
            "type": "text", 
            "text": text_prompt
        })
        
        conversation = [
            {
                "role": "user",
                "content": content
            }
        ]
        
        return conversation
    
    @app.infer
    def infer(self, inputs: RequestObjects) -> ResponseObjects:
        # Create conversation format
        conversation = self._create_conversation(inputs.audio_path, inputs.text_prompt)
        
        
        # Apply chat template
        model_inputs = self.processor.apply_chat_template(conversation)
        model_inputs = model_inputs.to("cuda", dtype=torch.bfloat16)
        
        # Generate response
        generation_kwargs = {
            "max_new_tokens": inputs.max_new_tokens,
            "do_sample": inputs.do_sample,
            "temperature": inputs.temperature,
            "top_p": inputs.top_p,
            "top_k": inputs.top_k,
        }
        with torch.no_grad():
            outputs = self.model.generate(**model_inputs, **generation_kwargs)
        
        # Decode the generated tokens
        decoded_outputs = self.processor.batch_decode(
            outputs[:, model_inputs.input_ids.shape[1]:], 
            skip_special_tokens=True
        )
        
        generated_text = decoded_outputs[0].strip()
        
        return ResponseObjects(
            generated_text=generated_text
        )

    def finalize(self):
        self.model = None

@inferless.local_entry_point
def my_local_entry(dynamic_params):
    request_objects = RequestObjects(**dynamic_params)
    model_instance = InferlessPythonModel()

    return model_instance.infer(request_objects)
```

### Step 2: Run with Remote GPU

From your local terminal, navigate to the folder containing your `app.py` and your `inferless-runtime-config.yaml` and run:

```bash theme={null}
 inferless remote-run app.py -c inferless-runtime-config.yaml --audio_path "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3" --text_prompt "What can you tell me about the audio?"
```

You can pass the other input parameters in the same way (e.g., `--max_new_tokens`, etc.) as long as your code expects them in the `inputs` dictionary.

If you want to exclude certain files or directories from being uploaded, use the `--exclude` or `-e` flag.

## Method A: Deploying the model on Inferless Platform

Inferless supports multiple ways of [importing your model](https://docs.inferless.com/model-import/file-structure-req/file-structure-requirements). For this tutorial, we will use GitHub.

### Step 1: Login to the inferless dashboard can click on Import model button

Navigate to your desired workspace in Inferless and Click on `Add a custom model` button that you see on the top right. An import wizard will open up.

### Step 2: Follow the UI to complete the model  Import

* Select the GitHub/GitLab Integration option to connect your source code repository with the deployment environment.
* Navigate to the specific GitHub repository that contains your model's code. Here, you will need to identify and enter the name of the model you wish to import.
* Choose the appropriate type of machine that suits your model's requirements. Additionally, specify the minimum and maximum number of replicas to define the scalability range for deploying your model.
* Optionally, you have the option to enable automatic build and deployment. This feature triggers a new deployment automatically whenever there is a new code push to your repository.
* If your model requires additional software packages, configure the Custom Runtime settings by including necessary pip or apt packages. Also, set up environment variables such as  Inference Timeout, Container Concurrency, and Scale Down Timeout to tailor the runtime environment according to your needs.
* Wait for the validation process to complete, ensuring that all settings are correct and functional. Once validation is successful, click on the "Import" button to finalize the import of your model.
  <img src="https://mintcdn.com/inferless-68/g8bkqnienvwe_7dP/images/inferless_model_import.png?fit=max&auto=format&n=g8bkqnienvwe_7dP&q=85&s=4cd9d6888f4fbd75d9d4e6eb90771bd3" alt="" width="2484" height="1478" data-path="images/inferless_model_import.png" />

### Step 3: Wait for the model build to complete usually takes \~5-10 minutes

### Step 4: Use the APIs to call the model

Once the model is in 'Active' status you can click on the 'API' page to call the model

### Here is the Demo:

<img src="https://mintcdn.com/inferless-68/txuhsMKn8Dl42Mmp/gif/voxtral-demo.gif?s=f55bf7d74283726b7be19c1b15dc8d4c" alt="" width="1400" height="659" data-path="gif/voxtral-demo.gif" />

## Method B: Deploying the model on Inferless CLI

Inferless allows you to deploy your model using Inferless-CLI. Follow the steps to deploy using Inferless CLI.

### Clone the repository of the model

Let's begin by cloning the model repository:

```bash theme={null}
git clone https://github.com/inferless/voxtral-mini-3b.git
```

### Deploy the Model

To deploy the model using Inferless CLI, execute the following command:

```bash theme={null}
inferless deploy --gpu A10 --runtime inferless-runtime-config.yaml
```

**Explanation of the Command:**

* `--gpu A10`: Specifies the GPU type for deployment. Available options include `A10`, `A100`, and `T4`.
* `--runtime inferless-runtime-config.yaml`: Defines the runtime configuration file. If not specified, the default Inferless runtime is used.
