Transformers documentation

Emu3

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2024-09-27 在 HF papers 上发布,并于 2025-01-10 贡献至 Hugging Face Transformers。

Emu3

FlashAttention SDPA

概述

Emu3 模型由 Xinlong Wang、Xiaosong Zhang、Zhengxiong Luo、Quan Sun、Yufeng Cui、Jinsheng Wang、Fan Zhang、Yueze Wang、Zhen Li、Qiying Yu、Yingli Zhao、Yulong Ao、Xuebin Min、Tao Li、Boya Wu、Bo Zhao、Bowen Zhang、Liangdong Wang、Guang Liu、Zheqi He、Xi Yang、Jingjing Liu、Yonghua Lin、Tiejun Huang 和 Zhongyuan Wang 在 Emu3: Next-Token Prediction is All You Need 中提出。

Emu3 是一种多模态 LLM,它使用向量量化将图像分词为离散 token。随后,离散化的图像 token 与文本 token id 融合,用于图像和文本生成。该模型还可以通过预测图像 token id 来生成图像。

该论文的摘要如下:

尽管下一词元预测(next-token prediction)被视为通往通用人工智能的一条有前景的路径,但它在多模态任务上一直难以表现出色,该领域目前仍由扩散模型(如 Stable Diffusion)和组合式方法(如 CLIP 与 LLM 的结合)主导。在本文中,我们介绍了 Emu3,这是一套全新的、最先进的多模态模型,完全通过下一词元预测进行训练。通过将图像、文本和视频离散化为词元空间,我们从零开始在一个多模态序列的混合数据上训练单个 Transformer。Emu3 在生成和感知任务上均优于多个成熟的特定任务模型,超越了 SDXL 和 LLaVA-1.6 等旗舰模型,同时消除了对扩散或组合式架构的需求。Emu3 还能够在视频序列中预测下一词元,从而生成高保真视频。我们通过将复杂的多模态模型设计收敛到一个核心焦点——词元——来简化设计,从而在训练和推理阶段都释放了巨大的扩展潜力。我们的结果表明,下一词元预测是构建超越语言的通用多模态智能的一条有前景的路径。我们开源了关键技术和模型,以支持该方向的进一步研究。

提示:

  • 我们建议用户在批量生成之前设置 processor.tokenizer.padding_side = "left",因为这会带来更准确的结果。

  • 请注意,该模型是使用特定的聊天提示格式进行训练的。请使用 processor.apply_chat_template(my_conversation_dict) 来正确格式化您的提示。

  • Emu3 拥有两个不同的检查点,分别用于图像生成和文本生成,在加载模型时请务必使用正确的检查点。为了生成图像,建议使用 prefix_constraints,以确保生成的 token 仅从可能的图像 token 中采样。更多用法示例请参见下文。

Transformers 中的 Emu3 实现使用一个特殊的图像 token 来指示在哪里合并图像嵌入。这个特殊图像 token 并非新引入,而是使用了其中一个保留 token:<|extra_0|>。为了正确生成,您需要在提示中图像应被嵌入的位置添加 <image>。

该模型由 RaushanTurganbay 贡献。 原始代码可在 此处 找到。

使用示例

文本生成推理

以下是如何以半精度(torch.bfloat16)加载模型并执行推理,从而根据文本或文本与图像输入生成文本输出:

import requests
from PIL import Image

from transformers import Emu3ForConditionalGeneration, Emu3Processor


processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", device_map="auto")

# prepare image and text prompt
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
prompt = "What do you see in this image?<image>"

inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device)

# autoregressively complete prompt
output = model.generate(**inputs, max_new_tokens=50)
print(processor.decode(output[0], skip_special_tokens=True))

图像生成推理

Emu3 还可以根据文本输入生成图像。以下是操作方法:

processor = Emu3Processor.from_pretrained("BAAI/Emu3-Gen-hf")
model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Gen-hf", device_map="auto", attn_implementation="flash_attention_2")


inputs = processor(
    text=["a portrait of young girl. masterpiece, film grained, best quality.", "a dog running under the rain"],
    padding=True,
    return_tensors="pt",
    return_for_image_generation=True,
)
inputs = inputs.to(device=model.device)

neg_prompt = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry."
neg_inputs = processor(text=[neg_prompt] * 2, return_tensors="pt").to(device=model.device)

image_sizes = inputs.pop("image_sizes")
HEIGHT, WIDTH = image_sizes[0]
VISUAL_TOKENS = model.vocabulary_mapping.image_tokens

def prefix_allowed_tokens_fn(batch_id, input_ids):
    height, width = HEIGHT, WIDTH
    visual_tokens = VISUAL_TOKENS
    image_wrapper_token_id = torch.tensor([processor.tokenizer.image_wrapper_token_id], device=model.device)
    eoi_token_id = torch.tensor([processor.tokenizer.eoi_token_id], device=model.device)
    eos_token_id = torch.tensor([processor.tokenizer.eos_token_id], device=model.device)
    pad_token_id = torch.tensor([processor.tokenizer.pad_token_id], device=model.device)
    eof_token_id = torch.tensor([processor.tokenizer.eof_token_id], device=model.device)
    eol_token_id = processor.tokenizer.encode("<|extra_200|>", return_tensors="pt").to(model.device)[0]

    position = torch.nonzero(input_ids == image_wrapper_token_id, as_tuple=True)[0][0]
    offset = input_ids.shape[0] - position
    if offset % (width + 1) == 0:
        return (eol_token_id, )
    elif offset == (width + 1) * height + 1:
        return (eof_token_id, )
    elif offset == (width + 1) * height + 2:
        return (eoi_token_id, )
    elif offset == (width + 1) * height + 3:
        return (eos_token_id, )
    elif offset > (width + 1) * height + 3:
        return (pad_token_id, )
    else:
        return visual_tokens


out = model.generate(
    **inputs,
    max_new_tokens=50_000, # make sure to have enough tokens for one image
    prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
    return_dict_in_generate=True,
    negative_prompt_ids=neg_inputs.input_ids, # indicate for Classifier-Free Guidance
    negative_prompt_attention_mask=neg_inputs.attention_mask,
)

image = model.decode_image_tokens(out.sequences[:, inputs.input_ids.shape[1]: ], height=HEIGHT, width=WIDTH)
images = processor.postprocess(list(image.float()), return_tensors="PIL.Image.Image").to(model.device) # internally we convert to np but it's not supported in bf16 precision
for i, image in enumerate(images['pixel_values']):
    image.save(f"result{i}.png")

Emu3Config

class transformers.Emu3Config

< >

( 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 = Nonevq_config: dict | transformers.models.emu3.configuration_emu3.Emu3VQVAEConfig | None = Nonetext_config: dict | transformers.models.emu3.configuration_emu3.Emu3TextConfig | None = Nonevocabulary_map: dict[str, int] | None = Nonetie_word_embeddings: bool = False )

参数

  • vq_config (Union[dict, ~models.emu3.configuration_emu3.Emu3VQVAEConfig], 可选) — 向量量化模块的配置字典。
  • text_config (Union[dict, ~models.emu3.configuration_emu3.Emu3TextConfig], 可选) — 文本骨干网络的配置对象或字典。
  • vocabulary_map (dict, 可选) — 包含分词器词汇映射的字典。用于从图像输入中获取 token。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 Emu3Model 配置的类。它根据指定的参数实例化 Emu3 模型,并定义模型架构。使用默认值实例化配置,将得到与 Emu3-community/Emu3-Chat-hf 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

Emu3VQVAEConfig

类 transformers.Emu3VQVAEConfig

< >

( 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 = Nonecodebook_size: int = 32768embed_dim: int = 4latent_channels: int = 4double_latent: bool = Falsein_channels: int = 3out_channels: int = 3temporal_downsample_factor: int = 4base_channels: int = 256channel_multiplier: list[int] | tuple[int, ...] = (1, 2, 2, 4)num_res_blocks: int = 2attn_resolutions: list[int] | tuple[int, ...] = (3,)hidden_size: int = 1024num_attention_heads: int = 1attention_dropout: float | int = 0.0 )

参数

  • codebook_size (int,可选,默认为 32768) — 模型使用的并行码本数量。
  • embed_dim (int,可选,默认为 4) — 码本中量化向量的维度。
  • latent_channels (int,可选,默认为 4) — 潜在空间的通道数。
  • double_latent (bool,可选,默认为 False) — 是否使用双 z 通道。
  • in_channels (int,可选,默认为 3) — 输入通道的数量。
  • out_channels (int,可选,默认为 3) — 解码器的输出通道数。
  • temporal_downsample_factor (int,可选,默认为 4) — 时间下采样因子。
  • base_channels (int,可选,默认为 256) — 中间块的基础通道数。
  • channel_multiplier (list[int],可选,默认为 [1, 2, 2, 4]) — 中间块的通道缩放因子。
  • num_res_blocks (int,可选,默认为 2) — 每个阶段中的残差块数量。
  • attn_resolutions (list[int],可选,默认为 [3]) — 应用注意力的阶段索引。
  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • num_attention_heads (int,可选,默认为 1) — Transformer 解码器中每个注意力层的注意力头数量。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。

这是用于存储 Emu3Model 配置的类。它根据指定的参数实例化 Emu3 模型,并定义模型架构。使用默认值实例化配置,将得到与 Emu3-community/Emu3-Chat-hf 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import Emu3VQVAE, Emu3VQVAEConfig

>>> # Initializing a video VQ model of Emu3 configuration
>>> configuration = Emu3VQVAEConfig()

>>> # Initializing a model from the Emu3 VQ model style configuration
>>> model = Emu3VQVAE(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Emu3TextConfig

class transformers.Emu3TextConfig

< >

( 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 = Nonevocab_size: int = 184622hidden_size: int = 4096intermediate_size: int = 14336num_hidden_layers: int = 32num_attention_heads: int = 32num_key_value_heads: int | None = 8hidden_act: str = 'silu'max_position_embeddings: int = 9216rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int = 151643bos_token_id: int = 151849eos_token_id: int | list[int] | None = 151850rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_dropout: float | int = 0.1initializer_range: float = 0.02tie_word_embeddings: bool = False )

参数

  • vocab_size (int,可选,默认为 184622) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 4096) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 14336) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 32) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 32) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 8) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 9216) — 该模型可能使用的最大序列长度。
  • rms_norm_eps (float,可选,默认为 1e-05) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int,可选,默认为 151643) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 151849) — 词汇表中用于表示流起始的 Token ID。
  • eos_token_id (Union[int, list[int]],可选,默认为 151850) — 词表中用于表示流结束(end-of-stream)的 token id。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_dropout (Union[float, int],可选,默认为 0.1) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 Emu3Model 配置的类。它根据指定的参数实例化 Emu3 模型,并定义模型架构。使用默认值实例化配置,将得到与 Emu3-community/Emu3-Chat-hf 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import Emu3Model, Emu3Config

>>> # Initializing a Emu3-community/Emu3-Chat-hf style configuration
>>> configuration = Emu3Config()

>>> # Initializing a model from the Emu3-community/Emu3-Chat-hf style configuration
>>> model = Emu3Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Emu3Processor

class transformers.Emu3Processor

< >

( image_processortokenizerchat_template = None**kwargs )

参数

  • image_processor (Emu3ImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (GPT2Tokenizer) — 分词器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。

构建一个 Emu3Processor,它将图像处理器和分词器封装为单一处理器。

Emu3Processor 提供了 Emu3ImageProcessor 和 GPT2Tokenizer 的所有功能。有关更多信息,请参阅 ~Emu3ImageProcessor 和 ~GPT2Tokenizer。

__call__

< >

( 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 = None**kwargs: *<class 'transformers.models.emu3.processing_emu3.Emu3ProcessorKwargs'> ) → ~feature_extraction_utils.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。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • return_for_image_generation (bool, kwargs, 可选, 默认为 False) — 指示处理后的文本是否用于图像生成任务。当为 True 时,处理器会为图像生成准备输入,即在提示词后追加图像起始标记和尺寸信息,且不应提供图像。当为 False 时,处理器会为基于图像和文本的文本生成准备输入,要求同时提供这两种输入。
  • ratio (str, kwargs, optional, 默认为 "1 --1"): 用于调整图像大小的比例。
  • image_area (int,kwargs,可选,默认为 518400) — 用于调整图像大小的目标图像面积。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

~feature_extraction_utils.BatchFeature

  • data (dict,可选) — 由 call/pad 方法返回的列表/数组/张量字典(例如 ‘input_values’、‘attention_mask’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
  • skip_tensor_conversion(list[str] 或 set[str],可选)——即使指定了 tensor_type,也不应转换为张量的键的列表或集合。

Emu3ImageProcessor

class transformers.Emu3ImageProcessor

< >

( do_resize: bool = Trueresample: Resampling = <Resampling.BICUBIC: 3>do_rescale: bool = Truerescale_factor: int | float = 0.00392156862745098do_normalize: bool = Trueimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonedo_convert_rgb: bool = Truedo_pad: bool = Truemin_pixels: int = 262144max_pixels: int = 1048576spatial_factor: int = 8**kwargs )

参数

  • do_resize (bool,可选,默认为 True) — 是否调整图像的高度(height)和宽度(width)维度。
  • resample (PILImageResampling,可选,默认为 Resampling.BICUBIC) — 调整图像大小时使用的重采样滤波器。
  • do_rescale (bool,可选,默认为 True) — 是否使用指定的缩放因子 rescale_factor 对图像进行重新缩放。
  • rescale_factor(int 或 float,可选,默认为 1/255)— 如果要对图像进行重新缩放,则使用的缩放因子。
  • do_normalize (bool,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (float 或 list[float],可选,默认为 [0.48145466, 0.4578275, 0.40821073]) — 对图像进行归一化时使用的均值。这是图像中每个通道的浮点数或浮点数列表。
  • image_std (float 或 list[float],可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 在对图像进行归一化时使用的标准差。这是一个浮点数,或一个包含图像每个通道对应浮点数的列表。
  • do_convert_rgb (bool,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_pad (bool,可选,默认为 True) — 是否对图像进行填充。如果为 True,则会将批次中图像的 patch 维度填充到该批次中最大的 patch 数量。填充将在底部和右侧使用零进行。
  • min_pixels (int,可选,默认为 512 * 512) — 用于调整图像大小的最小像素数。
  • max_pixels (int, 可选,默认为 1024 * 1024) — 用于调整图像尺寸的最大像素数。
  • spatial_factor (int,可选,默认为 8) — 在特征提取阶段,图像将被下采样的空间下采样因子

构建一个 Emu3 图像处理器,根据原始图像动态调整图像大小。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]do_resize: bool | None = Nonesize: dict[str, int] | None = Noneresample: PIL.Image.Resampling | None = Nonedo_rescale: bool | None = Nonerescale_factor: float | None = Nonedo_normalize: bool | None = Noneimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonedo_convert_rgb: bool | None = Nonedo_pad: bool = Truereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonedata_format: transformers.image_utils.ChannelDimension | None = <ChannelDimension.FIRST: 'channels_first'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None**kwargs )

参数

  • images (ImageInput) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_resize (bool,可选,默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选,默认为 self.size) — 调整大小后图像的尺寸。图像的最短边会被调整为 size[“shortest_edge”],最长边则按比例调整以保持输入的宽高比。
  • resample (int,可选,默认为 self.resample) — 在对图像进行缩放时使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,可选,默认为 self.do_rescale) — 是否对图像进行重新缩放。
  • rescale_factor (float,可选,默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,可选,默认为 self.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_convert_rgb (bool,可选,默认为 self.do_convert_rgb) — 是否将图像转换为 RGB。
  • do_pad (bool,可选,默认为 True) — 是否对图像进行填充。如果为 True,则会将批次中图像的 patch 维度填充到该批次中最大的 patch 数量。填充将在底部和右侧使用零进行。
  • return_tensors (str 或 TensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • Unset:返回一个np.ndarray列表。
    • TensorType.PYTORCH 或 'pt':返回类型为 torch.Tensor 的批次。
    • TensorType.NUMPY 或 'np':返回类型为 np.ndarray 的批次。
  • data_format (ChannelDimension 或 str, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • Unset:使用输入图像的通道维度格式。
  • 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) 格式。

Emu3VQVAE

class transformers.Emu3VQVAE

< >

( config: Emu3VQVAEConfig )

参数

  • config (Emu3VQVAEConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

Emu3 中用于将图像编码/解码为离散 token 的 VQ-VAE 模型。 该模型遵循 Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman 的论文“Make-a-scene: Scene-based text-to-image generation with human priors”。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

( *args**kwargs )

点分路径(例如 torch.float32)的模拟值:属性访问链和调用行为如同透传装饰器,repr 返回点分路径,将其用作基类时会替换为普通的 type 基类(PEP 560 __mro_entries__),因此真实的子类保留正常的元类,且 inspect.signature 读取的是它们真实的 __init__,而非模拟对象的。

Emu3TextModel

class transformers.Emu3TextModel

< >

( config: Emu3TextConfig )

参数

  • config (Emu3TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

未附加任何特定头部的裸 Emu3 文本模型,直接输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Emu3Config)和输入。

Emu3TextModel 的 forward 方法重写了 __call__ 特殊方法。

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

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

    如果使用了 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

Emu3Model

class transformers.Emu3Model

< >

( config: Emu3Config )

decode_image_tokens

< >

( image_tokens: LongTensorheight: intwidth: int )

参数

  • image_tokens(形状为 (batch_size, num_of_tokens) 的 torch.LongTensor)— 与输入图像对应的张量。
  • height (int) — 上采样之前生成图像的高度。
  • width (int) — 上采样之前生成图像的宽度。

通过上采样,使用 VQGAN 模块将语言模型生成的图像 token 解码为连续的像素值。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Emu3ImageProcessor 获取像素值。有关详细信息,请参阅 Emu3ImageProcessor.call()(Emu3Processor 使用 Emu3ImageProcessor 来处理图像)。
  • image_sizes (torch.LongTensor,形状为 (batch_size, 2)) — 批次中各图像的尺寸,每张图像对应 (height, width)。可以使用 AutoImageProcessor 获取图像尺寸。有关详细信息,请参阅 Emu3ImageProcessor.call()([]Emu3Processor] 使用 Emu3ImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Emu3Config)和输入。

Emu3Model 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

get_image_features

< >

( pixel_values: Tensorimage_sizes: LongTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Emu3VQVAEModelOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 `(batch_size, num_channels, image_size, image_size)` 的 torch.Tensor)— 与输入图像对应的张量。
  • image_sizes(形状为 (batch_size, 2) 的 torch.LongTensor)— 批次中各图像的尺寸,每张图像对应 (height, width)。

返回值

Emu3VQVAEModelOutput 或 tuple(torch.Tensor)

Emu3VQVAEModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Emu3Config)和输入。

使用 VQGAN 模块将图像离散化为 token,并通过文本嵌入层对其进行嵌入

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

  • image_tokens(形状为 (batch_size, config.vocab_size 的 torch.LongTensor)— VQ-VAE 模型预测的图像 token 的索引。

get_image_tokens

< >

( pixel_values: Tensorimage_sizes: LongTensor )

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。
  • image_sizes(形状为 (batch_size, 2) 的 torch.LongTensor)— 批次中各图像的尺寸,每张图像对应 (height, width)。

使用 VQGAN 模块将图像分词为离散 token。将获得的图像 token 转换为 BPE token,并用 “boi” 和 “eoi” 特殊 token 进行包裹。

get_placeholder_mask

< >

( input_ids: LongTensorinputs_embeds: Tensorimage_features: Tensor )

从 input_ids 或 inputs_embeds 中获取多模态占位符掩码,并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致,则会引发错误。

Emu3ForCausalLM

class transformers.Emu3ForCausalLM

< >

( config: Emu3TextConfig )

参数

  • config (Emu3TextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Emu3Config)和输入。

Emu3ForCausalLM 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

>>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
>>> import torch
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
>>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")

>>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)

>>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
>>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]

Emu3ForConditionalGeneration

class transformers.Emu3ForConditionalGeneration

< >

( config: Emu3Config )

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonelabels: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Emu3ImageProcessor 获取像素值。有关详细信息,请参阅 Emu3ImageProcessor.call()(Emu3Processor 使用 Emu3ImageProcessor 来处理图像)。
  • image_sizes (torch.LongTensor,形状为 (batch_size, 2)) — 批次中各图像的尺寸,每张图像对应 (height, width)。可以使用 AutoImageProcessor 获取图像尺寸。有关详细信息,请参阅 Emu3ImageProcessor.call()([]Emu3Processor] 使用 Emu3ImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 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(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Emu3Config)和输入。

Emu3ForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

>>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
>>> import torch
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
>>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")

>>> conversation = [
...     {
...     "role": "system",
...     "content": [
...         {"type": "text", "text": "You are a helpful assistant."},
...         ],
...     },
...     {
...     "role": "user",
...     "content": [
...         {"type": "image"},
...         {"type": "text", "text": "Please describe the image."},
...         ],
...     },
... ]

>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16)

>>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
>>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
Update on GitHub