# Mistral

[Mistral](https://huggingface.co/papers/2310.06825) 是一个 7B 参数的语言模型，提供预训练和指令微调两种变体，旨在平衡大模型的扩展成本与性能及高效推理。该模型使用滑动窗口注意力（SWA），以 8K 上下文长度和固定缓存大小进行训练，从而更有效地处理更长的序列。分组查询注意力（GQA）可加速推理并降低内存需求。Mistral 还采用了字节回退 BPE 分词器，通过确保字符永远不会映射到词表外（out-of-vocabulary）的标记，来提升标记处理能力和效率。

您可以在 [Mistral AI_](https://huggingface.co/mistralai) 组织下找到所有原始的 Mistral 检查点。

> [!TIP]
> 点击右侧边栏中的 Mistral 模型，以查看更多将 Mistral 应用于不同语言任务的示例。
>
> 在 [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": "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?"}
]

chatbot = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct-v0.3", device=0)
chatbot(messages)
```

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", attn_implementation="sdpa", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")

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: (...)"
```

```python
echo -e "My favorite condiment is" | transformers chat mistralai/Mistral-7B-v0.3 --dtype auto --device 0 --attn_implementation flash_attention_2
```

量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端，请参阅 [量化](../quantization/overview) 概述。

以下示例使用 [bitsandbytes](../quantization/bitsandbytes) 仅将权重量化为 4 位。

```python
import torch
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/Mistral-7B-Instruct-v0.3", quantization_config=quantization_config, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")

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

使用 [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) 可以更直观地了解模型能够和不能关注哪些 token。

```python
from transformers.utils.attention_visualizer import AttentionMaskVisualizer

visualizer = AttentionMaskVisualizer("mistralai/Mistral-7B-Instruct-v0.3")
visualizer("Do you have mayonnaise recipes?")
```

    

## MistralConfig[[transformers.MistralConfig]]

#### transformers.MistralConfig[[transformers.MistralConfig]]

```python
transformers.MistralConfig(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-06, 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, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, sliding_window: int | None = 4096, attention_dropout: float | int = 0.0)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/configuration_mistral.py#L28)

**参数：**

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-06`)：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` 映射来绑定权重嵌入。

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

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

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

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

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

示例：

```python
>>> from transformers import MistralModel, MistralConfig

>>> # Initializing a Mistral 7B style configuration
>>> configuration = MistralConfig()

>>> # Initializing a model from the Mistral 7B style configuration
>>> model = MistralModel(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`。

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

## MistralModel[[transformers.MistralModel]]

#### transformers.MistralModel[[transformers.MistralModel]]

```python
transformers.MistralModel(config: MistralConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L309)

**参数：**

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

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

该模型继承自 [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.MistralModel.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/main/src/transformers/models/mistral/modeling_mistral.py#L326)

**参数：**

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)

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

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

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

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

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

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

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

  如果使用了 `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)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `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 后的注意力权重，用于在自注意力头中计算加权平均值。

## MistralForCausalLM[[transformers.MistralForCausalLM]]

#### transformers.MistralForCausalLM[[transformers.MistralForCausalLM]]

```python
transformers.MistralForCausalLM(config: MistralConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L383)

**参数：**

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

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

该模型继承自 [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.MistralForCausalLM.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, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L398)

**参数：**

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)

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.Tensor`，形状为 `(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`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

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

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

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（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.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, MistralForCausalLM

>>> model = MistralForCausalLM.from_pretrained("meta-mistral/Mistral-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-mistral/Mistral-2-7b-hf")

>>> 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."
```

## MistralForSequenceClassification[[transformers.MistralForSequenceClassification]]

#### transformers.MistralForSequenceClassification[[transformers.MistralForSequenceClassification]]

```python
transformers.MistralForSequenceClassification(config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L460)

#### forward[[transformers.MistralForSequenceClassification.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/main/src/transformers/modeling_layers.py#L128)

**参数：**

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)

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/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.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` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

## MistralForTokenClassification[[transformers.MistralForTokenClassification]]

#### transformers.MistralForTokenClassification[[transformers.MistralForTokenClassification]]

```python
transformers.MistralForTokenClassification(config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L456)

#### forward[[transformers.MistralForTokenClassification.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/main/src/transformers/modeling_layers.py#L275)

**参数：**

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)

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/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.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` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

## MistralForQuestionAnswering[[transformers.MistralForQuestionAnswering]]

#### transformers.MistralForQuestionAnswering[[transformers.MistralForQuestionAnswering]]

```python
transformers.MistralForQuestionAnswering(config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L464)

#### forward[[transformers.MistralForQuestionAnswering.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/main/src/transformers/modeling_layers.py#L208)

**参数：**

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)

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/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.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` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

