Mllama
概述
Llama 3.2-Vision 多模态大语言模型(LLMs)集合是一组预训练和指令调优的图像推理生成模型,包含11B和90B两种规模(文本+图像输入/文本输出)。Llama 3.2-Vision 指令调优模型针对视觉识别、图像推理、图像描述以及回答关于图像的一般问题进行了优化。
模型架构: Llama 3.2-Vision 建立在 Llama 3.1 纯文本模型之上,Llama 3.1 是一个使用优化变压器架构的自回归语言模型。调优版本使用监督微调(SFT)和带有人类反馈的强化学习(RLHF)来与人类对帮助性和安全性的偏好保持一致。为了支持图像识别任务,Llama 3.2-Vision 模型使用了一个单独训练的视觉适配器,该适配器与预训练的 Llama 3.1 语言模型集成。适配器由一系列交叉注意力层组成,这些层将图像编码器表示输入到核心 LLM 中。
使用技巧
- 对于图像+文本和文本输入,使用
MllamaForConditionalGeneration
。 - 对于仅文本输入,使用
MllamaForCausalLM
进行生成,以避免加载视觉塔。 - 每个样本可以包含多张图像,且样本之间的图像数量可以不同。处理器会将输入填充到样本中图像数量的最大值,以及每张图像中瓦片数量的最大值。
- 传递给处理器的文本应在应插入图像的位置包含
"<|image|>"
标记。 - 处理器有自己的
apply_chat_template
方法,用于将聊天消息转换为文本,然后可以将该文本传递给处理器。
Mllama 有一个额外的标记,用作文本中图像位置的占位符。这意味着输入ID和输入嵌入层将有一个额外的标记。但由于输入和输出嵌入的权重没有绑定,lm_head
层少了一个标记,如果你想在图像标记上计算损失或应用一些logit处理器,将会失败。如果你正在训练,请确保在labels
中屏蔽掉特殊的"<|image|>"
标记,因为模型不应该被训练来预测它们。
否则,如果在生成时看到CUDA端的索引错误,请使用以下代码将lm_head
扩展一个额外的标记。
old_embeddings = model.get_output_embeddings()
num_tokens = model.vocab_size + 1
resized_embeddings = model._get_resized_lm_head(old_embeddings, new_num_tokens=num_tokens, mean_resizing=True)
resized_embeddings.requires_grad_(old_embeddings.weight.requires_grad)
model.set_output_embeddings(resized_embeddings)
使用示例
指令模型
import requests
import torch
from PIL import Image
from transformers import MllamaForConditionalGeneration, AutoProcessor
model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct"
model = MllamaForConditionalGeneration.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
processor = AutoProcessor.from_pretrained(model_id)
messages = [
[
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What does the image show?"}
]
}
],
]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
url = "https://llava-vl.github.io/static/images/view.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(text=text, images=image, return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=25)
print(processor.decode(output[0]))
基础模型
import requests
import torch
from PIL import Image
from transformers import MllamaForConditionalGeneration, AutoProcessor
model_id = "meta-llama/Llama-3.2-11B-Vision"
model = MllamaForConditionalGeneration.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
processor = AutoProcessor.from_pretrained(model_id)
prompt = "<|image|>If I had to write a haiku for this one"
url = "https://llava-vl.github.io/static/images/view.jpg"
raw_image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(text=prompt, images=raw_image, return_tensors="pt").to(model.device)
output = model.generate(**inputs, do_sample=False, max_new_tokens=25)
print(processor.decode(output[0], skip_special_tokens=True))
MllamaConfig
类 transformers.MllamaConfig
< source >( vision_config = None text_config = None image_token_index = 128256 **kwargs )
这是用于存储MllamaForConditionalGeneration配置的配置类。它用于根据指定的参数实例化一个Mllama模型,定义模型架构。使用默认值实例化配置将产生类似于Mllama-9B的配置。
例如 meta-llama/Llama-3.2-11B-Vision
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import MllamaForConditionalGeneration, MllamaConfig, MllamaVisionConfig, MllamaTextConfig
>>> # Initializing a CLIP-vision config
>>> vision_config = MllamaVisionConfig()
>>> # Initializing a Llama config
>>> text_config = MllamaTextConfig()
>>> # Initializing a mllama-11b style configuration
>>> configuration = MllamaConfig(vision_config, text_config)
>>> # Initializing a model from the mllama-11b style configuration
>>> model = MllamaForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
MllamaProcessor
类 transformers.MllamaProcessor
< source >( image_processor tokenizer )
参数
- image_processor (MllamaImageProcessor) — 图像处理器是一个必需的输入。
- tokenizer ([
PreTrainedTokenizer
,PreTrainedTokenizerFast
]) — tokenizer 是一个必需的输入。
构建一个Mllama处理器,它将MllamaImageProcessor和
PretrainedTokenizerFast
封装成一个单一的处理器,该处理器继承了图像处理器和
分词器的功能。有关更多信息,请参见__call__()
和decode()。
传递kwargs的首选方式是作为每个模态的字典,请参见下面的使用示例。
from transformers import MllamaProcessor
from PIL import Image
processor = MllamaProcessor.from_pretrained("meta-llama/Llama-3.2-11B-Vision")
processor(
images=your_pil_image,
text=["<|image|>If I had to write a haiku for this one"],
images_kwargs = {"size": {"height": 448, "width": 448}},
text_kwargs = {"padding": "right"},
common_kwargs = {"return_tensors": "pt"},
)
此方法将其所有参数转发给PreTrainedTokenizerFast的batch_decode()。请参考该方法的文档字符串以获取更多信息。
此方法将其所有参数转发给PreTrainedTokenizerFast的decode()。请参考该方法的文档字符串以获取更多信息。
post_process_image_text_to_text
< source >( generated_outputs ) → List[str]
对模型的输出进行后处理以解码文本。
MllamaImageProcessor
类 transformers.MllamaImageProcessor
< source >( do_convert_rgb: bool = True do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling =
参数
- do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为RGB。如果输入图像是其他格式(例如RGBA),这将非常有用。 仅当输入图像为PIL格式时才会生效。 - do_resize (
bool
, optional, defaults toTrue
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 图像块的大小。应该是一个包含 'height' 和 'width' 键的字典,两者都应为整数值。 高度和宽度值应相等。 - resample (
int
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举PILImageResampling
中的一个。只有在do_resize
设置为True
时才会生效。 - do_rescale (
bool
, optional, defaults toTrue
) — 是否对图像进行重新缩放. - rescale_factor (
float
, optional, defaults to 0.0) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toTrue
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_pad (
bool
, 可选, 默认为True
) — 是否将图像填充到批次中最大的高度和宽度。 - max_image_tiles (
int
, optional, defaults to 4) — 图像分割的最大块数。
构建一个Mllama图像处理器。
pad
< source >( image: ndarray size: typing.Dict[str, int] aspect_ratio: typing.Tuple[int, int] data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) → np.ndarray
将图像填充到size
x aspect_ratio
。例如,如果尺寸是{height: 224, width: 224},宽高比是(1, 2),图像将被填充到224x448。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_convert_rgb: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample: typing.Optional[PIL.Image.Resampling] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_pad: typing.Optional[bool] = None max_image_tiles: typing.Optional[int] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None ) → BatchFeature
的以下结构
参数
- 图片 (
ImageInput
) — 要预处理的图片列表。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为RGB. - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小. - size (
Dict[str, int]
, 可选, 默认为self.size
) — 图像瓦片的大小。应该是一个包含 'height' 和 'width' 键的字典,两者都应为整数值。 高度和宽度值应相等。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举PILImageResampling
中的一个。只有在do_resize
设置为True
时才会生效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_pad (
bool
, optional, defaults toself.do_pad
) — 是否将图像填充到批次中最大的高度和宽度。 - max_image_tiles (
int
, 可选, 默认为self.max_image_tiles
) — 图像分割的最大块数。 - input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
- return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回一个类型为tf.Tensor
的批次。TensorType.PYTORCH
或'pt'
:返回一个类型为torch.Tensor
的批次。TensorType.NUMPY
或'np'
:返回一个类型为np.ndarray
的批次。TensorType.JAX
或'jax'
:返回一个类型为jax.numpy.ndarray
的批次。
- 未设置:返回一个
返回
BatchFeature
的以下结构
- pixel_values (
TensorType
): 预处理后的像素值。 - aspect_ratio_ids (
TensorType
): 图像的宽高比ID。 - num_tiles (
List[List[int]]
): 批次中每个图像的瓦片数量。
预处理一批图像。
调整大小
< source >( image: ndarray size: typing.Dict[str, int] max_image_tiles: int resample: Resampling = Union[np.ndarray, Tuple[int, int]]
参数
- image (
np.ndarray
) — 要调整大小的图像。 - size (
Dict[str, int]
) — 输出图像的大小。 - max_image_tiles (
int
) — 图像分割的最大瓦片数。 - resample (
PILImageResampling
, optional, defaults toPILImageResampling.BICUBIC
) — 调整图像大小时使用的重采样过滤器。 - data_format (
str
或ChannelDimension
, 可选) — 图像的通道维度格式。如果未提供,将与输入图像相同。 - input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未提供,将会自动推断。
返回
Union[np.ndarray, Tuple[int, int]]
调整大小后的图像和一个包含沿高度和宽度维度的瓦片数量的元组。
调整图像大小以适应平铺画布,同时保持其宽高比。 最佳画布大小是根据最大平铺数量和平铺大小计算的。
该函数首先确定图像的最佳平铺排列方式,然后调整图像大小以适应此画布。返回调整后的图像以及沿高度和宽度维度的平铺数量。
MllamaForConditionalGeneration
类 transformers.MllamaForConditionalGeneration
< source >( config: MllamaConfig )
参数
- config (MllamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Mllama模型由视觉编码器和语言模型组成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None aspect_ratio_mask: typing.Optional[torch.Tensor] = None aspect_ratio_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None cross_attention_mask: typing.Optional[torch.Tensor] = None cross_attention_states: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None num_logits_to_keep: int = 0 ) → transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor
of shape(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)) -- 对应于输入图像的张量。可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取像素值。有关详细信息,请参阅 [MllamaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]
MllamaProcessor`] 使用 MllamaImageProcessor 处理图像)。 - aspect_ratio_mask (
torch.Tensor
形状为(batch_size, max_num_images, max_num_tiles)
, 可选) — 用于避免在填充的瓦片上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的瓦片,
- 0 表示 掩码 的瓦片。
- aspect_ratio_ids (
torch.Tensor
of shape(batch_size, max_num_images)
, optional) — Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model’s list of supported aspect ratios, offset by 1.例如,如果模型支持的宽高比为[[1, 1], [1, 2], [2, 1]]:
- An image with aspect ratio [1, 1] would have ID 1
- An image with aspect ratio [1, 2] would have ID 2
- An image with aspect ratio [2, 1] would have ID 3
id 0 保留用于填充(即没有图像)。
如果图像的宽高比为 [1, 2],这意味着它在水平方向上被分割成 2 个图块,其
aspect_ratio_id
将为 2。 - attention_mask (
torch.Tensor
of 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.
可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
如果使用了
past_key_values
,可以选择只输入最后的input_ids
(参见past_key_values
)。如果你想改变填充行为,你应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- cross_attention_mask (
torch.Tensor
of shape(batch_size, seq_length, max_num_images, max_num_tiles)
, optional) — Cross-attention mask to control the interaction between text tokens and image tiles. This 4D tensor defines which image tiles each text token should attend to.对于每个文本标记(在 seq_length 中):
- 1 indicates the token should attend to the corresponding image tile
- 0 indicates the token should not attend to the corresponding image tile
- cross_attention_states (
torch.FloatTensor
, optional) — 视觉模型的输出,用于交叉注意力。该张量包含语言模型将关注的处理后的图像特征。 - position_ids (
torch.LongTensor
of 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
ortuple(tuple(torch.FloatTensor))
, 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_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.允许两种格式:
- a Cache instance, see our kv cache guide;
- Tuple of
tuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
). This is also known as the legacy cache format.
模型将输出与输入相同的缓存格式。如果没有传递
past_key_values
,将返回旧的缓存格式。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后input_ids
(那些没有将其过去键值状态提供给此模型的input_ids
),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 表示输入序列标记在序列中的位置的索引。与position_ids
相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。 - Args —
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional): Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]
or -100 (seeinput_ids
docstring). Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
.num_logits_to_keep (
int
, 可选): 计算最后num_logits_to_keep
个token的logits。如果为0
,则计算所有input_ids
的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。
返回
transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MllamaConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失(用于下一个标记预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量包含预先计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
MllamaForConditionalGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaForConditionalGeneration
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaForConditionalGeneration.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> prompt = "<|image|>If I had to write a haiku for this one"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(text=prompt, images=image, return_tensors="pt")
>>> # Generate
>>> output = model.generate(**inputs, max_new_tokens=15)
>>> prompt_len = inputs.input_ids.shape[-1]
>>> generated_ids = output[:, prompt_len:]
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
>>> print(generated_text)
[', it would be:.\\nA stop sign in Chinatown.\\n']
MllamaForCausalLM
类 transformers.MllamaForCausalLM
< source >( config )
参数
- config (MllamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Mllama 文本模型,顶部带有语言建模头。 该模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None cross_attention_states: typing.Optional[torch.LongTensor] = None cross_attention_mask: typing.Optional[torch.LongTensor] = None full_text_row_masked_out_mask: typing.Optional[typing.Tuple[torch.Tensor, torch.Tensor]] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None num_logits_to_keep: int = 0 **loss_kwargs ) → transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor
形状为(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)) -- 对应于输入图像的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取。详情请参见 [MllamaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]
MllamaProcessor`] 使用 MllamaImageProcessor 处理图像)。 - aspect_ratio_mask (
torch.Tensor
形状为(batch_size, max_num_images, max_num_tiles)
, 可选) — 用于避免在填充的瓦片上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的瓦片,
- 0 表示 掩码 的瓦片。
- aspect_ratio_ids (
torch.Tensor
of shape(batch_size, max_num_images)
, optional) — Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model’s list of supported aspect ratios, offset by 1.例如,如果模型支持的宽高比为[[1, 1], [1, 2], [2, 1]]:
- An image with aspect ratio [1, 1] would have ID 1
- An image with aspect ratio [1, 2] would have ID 2
- An image with aspect ratio [2, 1] would have ID 3
id 0 保留用于填充(即没有图像)。
如果图像的宽高比为 [1, 2],这意味着它在水平方向上被分割成 2 个图块,其
aspect_ratio_id
将为 2。 - attention_mask (
torch.Tensor
of 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.
可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
如果使用了
past_key_values
,可以选择只输入最后的input_ids
(参见past_key_values
)。如果你想改变填充行为,你应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- cross_attention_mask (
torch.Tensor
of shape(batch_size, seq_length, max_num_images, max_num_tiles)
, optional) — Cross-attention mask to control the interaction between text tokens and image tiles. This 4D tensor defines which image tiles each text token should attend to.对于每个文本标记(在 seq_length 中):
- 1 indicates the token should attend to the corresponding image tile
- 0 indicates the token should not attend to the corresponding image tile
- cross_attention_states (
torch.FloatTensor
, optional) — 视觉模型的输出,用于交叉注意力。该张量包含语言模型将关注的处理后的图像特征。 - position_ids (
torch.LongTensor
of 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
ortuple(tuple(torch.FloatTensor))
, 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_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.允许两种格式:
- a Cache instance, see our kv cache guide;
- Tuple of
tuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
). This is also known as the legacy cache format.
模型将输出与输入相同的缓存格式。如果没有传递
past_key_values
,将返回旧的缓存格式。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后input_ids
(那些没有将其过去键值状态提供给此模型的input_ids
),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 表示输入序列标记在序列中的位置的索引。与position_ids
相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。 - Args —
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional): Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]
or -100 (seeinput_ids
docstring). Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
.num_logits_to_keep (
int
, 可选): 计算最后num_logits_to_keep
个token的logits。如果为0
,则计算所有input_ids
的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。
返回
transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(MllamaTextConfig
)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个标记的预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
MllamaForCausalLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, MllamaForCausalLM
>>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
>>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
>>> prompt = "If I had to write a haiku, it would be:"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
>>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(result)
If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
I love the idea of snowflakes gently falling, each one
MllamaTextModel
类 transformers.MllamaTextModel
< source >( 配置: MllamaTextConfig )
参数
- config (MllamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Mllama 文本模型由具有自注意力和交叉注意力层的变压器组成。 该模型继承自 PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法 (如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None cross_attention_states: typing.Optional[torch.FloatTensor] = None cross_attention_mask: typing.Optional[torch.Tensor] = None full_text_row_masked_out_mask: typing.Optional[typing.Tuple[torch.Tensor, torch.Tensor]] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None ) → transformers.modeling_outputs.BaseModelOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
of 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.
可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
如果使用了
past_key_values
,可以选择只输入最后的input_ids
(参见past_key_values
)。如果你想改变填充行为,你应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- cross_attention_mask (
torch.Tensor
of shape(batch_size, seq_length, max_num_images, max_num_tiles)
, optional) — Cross-attention mask to control the interaction between text tokens and image tiles. This 4D tensor defines which image tiles each text token should attend to.对于每个文本标记(在 seq_length 中):
- 1 indicates the token should attend to the corresponding image tile
- 0 indicates the token should not attend to the corresponding image tile
- cross_attention_states (
torch.FloatTensor
, optional) — 视觉模型的输出,用于交叉注意力。该张量包含语言模型将关注的处理后的图像特征。 - position_ids (
torch.LongTensor
of 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
ortuple(tuple(torch.FloatTensor))
, 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_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.允许两种格式:
- a Cache instance, see our kv cache guide;
- Tuple of
tuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
). This is also known as the legacy cache format.
模型将输出与输入相同的缓存格式。如果没有传递
past_key_values
,将返回旧的缓存格式。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后input_ids
(那些没有将其过去键值状态提供给此模型的input_ids
),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 表示输入序列标记在序列中的位置的索引。与position_ids
不同, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。
返回
transformers.modeling_outputs.BaseModelOutputWithPast 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPast 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,取决于配置(MllamaTextConfig
)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递了use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量,并且如果config.is_encoder_decoder=True
,则还包含 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预先计算的隐藏状态(自注意力块中的键和值,并且如果
config.is_encoder_decoder=True
,则还包含交叉注意力块中的键和值),可以用于(参见past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
MllamaTextModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoProcessor, MllamaTextModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaTextModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> text = "<|image|>If I had to write a haiku for this one"
>>> inputs = processor(text=text, return_tensors="pt")
>>> output = model(**inputs)
>>> print(output.last_hidden_state.shape)
torch.Size([1, 13, 4096])
MllamaForCausalLM
类 transformers.MllamaForCausalLM
< source >( config )
参数
- config (MllamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Mllama 文本模型,顶部带有语言建模头。 该模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None cross_attention_states: typing.Optional[torch.LongTensor] = None cross_attention_mask: typing.Optional[torch.LongTensor] = None full_text_row_masked_out_mask: typing.Optional[typing.Tuple[torch.Tensor, torch.Tensor]] = None past_key_values: typing.Union[transformers.cache_utils.Cache, typing.List[torch.FloatTensor], NoneType] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None num_logits_to_keep: int = 0 **loss_kwargs ) → transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor
形状为(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)) -- 对应于输入图像的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取。详情请参见 [MllamaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]
MllamaProcessor`] 使用 MllamaImageProcessor 处理图像)。 - aspect_ratio_mask (
torch.Tensor
形状为(batch_size, max_num_images, max_num_tiles)
, 可选) — 用于避免在填充的瓦片上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的瓦片,
- 0 表示 掩码 的瓦片。
- aspect_ratio_ids (
torch.Tensor
of shape(batch_size, max_num_images)
, optional) — Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model’s list of supported aspect ratios, offset by 1.例如,如果模型支持的宽高比为[[1, 1], [1, 2], [2, 1]]:
- An image with aspect ratio [1, 1] would have ID 1
- An image with aspect ratio [1, 2] would have ID 2
- An image with aspect ratio [2, 1] would have ID 3
id 0 保留用于填充(即没有图像)。
如果图像的宽高比为 [1, 2],这意味着它在水平方向上被分割成 2 个图块,其
aspect_ratio_id
将为 2。 - attention_mask (
torch.Tensor
of 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.
可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
如果使用了
past_key_values
,可以选择只输入最后的input_ids
(参见past_key_values
)。如果你想改变填充行为,你应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- cross_attention_mask (
torch.Tensor
of shape(batch_size, seq_length, max_num_images, max_num_tiles)
, optional) — Cross-attention mask to control the interaction between text tokens and image tiles. This 4D tensor defines which image tiles each text token should attend to.对于每个文本标记(在 seq_length 中):
- 1 indicates the token should attend to the corresponding image tile
- 0 indicates the token should not attend to the corresponding image tile
- cross_attention_states (
torch.FloatTensor
, optional) — 视觉模型的输出,用于交叉注意力。该张量包含语言模型将关注的处理后的图像特征。 - position_ids (
torch.LongTensor
of 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
ortuple(tuple(torch.FloatTensor))
, 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_values
returned by the model at a previous stage of decoding, whenuse_cache=True
orconfig.use_cache=True
.允许两种格式:
- a Cache instance, see our kv cache guide;
- Tuple of
tuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
). This is also known as the legacy cache format.
模型将输出与输入相同的缓存格式。如果没有传递
past_key_values
,将返回旧的缓存格式。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后input_ids
(那些没有将其过去键值状态提供给此模型的input_ids
),而不是形状为(batch_size, sequence_length)
的所有input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - cache_position (
torch.LongTensor
of shape(sequence_length)
, optional) — 表示输入序列标记在序列中的位置的索引。与position_ids
相反, 这个张量不受填充的影响。它用于在正确的位置更新缓存并推断 完整的序列长度。 - Args —
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional): Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size]
or -100 (seeinput_ids
docstring). Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
.num_logits_to_keep (
int
, 可选): 计算最后num_logits_to_keep
个token的logits。如果为0
,则计算所有input_ids
的logits(特殊情况)。生成时只需要最后一个token的logits,仅计算该token的logits可以节省内存,这对于长序列或大词汇量来说非常重要。
返回
transformers.modeling_outputs.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithPast 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,取决于配置(MllamaTextConfig
)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个标记的预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
MllamaForCausalLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, MllamaForCausalLM
>>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
>>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
>>> prompt = "If I had to write a haiku, it would be:"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
>>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(result)
If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
I love the idea of snowflakes gently falling, each one
MllamaVisionModel
类 transformers.MllamaVisionModel
< source >( 配置: MllamaVisionConfig )
参数
- config (MllamaConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Mllama视觉模型由两个视觉编码器组成。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: Tensor aspect_ratio_ids: Tensor aspect_ratio_mask: Tensor output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
形状为(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)) -- 对应于输入图像的张量。像素值可以使用 [AutoImageProcessor](/docs/transformers/v4.47.1/en/model_doc/auto#transformers.AutoImageProcessor) 获取。详情请参见 [MllamaImageProcessor.__call__()](/docs/transformers/v4.47.1/en/model_doc/imagegpt#transformers.ImageGPTFeatureExtractor.__call__) ([]
MllamaProcessor`] 使用 MllamaImageProcessor 处理图像)。 - aspect_ratio_mask (
torch.Tensor
形状为(batch_size, max_num_images, max_num_tiles)
, 可选) — 用于避免在填充的瓦片上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码 的瓦片,
- 0 表示 掩码 的瓦片。
- aspect_ratio_ids (
torch.Tensor
of shape(batch_size, max_num_images)
, optional) — Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model’s list of supported aspect ratios, offset by 1.例如,如果模型支持的宽高比为[[1, 1], [1, 2], [2, 1]]:
- An image with aspect ratio [1, 1] would have ID 1
- An image with aspect ratio [1, 2] would have ID 2
- An image with aspect ratio [2, 1] would have ID 3
id 0 保留用于填充(即没有图像)。
如果图像的宽高比为 [1, 2],这意味着它在水平方向上被分割成 2 个图块,其
aspect_ratio_id
将为 2。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,取决于配置(MllamaVisionConfig
)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力softmax后的注意力权重,用于计算自注意力头中的加权平均值。
MllamaVisionModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaVisionModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaVisionModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> output = model(**inputs)
>>> print(output.last_hidden_state.shape)
torch.Size([1, 1, 4, 1025, 7680])