# Mixtral

## 概述

[Mixtral-8x7B](https://huggingface.co/papers/2401.04088) 由 Albert Jiang、Alexandre Sablayrolles、Arthur Mensch、Chris Bamford、Devendra Singh Chaplot、Diego de las Casas、Florian Bressand、Gianna Lengyel、Guillaume Lample、Lélio Renard Lavaud、Lucile Saulnier、Marie-Anne Lachaux、Pierre Stock、Teven Le Scao、Thibaut Lavril、Thomas Wang、Timothée Lacroix 和 William El Sayed 在 [Mixtral of Experts 博客文章](https://mistral.ai/news/mixtral-of-experts/) 中发布。

该博客文章的引言部分写道：

*今天，我们团队自豪地发布了 Mixtral 8x7B，这是一款采用开放权重的高质量稀疏专家混合（SMoE）模型，基于 Apache 2.0 许可证。在大多数基准测试中，Mixtral 的性能优于 Llama 2 70B，且推理速度提升 6 倍。它是采用宽松许可证的最强开放权重模型，在成本与性能的权衡方面也是整体表现最佳的模型。具体而言，在大多数标准基准测试中，它的性能与 GPT3.5 相当或更优。*

Mixtral-8x7B 是 [mistral.ai](https://mistral.ai/) 继 [Mistral-7B](mistral) 之后发布的第二个大型语言模型（LLM）。

### 架构细节

Mixtral-8x7B 是一个仅包含解码器的 Transformer，其架构选择如下：

- Mixtral is a Mixture of Experts (MoE) model with 8 experts per MLP, with a total of 45 billion parameters. To learn more about mixture-of-experts, refer to the [blog post](https://huggingface.co/blog/moe).
- 尽管该模型拥有 450 亿个参数，但单次前向传播所需的计算量与一个 140 亿参数模型相同。这是因为，虽然每个专家都必须被加载到内存中（需要约 700 亿参数的内存占用），但来自隐藏状态的每个 token 都会被分发两次（top 2 路由），因此计算量（即每次前向计算所需的操作量）仅为 2 X sequence_length。

以下实现细节与 Mistral AI 的首个模型 [Mistral-7B](mistral) 相同：

- 滑动窗口注意力 - 使用 8k 上下文长度和固定缓存大小进行训练，理论注意力跨度为 128K 个 token
- GQA （分组查询注意力）- 允许更快的推理和更低的缓存大小。
- 字节回退 BPE 分词器 - 确保字符永远不会被映射到词表外（OOV）标记。

有关更多详细信息，请参阅[发布博客文章](https://mistral.ai/news/mixtral-of-experts/)。

### 许可证

`Mixtral-8x7B` 采用 Apache 2.0 许可证发布。

## 使用技巧

Mistral 团队发布了 2 个检查点：

- 一个基础模型，[Mixtral-8x7B-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)，该模型已在互联网规模的数据上经过预训练，用于预测下一个 token。
- 一个经过指令微调的模型 [Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1)，它是基于监督微调（SFT）和直接偏好优化（DPO）针对聊天场景优化的基础模型。

基础模型可以按以下方式使用：

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")

prompt = "My favourite condiment is"

model_inputs = tokenizer([prompt], return_tensors="pt").to(model.device)

generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True)
tokenizer.batch_decode(generated_ids)[0]
"My favourite condiment is to ..."
```

经过指令微调的模型可以按以下方式使用：

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")

messages = [
    {"role": "user", "content": "What is your favourite condiment?"},
    {"role": "assistant", "content": "Well, I'm quite partial to a good squeeze of fresh lemon juice. It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!"},
    {"role": "user", "content": "Do you have mayonnaise recipes?"}
]

model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)

generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True)
tokenizer.batch_decode(generated_ids)[0]
"Mayonnaise can be made as follows: (...)"
```

如图所示，指令微调模型需要应用[聊天模板](../chat_templating)，以确保输入以正确的格式进行准备。

## 使用 Flash Attention 加速 Mixtral

上述代码片段展示了未使用任何优化技巧的推理过程。不过，通过利用 [Flash Attention](../kernel_doc/loading_kernels#attention-kernels)，可以大幅提升模型速度。Flash Attention 是模型内部所用注意力机制的一种更快实现。

首先，请确保安装最新版本的 Flash Attention 2，以包含滑动窗口注意力功能。

```bash
pip install -U flash-attn --no-build-isolation
```

请确保您的硬件与 Flash-Attention 2 兼容。有关详细信息，请参阅 [flash attention 仓库](https://github.com/Dao-AILab/flash-attention) 的官方文档。同时，请确保以半精度（例如 `torch.float16`）加载您的模型。

要使用 Flash Attention-2 加载并运行模型，请参阅以下代码片段：

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1", attn_implementation="flash_attention_2", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")

prompt = "My favourite condiment is"

model_inputs = tokenizer([prompt], return_tensors="pt").to(model.device)

generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True)
tokenizer.batch_decode(generated_ids)[0]
"The expected output"
```

### 预期加速

下图展示了预期的加速效果，对比了使用 `mistralai/Mixtral-8x7B-v0.1` 检查点时，transformers 中纯推理时间的原生实现与 Flash Attention 2 版本模型之间的差异。

### 滑动窗口 Attention

当前实现支持滑动窗口注意力机制和内存高效的缓存管理。若要启用滑动窗口注意力，请确保使用与滑动窗口注意力兼容的 `flash-attn` 版本（`>=2.3.0`）。

Flash Attention-2 模型还采用了更节省内存的缓存切片机制——按照 Mistral 模型官方实现中推荐的滚动缓存机制，我们将缓存大小固定为 `self.config.sliding_window`，仅支持 `padding_side="left"` 的批量生成，并使用当前 token 的绝对位置来计算位置嵌入。

## 使用量化缩小 Mixtral

由于 Mixtral 模型拥有 450 亿个参数，在半精度（float16）下大约需要 90GB 的 GPU 显存，因为每个参数占用 2 字节。不过，可以使用 [量化](../quantization/overview) 来缩小模型的体积。如果将模型量化到 4 位（即每个参数占用半字节），那么一块 40GB 显存的 A100 就足以容纳整个模型，因为此时大约只需要 27 GB 的显存。

量化模型只需将 `quantization_config` 传递给模型即可。下面，我们将使用 bitsandbytes 量化库（有关其他量化方法，请参阅 [此页面](../quantization/overview)）：

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

# specify how to quantize the model
quantization_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype="torch.float16",
)

model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", quantization_config=True, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")

prompt = "My favourite condiment is"

messages = [
    {"role": "user", "content": "What is your favourite condiment?"},
    {"role": "assistant", "content": "Well, I'm quite partial to a good squeeze of fresh lemon juice. It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!"},
    {"role": "user", "content": "Do you have mayonnaise recipes?"}
]

model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)

generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True)
tokenizer.batch_decode(generated_ids)[0]
"The expected output"
```

该模型由 [Younes Belkada](https://huggingface.co/ybelkada) 和 [Arthur Zucker](https://huggingface.co/ArthurZ) 贡献。原始代码可在[此处](https://github.com/mistralai/mistral-src)找到。

## 资源

以下是 Hugging Face 官方和社区（以 🌎 标识）提供的资源列表，可帮助您快速上手 Mixtral。如果您希望提交资源以收录在此处，欢迎随时发起 Pull Request，我们将进行审核！理想情况下，该资源应展示一些新内容，而非重复现有资源。

- 可以在[此处](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Mistral/Supervised_fine_tuning_(SFT)_of_an_LLM_using_Hugging_Face_tooling.ipynb)找到一个用于对 Mixtral-8x7B 执行监督微调（SFT）的演示笔记本。🌎
- 一篇关于使用 PEFT 微调 Mixtral-8x7B 的[博客文章](https://medium.com/@prakharsaxena11111/finetuning-mixtral-7bx8-6071b0ebf114)。🌎
- Hugging Face 的 [Alignment Handbook](https://github.com/huggingface/alignment-handbook) 包含用于对 Mistral-7B 执行监督微调（SFT）和直接偏好优化的脚本和配方。其中包括用于全量微调、在单个加速器上运行 QLoRa 以及多加速器微调的脚本。
- [因果语言建模任务指南](../tasks/language_modeling)

## MixtralConfig[[transformers.MixtralConfig]]

#### transformers.MixtralConfig[[transformers.MixtralConfig]]

```python
transformers.MixtralConfig(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, vocab_size: int = 32000, hidden_size: int = 4096, intermediate_size: int = 14336, num_hidden_layers: int = 32, num_attention_heads: int = 32, num_key_value_heads: int = 8, head_dim: int | None = None, hidden_act: str = 'silu', max_position_embeddings: int = 131072, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = None, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, tie_word_embeddings: bool = False, sliding_window: int | None = None, attention_dropout: float | int = 0.0, num_experts_per_tok: int = 2, num_local_experts: int = 8, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, router_jitter_noise: float = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/configuration_mixtral.py#L25)

**参数：**

vocab_size (`int`，*可选*，默认值为 `32000`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

hidden_size (`int`，*可选*，默认为 `4096`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认值为 `14336`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `32`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `32`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `8`) : 这是用于实现 Grouped Query Attention 的 key_value 头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用 Multi Head Attention (MHA)；如果 `num_key_value_heads=1`，模型将使用 Multi Query Attention (MQA)；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

head_dim (`int`, *可选*) : 注意力头维度。如果为 None，则默认为 hidden_size // num_attention_heads

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

max_position_embeddings (`int`，*可选*，默认值为 `131072`)：该模型可能使用的最大序列长度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

rms_norm_eps (`float`，*可选*，默认值为 `1e-05`)：rms 归一化层中使用的 epsilon。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

pad_token_id (`int`, *可选*) : 词表中用于填充的 Token id。

bos_token_id (`int`，*可选*，默认为 `1`)：词汇表中用于表示流开始的 Token id。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `2`)：词汇表中用于表示流结束（end-of-stream）的 token id。

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

sliding_window (`int`, *可选*) : 滑动窗口注意力机制的窗口大小。如果为 `None`，则不应用滑动窗口。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

num_experts_per_tok (`int`，*可选*，默认为 `2`)：每个 token 路由到的专家数量。这是 token 选择路由的 top-k 值。

num_local_experts (`int`, *可选*, 默认为 `8`) : 每个设备上的本地专家数量。`num_experts` 应能被 `num_local_experts` 整除。

output_router_logits (`bool`，*可选*，默认为 `False`)：是否由模型返回路由器 logits。启用此选项后，模型还将输出辅助损失，包括负载均衡损失和路由器 z-loss。

router_aux_loss_coef (`float`, *可选*，默认为 `0.001`)：辅助负载均衡损失系数。用于惩罚 MoE 模型中专家路由的不均衡。

router_jitter_noise (`float`, *可选*, 默认为 `0.0`) : 在训练期间为路由器 logits 添加的噪声量，以实现更好的负载均衡。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

这是用于存储 MixtralModel 配置的类。它根据指定的参数实例化 Mixtral 模型，并定义模型架构。使用默认值实例化配置将得到与 [mistralai/Mixtral-8x7B-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) 类似的配置。

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

示例：

```python
>>> from transformers import MixtralModel, MixtralConfig

>>> # Initializing a Mixtral 7B style configuration
>>> configuration = MixtralConfig()

>>> # Initializing a model from the Mixtral 7B style configuration
>>> model = MixtralModel(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/v5.23.0/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[str, str | tokenizers.AddedToken | collections.abc.Sequence[str | tokenizers.AddedToken]], replace_extra_special_tokens: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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[str, str | tokenizers.AddedToken | collections.abc.Sequence[str | tokenizers.AddedToken]], replace_extra_special_tokens: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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[int], token_ids_1: None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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[int], token_ids_1: None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：启用并控制填充。接受以下值： - `True` 或 `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`：填充至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认值）：不进行填充（即，可以输出包含不同长度序列的批次）。

truncation (`bool`、`str` 或 [TruncationStrategy](/docs/transformers/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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[int], token_ids_1: None = None, already_has_special_tokens: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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/v5.23.0/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[int], 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/v5.23.0/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/v5.23.0/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `False`)：启用并控制填充。接受以下值： - `True` 或 `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`：填充至由参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `False` 或 `'do_not_pad'`（默认值）：不进行填充（即，可以输出包含不同长度序列的批次）。

truncation (`bool`、`str` 或 [TruncationStrategy](/docs/transformers/v5.23.0/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/v5.23.0/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/v5.23.0/zh/main_classes/tokenizer#transformers.BatchEncoding)

一个包含以下字段的 [BatchEncoding](/docs/transformers/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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[int], 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/v5.23.0/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/v5.23.0/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`。

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

## MixtralModel[[transformers.MixtralModel]]

#### transformers.MixtralModel[[transformers.MixtralModel]]

```python
transformers.MixtralModel(config: MixtralConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L399)

**参数：**

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

未添加任何特定头部的裸 Mixtral 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/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.MixtralModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = 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.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L416)

**参数：**

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

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/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

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

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

**返回：** `MoeModelOutputWithPast` 或 `tuple(torch.Tensor)`

`MoeModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MixtralConfig](/docs/transformers/v5.23.0/zh/model_doc/mixtral#transformers.MixtralConfig)）和输入。

[MixtralModel](/docs/transformers/v5.23.0/zh/model_doc/mixtral#transformers.MixtralModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

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

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

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

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，当传入 `output_router_probs=True` 且 `config.add_router_probs=True`，或当 `config.output_router_probs=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits（softmax 之后），这些术语用于计算混合专家模型的辅助损失。

## MixtralForCausalLM[[transformers.MixtralForCausalLM]]

#### transformers.MixtralForCausalLM[[transformers.MixtralForCausalLM]]

```python
transformers.MixtralForCausalLM(config: MixtralConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L547)

**参数：**

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

用于因果语言建模的 Mixtral 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/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.MixtralForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = 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.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, output_router_logits: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L565)

**参数：**

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

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/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

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

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 用于计算因果语言建模损失的标签。索引应在 `[-100, 0, ..., config.vocab_size]` 范围内（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的 token 将被忽略（被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。 标签会在**内部进行移位**，因此使用 `labels[..., 1:]` 来预测 `logits[..., :-1, :]`。请传入与 `input_ids` 匹配的未移位标签（即 `labels = input_ids`）。在传入之前，请**不要**自行对标签进行移位。 如果标签已经移位（例如在使用序列并行时），请将其作为 `shift_labels` 关键字参数传入，系统将按原样使用它们。 为了计算损失，仍然必须传入 `labels`。

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

output_router_logits (`bool`, *可选*) : 是否返回所有路由器的 logits。它们对于计算路由器损失很有用，在推理期间不应返回。

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

**返回：** `MoeCausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`MoeCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[MixtralConfig](/docs/transformers/v5.23.0/zh/model_doc/mixtral#transformers.MixtralConfig)）和输入。

[MixtralForCausalLM](/docs/transformers/v5.23.0/zh/model_doc/mixtral#transformers.MixtralForCausalLM) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **aux_loss** (`torch.Tensor`，*可选*，当传入 `output_router_logits=True` 或 `config.output_router_logits=True`，且模型使用负载均衡损失训练其路由器时返回) -- 稀疏模块的负载均衡辅助损失。使用路由器偏差来平衡其专家的模型（DeepSeek-V3 及由其衍生的架构）在此处返回 `None`，但仍会返回 `router_logits`。
- **router_logits** (`tuple(torch.Tensor)`，*可选*，在传入 `output_router_logits=True` 或 `config.output_router_logits=True` 时返回) -- 一个 `torch.Tensor` 元组（每个稀疏层对应一个），形状为 `(batch_size * sequence_length, num_experts)`。

  由 MoE 路由器计算的原始路由器 logits。可用于计算负载均衡损失，或检查 token 如何被分发到各个专家。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/v5.23.0/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

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

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

示例：

```python
>>> from transformers import AutoTokenizer, MixtralForCausalLM

>>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```

## MixtralForSequenceClassification[[transformers.MixtralForSequenceClassification]]

#### transformers.MixtralForSequenceClassification[[transformers.MixtralForSequenceClassification]]

```python
transformers.MixtralForSequenceClassification(config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L644)

#### forward[[transformers.MixtralForSequenceClassification.forward]]

```python
forward(input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, **kwargs: Unpack[TransformersKwargs])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/modeling_layers.py#L140)

**参数：**

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

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

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

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*)：用于计算序列分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels == 1`，则计算回归损失（均方损失）；如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

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

**返回：** `SequenceClassifierOutputWithPast`

`GenericForSequenceClassification` 的 forward 方法重写了 `__call__` 特殊方法。

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

## MixtralForTokenClassification[[transformers.MixtralForTokenClassification]]

#### transformers.MixtralForTokenClassification[[transformers.MixtralForTokenClassification]]

```python
transformers.MixtralForTokenClassification(config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L648)

#### forward[[transformers.MixtralForTokenClassification.forward]]

```python
forward(input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, **kwargs: Unpack[TransformersKwargs])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/modeling_layers.py#L287)

**参数：**

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

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

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

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算 token 分类损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。

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

**返回：** `TokenClassifierOutput`

`GenericForTokenClassification` 的 forward 方法重写了 `__call__` 特殊方法。

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

## MixtralForQuestionAnswering[[transformers.MixtralForQuestionAnswering]]

#### transformers.MixtralForQuestionAnswering[[transformers.MixtralForQuestionAnswering]]

```python
transformers.MixtralForQuestionAnswering(config)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/mixtral/modeling_mixtral.py#L652)

#### forward[[transformers.MixtralForQuestionAnswering.forward]]

```python
forward(input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.Tensor | None = None, start_positions: torch.LongTensor | None = None, end_positions: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/modeling_layers.py#L220)

**参数：**

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

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

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

start_positions (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*)：用于计算 token 分类损失的标注 span 起始位置（索引）的标签。位置会被截断至序列长度（`sequence_length`）。序列之外的位置在计算损失时不予考虑。

end_positions (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*)：用于计算 token 分类损失的标注 span 结束位置（索引）的标签。位置会被截断至序列长度（`sequence_length`）。序列之外的位置在计算损失时不予考虑。

**返回：** `QuestionAnsweringModelOutput`

`GenericForQuestionAnswering` 的 forward 方法重写了 `__call__` 特殊方法。

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

