Transformers 文档

Mistral3

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

Mistral3

概述

Mistral Small 3 (2501) 的基础上,Mistral Small 3.1 (2503) 增加了最先进的视觉理解能力,并将长上下文能力增强至 128k tokens,而不会影响文本性能。这款模型拥有 240 亿参数,在文本和视觉任务中均实现了顶级的性能。

它非常适合用于:

  • 快速响应的对话代理。
  • 低延迟的函数调用。
  • 通过微调成为主题专家。
  • 供爱好者和处理敏感数据的组织进行本地推理。
  • 编程和数学推理。
  • 长文档理解。
  • 视觉理解。

此模型由 cyrilvallezyonigozlan 贡献。

原始代码可以在这里这里找到。

使用示例

使用 Pipeline 进行推理

以下是如何使用 image-text-to-text pipeline 在几行代码中对 Mistral3 模型执行推理的方法

>>> 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."},
...         ],
...     },
... ]

>>> pipe = pipeline("image-text-to-text", model="mistralai/Mistral-Small-3.1-24B-Instruct-2503", torch_dtype=torch.bfloat16)
>>> outputs = pipe(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'

对单张图像进行推理

此示例演示了如何使用聊天模板对 Mistral3 模型上的单张图像执行推理。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.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, dtype=torch.bfloat16)

>>> 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 two cats lying on a pink blanket. The larger cat, which appears to be an"...

纯文本生成

此示例展示了如何在不提供任何图像输入的情况下使用 Mistral3 模型生成文本。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = ".mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> 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, dtype=torch.float16)
>>> 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 )
 > ^ <
```"

批量图像和文本输入

Mistral3 模型也支持批量图像和文本输入。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> torch_device = "cuda"
>>> model_checkpoint = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16)

>>> messages = [
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/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, dtype=torch.bfloat16)

>>> 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"]

批量多图像输入以及使用 BitsAndBytes 进行量化

Mistral3 模型的此实现支持批量文本-图像输入,其中每个文本的图像数量不同。此示例还展示了如何使用 BitsAndBytes 以 4 位量化加载模型。

>>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
>>> import torch

>>> torch_device = "cuda"
>>> 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
... )

>>> messages = [
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"},
...                 {"type": "text", "text": "Write a haiku for this image"},
...             ],
...         },
...     ],
...     [
...         {
...             "role": "user",
...             "content": [
...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"},
...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.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, dtype=torch.bfloat16)

>>> 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

class transformers.Mistral3Config

< >

( vision_config = None text_config = None image_token_index = 10 projector_hidden_act = 'gelu' vision_feature_layer = -1 multimodal_projector_bias = False spatial_merge_size = 2 **kwargs )

参数

  • vision_config (Union[AutoConfig, dict], 可选, 默认为 PixtralVisionConfig) — 视觉骨干网络的配置对象或字典。
  • text_config (Union[AutoConfig, dict], 可选, 默认为 MistralConfig) — 文本骨干网络的配置对象或字典。
  • image_token_index (int, 可选, 默认为 10) — 用于编码图像提示的图像 token 索引。
  • projector_hidden_act (str, 可选, 默认为 "gelu") — 多模态投影器使用的激活函数。
  • vision_feature_layer (Union[int, List[int]], 可选, 默认为 -1) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。
  • multimodal_projector_bias (bool, 可选, 默认为 False) — 是否在多模态投影器中使用偏置。
  • spatial_merge_size (int, 可选, 默认为 2) — 空间合并操作的下采样因子。

这是用于存储 Mistral3ForConditionalGeneration 配置的配置类。它用于根据指定的参数实例化 Mistral3 模型,定义模型架构。使用默认值实例化配置将产生与 mistralai/Mistral-Small-3.1-24B-Instruct-2503 类似的配置

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

>>> 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

Mistral3ForConditionalGeneration

class transformers.Mistral3ForConditionalGeneration

< >

( config: Mistral3Config )

参数

  • config (Mistral3ConfigMistral3VisionConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

MISTRAL3 模型由视觉骨干网络和语言模型组成。此模型继承自 PreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, typing.List[int], NoneType] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 image_sizes: Tensor = None **lm_kwargs ) transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列 token 的索引。如果您提供填充,默认情况下将忽略填充。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) -- 与输入图像对应的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.50.0/en/model_doc/auto#transformers.AutoImageProcessor) 获得。有关详细信息,请参阅 [CLIPImageProcessor.__call__()](/docs/transformers/v4.50.0/en/model_doc/vilt#transformers.ViltFeatureExtractor.__call__) ([]Mistral3Processor] 使用 CLIPImageProcessor 处理图像)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 掩码,用于避免在填充 token 索引上执行注意力机制。在 [0, 1] 中选择的掩码值:

    • 1 表示 未被掩码 的 token,
    • 0 表示 已被掩码 的 token。

    什么是注意力掩码?

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    如果使用 past_key_values,则可以选择仅输入最后的 decoder_input_ids(请参阅 past_key_values)。

    如果要更改填充行为,则应阅读 modeling_opt._prepare_decoder_attention_mask 并根据您的需要进行修改。有关默认策略的更多信息,请参见 论文 中的图 1。

    • 1 表示头 未被掩码
    • 0 表示头 已被掩码
  • position_ids (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 位置嵌入中每个输入序列 token 的位置索引。在范围 [0, config.n_positions - 1] 中选择。 什么是位置 ID?
  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(tuple(torch.FloatTensor)) 元组,其中每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

    包含预先计算的隐藏状态(自注意力模块和交叉注意力模块中的键和值),可以用于(参见 past_key_values 输入)加速顺序解码。

    如果使用 past_key_values,用户可以选择仅输入最后一次的 decoder_input_ids(那些没有将其过去的键值状态提供给此模型的输入),形状为 (batch_size, 1),而不是所有形状为 (batch_size, sequence_length)decoder_input_ids

  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • vision_feature_layer (Union[int, List[int]], 可选, 默认为 -2) — 用于选择视觉特征的层索引。如果提供多个索引,则会将相应索引的视觉特征连接起来以形成视觉特征。
  • vision_feature_select_strategy (str, 可选, 默认为 "default") — 用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是 "default""full" 之一。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • cache_position (形状为 (sequence_length)torch.LongTensor, 可选) — 索引,描述输入序列标记在序列中的位置。 与 position_ids 相反,此张量不受填充的影响。 它用于在正确的位置更新缓存并推断完整序列长度。
  • labels (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 用于计算掩码语言建模损失的标签。 索引应为 [0, ..., config.vocab_size] 或 -100(请参阅 input_ids 文档字符串)。 索引设置为 -100 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。
  • logits_to_keep (inttorch.Tensor, 可选) — 如果是 int,则计算最后 logits_to_keep 个标记的 logits。 如果是 0,则计算所有 input_ids 的 logits(特殊情况)。 仅生成最后一个标记 logits 是必需的,并且仅针对该标记计算它们可以节省内存,这对于长序列或大词汇量大小而言变得非常重要。 如果是 torch.Tensor,则必须是与序列长度维度中要保留的索引相对应的 1D 张量。 这在使用打包张量格式(批次和序列长度的单个维度)时很有用。

返回

transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.mistral3.modeling_mistral3.Mistral3CausalLMOutputWithPasttorch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (Mistral3Config) 和输入。

  • loss (形状为 (1,)torch.FloatTensor, 可选, 当提供 labels 时返回) — 语言建模损失(用于下一个标记预测)。

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头的预测分数(SoftMax 之前每个词汇表标记的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(tuple(torch.FloatTensor)) 元组,其中每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)

    包含预先计算的隐藏状态(自注意力模块中的键和值),可以用于(参见 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。

Mistral3ForConditionalGeneration 前向方法,覆盖了 __call__ 特殊方法。

尽管前向传递的配方需要在该函数中定义,但应该在此之后调用 Module 实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> from PIL import Image
>>> import requests
>>> 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"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> 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."
< > 在 GitHub 上更新