# Mistral 3

[Mistral 3](https://mistral.ai/news/mistral-small-3) 是一款针对延迟进行优化的模型，其层数大幅减少，从而降低了每次前向传播的耗时。该模型新增了视觉理解能力，并支持长达 128K 个 token 的长上下文，且不会牺牲性能。

您可以在 [Mistral AI](https://huggingface.co/mistralai/models?search=mistral-small-3) 组织下找到原始的 Mistral 3 检查点。

> [!TIP]
> 该模型由 [cyrilvallez](https://huggingface.co/cyrilvallez) 和 [yonigozlan](https://huggingface.co/yonigozlan) 贡献。点击右侧边栏中的 Mistral3 模型，以查看更多将 Mistral3 应用于不同任务的示例。
>
> 在 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 中设置 `use_kernels=True`，即可用 Hub 上的优化内核替换受支持的层。有关详细信息，请参阅 [加载内核](../kernel_doc/loading_kernels)。

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 和 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类为图像生成文本。

```python
from transformers import pipeline

messages = [
    {"role": "user",
        "content":[
            {"type": "image",
            "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",},
            {"type": "text", "text": "Describe this image."}
        ,]
    ,}
,]

pipeline = pipeline(
    task="image-text-to-text",
    model="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
    device=0
)
outputs = pipeline(text=messages, max_new_tokens=50, return_full_text=False)

outputs[0]["generated_text"]
'The image depicts a vibrant and lush garden scene featuring a variety of wildflowers and plants. The central focus is on a large, pinkish-purple flower, likely a Greater Celandine (Chelidonium majus), with a'
```

```python
from transformers import AutoModelForImageTextToText, AutoProcessor

model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
processor = AutoProcessor.from_pretrained(model_checkpoint)
model = AutoModelForImageTextToText.from_pretrained(
    model_checkpoint,
    device_map="auto",
)

messages = [
    {"role": "user",
        "content":[
            {"type": "image",
            "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",},
            {"type": "text", "text": "Describe this image."}
        ,]
    ,}
,]

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True, return_dict=True,
    return_tensors="pt").to(model.device)

generate_ids = model.generate(**inputs, max_new_tokens=20)
decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)

decoded_output
'The image depicts a vibrant and lush garden scene featuring a variety of wildflowers and plants. The central focus is on a large, pinkish-purple flower, likely a Greater Celandine (Chelidonium majus), with a'
```

## 备注

- Mistral 3 支持纯文本生成。

```py
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText

model_checkpoint = ".mistralai/Mistral-Small-3.1-24B-Instruct-2503"
processor = AutoProcessor.from_pretrained(model_checkpoint)
model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map="auto")

SYSTEM_PROMPT = "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat."
user_prompt = "Give me 5 non-formal ways to say 'See you later' in French."

messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": user_prompt},
]

text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(text=text, return_tensors="pt").to(0)
generate_ids = model.generate(**inputs, max_new_tokens=50, do_sample=False)
decoded_output = processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)[0]

print(decoded_output)
"1. À plus tard!
 2. Salut, à plus!
 3. À toute!
 4. À la prochaine!
 5. Je me casse, à plus!

```

 /\_/\
( o.o )
 > ^ <

```"
````

- Mistral 3 支持批量图像和文本输入。

```py
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText

model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
processor = AutoProcessor.from_pretrained(model_checkpoint)
model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map="auto")

messages = [
     [
         {
             "role": "user",
             "content": [
                 {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/llava_view.jpg"},
                 {"type": "text", "text": "Write a haiku for this image"},
             ],
         },
     ],
     [
         {
             "role": "user",
             "content": [
                 {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
                 {"type": "text", "text": "Describe this image"},
             ],
         },
     ],
 ]

 inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device)

 output = model.generate(**inputs, max_new_tokens=25)

 decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
 decoded_outputs
["Write a haiku for this imageCalm waters reflect\nWhispers of the forest's breath\nPeace on wooden path"
, "Describe this imageThe image depicts a vibrant street scene in what appears to be a Chinatown district. The focal point is a traditional Chinese"]
```

- Mistral 3 还支持批量处理图像和文本输入，且每段文本对应的图像数量可以不同。下面的示例使用 bitsandbytes 对模型进行量化。

```py
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig

model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
processor = AutoProcessor.from_pretrained(model_checkpoint)
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModelForImageTextToText.from_pretrained(
     model_checkpoint, quantization_config=quantization_config
 device_map="auto")

messages = [
     [
         {
             "role": "user",
             "content": [
                 {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/llava_view.jpg"},
                 {"type": "text", "text": "Write a haiku for this image"},
             ],
         },
     ],
     [
         {
             "role": "user",
             "content": [
                 {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/statue_of_liberty.jpg"},
                 {"type": "image", "url": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/dreamstime_golden_gate_flowers.jpg"},
                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"},
             ],
         },
     ],
 ]

 inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device)

 output = model.generate(**inputs, max_new_tokens=25)

 decoded_outputs = processor.batch_decode(output, skip_special_tokens=True)
 decoded_outputs
["Write a haiku for this imageSure, here is a haiku inspired by the image:\n\nCalm lake's wooden path\nSilent forest stands guard\n", "These images depict two different landmarks. Can you identify them? Certainly! The images depict two iconic landmarks:\n\n1. The first image shows the Statue of Liberty in New York City."]
```

## Mistral3Config[[transformers.Mistral3Config]]

#### transformers.Mistral3Config[[transformers.Mistral3Config]]

```python
transformers.Mistral3Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_index: int = 10, projector_hidden_act: str = 'gelu', vision_feature_layer: int | list[int] = -1, multimodal_projector_bias: bool = False, spatial_merge_size: int = 2, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/configuration_mistral3.py#L26)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

image_token_index (`int`，*可选*，默认为 `10`)：用作输入图像占位符的图像标记索引。

projector_hidden_act (`str`，*可选*，默认为 `gelu`)：多模态投影器所使用的激活函数。

vision_feature_layer (`Union[int, list[int]]`，*可选*，默认值为 `-1`)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

multimodal_projector_bias (`bool`, *可选*, 默认为 `False`) : 是否在多模态投影器中使用偏置。

spatial_merge_size (`int`, *可选*，默认为 `2`)：用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Mistral3Model 配置的类。它根据指定的参数实例化 Mistral3 模型，并定义模型架构。使用默认值实例化配置将得到与 [mistralai/Mistral-Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import Mistral3ForConditionalGeneration, Mistral3Config, PixtralVisionConfig, MistralConfig

>>> # Initializing a Pixtral-vision config
>>> vision_config = PixtralVisionConfig()

>>> # Initializing a Mistral config
>>> text_config = MistralConfig()

>>> # Initializing a Mistral3 configuration
>>> configuration = Mistral3Config(vision_config, text_config)

>>> # Initializing a model from the mistral3.1 configuration
>>> model = Mistral3ForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## MistralCommonBackend[[transformers.MistralCommonBackend]]

#### transformers.MistralCommonBackend[[transformers.MistralCommonBackend]]

```python
transformers.MistralCommonBackend(tokenizer_path: str | os.PathLike | pathlib.Path, mode: str | ValidationMode = 'test', model_max_length: int = 1000000000000000019884624838656, padding_side: str = 'left', truncation_side: str = 'right', model_input_names: list[str] | None = None, clean_up_tokenization_spaces: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L194)

用于封装 `mistral-common` 分词器的类。

`mistral-common` 是 Mistral AI 模型的官方分词器库。要使用它，您需要通过以下方式安装：

```bash
pip install transformers[mistral-common]
```

否则，分词器将回退到 Transformers 的分词器实现。

有关 `mistral-common` 的更多信息，请参阅 [mistral-common](https://github.com/mistralai/mistral-common)。

此类是 `mistral_common.tokens.tokenizers.mistral.MistralTokenizer` 的封装。它提供了一个兼容 Hugging Face 的接口，用于使用官方的 mistral-common 分词器进行分词，并继承自 `PreTrainedTokenizerBase` 类。

以下是与 `PythonBackend` 类的主要行为差异：

- 不支持序列对。为了保持兼容性，保留了该签名，但所有与序列对相关的参数均会被忽略。序列对的返回值将返回为 `None`。
- 不支持 `is_split_into_words` 参数。
- 无法向分词器添加新 token。与 Transformers 不同，特殊 token 的处理方式有所区别。在 `mistral-common` 中，特殊 token 永远不会被直接编码。这意味着：`tokenizer.encode("<s>")` 不会返回 `<s>` token 的 ID，而是返回一个 ID 列表，对应于字符串 `"<s>"` 的分词结果。更多信息请参阅 [mistral-common 文档](https://mistralai.github.io/mistral-common/usage/tokenizers/#special-tokens)。

如果您有改进此类的建议，请根据问题类型在相应的 GitHub 仓库中提交 issue：若与 tokenizer 相关，请在 [mistral-common GitHub 仓库](https://github.com/mistralai/mistral-common/issues) 中提交；若与 Hugging Face 接口相关，请在 [Transformers GitHub 仓库](https://github.com/huggingface/transformers/issues) 中提交。

#### add_special_tokens[[transformers.MistralCommonBackend.add_special_tokens]]

```python
add_special_tokens(special_tokens_dict: dict, replace_extra_special_tokens: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1679)

`MistralCommonBackend` 在设计上未实现 `add_special_tokens`。

如果您希望实现此行为，请在 `Transformers` 或 `mistral-common` 仓库中提交 issue 以提出请求。

#### add_tokens[[transformers.MistralCommonBackend.add_tokens]]

```python
add_tokens(special_tokens_dict: dict, replace_extra_special_tokens: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1691)

`MistralCommonBackend` 在设计上未实现 `add_special_tokens`。

如果您希望实现此行为，请在 `Transformers` 或 `mistral-common` 仓库中提交 issue 以提出请求。

#### apply_chat_template[[transformers.MistralCommonBackend.apply_chat_template]]

```python
apply_chat_template(conversation: list[dict[str, str]] | list[list[dict[str, str]]], tools: list[dict | collections.abc.Callable] | None = None, add_generation_prompt: bool = False, continue_final_message: bool = False, tokenize: bool = True, padding: bool | str | transformers.utils.generic.PaddingStrategy = False, truncation: bool = False, max_length: int | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_dict: bool = True, reasoning_effort: ReasoningEffort | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1038)

**参数：**

conversation (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]) : 一个包含 "role" 和 "content" 键的字典列表，表示迄今为止的聊天历史记录。

tools (`List[Union[Dict, Callable]]`，*可选*)：一个工具（可调用函数）列表，模型可以访问这些工具。如果模板不支持函数调用，此参数将不起作用。每个工具应以 JSON Schema 的形式传入，提供工具的名称、描述和参数类型。有关更多信息，请参阅我们的[聊天模板指南](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)。

add_generation_prompt (`bool`，*可选*)：此参数对 `MistralCommonBackend` 无效。但为了保持 API 的一致性，它不能与 `continue_final_message` 同时使用。如果任何对话以助手消息结尾，则会引发错误。在这种情况下，请改用 `continue_final_message`。

continue_final_message (bool, *optional*) : 如果设置此项，聊天将被格式化，使得聊天中的最后一条消息是开放式的，不包含任何 EOS 标记。模型将继续该消息，而不是开始一条新消息。这允许您“预填充”模型响应的一部分。不能与 `add_generation_prompt` 同时使用。

tokenize (`bool`，默认为 `True`)：是否对输出进行分词。如果为 `False`，输出将是一个字符串。

padding (`bool`、`str` 或 [PaddingStrategy](/docs/transformers/main/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：选择一种策略来填充返回的序列（根据模型的填充方向和填充索引），可选策略如下： - `True` 或 `'longest'`：填充到批次中最长的序列（如果只提供了单个序列，则不进行填充）。 - `'max_length'`：填充到由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充到模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认）：不进行填充（即可以输出包含不同长度序列的批次）。

truncation (`bool`，默认为 `False`)：是否在最大长度处截断序列。如果 tokenize 为 `False`，则此参数无效。

max_length (`int`, *可选*) : 用于填充或截断的最大长度（以 token 计）。如果 tokenize 为 `False`，则此参数无效。如果未指定，将使用分词器的 `max_length` 属性作为默认值。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*) : 如果设置，将返回特定框架的张量。如果 tokenize 为 `False`，则无效。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。

return_dict (`bool`，默认为 `False`) : 是否返回包含命名输出的字典。如果 tokenize 为 `False`，则此参数无效。如果至少一个对话包含图像，其像素值将返回在 `pixel_values` 键中，图像尺寸将返回在 `image_sizes` 键中。

reasoning_effort (`ReasoningEffort`, *可选*) : 对于支持推理的模型，用于聊天补全的推理力度。可能的值包括： - `ReasoningEffort.none`：模型不进行推理。 - `ReasoningEffort.high`：模型将采用推理方式。如果未指定，则使用默认的推理力度。

kwargs （额外的关键字参数，*可选*）：传递给 mistral-common `ChatCompletionRequest.from_openai` 方法的额外参数。

**返回：** `Union[str, list[int], list[str], list[list[int]], BatchEncoding]`

到目前为止的已分词聊天内容，包括控制标记。此输出已准备好传递给模型，可以直接传递，也可以通过 `generate()` 等方法进行传递。

将包含 `"role"` 和 `"content"` 键的字典列表转换为 token id 列表。

#### batch_decode[[transformers.MistralCommonBackend.batch_decode]]

```python
batch_decode(sequences: typing.Union[list[int], list[list[int]], numpy.ndarray, ForwardRef('torch.Tensor')], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L512)

**参数：**

sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`) : 标记化输入 ID 的列表。可通过 `__call__` 方法获取。

skip_special_tokens (`bool`，*可选*，默认为 `False`)：是否在解码过程中移除特殊标记。

clean_up_tokenization_spaces (`bool`，*可选*)：是否清理分词空格。如果为 `None`，则默认为 `self.clean_up_tokenization_spaces`。

kwargs （额外的关键字参数，*可选*）：`MistralCommonBackend.batch_decode` 不支持。如果使用该参数，将引发错误。

**返回：** `list[str]`

解码后的句子列表。

通过调用 decode，将 token id 的列表的列表转换为字符串列表。

此方法是为了向后兼容而提供的。`decode` 方法现在原生支持批量输入，因此您可以直接使用 `decode` 而无需使用 `batch_decode`。

#### build_inputs_with_special_tokens[[transformers.MistralCommonBackend.build_inputs_with_special_tokens]]

```python
build_inputs_with_special_tokens(token_ids_0: list, token_ids_1: None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1284)

**参数：**

token_ids_0 (`list[int]`) : 将添加特殊标记的 ID 列表。

token_ids_1 (`None`, *可选*) : None，保留以匹配 Transformers 的签名。

**返回：** `list[int]`

包含相应特殊标记的输入 ID 列表。

通过添加特殊标记，从序列构建模型输入。

此方法会根据分词器的`mode`动态构建输入：
- `"test"`：seq0 [EOS]
- `"finetuning"`：[BOS] seq0

#### convert_added_tokens[[transformers.MistralCommonBackend.convert_added_tokens]]

```python
convert_added_tokens(obj: tokenizers.AddedToken | typing.Any, save: bool = False, add_type_field: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1704)

`MistralCommonBackend` 在设计上未实现 `convert_added_tokens`。

如果您希望实现此行为，请在 `Transformers` 或 `mistral-common` 仓库中提交 issue 以提出请求。

#### create_token_type_ids_from_sequences[[transformers.MistralCommonBackend.create_token_type_ids_from_sequences]]

```python
create_token_type_ids_from_sequences(token_ids_0: list, token_ids_1: None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1313)

**参数：**

token_ids_0 (`list[int]`) : ID 列表。

token_ids_1 (`None`, *可选*) : None，保留以匹配 Transformers 的签名。

**返回：** `list[int]`

根据配置的模式生成的 Token 类型 ID。

使用添加了特殊标记的标记 ID 创建一个全零掩码。

保留以匹配 Transformers 的实现。

#### decode[[transformers.MistralCommonBackend.decode]]

```python
decode(token_ids: typing.Union[int, list[int], list[list[int]], numpy.ndarray, ForwardRef('torch.Tensor')], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L475)

**参数：**

token_ids (`Union[int, list[int], list[list[int]], np.ndarray, torch.Tensor]`) : 单个序列或一批（序列列表）的标记化输入 ID。可通过 `__call__` 方法获取。

skip_special_tokens (`bool`，*可选*，默认为 `False`)：是否在解码过程中移除特殊标记。

clean_up_tokenization_spaces (`bool`，*可选*)：是否清理分词空格。如果为 `None`，则默认为 `self.clean_up_tokenization_spaces`。

kwargs （额外的关键字参数，*可选*）：`MistralCommonBackend.decode` 不支持。如果使用该参数，将引发错误。

**返回：** `Union[str, list[str]]`

单个序列的解码字符串，或一批序列的解码字符串列表。

使用分词器和词汇表将字符串中的 id 序列进行转换，并可选择移除特殊标记以及清理分词空格。

#### encode[[transformers.MistralCommonBackend.encode]]

```python
encode(text: str | list[int], text_pair: None = None, add_special_tokens: bool = True, padding: bool | str | transformers.utils.generic.PaddingStrategy = False, truncation: bool | str | transformers.tokenization_utils_base.TruncationStrategy | None = None, max_length: int | None = None, stride: int = 0, pad_to_multiple_of: int | None = None, padding_side: str | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, verbose: bool = True, return_offsets_mapping: typing.Literal[False] = False, split_special_tokens: typing.Literal[False] = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L378)

**参数：**

text (`str` 或 `list[int]`) : 要编码的第一个序列。它可以是一个字符串或一个整数列表（分词后的字符串 ID）。

text_pair (`None`, *可选*) : `MistralCommonBackend.encode` 不支持此参数。保留该参数以匹配 `PreTrainedTokenizerBase.encode` 的签名。

add_special_tokens (`bool`，*可选*，默认为 `True`)：在编码序列时是否添加特殊标记。这将使用底层的 `PretrainedTokenizerBase.build_inputs_with_special_tokens` 函数，该函数定义了哪些标记会自动添加到输入 id 中。如果您希望自动添加 `bos` 或 `eos` 标记，此参数非常有用。当 Tokenizer 以 `finetuning` 模式加载时，它会同时添加 `bos` 和 `eos`。否则，在“test”模式下，它仅添加 `bos`。

padding (`bool`、`str` 或 [PaddingStrategy](/docs/transformers/main/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：启用并控制填充。接受以下值： - `True` 或 `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`：填充至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认值）：不进行填充（即，可以输出包含不同长度序列的批次）。

truncation (`bool`、`str` 或 [TruncationStrategy](/docs/transformers/main/zh/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)，*optional*，默认为 `False`)：启用并控制截断。接受以下值： - `True` 或 `'longest_first'`：截断至参数 `max_length` 指定的最大长度，或者在未提供该参数时，截断至模型可接受的最大输入长度。 - `False` 或 `'do_not_truncate'`（默认）：不截断（即，可以输出序列长度大于模型最大可接受输入大小的批次）。

max_length (`int`, *可选*) : 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 `None`，当截断/填充参数需要最大长度时，将使用预定义的最大模型长度。如果模型没有特定的最大输入长度（例如 XLNet），则禁用截断/填充至最大长度的功能。

stride (`int`，*可选*，默认为 0)：如果与 `max_length` 一起设置为某个数值，则当 `return_overflowing_tokens=True` 时，返回的溢出 token 将包含来自截断序列末尾的若干 token，以在截断序列和溢出序列之间提供一定的重叠。该参数的值定义了重叠 token 的数量。

pad_to_multiple_of (`int`，*可选*)：如果设置，则将序列填充为所提供值的倍数。需要启用 `padding`。这对于在计算能力 `>= 7.5`（Volta）的 NVIDIA 硬件上启用 Tensor Cores 的使用特别有用。

padding_side (`str`, *可选*) : 模型应应用填充的一侧。应在 ['right', 'left'] 中进行选择。默认值取自同名的类属性。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回张量而不是 Python 整数列表。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。

- ****kwargs** : `MistralCommonBackend.encode` 不支持。如果使用该参数，将引发错误。

**返回：** `list[int]`，`torch.Tensor`

文本的标记化 ID。

使用分词器和词汇表将字符串转换为 id（整数）序列。

#### from_pretrained[[transformers.MistralCommonBackend.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, *init_inputs, mode: str | ValidationMode = 'test', cache_dir: str | os.PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = 'main', model_max_length: int = 1000000000000000019884624838656, padding_side: str = 'left', truncation_side: str = 'right', model_input_names: list[str] | None = None, clean_up_tokenization_spaces: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1437)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`) : 可以是以下之一： - 一个字符串，即托管在 huggingface.co 上某个模型仓库中的预定义分词器的 *model id*。 - 一个指向包含分词器配置的 *目录* 的路径，例如使用 `MistralCommonBackend.tokenization_mistral_common.save_pretrained` 方法保存的目录，如 `./my_model_directory/`。

mode (`Union[str, ValidationMode]`，*可选*，默认为 `ValidationMode.test`)：`MistralTokenizer` 分词器的验证模式。可能的值包括：- `"finetuning"` 或 `ValidationMode.finetuning`：微调模式。- `"test"` 或 `ValidationMode.test`：测试模式。它会改变分词器验证输入并准备发往模型的请求的方式。

cache_dir (`str` 或 `os.PathLike`，*可选*)：如果不应使用标准缓存，则下载预定义分词器词汇文件时应缓存到的目录路径。

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载词汇表文件，并在存在缓存版本时覆盖它们。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP bearer 授权令牌。如果为 `True`，将使用运行 `hf auth login` 时生成的令牌（存储在 `~/.huggingface` 中）。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅依赖本地文件，而不尝试下载任何文件。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。由于我们在 huggingface.co 上使用基于 git 的系统来存储模型和其他工件，因此它可以是分支名称、标签名称或提交 id，`revision` 可以是 git 允许的任何标识符。

max_length (`int`, *可选*) : 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 `None`，当截断/填充参数需要最大长度时，将使用预定义的最大模型长度。如果模型没有特定的最大输入长度（例如 XLNet），则禁用截断/填充至最大长度的功能。

padding_side (`str`, *可选*, 默认为 `"left"`) : 模型应应用填充的一侧。应在 ['right', 'left'] 之间选择。默认值取自同名的类属性。

truncation_side (`str`，*可选*，默认为 `"right"`)：模型应应用截断的一侧。应在 ['right', 'left'] 中进行选择。

model_input_names (`List[str]`, *可选*) : 模型前向传播接受的输入列表（例如 `"token_type_ids"` 或 `"attention_mask"`）。默认值取自同名的类属性。

clean_up_tokenization_spaces (`bool`，*可选*，默认为 `False`)：模型是否应清理在分词过程中对输入文本进行拆分时所添加的空格。

kwargs （额外的关键字参数，*可选*）：`MistralCommonBackend.from_pretrained` 不支持。如果使用该参数，将引发错误。

从预定义的 tokenizer 实例化一个 `MistralCommonBackend`。

#### get_chat_template[[transformers.MistralCommonBackend.get_chat_template]]

```python
get_chat_template(chat_template: str | None = None, tools: list[dict] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1713)

`MistralCommonBackend` 出于设计考虑未实现 `get_chat_template`，因为 `mistral-common` 不使用聊天模板。

#### get_special_tokens_mask[[transformers.MistralCommonBackend.get_special_tokens_mask]]

```python
get_special_tokens_mask(token_ids_0: list, token_ids_1: None = None, already_has_special_tokens: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L691)

**参数：**

token_ids_0 (`list[int]`) : 序列的 id 列表。

token_ids_1 (`None`, *可选*) : None，保留以匹配 Transformers 的实现。

already_has_special_tokens (`bool`，*可选*，默认为 `False`)：标记列表是否已使用模型的特殊标记进行格式化。

**返回：** 一个包含 [0, 1] 范围内整数的列表

1 表示特殊标记，0 表示序列标记。

从未添加特殊标记的标记列表中获取序列 ID。当使用分词器的 `prepare_for_model` 或 `encode_plus` 方法添加特殊标记时，会调用此方法。

#### get_vocab[[transformers.MistralCommonBackend.get_vocab]]

```python
get_vocab()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L352)

**返回：** `Dict[str, int]`

词汇表。

返回一个从 token 到索引的字典形式的词汇表。

这是一次有损转换。由于部分 UTF-8 字节序列被转换为 �，可能会有多个 token id 解码为相同的字符串。

#### num_special_tokens_to_add[[transformers.MistralCommonBackend.num_special_tokens_to_add]]

```python
num_special_tokens_to_add(pair: typing.Literal[False] = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1337)

**参数：**

pair (`Literal[False]`，*可选*)：False，保留以匹配 Transformer 的签名。

**返回：** `int`

添加到序列中的特殊标记数量。

在编码包含特殊标记的序列时，返回所添加标记的数量。

这会编码一个虚拟输入并检查新增的 token 数量，因此效率不高。请勿将其放入训练循环中。

#### prepare_for_model[[transformers.MistralCommonBackend.prepare_for_model]]

```python
prepare_for_model(ids: list, pair_ids: None = None, add_special_tokens: bool = True, padding: bool | str | transformers.utils.generic.PaddingStrategy = False, truncation: bool | str | transformers.tokenization_utils_base.TruncationStrategy | None = None, max_length: int | None = None, stride: int = 0, pad_to_multiple_of: int | None = None, padding_side: str | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_token_type_ids: bool | None = None, return_attention_mask: bool | None = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_length: bool = False, verbose: bool = True, prepend_batch_axis: bool = False, return_offsets_mapping: typing.Literal[False] = False, split_special_tokens: typing.Literal[False] = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L844)

**参数：**

ids (`list[int]`) : 第一个序列的标记化输入 ID。

pair_ids (`None`, *可选*) : `MistralCommonBackend` 不支持此参数。保留该参数以匹配 `PreTrainedTokenizerBase` 的接口。

add_special_tokens (`bool`，*可选*，默认为 `True`)：在编码序列时是否添加特殊标记。这将使用底层的 `PretrainedTokenizerBase.build_inputs_with_special_tokens` 函数，该函数定义了哪些标记会自动添加到输入 id 中。如果您希望自动添加 `bos` 或 `eos` 标记，此参数非常有用。当 Tokenizer 以 `finetuning` 模式加载时，它会同时添加 `bos` 和 `eos`。否则，在“test”模式下，它仅添加 `bos`。

padding (`bool`、`str` 或 [PaddingStrategy](/docs/transformers/main/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：启用并控制填充。接受以下值： - `True` 或 `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`：填充至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认值）：不进行填充（即，可以输出包含不同长度序列的批次）。

truncation (`bool`、`str` 或 [TruncationStrategy](/docs/transformers/main/zh/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)，*optional*，默认为 `False`)：启用并控制截断。接受以下值： - `True` 或 `'longest_first'`：截断至参数 `max_length` 指定的最大长度，或者在未提供该参数时，截断至模型可接受的最大输入长度。 - `False` 或 `'do_not_truncate'`（默认）：不截断（即，可以输出序列长度大于模型最大可接受输入大小的批次）。

max_length (`int`, *可选*) : 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 `None`，当截断/填充参数需要最大长度时，将使用预定义的最大模型长度。如果模型没有特定的最大输入长度（例如 XLNet），则禁用截断/填充至最大长度的功能。

stride (`int`，*可选*，默认为 0)：如果与 `max_length` 一起设置为某个数值，则当 `return_overflowing_tokens=True` 时，返回的溢出 token 将包含来自截断序列末尾的若干 token，以在截断序列和溢出序列之间提供一定的重叠。该参数的值定义了重叠 token 的数量。

pad_to_multiple_of (`int`，*可选*)：如果设置，则将序列填充为所提供值的倍数。需要启用 `padding`。这对于在计算能力 `>= 7.5`（Volta）的 NVIDIA 硬件上启用 Tensor Cores 的使用特别有用。

padding_side (`str`, *可选*) : 模型应应用填充的一侧。应在 ['right', 'left'] 中进行选择。默认值取自同名的类属性。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回张量而不是 Python 整数列表。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。

return_token_type_ids (`bool`, *可选*) : 是否返回 token 类型 ID。对于 `MistralCommonBackend`，由于仅支持单个序列，因此返回一个长度等于序列长度的全零列表。  [什么是 token 类型 ID？](../glossary#token-type-ids)

return_attention_mask (`bool`，*可选*)：是否返回注意力掩码。如果保持默认值，将根据特定分词器的默认设置返回注意力掩码，该设置由 `return_outputs` 属性定义。[什么是注意力掩码？](../glossary#attention-mask)

return_overflowing_tokens (`bool`，*可选*，默认为 `False`)：是否返回溢出的 token 序列。如果提供了输入 id 的序列对（或序列对的批次），并且 `truncation_strategy = longest_first` 或 `True`，则会引发错误，而不是返回溢出的 token。

return_special_tokens_mask (`bool`，*可选*，默认为 `False`)：是否返回特殊标记掩码信息。

return_length (`bool`，*可选*，默认为 `False`)：是否返回编码后输入的长度。

verbose (`bool`，*可选*，默认为 `True`)：是否打印更多信息和警告。

return_offsets_mapping (`Literal[False]`，*可选*)：False，保留以匹配 Transformers 的签名。

split_special_tokens (`Literal[False]`，*可选*)：False，保留以匹配 Transformers 的签名。

- ****kwargs** : 传递给 `self.tokenize()` 方法

**返回：** [BatchEncoding](/docs/transformers/main/zh/main_classes/tokenizer#transformers.BatchEncoding)

一个包含以下字段的 [BatchEncoding](/docs/transformers/main/zh/main_classes/tokenizer#transformers.BatchEncoding)：

- **input_ids** -- 输入模型的 token id 列表。

  [什么是输入 ID？](../glossary#input-ids)

- **attention_mask** -- 指定模型应关注哪些 token 的索引列表（当 `return_attention_mask=True` 或 *"attention_mask"* 位于 `self.model_input_names` 中时）。

  [什么是注意力掩码？](../glossary#attention-mask)

- **overflowing_tokens** -- 溢出 token 序列的列表（当指定了 `max_length` 且 `return_overflowing_tokens=True` 时）。
- **num_truncated_tokens** -- 被截断的 token 数量（当指定了 `max_length` 且 `return_overflowing_tokens=True` 时）。
- **special_tokens_mask** -- 由 0 和 1 组成的列表，其中 1 表示添加的特殊标记，0 表示常规序列标记（当 `add_special_tokens=True` 且 `return_special_tokens_mask=True` 时）。
- **length** -- 输入的长度（当 `return_length=True` 时）

准备输入 ID 序列，以便模型可以使用。它会添加特殊标记，在序列溢出时进行截断（同时考虑特殊标记），并为溢出的标记管理一个移动窗口（具有用户定义的步长）。

#### save_chat_templates[[transformers.MistralCommonBackend.save_chat_templates]]

```python
save_chat_templates(save_directory: str | os.PathLike, tokenizer_config: dict, filename_prefix: str | None, save_jinja_files: bool)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1718)

`MistralCommonBackend` 出于设计考虑未实现 `save_chat_templates`，因为 `mistral-common` 不使用聊天模板。

#### save_pretrained[[transformers.MistralCommonBackend.save_pretrained]]

```python
save_pretrained(save_directory: str | os.PathLike | pathlib.Path, push_to_hub: bool = False, token: str | bool | None = None, commit_message: str | None = None, repo_id: str | None = None, private: bool | None = None, save_format: str | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1552)

**参数：**

save_directory (`str | os.PathLike | Path`) : 保存分词器的目录。

push_to_hub (`bool`, *可选*, 默认为 `False`) : 保存后推送到 HF Hub。

token (`str` 或 `bool`，*可选*)：用于 Hub 身份验证的令牌。

commit_message (`str`, *可选*) : 推送时的提交信息。

repo_id (`str`, *可选*) : Hub 仓库 ID。

private (`bool`, *可选*) : 该仓库是否为私有。

save_format (`str`, *可选*) : `"mistral"` 用于保存原生 tekken 格式，`"hf"` 用于 HuggingFace 格式。  *None* 保留原始格式。

kwargs (`dict`, *可选*) : 不支持 — 将引发错误。

**返回：** `tuple[str, ...]`

已保存文件的路径。

保存完整的分词器状态。

当 `save_format` 为 `"mistral"`（对于 tekken 分词器则为 *None*）时，原始分词器文件（例如 `tekken.json`）将被写入 *save_directory*。当 `save_format` 为 `"hf"` 时，则会生成 HF 格式的文件（`tokenizer.json` + `tokenizer_config.json`）。

#### save_vocabulary[[transformers.MistralCommonBackend.save_vocabulary]]

```python
save_vocabulary(save_directory: str, filename_prefix: str | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L1729)

`MistralCommonBackend` 在设计上未实现 `save_vocabulary`。

这是因为 `mistral-common` 由一个分词器文件进行配置。如果您希望保存词汇表，请考虑改用 `save_pretrained` 方法。

#### tokenize[[transformers.MistralCommonBackend.tokenize]]

```python
tokenize(text: str, return_offsets_mapping: typing.Literal[False] = False, split_special_tokens: typing.Literal[False] = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L645)

**参数：**

text (`str`) : 要编码的序列。

return_offsets_mapping (`Literal[False]`，*可选*)：False，保留以匹配 Transformers 的签名。

split_special_tokens (`Literal[False]`，*可选*)：False，保留以匹配 Transformers 的签名。

- ****kwargs**（额外的关键字参数）：`MistralCommonBackend.tokenize` 不支持。如果使用该参数，将引发错误。

**返回：** `list[str]`

令牌列表。

使用分词器将字符串转换为标记序列。

对于基于单词的词汇表，按单词进行拆分；对于基于子词的词汇表，按子词进行拆分。

#### truncate_sequences[[transformers.MistralCommonBackend.truncate_sequences]]

```python
truncate_sequences(ids: list, pair_ids: None = None, num_tokens_to_remove: int = 0, truncation_strategy: str | transformers.tokenization_utils_base.TruncationStrategy = 'longest_first', stride: int = 0, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_mistral_common.py#L974)

**参数：**

ids (`list[int]`) : 标记化后的输入 ID。可以通过链接调用 `tokenize` 和 `convert_tokens_to_ids` 方法从字符串中获取。

pair_ids (`None`, *可选*) : `MistralCommonBackend` 不支持此参数。保留该参数以匹配 `PreTrainedTokenizerBase.truncate_sequences` 的签名。

num_tokens_to_remove (`int`，*可选*，默认为 0)：使用截断策略移除的 token 数量。

truncation_strategy (`str` 或 [TruncationStrategy](/docs/transformers/main/zh/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)，*可选*，默认为 `'longest_first'`)：截断所遵循的策略。可以是： - `'longest_first'`：截断至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则截断至模型可接受的最大输入长度。 - `'do_not_truncate'`（默认）：不截断（即，可以输出序列长度大于模型最大可接受输入大小的批次）。

stride (`int`，*可选*，默认为 0)：如果设置为正数，则返回的溢出 token 将包含主序列返回中的一些 token。此参数的值定义了额外 token 的数量。

**返回：** `Tuple[list[int], None, list[int]]`

截断后的 `ids` 以及溢出 token 的列表。为了与 Transformers 的签名保持一致，返回 `None`。

按照策略就地截断序列对。

## Mistral3Model[[transformers.Mistral3Model]]

#### transformers.Mistral3Model[[transformers.Mistral3Model]]

```python
transformers.Mistral3Model(config: Mistral3Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L199)

**参数：**

config ([Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Mistral3 模型由视觉骨干网络和语言模型组成，不包含语言建模头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Mistral3Model.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, vision_feature_layer: int | list[int] | None = None, use_cache: bool | None = None, image_sizes: typing.Optional[torch.Tensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L269)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.FloatTensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 获取像素值。有关详细信息，请参阅 [PixtralImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[PixtralProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralProcessor) 使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 处理图像）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.FloatTensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`，*可选*)：批次中图像的尺寸，每张图像为 (height, width)。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `Mistral3ModelOutputWithPast` 或 `tuple(torch.FloatTensor)`

`Mistral3ModelOutputWithPast` 或 `torch.FloatTensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config)）和输入。

[Mistral3Model](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Model) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions**（`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）—— 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **image_hidden_states** (`torch.FloatTensor`，*可选*) -- 一个尺寸为 `(batch_size, num_images, sequence_length, hidden_size)` 的 `torch.FloatTensor`。由视觉编码器生成的模型 image_hidden_states，并在投影最后一个隐藏状态之后得到。

#### get_image_features[[transformers.Mistral3Model.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, image_sizes: Tensor, vision_feature_layer: int | list[int] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L208)

**参数：**

pixel_values (`torch.FloatTensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 获取像素值。有关详细信息，请参阅 [PixtralImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[PixtralProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralProcessor) 使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 处理图像）。

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`)：批次中图像的尺寸，每张图像为 (height, width)。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.FloatTensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.FloatTensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config)）和输入。

从视觉塔获取图像的最后隐藏状态，并应用多模态投影。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.FloatTensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测（分类）目标进行训练。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions**（`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）—— 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

#### get_placeholder_mask[[transformers.Mistral3Model.get_placeholder_mask]]

```python
get_placeholder_mask(input_ids: LongTensor, inputs_embeds: FloatTensor, image_features: FloatTensor)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L245)

从 `input_ids` 或 `inputs_embeds` 中获取多模态占位符掩码，并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致，则会引发错误。

## Mistral3ForConditionalGeneration[[transformers.Mistral3ForConditionalGeneration]]

#### transformers.Mistral3ForConditionalGeneration[[transformers.Mistral3ForConditionalGeneration]]

```python
transformers.Mistral3ForConditionalGeneration(config: Mistral3Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L336)

**参数：**

config ([Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由视觉骨干网络和语言模型组成的 MISTRAL3 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.Mistral3ForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, image_sizes: typing.Optional[torch.Tensor] = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L366)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.FloatTensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 获取像素值。有关详细信息，请参阅 [PixtralImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[PixtralProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralProcessor) 使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 处理图像）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.FloatTensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`，*可选*)：批次中图像的尺寸，每张图像为 (height, width)。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `Mistral3CausalLMOutputWithPast` 或 `tuple(torch.FloatTensor)`

`Mistral3CausalLMOutputWithPast` 或 `torch.FloatTensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config)）和输入。

[Mistral3ForConditionalGeneration](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3ForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple[torch.FloatTensor]`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions**（`tuple[torch.FloatTensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）—— 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **image_hidden_states** (`torch.FloatTensor`，*可选*) -- 一个尺寸为 `(batch_size, num_images, sequence_length, hidden_size)` 的 `torch.FloatTensor`。由视觉编码器生成的模型 image_hidden_states，并在投影最后一个隐藏状态之后得到。

示例：

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration

>>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
>>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")

>>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=image, text=prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is the image?The image depicts two cats lying on a pink blanket."
```

#### get_image_features[[transformers.Mistral3ForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, image_sizes: Tensor, vision_feature_layer: int | list[int] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral3/modeling_mistral3.py#L349)

**参数：**

pixel_values (`torch.FloatTensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 获取像素值。有关详细信息，请参阅 [PixtralImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[PixtralProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralProcessor) 使用 [PixtralImageProcessor](/docs/transformers/main/zh/model_doc/pixtral#transformers.PixtralImageProcessor) 处理图像）。

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`)：批次中图像的尺寸，每张图像为 (height, width)。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.FloatTensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.FloatTensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Mistral3Config](/docs/transformers/main/zh/model_doc/mistral3#transformers.Mistral3Config)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.FloatTensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测（分类）目标进行训练。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions**（`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）—— 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration

>>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
>>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

