Transformers 文档
Mixtral
并获得增强的文档体验
开始使用
该模型于 2023-12-11 发布,并于 2023-12-11 添加到 Hugging Face Transformers。
Mixtral
概述
Mixtral-8x7B 在 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 博客文章中被介绍。
博客文章的开头说道:
今天,我们团队很荣幸发布 Mixtral 8x7B,这是一款高质量的稀疏专家混合模型(SMoE),具有开放的权重。根据 Apache 2.0 许可。Mixtral 在大多数基准测试中,以 6 倍更快的推理速度超越 Llama 2 70B。它是拥有宽松许可的最强开放权重模型,也是在成本/性能权衡方面整体最佳的模型。特别是,它在大多数标准基准测试中与 GPT3.5 持平或超越 GPT3.5。
Mixtral-8x7B 是 mistral.ai 在 Mistral-7B 之后发布的第二个大型语言模型(LLM)。
架构细节
Mixtral-8x7B 是一个仅解码器的 Transformer 模型,具有以下架构选择:
- Mixtral 是一个专家混合(MoE)模型,每个 MLP 有 8 个专家,总共有 450 亿个参数。要了解更多关于专家混合的信息,请参阅博客文章。
- 尽管该模型有 450 亿个参数,但单次前向传播所需的计算量与 140 亿参数模型相同。这是因为虽然每个专家都必须加载到 RAM 中(70B 左右的 RAM 要求),但每个 token 的隐藏状态都会被分派两次(前 2 名路由),因此计算量(每次前向计算所需的操作)仅为 2 x 序列长度。
以下实现细节与 Mistral AI 的第一个模型 Mistral-7B 相同:
- 滑动窗口注意力 - 使用 8k 上下文长度和固定缓存大小进行训练,理论注意力跨度为 128K 个 token。
- GQA(分组查询注意力) - 允许更快的推理和更小的缓存大小。
- Byte-fallback BPE 分词器 - 确保字符永远不会映射到词汇表外的 token。
更多详情请参阅发布博客文章。
许可证
Mixtral-8x7B 在 Apache 2.0 许可下发布。
使用技巧
Mistral 团队发布了 2 个检查点:
- 一个基础模型 Mixtral-8x7B-v0.1,该模型已在互联网规模的数据上进行了预训练,以预测下一个 token。
- 一个经过指令微调的模型 Mixtral-8x7B-Instruct-v0.1,该模型是基础模型,通过监督微调(SFT)和直接偏好优化(DPO)进行了对话优化。
基础模型可以按如下方式使用:
>>> 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 ..."指令微调模型可以按如下方式使用:
>>> 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: (...)"可以看到,指令微调模型需要应用聊天模板,以确保输入以正确的格式准备。
使用 Flash Attention 加速 Mixtral
上面的代码片段展示了没有任何优化技巧的推理过程。然而,通过利用 Flash Attention 可以大幅提高模型速度,它是模型内部所使用的注意力机制的一种更快的实现方式。
首先,请确保安装最新版本的 Flash Attention 2,以包含滑动窗口注意力功能。
pip install -U flash-attn --no-build-isolation
请确保你的硬件与 Flash-Attention 2 兼容。在 flash attention 仓库 的官方文档中阅读更多相关信息。此外,请确保以半精度(例如 torch.float16)加载模型。
要加载并运行使用 Flash Attention-2 的模型,请参阅以下代码片段:
>>> import torch
>>> from transformers import AutoModelForCausalLM, AutoTokenizer
>>> model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1", dtype=torch.float16, 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 版本模型进行纯推理时间比较的预期加速图。

滑动窗口注意力
当前实现支持滑动窗口注意力机制和内存高效的缓存管理。要启用滑动窗口注意力,请确保您拥有与滑动窗口注意力兼容的 flash-attn 版本(>=2.3.0)。
Flash Attention-2 模型还使用了更内存高效的缓存切片机制 - 正如 Mistral 模型官方实现推荐的那样,我们保持缓存大小固定(self.config.sliding_window),仅支持 padding_side="left" 的批量生成,并使用当前 token 的绝对位置来计算位置嵌入。
通过量化缩小 Mixtral 的体积
由于 Mixtral 模型有 450 亿个参数,在半精度(float16)下大约需要 90GB 的 GPU RAM,因为每个参数存储为 2 字节。然而,可以通过量化来缩小模型体积。如果模型被量化到 4 位(每个参数半字节),则单个 A100 40GB RAM 就足以容纳整个模型,此时只需要大约 27 GB RAM。
量化模型就像向模型传递 quantization_config 一样简单。下面,我们将利用 bitsandbytes 量化库(但有关替代量化方法,请参阅此页面)。
>>> 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/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和Arthur Zucker贡献。原始代码可以在这里找到。
资源
一系列官方 Hugging Face 和社区(由 🌎 表示)资源,帮助您开始使用 Mixtral。如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将对其进行审核!该资源应最好能展示新内容,而不是复制现有资源。
- 使用 Hugging Face 工具对 Mixtral-8x7B 进行监督微调(SFT)的演示笔记本可以在这里找到。🌎
- 一篇关于使用 PEFT 微调 Mixtral-8x7B 的博客文章。🌎
- Hugging Face 的Alignment Handbook包含用于使用 Mistral-7B 进行监督微调(SFT)和直接偏好优化(DPO)的脚本和配方。这包括全量微调、单加速器上的 QLoRa 以及多加速器微调的脚本。
- 因果语言建模任务指南
MixtralConfig
class transformers.MixtralConfig
< source >( vocab_size: int | None = 32000 hidden_size: int | None = 4096 intermediate_size: int | None = 14336 num_hidden_layers: int | None = 32 num_attention_heads: int | None = 32 num_key_value_heads: int | None = 8 head_dim: int | None = None hidden_act: str | None = 'silu' max_position_embeddings: int | None = 131072 initializer_range: float | None = 0.02 rms_norm_eps: int | None = 1e-05 use_cache: bool | None = True pad_token_id: int | None = None bos_token_id: int | None = 1 eos_token_id: int | None = 2 tie_word_embeddings: bool | None = False sliding_window: int | None = None attention_dropout: float | None = 0.0 num_experts_per_tok: int | None = 2 num_local_experts: int | None = 8 output_router_logits: bool | None = False router_aux_loss_coef: float | None = 0.001 router_jitter_noise: float | None = 0.0 rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None **kwargs )
参数
- vocab_size (
int, optional, defaults to 32000) — Mixtral 模型词汇量大小。定义通过调用 MixtralModel 传递的inputs_ids可以表示的不同 token 的数量。 - hidden_size (
int, optional, defaults to 4096) — 隐藏表示的维度。 - intermediate_size (
int, optional, defaults to 14336) — MLP 表示的维度。 - num_hidden_layers (
int, optional, defaults to 32) — Transformer 编码器中的隐藏层数量。 - num_attention_heads (
int, optional, defaults to 32) — Transformer 编码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, optional, defaults to 8) — 这是实现分组查询注意力(Grouped Query Attention)所需的键值头的数量。如果num_key_value_heads=num_attention_heads,模型将使用多头注意力(MHA);如果num_key_value_heads=1,模型将使用多查询注意力(MQA);否则使用 GQA。将多头检查点转换为 GQA 检查点时,每个组的键头和值头应通过平均池化原始组内所有头来构建。有关更多详细信息,请参阅此论文。如果未指定,则默认为8。 - head_dim (
int, optional, defaults tohidden_size // num_attention_heads) — 注意力头的维度。 - hidden_act (
strorfunction, optional, defaults to"silu") — 解码器中的非线性激活函数(函数或字符串)。 - max_position_embeddings (
int, optional, defaults to4096*32) — 该模型可能使用的最大序列长度。Mixtral 的滑动窗口注意力允许长达 4096*32 个 token 的序列。 - initializer_range (
float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准偏差。 - rms_norm_eps (
float, optional, defaults to 1e-05) — RMS 归一化层使用的 epsilon。 - use_cache (
bool, optional, defaults toTrue) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。仅在config.is_decoder=True时相关。 - pad_token_id (
int, optional) — 填充 token 的 ID。 - bos_token_id (
int, optional, defaults to 1) — “开始序列” token 的 ID。 - eos_token_id (
int, optional, defaults to 2) — “序列结束” token 的 ID。 - tie_word_embeddings (
bool, optional, defaults toFalse) — 模型输入和输出词嵌入是否应绑定。 - sliding_window (
int, optional) — 滑动窗口注意力的窗口大小。如果未指定,默认为4096。 - attention_dropout (
float, 可选, 默认值 0.0) — 注意力概率的 dropout 比率。 - num_experts_per_tok (
int, 可选, 默认值 2) — 每个 token 的路由专家数量,也可以理解为top-k路由参数 - num_local_experts (
int, 可选, 默认值 8) — 每个稀疏 MLP 层的专家数量。 - output_router_logits (
bool, 可选, 默认值False) — 模型是否应该返回路由 logits。启用此选项将允许模型输出辅助损失。更多详情请参阅 此处 - router_aux_loss_coef (
float, 可选, 默认值 0.001) — 总损失的辅助损失系数。 - router_jitter_noise (
float, 可选, 默认值 0.0) — 添加到路由器的噪声量。 - rope_parameters (
RopeParameters, 可选) — 包含 RoPE 嵌入配置参数的字典。字典应包含rope_theta的值,并且如果需要使用更长的max_position_embeddings来进行 RoPE 缩放,则可选地包含用于缩放的参数。
这是用于存储 MixtralModel 配置的类。它用于根据指定的参数实例化 Mixtral 模型,定义模型架构。使用默认值实例化配置将产生与 Mixtral-7B-v0.1 或 Mixtral-7B-Instruct-v0.1 类似的配置。
mixtralai/Mixtral-8x7B mixtralai/Mixtral-7B-Instruct-v0.1
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。
>>> 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.configMistralCommonBackend
class transformers.MistralCommonBackend
< source >( tokenizer_path: str | os.PathLike | pathlib.Path mode: ValidationMode = <ValidationMode.test: '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 )
包装 mistral-common 分词器的类。
否则,分词器将回退到 Transformers 的分词器实现。
有关 mistral-common 的更多信息,请参阅 mistral-common。
此类是 mistral_common.tokens.tokenizers.mistral.MistralTokenizer 的包装器。它提供了一个 Hugging Face 兼容的接口来使用官方的 mistral-common 分词器进行分词,并继承自 PreTrainedTokenizerBase 类。
以下是与 PythonBackend 类相比的关键行为差异:
- 不支持序列对。为保持兼容性,保留了签名,但忽略了与序列对相关的所有参数。对的返回值将返回
None。 - 不支持
is_split_into_words参数。 - 无法向分词器添加新 token。特殊 token 的处理方式与 Transformers 不同。在
mistral-common中,特殊 token 永远不会被直接编码。这意味着:tokenizer.encode("<s>")将不会返回<s>token 的 ID。相反,它将返回字符串"<s>"的分词结果对应的 ID 列表。更多信息请参见 mistral-common 文档。
如果您对改进此类有任何建议,请根据问题是与分词器相关还是与 Hugging Face 接口相关,在 mistral-common GitHub 存储库或 Transformers GitHub 存储库中提交 issue。
add_special_tokens
< source >( special_tokens_dict: dict replace_extra_special_tokens: bool = True )
MistralCommonBackend 因设计原因未实现 add_special_tokens。
如果您希望实现此功能,请在 Transformers 或 mistral-common 存储库中提交 issue 以请求。
MistralCommonBackend 因设计原因未实现 add_special_tokens。
如果您希望实现此功能,请在 Transformers 或 mistral-common 存储库中提交 issue 以请求。
apply_chat_template
< source >( 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 **kwargs ) → Union[str, list[int], list[str], list[list[int]], BatchEncoding]
参数
- conversation (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]) — 一个包含“role”和“content”键的字典列表,表示到目前为止的聊天记录。
- tools (
List[Union[Dict, Callable]], 可选) — 模型可访问的工具(可调用函数)列表。如果模板不支持函数调用,此参数将不起作用。每个工具应作为 JSON Schema 传递,提供工具的名称、描述和参数类型。有关更多信息,请参阅我们的 聊天模板指南。 - add_generation_prompt (
bool, 可选) — 此参数对MistralCommonBackend无效。但是,它不能与continue_final_message同时使用,以保持 API 的一致性。如果任何对话以助手消息结束,将引发错误。在这种情况下,请改用continue_final_message。 - continue_final_message (bool, 可选) — 如果设置了此项,则聊天将被格式化,以便最后的聊天消息是开放式的,没有 EOS 标记。模型将继续此消息而不是开始新消息。这允许您“预填充”模型响应的一部分。不能与
add_generation_prompt同时使用。 - tokenize (
bool, 默认值True) — 是否对输出进行 token 化。如果为False,输出将是一个字符串。 - padding (
bool,str或 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, 可选) — 如果设置,将返回特定框架的张量。如果 tokenize 为False,则无效。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。
- return_dict (
bool, 默认值False) — 是否返回带有命名输出的字典。如果 tokenize 为False,则无效。如果至少一个对话包含图像,其像素值将返回在pixel_values键中。 - kwargs (其他关键字参数, 可选) —
MistralCommonBackend.apply_chat_template不支持。如果使用,将引发错误。
返回
Union[str, list[int], list[str], list[list[int]], BatchEncoding]
已分词的聊天内容,包括控制 token。此输出已准备好直接传递给模型,或通过 generate() 等方法传递。
将包含“role”和“content”键的字典列表转换为 token ID 列表。
batch_decode
< source >( 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 ) → list[str]
参数
- sequences (
Union[list[int], list[list[int]], np.ndarray, torch.Tensor]) — Tokenized 输入 ID 列表。可以通过__call__方法获得。 - skip_special_tokens (
bool, optional, defaults toFalse) — 是否在解码时移除特殊 token。 - clean_up_tokenization_spaces (
bool, optional) — 是否清理 tokenization 后的空格。如果为None,则默认使用self.clean_up_tokenization_spaces。 - kwargs (additional keyword arguments, optional) —
MistralCommonBackend.batch_decode不支持。如果使用,将引发错误。
返回
list[str]
解码后的句子列表。
通过调用 decode 将标记 ID 列表的列表转换为字符串列表。
此方法仅用于向后兼容。decode 方法现在支持批处理输入,因此您可以直接使用 decode 而不是 batch_decode。
build_inputs_with_special_tokens
< source >( token_ids_0: list token_ids_1: None = None ) → list[int]
通过添加特殊 token 从序列构建模型输入。
此方法根据分词器的 mode 动态构建输入
"test":seq0 [EOS]"finetuning":[BOS] seq0
convert_added_tokens
< source >( obj: typing.Union[tokenizers.AddedToken, typing.Any] save: bool = False add_type_field: bool = True )
MistralCommonBackend 因设计原因未实现 convert_added_tokens。
如果您希望实现此功能,请在 Transformers 或 mistral-common 存储库中提交 issue 以请求。
create_token_type_ids_from_sequences
< source >( token_ids_0: list token_ids_1: None = None ) → list[int]
使用特殊标记添加的 token id 创建一个零掩码。
为匹配 Transformers 的实现而保留。
decode
< source >( 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 ) → Union[str, list[str]]
参数
- token_ids (
Union[int, list[int], list[list[int]], np.ndarray, torch.Tensor]) — 单个序列或一批(序列列表)的 tokenized 输入 ID。可以通过__call__方法获得。 - skip_special_tokens (
bool, optional, defaults toFalse) — 是否在解码时移除特殊 token。 - clean_up_tokenization_spaces (
bool, optional) — 是否清理 tokenization 后的空格。如果为None,则默认使用self.clean_up_tokenization_spaces。 - kwargs (additional keyword arguments, optional) —
MistralCommonBackend.decode不支持。如果使用,将引发错误。
返回
Union[str, list[str]]
单个序列的解码字符串,或序列批次的解码字符串列表。
使用分词器和词汇表将 ID 序列转换为字符串,可以选择移除特殊标记并清理分词空间。
编码
< source >( 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 ) → list[int], torch.Tensor
参数
- text (
strorlist[int]) — 第一个要编码的序列。这可以是一个字符串或一个整数列表(tokenized 字符串 ID)。 - text_pair (
None, optional) —MistralCommonBackend.encode不支持。为匹配PreTrainedTokenizerBase.encode签名而保留。 - add_special_tokens (
bool, optional, defaults toTrue) — 是否在编码序列时添加特殊 token。这将使用底层的PretrainedTokenizerBase.build_inputs_with_special_tokens函数,该函数定义了哪些 token 会被自动添加到输入 ID 中。如果您想自动添加bos或eostoken,这将非常有用。当 Tokenizer 以finetuning模式加载时,它会同时添加bos和eos。否则,对于“test”模式,它只添加bos。 - padding (
bool,stror PaddingStrategy, optional, defaults toFalse) — 激活和控制 padding。接受以下值:True或'longest':填充到 batch 中的最长序列(如果只提供单个序列,则不填充)。'max_length':填充到使用参数max_length指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。False或'do_not_pad'(默认):不填充(即,可以输出具有不同长度的序列的 batch)。
- truncation (
bool,stror TruncationStrategy, optional, defaults toFalse) — 激活和控制截断。接受以下值:True或'longest_first':截断到使用参数max_length指定的最大长度,或者如果未提供该参数,则截断到模型可接受的最大输入长度。False或'do_not_truncate'(默认):不截断(即,可以输出 batch,其中序列长度大于模型允许的最大输入大小)。
- max_length (
int, optional) — 控制由truncation/padding参数之一使用的最大长度。如果未设置或设置为
None,则在需要截断/填充参数的最大长度时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如 XLNet),则截断/填充到最大长度将无效。 - stride (
int, optional, defaults to 0) — 如果设置了max_length,当return_overflowing_tokens=True时,返回的溢出 token 将包含截断序列末尾的一些 token,以在截断序列和溢出序列之间提供一些重叠。此参数的值定义了重叠 token 的数量。 - pad_to_multiple_of (
int, optional) — 如果设置,则将序列填充到指定值的倍数。需要激活padding。这对于在计算能力>= 7.5(Volta)的 NVIDIA 硬件上启用 Tensor Core 非常有用。 - padding_side (
str, optional) — 模型应该应用 padding 的侧边。应在 [‘right’, ‘left’] 之间选择。默认值从同名的类属性中选取。 - return_tensors (
str或 TensorType, 可选) — 如果设置为 True,则返回张量而不是 Python 整数列表。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。
- **kwargs —
MistralCommonBackend.encode不支持。使用时将引发错误。
返回
list[int], torch.Tensor
文本的 tokenized ID。
使用分词器和词汇表将字符串转换为 ID 序列(整数)。
from_pretrained
< source >( pretrained_model_name_or_path: str | os.PathLike *init_inputs mode: str | mistral_common.protocol.instruct.validator.ValidationMode = <ValidationMode.test: '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 )
参数
- pretrained_model_name_or_path (
str或os.PathLike) — 可以是:- 一个字符串,即托管在 huggingface.co 上的模型仓库中的预定义分词器的模型 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 授权的 token。如果设置为True,将使用运行hf auth login时生成的 token(存储在~/.huggingface)。 - local_files_only (
bool, 可选,默认为False) — 是否仅依赖本地文件,而不尝试下载任何文件。 - revision (
str, 可选,默认为"main") — 要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID,因为我们使用基于 git 的系统在 huggingface.co 上存储模型和其他制品,所以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。
MistralCommonBackend 因设计原因未实现 get_chat_template,因为 mistral-common 不使用 chat templates。
get_special_tokens_mask
< source >( token_ids_0: list token_ids_1: None = None already_has_special_tokens: bool = False ) → A list of integers in the range [0, 1]
从未添加特殊令牌的令牌列表中检索序列 ID。使用分词器 prepare_for_model 或 encode_plus 方法添加特殊令牌时会调用此方法。
返回作为 token 到 index 字典的词汇表。
这是一个有损转换。由于 partial UTF-8 字节序列被转换为 �,可能会有多个 token ID 解码为相同的字符串。
num_special_tokens_to_add
< source >( pair: typing.Literal[False] = False ) → int
返回使用特殊标记编码序列时添加的标记数量。
此方法对一个虚拟输入进行编码,并检查添加的标记数量,因此效率不高。请勿将其放入您的训练循环中。
prepare_for_model
< source >( 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 return_offsets_mapping: typing.Literal[False] = False split_special_tokens: typing.Literal[False] = False **kwargs ) → BatchEncoding
参数
- ids (
list[int]) — Tokenized input ids of the first sequence. - pair_ids (
None, optional) — Not supported byMistralCommonBackend. Kept to match the interface ofPreTrainedTokenizerBase. - add_special_tokens (
bool, optional, defaults toTrue) — Whether or not to add special tokens when encoding the sequences. This will use the underlyingPretrainedTokenizerBase.build_inputs_with_special_tokensfunction, which defines which tokens are automatically added to the input ids. This is useful if you want to addbosoreostokens automatically. When Tokenizer is loading withfinetuningmode it adds bothbosandeos. Else, for “test” mode it only addsbos. - padding (
bool,stror PaddingStrategy, optional, defaults toFalse) — Activates and controls padding. Accepts the following values:Trueor'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence is provided).'max_length': Pad to a maximum length specified with the argumentmax_lengthor to the maximum acceptable input length for the model if that argument is not provided.Falseor'do_not_pad'(default): No padding (i.e., can output a batch with sequences of different lengths).
- truncation (
bool,stror TruncationStrategy, optional, defaults toFalse) — Activates and controls truncation. Accepts the following values:Trueor'longest_first': Truncate to a maximum length specified with the argumentmax_lengthor to the maximum acceptable input length for the model if that argument is not provided.Falseor'do_not_truncate'(default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
- max_length (
int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.If left unset or set to
None, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. - stride (
int, optional, defaults to 0) — If set to a number along withmax_length, the overflowing tokens returned whenreturn_overflowing_tokens=Truewill contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens. - pad_to_multiple_of (
int, optional) — If set will pad the sequence to a multiple of the provided value. Requirespaddingto be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability>= 7.5(Volta). - padding_side (
str, optional) — The side on which the model should have padding applied. Should be selected between [‘right’, ‘left’]. Default value is picked from the class attribute of the same name. - return_tensors (
stror TensorType, optional) — If set, will return tensors instead of list of python integers. Acceptable values are:'pt': Return PyTorchtorch.Tensorobjects.
- return_token_type_ids (
bool, optional) — Whether to return token type IDs. ForMistralCommonBackendit returns a list of zeros of the sequence length as only one sequence is supported. - return_attention_mask (
bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by thereturn_outputsattribute. - return_overflowing_tokens (
bool, optional, defaults toFalse) — Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch of pairs) is provided withtruncation_strategy = longest_firstorTrue, an error is raised instead of returning overflowing tokens. - return_special_tokens_mask (
bool, optional, defaults toFalse) — Whether or not to return special tokens mask information. - return_length (
bool, optional, defaults toFalse) — Whether or not to return the lengths of the encoded inputs. - verbose (
bool, optional, defaults toTrue) — Whether or not to print more information and warnings. - return_offsets_mapping (
Literal[False], optional) — False, kept to match Transformers’ signature. - split_special_tokens (
Literal[False], optional) — False, kept to match Transformers’ signature. - **kwargs — passed to the
self.tokenize()method
一个 BatchEncoding 对象,包含以下字段:
-
input_ids — 要输入到模型中的标记 ID 列表。
-
attention_mask — 指定模型应关注哪些标记的索引列表(当
return_attention_mask=True或如果 *“attention_mask”* 在self.model_input_names中时)。 -
overflowing_tokens — 溢出标记序列列表(当指定
max_length且return_overflowing_tokens=True时)。 -
num_truncated_tokens — 截断标记的数量(当指定
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
< source >( save_directory: str | os.PathLike tokenizer_config: dict filename_prefix: str | None save_jinja_files: bool )
MistralCommonBackend 不实现 save_chat_templates 是出于设计考虑,因为 mistral-common 不使用 chat templates。
save_pretrained
< source >( 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 **kwargs ) → 元组 str
参数
- save_directory (
str或os.PathLike) — Tokenizer 将被保存的目录路径。 - push_to_hub (
bool, 可选, 默认为False) — 是否在保存分词器后将其推送到 Hugging Face 模型中心。您可以使用repo_id指定要推送到的存储库(默认为您自己的命名空间中的save_directory名称)。 - token (
str或 bool, 可选, 默认为None) — 用于推送到模型中心的 token。如果为True,将使用HF_TOKEN环境变量中的 token。 - commit_message (
str, 可选) — 推送到 hub 时使用的 commit 消息。 - repo_id (
str, 可选) — 推送到 Hub 的存储库名称。 - private (
bool, 可选) — 模型存储库是私有的还是公开的。 - kwargs (
Dict[str, Any], 可选) —MistralCommonBackend.save_pretrained不支持。如果使用,将引发错误。
返回
str 的元组
已保存的文件。
保存完整的 tokenizer 状态。
此方法可确保完整的 tokenizer 稍后可以使用 ~MistralCommonBackend.tokenization_mistral_common.from_pretrained 类方法重新加载。
MistralCommonBackend 不实现 save_vocabulary,这是出于设计考虑。
这是因为 mistral-common 由一个 tokenizer 文件配置。如果您想保存词汇表,请考虑使用 save_pretrained 方法。
tokenize
< source >( text: str return_offsets_mapping: typing.Literal[False] = False split_special_tokens: typing.Literal[False] = False **kwargs ) → list[str]
使用分词器将字符串转换为标记序列。
根据词汇表拆分为单词或子词。
truncate_sequences
< source >( 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 ) → Tuple[list[int], None, list[int]]
参数
- ids (
list[int]) — Tokenized 输入 id。可以通过链式调用tokenize和convert_tokens_to_ids方法从字符串获得。 - pair_ids (
None, 可选) —MistralCommonBackend不支持。为了匹配PreTrainedTokenizerBase.truncate_sequences的签名而保留。 - num_tokens_to_remove (
int, 可选, 默认为 0) — 使用截断策略要删除的 token 数量。 - truncation_strategy (
str或 TruncationStrategy, 可选, 默认为'longest_first') — 要遵循的截断策略。可以是:'longest_first':截断到max_length参数指定的最大长度,或者如果未提供该参数,则截断到模型的最大可接受输入长度。'do_not_truncate'(默认):不截断(即,可以输出超过模型最大允许输入大小的序列长度的批次)。
- stride (
int, 可选, 默认为 0) — 如果设置为正数,则返回的溢出 token 将包含主返回序列中的一些 token。此参数的值定义了附加 token 的数量。
返回
list[int], None, list[int] 的元组
截断后的 ids 和溢出标记列表。None 返回以匹配 Transformers 的签名。
根据策略原地截断序列对。
MixtralModel
class transformers.MixtralModel
< source >( config: MixtralConfig )
参数
- config (MixtralConfig) — 模型的配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
输出原始隐藏状态的裸 Mixtral 模型,没有在其顶部添加任何特定头部。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None cache_position: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.MoeModelOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)的torch.LongTensor, 可选) — 词汇表中输入序列 token 的索引。默认会忽略 padding。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (形状为
(batch_size, sequence_length)的torch.Tensor, 可选) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值选择在[0, 1]之间:- 1 表示未掩码的 token,
- 0 表示掩码的 token。
- position_ids (形状为
(batch_size, sequence_length)的torch.LongTensor, 可选) — 位置嵌入中每个输入序列 token 的位置索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预先计算好的隐藏状态(自注意力模块和交叉注意力模块中的键值),可用于加速序列解码。这通常是当use_cache=True或config.use_cache=True时,模型在解码的先前阶段返回的past_key_values。仅允许 Cache 实例作为输入,请参阅我们的 kv cache 指南。如果未传递
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户应仅输入未处理的input_ids(即没有为其提供过去键值状态的模型输入),形状为(batch_size, unprocessed_length),而不是所有input_ids,形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望比模型内部嵌入查找矩阵对input_ids索引到相关向量的转换有更多的控制,这将非常有用。 - use_cache (
bool, optional) — 如果设置为True,则返回past_key_values键值状态,并可用于加速解码(参见past_key_values)。 - cache_position (
torch.LongTensorof shape(sequence_length), optional) — 指示输入序列在序列中的位置的索引。与position_ids不同,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。
返回
transformers.modeling_outputs.MoeModelOutputWithPast 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.MoeModelOutputWithPast 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置(MixtralConfig)和输入。
-
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 -
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seepast_key_valuesinput) to speed up sequential decoding. -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
-
router_logits (
tuple(torch.FloatTensor), 可选, 当传递output_router_probs=True且config.add_router_probs=True时,或config.output_router_probs=True时返回) — 形状为(batch_size, sequence_length, num_experts)的torch.FloatTensor元组(每一层一个)。由 MoE 路由器计算的原始路由器对数(softmax 后),这些术语用于计算专家混合模型的辅助损失。
MixtralModel 的 forward 方法,重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
MixtralForCausalLM
class transformers.MixtralForCausalLM
< source >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (MixtralForCausalLM) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
Mixtral 模型,用于因果语言建模。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None output_router_logits: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.MoeCausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列中 token 的索引。默认情况下会忽略填充。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免在填充 token 索引上执行注意力的掩码。掩码值选择在[0, 1]中:- 1 表示未掩码的 token,
- 0 表示已掩码的 token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 每个输入序列 token 在位置嵌入中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预先计算好的隐藏状态(自注意力模块和交叉注意力模块中的键值),可用于加速序列解码。这通常是当use_cache=True或config.use_cache=True时,模型在解码的先前阶段返回的past_key_values。仅允许 Cache 实例作为输入,请参阅我们的 kv cache 指南。如果未传递
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,则用户应仅输入未处理的input_ids(即没有为其提供过去键值状态的模型输入),形状为(batch_size, unprocessed_length),而不是所有input_ids,形状为(batch_size, sequence_length)。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望比模型内部嵌入查找矩阵对input_ids索引到相关向量的转换有更多的控制,这将非常有用。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应在[0, ..., config.vocab_size]或 -100 范围内(参见input_ids文档字符串)。索引设置为-100的 token 被忽略(掩码),损失仅为标签在[0, ..., config.vocab_size]范围内的 token 计算。 - use_cache (
bool, optional) — 如果设置为True,则返回past_key_values键值状态,并可用于加速解码(参见past_key_values)。 - output_router_logits (
bool, optional) — 是否返回所有路由器的 logits。它们对于计算路由器损失很有用,在推理过程中不应返回。 - cache_position (
torch.LongTensorof shape(sequence_length), optional) — 指示输入序列在序列中的位置的索引。与position_ids不同,此张量不受填充的影响。它用于在正确的位置更新缓存并推断完整的序列长度。 - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — 如果是int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,并且仅为该 token 计算它们可以节省内存,这对于长序列或大词汇量来说非常重要。如果是torch.Tensor,则必须是 1D 的,对应于序列长度维度中要保留的索引。这在打包张量格式(批次和序列长度的单维度)时很有用。
返回
transformers.modeling_outputs.MoeCausalLMOutputWithPast 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.MoeCausalLMOutputWithPast 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置(MixtralConfig)和输入。
-
loss (
torch.FloatTensor形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。 -
logits (形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
aux_loss (
torch.FloatTensor,可选,当提供labels时返回) — 稀疏模块的辅助损失。 -
router_logits (
tuple(torch.FloatTensor), 可选, 当传递output_router_probs=True且config.add_router_probs=True时,或config.output_router_probs=True时返回) — 形状为(batch_size, sequence_length, num_experts)的torch.FloatTensor元组(每一层一个)。由 MoE 路由器计算的原始路由器对数(softmax 后),这些术语用于计算专家混合模型的辅助损失。
-
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
MixtralForCausalLM 的 forward 方法,重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> 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
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.SequenceClassifierOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中的输入序列 token 的索引。默认情况下,将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力。Mask 值选择在[0, 1]中:- 1 表示未被 mask 的 token,
- 0 表示被 mask 的 token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在位置嵌入中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常由模型在解码的先前阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只有 Cache 实例允许作为输入,请参阅我们的 kv cache 指南。如果未传递
past_key_values,则默认初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,用户应仅输入未处理的input_ids(其过去密钥值状态未提供给此模型的那些),形状为(batch_size, unprocessed_length),而不是所有形状为(batch_size, sequence_length)的input_ids。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传递嵌入表示,而不是传递input_ids。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将input_ids索引转换为相关向量,这将非常有用。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应为[0, ..., config.vocab_size]或 -100(请参阅input_ids文档字符串)。索引设置为-100的 token 将被忽略(mask),仅为标签在[0, ..., config.vocab_size]范围内的 token 计算损失。 - use_cache (
bool, optional) — 如果设置为True,将返回past_key_values键值状态,并可用于加速解码(请参阅past_key_values)。
返回
transformers.modeling_outputs.SequenceClassifierOutputWithPast 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.SequenceClassifierOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
logits (形状为
(batch_size, config.num_labels)的torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。 -
past_key_values (
Cache, optional, 当传递use_cache=True或当config.use_cache=True时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The GenericForSequenceClassification forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
MixtralForTokenClassification
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None use_cache: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中的输入序列 token 的索引。默认情况下,将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力。Mask 值选择在[0, 1]中:- 1 表示未被 mask 的 token,
- 0 表示被 mask 的 token。
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 输入序列 token 在位置嵌入中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常由模型在解码的先前阶段返回的past_key_values组成,当use_cache=True或config.use_cache=True时。只有 Cache 实例允许作为输入,请参阅我们的 kv cache 指南。如果未传递
past_key_values,则默认初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用
past_key_values,用户应仅输入未处理的input_ids(其过去密钥值状态未提供给此模型的那些),形状为(batch_size, unprocessed_length),而不是所有形状为(batch_size, sequence_length)的input_ids。 - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传递嵌入表示,而不是传递input_ids。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将input_ids索引转换为相关向量,这将非常有用。 - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应为[0, ..., config.vocab_size]或 -100(请参阅input_ids文档字符串)。索引设置为-100的 token 将被忽略(mask),仅为标签在[0, ..., config.vocab_size]范围内的 token 计算损失。 - use_cache (
bool, optional) — 如果设置为True,将返回past_key_values键值状态,并可用于加速解码(请参阅past_key_values)。
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.TokenClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.
-
loss (形状为
(1,)的torch.FloatTensor,可选,当提供labels时返回) — 分类损失。 -
logits (形状为
(batch_size, sequence_length, config.num_labels)的torch.FloatTensor) — 分类分数(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The GenericForTokenClassification forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
MixtralForQuestionAnswering
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None start_positions: torch.LongTensor | None = None end_positions: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — 词汇表中的输入序列 token 的索引。默认情况下,将忽略填充(padding)。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - start_positions (
torch.LongTensorof shape(batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss. - end_positions (
torch.LongTensorof shape(batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
返回
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.QuestionAnsweringModelOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.
-
loss (
torch.FloatTensorof shape(1,), 可选, 当提供labels时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。 -
start_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。 -
end_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围结束分数(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The GenericForQuestionAnswering forward method, overrides the __call__ special method.
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。