Transformers documentation
Pixtral
该模型于 2024-10-09 在 HF papers 上发布,并于 2024-09-14 贡献至 Hugging Face Transformers。
Pixtral
Pixtral 是一个多模态模型,经过训练以理解自然图像和文档。得益于其 2D RoPE 嵌入,它可以接受自然分辨率和宽高比的图像,而无需调整大小或填充。此外,Pixtral 拥有 128K token 的长上下文窗口,用于处理大量图像。Pixtral 将 400M 视觉编码器与 12B Mistral Nemo 解码器相结合。
Pixtral architecture. Taken from the blog post. 您可以在 Mistral AI 组织下找到所有原始的 Pixtral 检查点。
该模型由 amyeroberts 和 ArthurZ 贡献。 点击右侧边栏中的 Pixtral 模型,以获取更多关于如何将 Pixtral 应用于不同视觉和语言任务的示例。
import torch
from transformers import AutoProcessor, LlavaForConditionalGeneration
model_id = "mistral-community/pixtral-12b"
model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
url_dog = "https://picsum.photos/id/237/200/300"
url_mountain = "https://picsum.photos/seed/picsum/200/300"
chat = [
{
"role": "user", "content": [
{"type": "text", "content": "Can this animal"},
{"type": "image", "url": url_dog},
{"type": "text", "content": "live here?"},
{"type": "image", "url" : url_mountain}
]
}
]
inputs = processor.apply_chat_template(chat, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device)
generate_ids = model.generate(**inputs, max_new_tokens=500)
output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]量化通过以较低精度表示权重来降低大模型的内存负担。有关更多可用的量化后端,请参阅 量化 概述。
以下示例使用 bitsandbytes 将模型量化为 4 位。
import requests
import torch
from PIL import Image
from transformers import AutoProcessor, BitsAndBytesConfig, LlavaForConditionalGeneration
model_id = "mistral-community/pixtral-12b"
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
model = LlavaForConditionalGeneration.from_pretrained(
model_id,
quantization_config=quantization_config,
device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_id)
dog_url = "https://picsum.photos/id/237/200/300"
mountain_url = "https://picsum.photos/seed/picsum/200/300"
dog_image = Image.open(requests.get(dog_url, stream=True).raw)
mountain_image = Image.open(requests.get(mountain_url, stream=True).raw)
chat = [
{
"role": "user", "content": [
{"type": "text", "text": "Can this animal"},
{"type": "image"},
{"type": "text", "text": "live here?"},
{"type": "image"}
]
}
]
prompt = processor.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
inputs = processor(text=prompt, images=[dog_image, mountain_image], return_tensors="pt").to(model.device)
inputs["pixel_values"] = inputs["pixel_values"].to(model.dtype)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
generate_ids = model.generate(**inputs, max_new_tokens=100)
output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
print(output)备注
Pixtral 使用 PixtralVisionModel 作为视觉编码器,并使用 MistralForCausalLM 作为语言解码器。
该模型在内部将
[IMG]标记占位符替换为图像嵌入。"<s>[INST][IMG]\nWhat are the things I should be cautious about when I visit this place?[/INST]"[IMG]标记会被替换为一定数量的[IMG]标记,具体数量取决于每张图片的高度和宽度。图像的每行之间由一个[IMG_BREAK]标记分隔,每张图片之间由一个[IMG_END]标记分隔。请使用~Processor.apply_chat_template方法来自动处理这些标记。
PixtralVisionConfig
class transformers.PixtralVisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024intermediate_size: int = 4096num_hidden_layers: int = 24num_attention_heads: int = 16num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'attention_dropout: float | int = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneinitializer_range: float = 0.02 )
参数
- hidden_size (
int,可选,默认为1024) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为4096) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为24) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为1024) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
这是用于存储 PixtralVisionModel 配置的类。它根据指定的参数实例化 Pixtral 模型,并定义模型架构。使用默认值实例化配置,将得到与 mistral-labs/pixtral-12b 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import PixtralVisionModel, PixtralVisionConfig
>>> # Initializing a Pixtral-12B style configuration
>>> config = PixtralVisionConfig()
>>> # Initializing a model (with randomly initialized weights) from the configuration
>>> model = PixtralVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configMistralCommonBackend
class transformers.MistralCommonBackend
< source >( tokenizer_path: str | os.PathLike | pathlib.Pathmode: str | ValidationMode = 'test'model_max_length: int = 1000000000000000019884624838656padding_side: str = 'left'truncation_side: str = 'right'model_input_names: list[str] | None = Noneclean_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。与 Transformers 不同,特殊 token 的处理方式有所区别。在
mistral-common中,特殊 token 永远不会被直接编码。这意味着:tokenizer.encode("<s>")不会返回<s>token 的 ID,而是返回一个 ID 列表,对应于字符串"<s>"的分词结果。更多信息请参阅 mistral-common 文档。
如果您有改进此类的建议,请根据问题类型在相应的 GitHub 仓库中提交 issue:若与 tokenizer 相关,请在 mistral-common GitHub 仓库 中提交;若与 Hugging Face 接口相关,请在 Transformers GitHub 仓库 中提交。
add_special_tokens
< source >( special_tokens_dict: dictreplace_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 = Noneadd_generation_prompt: bool = Falsecontinue_final_message: bool = Falsetokenize: bool = Truepadding: bool | str | transformers.utils.generic.PaddingStrategy = Falsetruncation: bool = Falsemax_length: int | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonereturn_dict: bool = Truereasoning_effort: ReasoningEffort | None = None**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无效。但为了保持 API 的一致性,它不能与continue_final_message同时使用。 如果任何对话以助手消息结尾,则会引发错误。在这种情况下,请改用continue_final_message。 - continue_final_message (bool, 可选) —
如果设置此项,聊天将被格式化,使得聊天中的最后一条消息是开放式的,不包含任何 EOS token。模型将继续该消息,而不是开始一条新消息。这允许你“预填充”模型响应的一部分。不能与
add_generation_prompt同时使用。 - tokenize (
bool,默认为True) — 是否对输出进行分词。如果为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键中,图像尺寸将返回在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
< source >( sequences: typing.Union[list[int], list[list[int]], numpy.ndarray, ForwardRef('torch.Tensor')]skip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool | None = None**kwargs ) → list[str]
参数
- 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
< source >( token_ids_0: listtoken_ids_1: None = None ) → list[int]
通过添加特殊标记,从序列构建模型输入。
此方法会根据分词器的 mode 动态构建输入:
"test":seq0 [EOS]"finetuning":[BOS] seq0
convert_added_tokens
< source >( obj: tokenizers.AddedToken | typing.Anysave: bool = Falseadd_type_field: bool = True )
MistralCommonBackend 在设计上未实现 convert_added_tokens。
如果您希望实现此行为,请在 Transformers 或 mistral-common 仓库中提交 issue 以提出请求。
create_token_type_ids_from_sequences
< source >( token_ids_0: listtoken_ids_1: None = None ) → list[int]
使用添加了特殊标记的标记 ID 创建一个全零掩码。
保留以匹配 Transformers 的实现。
decode
< source >( token_ids: typing.Union[int, list[int], list[list[int]], numpy.ndarray, ForwardRef('torch.Tensor')]skip_special_tokens: bool = Falseclean_up_tokenization_spaces: bool | None = None**kwargs ) → Union[str, list[str]]
参数
- 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
< source >( text: str | list[int]text_pair: None = Noneadd_special_tokens: bool = Truepadding: bool | str | transformers.utils.generic.PaddingStrategy = Falsetruncation: bool | str | transformers.tokenization_utils_base.TruncationStrategy | None = Nonemax_length: int | None = Nonestride: int = 0pad_to_multiple_of: int | None = Nonepadding_side: str | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Noneverbose: bool = Truereturn_offsets_mapping: typing.Literal[False] = Falsesplit_special_tokens: typing.Literal[False] = False**kwargs ) → list[int], torch.Tensor
参数
- 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, ,可选, ,默认为False) — 启用并控制填充。接受以下值:True或'longest':填充至批次中最长的序列(如果仅提供单个序列,则不进行填充)。'max_length':填充至由参数max_length指定的最大长度;若未提供该参数,则填充至模型可接受的最大输入长度。False或'do_not_pad'(默认值):不进行填充(即可以输出包含不同长度序列的批次)。
- truncation (
bool,str或 TruncationStrategy, 可选, 默认值为False) — 启用并控制截断。接受以下值:True或'longest_first':截断至由参数max_length指定的最大长度,或者在未提供该参数时,截断至模型可接受的最大输入长度。False或'do_not_truncate'(默认值):不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。
- max_length (
int, 可选) — 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 None,则当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(如 XLNet),则禁用截断/填充到最大长度的功能。如果未设置或设置为
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, 可选) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。
- **kwargs —
MistralCommonBackend.encode不支持。 如果使用了该参数,将引发错误。
返回值
list[int], torch.Tensor
文本的标记化 ID。
使用分词器和词汇表将字符串转换为 id(整数)序列。
from_pretrained
< source >( pretrained_model_name_or_path: str | os.PathLike*init_inputsmode: str | ValidationMode = 'test'cache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'model_max_length: int = 1000000000000000019884624838656padding_side: str = 'left'truncation_side: str = 'right'model_input_names: list[str] | None = Noneclean_up_tokenization_spaces: bool = False**kwargs )
参数
- 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:测试模式。它会改变 tokenizer 验证输入并准备模型请求的方式。"finetuning"或ValidationMode.finetuning:微调模式。"test"或ValidationMode.test:测试模式。 它会改变分词器验证输入并准备模型请求的方式。
- cache_dir (
str或os.PathLike,可选) — 如果不应使用标准缓存,则下载的预定义分词器词汇文件应缓存到的目录路径。 - force_download (
bool,可选,默认为False) — 是否强制(重新)下载词汇表文件,并在缓存版本已存在时覆盖它们。 - token(
str或 bool,可选)— 用于远程文件的 HTTP 承载者授权令牌。如果为True,则使用运行hf auth login时生成的令牌(存储在~/.huggingface中)。 - local_files_only(
bool,可选,默认为False)— 是否仅依赖本地文件,而不尝试下载任何文件。 - revision (
str,可选,默认为"main") — 要使用的特定模型版本。由于我们在 huggingface.co 上使用基于 git 的系统来存储模型和其他工件,因此它可以是分支名称、标签名称或提交 id,revision可以是 git 允许的任何标识符。 - max_length (
int, 可选) — 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 None,则当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(如 XLNet),则禁用截断/填充到最大长度的功能。如果未设置或设置为
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 不使用聊天模板。
get_special_tokens_mask
< source >( token_ids_0: listtoken_ids_1: None = Nonealready_has_special_tokens: bool = False ) → A list of integers in the range [0, 1]
从未添加特殊标记的标记列表中获取序列 ID。当使用分词器的 prepare_for_model 或 encode_plus 方法添加特殊标记时,会调用此方法。
返回一个从 token 到索引的字典形式的词汇表。
这是一种有损转换。由于部分 UTF-8 字节序列会被转换为 �,可能会有多个 token id 解码为相同的字符串。
num_special_tokens_to_add
< source >( pair: typing.Literal[False] = False ) → int
在编码包含特殊标记的序列时,返回所添加标记的数量。
这会编码一个虚拟输入并检查新增的 token 数量,因此效率不高。请勿将其放在训练循环内部。
prepare_for_model
< source >( ids: listpair_ids: None = Noneadd_special_tokens: bool = Truepadding: bool | str | transformers.utils.generic.PaddingStrategy = Falsetruncation: bool | str | transformers.tokenization_utils_base.TruncationStrategy | None = Nonemax_length: int | None = Nonestride: int = 0pad_to_multiple_of: int | None = Nonepadding_side: str | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonereturn_token_type_ids: bool | None = Nonereturn_attention_mask: bool | None = Nonereturn_overflowing_tokens: bool = Falsereturn_special_tokens_mask: bool = Falsereturn_length: bool = Falseverbose: bool = Trueprepend_batch_axis: bool = Falsereturn_offsets_mapping: typing.Literal[False] = Falsesplit_special_tokens: typing.Literal[False] = False**kwargs ) → BatchEncoding
参数
- 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, ,可选, ,默认为False) — 启用并控制填充。接受以下值:True或'longest':填充至批次中最长的序列(如果仅提供单个序列,则不进行填充)。'max_length':填充至由参数max_length指定的最大长度;若未提供该参数,则填充至模型可接受的最大输入长度。False或'do_not_pad'(默认值):不进行填充(即可以输出包含不同长度序列的批次)。
- truncation (
bool,str或 TruncationStrategy, 可选, 默认值为False) — 启用并控制截断。接受以下值:True或'longest_first':截断至由参数max_length指定的最大长度,或者在未提供该参数时,截断至模型可接受的最大输入长度。False或'do_not_truncate'(默认值):不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。
- max_length (
int, 可选) — 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 None,则当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(如 XLNet),则禁用截断/填充到最大长度的功能。如果未设置或设置为
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, 可选) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。
- return_token_type_ids (
bool, 可选) — 是否返回 token type ID。对于MistralCommonBackend,它返回一个与序列长度相同的零列表,因为仅支持单个序列。 - return_attention_mask (
bool, 可选) — 是否返回注意力掩码。如果保持默认值,将根据特定分词器的默认设置返回注意力掩码,该设置由return_outputs属性定义。 - return_overflowing_tokens (
bool,可选,默认为False) — 是否返回溢出的 token 序列。如果提供了输入 id 的序列对(或序列对批次),且truncation_strategy = longest_first或True,则会抛出错误,而不是返回溢出的 token。 - return_special_tokens_mask (
bool,可选,默认为False) — 是否返回特殊 token 掩码信息。 - 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:
-
input_ids — 要输入模型的 token id 列表。
-
attention_mask — 索引列表,指定模型应关注哪些 token(当
return_attention_mask=True或 “attention_mask” 位于self.model_input_names中时)。 -
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
< source >( save_directory: str | os.PathLiketokenizer_config: dictfilename_prefix: str | Nonesave_jinja_files: bool )
MistralCommonBackend 出于设计考虑未实现 save_chat_templates,因为 mistral-common 不使用聊天模板。
save_pretrained
< source >( save_directory: str | os.PathLike | pathlib.Pathpush_to_hub: bool = Falsetoken: str | bool | None = Nonecommit_message: str | None = Nonerepo_id: str | None = Noneprivate: bool | None = Nonesave_format: str | None = None**kwargs ) → tuple[str, ...]
参数
- save_directory (
str | os.PathLike | Path) — 保存 tokenizer 的目录。 - 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)。
MistralCommonBackend 在设计上未实现 save_vocabulary。
这是因为 mistral-common 由一个分词器文件进行配置。如果您希望保存词表,请考虑改用 save_pretrained 方法。
tokenize
< source >( text: strreturn_offsets_mapping: typing.Literal[False] = Falsesplit_special_tokens: typing.Literal[False] = False**kwargs ) → list[str]
使用分词器将字符串转换为标记序列。
对于基于单词的词汇表,按单词进行拆分;对于基于子词的词汇表,按子词进行拆分。
truncate_sequences
< source >( ids: listpair_ids: None = Nonenum_tokens_to_remove: int = 0truncation_strategy: str | transformers.tokenization_utils_base.TruncationStrategy = 'longest_first'stride: int = 0**kwargs ) → Tuple[list[int], None, list[int]]
参数
- 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, 可选, 默认为'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。
按照策略就地截断序列对。
PixtralVisionModel
class transformers.PixtralVisionModel
< source >( config: PixtralVisionConfig )
参数
- config (PixtralVisionConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Pixtral 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorimage_sizes: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 与输入图像对应的张量。可以使用 PixtralImageProcessor 获取像素值。有关详细信息,请参阅 PixtralImageProcessor.call()(PixtralProcessor 使用 PixtralImageProcessor 处理图像)。 - image_sizes(形状为
(batch_size, 2)的torch.Tensor,可选) — 批次中各图像的尺寸,每张图像表示为 (height, width)。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(PixtralVisionConfig)和输入。
PixtralVisionModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。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 之后的权重,用于在自注意力头中计算加权平均值。
PixtralImageProcessor
class transformers.PixtralImageProcessor
< source >( **kwargs: *<class 'transformers.models.pixtral.image_processing_pixtral.PixtralImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'longest_edge' -- 1024}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为[0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - patch_size (
Union[dict[str, *kwargs*, int], int]可选,默认为{"height" -- 16, "width": 16}): 模型中 patch 的大小,用于计算输出图像的尺寸。
构建一个 PixtralImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.pixtral.image_processing_pixtral.PixtralImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - patch_size (
Union[dict[str, *kwargs*, int], int]可选,默认为{"height" -- 16, "width": 16}): 模型中 patch 的大小,用于计算输出图像的尺寸。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
PixtralImageProcessorPil
class transformers.PixtralImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.pixtral.image_processing_pil_pixtral.PixtralImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'longest_edge' -- 1024}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为[0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - patch_size (
Union[dict[str, *kwargs*, int], int]可选,默认为{"height" -- 16, "width": 16}): 模型中 patch 的大小,用于计算输出图像的尺寸。
构建一个 PixtralImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.pixtral.image_processing_pil_pixtral.PixtralImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - patch_size (
Union[dict[str, *kwargs*, int], int]可选,默认为{"height" -- 16, "width": 16}): 模型中 patch 的大小,用于计算输出图像的尺寸。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
PixtralProcessor
class transformers.PixtralProcessor
< source >( image_processor = Nonetokenizer = Nonepatch_size: int = 16spatial_merge_size: int = 1chat_template = Noneimage_token = '[IMG]'image_break_token = '[IMG_BREAK]'image_end_token = '[IMG_END]'**kwargs )
参数
- image_processor (
PixtralImageProcessor) — 图像处理器是必需的输入。 - tokenizer (
MistralCommonBackend) — tokenizer 是必需的输入。 - patch_size (
int,可选,默认为 16) — 视觉塔的 patch 大小。 - spatial_merge_size (
int,可选,默认为 1) — 空间合并操作的下采样因子。 - chat_template (
str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。 - image_token (
str,可选,默认为"[IMG]") — 用于表示图像位置的专用标记。 - image_break_token (
str,可选,默认为"[IMG_BREAK]") — 用于表示图像中一行像素结束的特殊标记。 - image_end_token (
str,可选,默认为"[IMG_END]") — 用于表示图像输入结束的特殊标记。
构建一个 PixtralProcessor,它将图像处理器和分词器封装为单个处理器。
PixtralProcessor 提供了 PixtralImageProcessor 和 MistralCommonBackend 的所有功能。有关更多信息,请参阅 ~PixtralImageProcessor 和 ~MistralCommonBackend。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - text (
Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True,以避免与批量输入产生歧义。 - videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。