Transformers 文档

GlmImage

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2026-01-10 发布,并于 2026-01-13 添加到 Hugging Face Transformers。

GlmImage

概述

GLM-Image 是一个图像生成模型,它采用了混合自回归 + 扩散解码器架构,有效提升了视觉保真度和精细细节的上限。在通用图像生成质量方面,它与行业标准的 LDM(潜在扩散模型)方法相当,但在知识密集型图像生成场景中表现出显著优势。

模型架构:混合自回归 + 扩散解码器设计、

  • 自回归生成器:一个 9B 参数模型,从 GLM-4-9B-0414 初始化,并扩展了词汇表以包含视觉标记。该模型首先生成大约 256 个标记的紧凑编码,然后扩展到 1K-4K 个标记,对应于 1K-2K 高分辨率图像输出。
  • 扩散解码器:一个 7B 参数解码器,基于单流 DiT(Diffusion Transformer)架构用于潜在空间图像解码。它配备了字形编码器文本模块,显著提高了图像中准确文本渲染的能力。

解耦强化学习后训练:该模型引入了一种精细的模块化反馈策略,使用 GRPO 算法,显著增强了语义理解和视觉细节质量。

  • 自回归模块:提供专注于美学和语义对齐的低频反馈信号,改善指令遵循和艺术表现力。
  • 解码器模块:提供针对细节保真度和文本准确性的高频反馈,从而实现高度逼真的纹理、光照和颜色再现,以及更精确的文本渲染。

GLM-Image 在单个模型中支持文本到图像和图像到图像生成

  • 文本到图像:根据文本描述生成高细节图像,在信息密集型场景中表现尤为出色。

  • 图像到图像:支持广泛的任务,包括图像编辑、风格迁移、多主体一致性以及人物和物体的身份保留生成。

  • GlmImageForConditionalGeneration 是 GLM-Image 模型中的自回归部分,完整的图像生成流程请参考此处

此模型由 Raushan TurganbayYuxuan Zhang 贡献。

使用示例

使用带有图像输入的 GLM-Image 生成视觉标记供 DIT 使用。

from transformers import GlmImageForConditionalGeneration, AutoProcessor
import torch

model = GlmImageForConditionalGeneration.from_pretrained(
    pretrained_model_name_or_path="zai-org/GLM-Image/vision_language_encoder",
    dtype=torch.bfloat16,
    device_map="cuda:0"
)
processor = AutoProcessor.from_pretrained(
    pretrained_model_name_or_path="zai-org/GLM-Image/processor",
    use_fast=True
)

# Case1 T2I
prompt = "现代美食杂志风格的甜点制作教程图,主题为覆盆子慕斯蛋糕。整体布局干净明亮,分为四个主要区域:顶部左侧是黑色粗体标题“覆盆子慕斯蛋糕制作指南”,右侧搭配光线柔和的成品蛋糕特写照片,蛋糕呈淡粉色,表面点缀新鲜覆盆子与薄荷叶;左下方为配料清单区域,标题“配料”使用简洁字体,下方列有“面粉 150g”“鸡蛋 3个”“细砂糖 120g”“覆盆子果泥 200g”“明胶片 10g”“淡奶油 300ml”“新鲜覆盆子”等配料,每种配料旁配有简约线图标(如面粉袋、鸡蛋、糖罐等);右下方是四个等大的步骤方框,每个方框内含高清微距实拍图及对应操作说明,从上到下依次为:步骤1展示打蛋器打发白色泡沫(对应说明“打发蛋白至干性发泡”),步骤2展示红白相间的混合物被刮刀翻拌(对应说明“轻柔翻拌果泥与面糊”),步骤3展示粉色液体被倒入圆形模具(对应说明“倒入模具并冷藏4小时”),步骤4展示成品蛋糕表面装饰覆盆子与薄荷叶(对应说明“用覆盆子和薄荷装饰”);底部边缘设浅棕色信息条,左侧图标分别代表“准备时间:30分钟”“烹饪时间:20分钟”“份量:8人份”。整体色调以奶油白、淡粉色为主,背景带轻微纸质纹理,图文排版紧凑有序,信息层级分明。"
target_h, target_w = 1152, 768
use_reference_images = False
reference_image_paths = None

# ## Case2
# prompt = "Replace the background of the snow forest with an underground station featuring an automatic escalator."
# cond_0 = "cond.jpg"
# target_h, target_w = 1152, 768
# use_reference_images = True
# reference_image_paths = [cond_0]

## Case3
# prompt = "Make the man in the first figure and the child from the second image bow at the same time in a respectful KTV."
# cond_0 = "cond_0.jpg"
# cond_1 = "cond_1.jpg"
# target_h, target_w = 1152, 768
# use_reference_images = True
# reference_image_paths = [cond_0, cond_1]


def build_messages(prompt, use_reference_images, reference_image_paths):
    content = []
    if use_reference_images:
        for img_path in reference_image_paths:
            content.append({"type": "image", "url": img_path})
    content.append({"type": "text", "text": prompt})
    return [{"role": "user", "content": content}]


def compute_generation_params(image_grid_thw, use_reference_images):
    grid_sizes = []
    for i in range(image_grid_thw.shape[0]):
        t, h, w = image_grid_thw[i].tolist()
        grid_sizes.append(int(h * w))

    target_output_length = grid_sizes[0]

    if use_reference_images:
        max_new_tokens = grid_sizes[-1] + 1
        output_start_offset = 0
        output_length = grid_sizes[-1]
    else:
        total_tokens = sum(grid_sizes)
        max_new_tokens = total_tokens + 1
        output_start_offset = sum(grid_sizes[1:])
        output_length = target_output_length

    return max_new_tokens, output_start_offset, output_length


messages = build_messages(prompt, use_reference_images, reference_image_paths if use_reference_images else None)

inputs = processor.apply_chat_template(
    messages,
    target_h=target_h,
    target_w=target_w,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

image_grid_thw = inputs.get('image_grid_thw')
print(f"image_grid_thw: {image_grid_thw}")

max_new_tokens, output_start_offset, output_length = compute_generation_params(
    image_grid_thw, use_reference_images
)

print(f"use_reference_images: {use_reference_images}")
print(f"max_new_tokens: {max_new_tokens}")
print(f"output_start_offset: {output_start_offset}")
print(f"output_length: {output_length}")

outputs = model.generate(
    **inputs,
    max_new_tokens=max_new_tokens,
    do_sample=True
)

input_length = inputs["input_ids"].shape[-1]
output_tokens = outputs[0][input_length:][output_start_offset:output_start_offset + output_length]
print(f"Input length: {input_length}")
print(f"Total generated tokens: {outputs[0].shape[-1] - input_length}")
print(f"Extracted output tokens shape: {output_tokens.shape}")
print(f"Output tokens: {output_tokens}")

GlmImageConfig

class transformers.GlmImageConfig

< >

( text_config = None vision_config = None vq_config = None image_token_id = 167855 image_start_token_id = 16384 image_end_token_id = 16385 tie_word_embeddings: bool | None = False **kwargs )

参数

  • text_config (Union[PreTrainedConfig, dict], optional, defaults to GlmImageTextConfig) — 文本骨干的配置对象或字典。
  • vision_config (Union[PreTrainedConfig, dict], optional, defaults to GlmImageVisionConfig) — 视觉骨干的配置对象或字典。
  • vq_config (Union[Dict, GlmImageVQVAEConfig], optional) — GlmImageVQVAEConfig 实例,包含 VQ-VAE 模型的配置。
  • image_token_id (int, optional, defaults to 167855) — 用于编码图像提示的图像标记索引。
  • image_start_token_id (int, optional, defaults to 16384) — 用于编码图像开始的图像开始标记索引。
  • image_end_token_id (int, optional, defaults to 16385) — 用于编码图像结束的图像结束标记索引。
  • tie_word_embeddings (bool, optional, defaults to False) — 模型的输入和输出词嵌入是否应该绑定。

这是用于存储 GlmImageModel 配置的配置类。它用于根据指定的参数实例化 GLM-Image 模型,定义模型架构。使用默认值实例化配置将生成与 GLM-Image zai-org/GLM-Image 架构类似的配置。

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

>>> from transformers import Glm4vForConditionalGeneration, Glm4vConfig

>>> # Initializing a GLM-Image style configuration
>>> configuration = Glm4vConfig()

>>> # Initializing a model from the GLM-Image style configuration
>>> model = Glm4vForConditionalGeneration(configuration)

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

GlmImageVisionConfig

class transformers.GlmImageVisionConfig

< >

( depth = 40 hidden_size = 1536 hidden_act = 'gelu' attention_bias = True attention_dropout = 0.0 num_heads = 16 in_channels = 3 image_size = 2048 patch_size = 16 layer_norm_eps = 1e-06 spatial_merge_size = 1 intermediate_size = 6144 initializer_range = 0.02 **kwargs )

参数

  • depth (int, optional, defaults to 40) — 模型中的层数(深度)。
  • hidden_size (int, optional, defaults to 1536) — 编码器层和池化器层的维度。
  • hidden_act (str or function, optional, defaults to "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu""relu""selu""gelu_new"
  • attention_bias (bool, optional, defaults to True) — 是否在查询、键和值中添加偏置。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力权重的 dropout 概率。
  • num_heads (int, optional, defaults to 16) — Transformer 架构中每个注意力层的注意力头数。
  • in_channels (int, optional, defaults to 3) — 输入通道数。
  • image_size (int or list[int], optional, defaults to 2048) — 每张图像的大小(分辨率)。
  • patch_size (int, optional, defaults to 16) — 每个 patch 的大小(分辨率)。
  • layer_norm_eps (float, optional, defaults to 1e-06) — 层归一化层使用的 epsilon。
  • spatial_merge_size (int, optional, defaults to 1) — 用于合并空间维度的尺寸。
  • intermediate_size (int, optional, defaults to 6144) — Transformer 编码器中“中间”(即前馈)层的维度。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。

这是用于存储 GlmImageVisionModel 配置的配置类。它用于根据指定的参数实例化 GlmImageVisionModel 模型,定义模型架构。使用默认值实例化配置将生成与 GLM-Image zai-org/GLM-Image 相似的配置。

GlmImageTextConfig

class transformers.GlmImageTextConfig

< >

( vocab_size: int = 168064 hidden_size: int | None = 4096 intermediate_size: int | None = 13696 num_hidden_layers: int | None = 40 num_attention_heads: int | None = 32 num_key_value_heads: int | None = 2 hidden_act: str | None = 'silu' max_position_embeddings: int = 131072 initializer_range: float | None = 0.02 rms_norm_eps: int | None = 1e-05 use_cache: bool | None = True attention_dropout: float | None = 0.0 rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None pad_token_id: int = 167841 vision_vocab_size: int = 16512 attention_bias: bool = True eos_token_id: int = 16385 **kwargs )

参数

  • vocab_size (int, optional, defaults to 168064) — GlmImage 模型的词汇表大小。定义了调用 GlmImageModel 时传入的 inputs_ids 可以表示的不同 token 数量。
  • hidden_size (int, optional, defaults to 4096) — 隐藏表示的维度。
  • intermediate_size (int, optional, defaults to 13696) — MLP 表示的维度。
  • num_hidden_layers (int, optional, defaults to 40) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 32) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, optional, defaults to 2) — 用于实现分组查询注意力(Grouped Query Attention)的键值头数量。如果 num_key_value_heads=num_attention_heads,模型将使用多头注意力(MHA);如果 num_key_value_heads=1,模型将使用多查询注意力(MQA),否则使用 GQA。将多头检查点转换为 GQA 检查点时,每个组的键和值头应通过对其组内所有原始头进行均值池化来构建。有关更多详细信息,请查看 这篇论文。如果未指定,将默认为 32
  • hidden_act (str or function, optional, defaults to "silu") — 解码器中的非线性激活函数(函数或字符串)。
  • max_position_embeddings (int, optional, defaults to 131072) — 此模型可能使用的最大序列长度。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float, optional, defaults to 1e-05) — RMS 归一化层使用的 epsilon。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 时相关。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的 dropout 率。
  • rope_parameters (RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,以及在需要使用更长的 max_position_embeddings 时用于缩放的可选参数。
  • pad_token_id (int, optional, defaults to 167841) — padding token 的 ID。
  • vision_vocab_size (int, optional, defaults to 16512) — GlmImage 模型的视觉词汇表大小。定义了调用 GlmImageVisionModel 时传入的 inputs_ids 可以表示的不同 token 数量。
  • attention_bias (bool, optional, defaults to True) — 是否在查询、键和值中添加偏置。
  • eos_token_id (int, optional, defaults to 16385) — 序列结束 token 的 ID。

这是用于存储 GlmImageTextModel 配置的配置类。它用于根据指定的参数实例化 GLM-Image 模型,定义模型架构。使用默认值实例化配置将生成与 GLM-Image zai-org/GLM-Image 相似的配置。

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

>>> from transformers import GlmImageTextModel, GlmImageConfig

>>> # Initializing a GlmImageConfig style configuration
>>> configuration = GlmImageConfig()

>>> # Initializing a model from the GlmImageConfig style configuration
>>> model = GlmImageTextModel(configuration)

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

GlmImageVQVAEConfig

class transformers.GlmImageVQVAEConfig

< >

( embed_dim: int = 2048 num_embeddings: int = 16384 latent_channels: int = 1536 in_channels: int = 3 initializer_range = 0.02 **kwargs )

参数

  • embed_dim (int, optional, defaults to 2048) — 每个嵌入向量的维度。
  • num_embeddings (int, optional, defaults to 16384) — 码本嵌入的数量。
  • latent_channels (int, optional, defaults to 1536) — 潜在空间的通道数量。
  • in_channels (int, optional, defaults to 3) — 输入通道的数量。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 GlmImageVQModel 配置的配置类。它用于根据指定的参数实例化 GlmImageVQModel,定义模型架构。配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。使用默认值实例化配置将生成与 zai-org/GLM-Image 架构的 VQModel 相似的配置。

GlmImageImageProcessor

class transformers.GlmImageImageProcessor

< >

( do_resize: bool = True size: dict[str, int] | None = None resample: Resampling = <Resampling.BICUBIC: 3> do_rescale: bool = True rescale_factor: int | float = 0.00392156862745098 do_normalize: bool = True image_mean: float | list[float] | None = None image_std: float | list[float] | None = None do_convert_rgb: bool = True min_pixels: int | None = None max_pixels: int | None = None patch_size: int = 14 temporal_patch_size: int = 2 merge_size: int = 2 **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — 是否调整图像的(高度、宽度)尺寸。
  • size (dict[str, int], optional, defaults to {"shortest_edge" -- 56 * 56, "longest_edge": 28 * 28 * 1280}): 调整大小后的图像尺寸。必须包含 shortest_edgelongest_edge 键。
  • resample (PILImageResampling, optional, defaults to Resampling.BICUBIC) — 调整图像大小时使用的重采样滤波器。
  • do_rescale (bool, optional, defaults to True) — 是否按指定的比例因子 rescale_factor 重新缩放图像。
  • rescale_factor (int or float, optional, defaults to 1/255) — 如果重新缩放图像,使用的比例因子。
  • do_normalize (bool, optional, defaults to True) — 是否对图像进行归一化。
  • image_mean (float or list[float], optional, defaults to [0.48145466, 0.4578275, 0.40821073]) — 如果归一化图像,使用的均值。这是一个浮点数或图像中每个通道的浮点数列表。
  • image_std (float or list[float], optional, defaults to [0.26862954, 0.26130258, 0.27577711]) — 如果归一化图像,使用的标准差。这是一个浮点数或图像中每个通道的浮点数列表。
  • do_convert_rgb (bool, optional, defaults to True) — 是否将图像转换为 RGB 格式。
  • min_pixels (int, optional, defaults to 56 * 56) — 调整图像大小的最小像素数。
  • max_pixels (int, optional, defaults to 28 * 28 * 1280) — 调整图像大小的最大像素数。
  • patch_size (int, optional, defaults to 14) — 视觉编码器的空间块大小。
  • temporal_patch_size (int, optional, defaults to 2) — 视觉编码器的时间块大小。
  • merge_size (int, optional, defaults to 2) — 视觉编码器合并到 LLM 编码器的合并大小。

构造一个 Qwen2-VL 图像处理器,它根据原始图像动态调整图像大小。

preprocess

< >

( 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 = None size: dict[str, int] | None = None min_pixels: int | None = None max_pixels: int | None = None resample: PIL.Image.Resampling | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_normalize: bool | None = None image_mean: float | list[float] | None = None image_std: float | list[float] | None = None patch_size: int | None = None temporal_patch_size: int | None = None merge_size: int | None = None do_convert_rgb: bool | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None data_format: transformers.image_utils.ChannelDimension | None = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None )

参数

  • images (ImageInput) — 要预处理的图像。期望单个或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], optional, defaults to self.size) — 调整大小后的图像尺寸。图像的最短边被调整为 size["shortest_edge"],最长边保持输入纵横比进行调整。
  • resample (int, optional, defaults to self.resample) — 如果调整图像大小,使用的重采样滤波器。这可以是枚举 PILImageResampling 之一。仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,用于重新缩放图像的比例因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时有效。
  • image_std (float or list[float], optional, defaults to self.image_std) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时有效。
  • min_pixels (int, optional, defaults to self.min_pixels) — 用于调整图像大小的最小像素值。
  • max_pixels (int, optional, defaults to self.max_pixels) — 用于调整图像大小的最大像素值。
  • patch_size (int, optional, defaults to self.patch_size) — 视觉编码器的空间切块大小。
  • temporal_patch_size (int, optional, defaults to self.temporal_patch_size) — 视觉编码器的时间切块大小。
  • merge_size (int, optional, defaults to self.merge_size) — 视觉编码器到 LLM 编码器的合并大小。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (str or TensorType, optional) — 返回张量的类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.PYTORCH'pt':返回类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回类型为 np.ndarray 的批次。
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimension or str, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。

GlmImageImageProcessorFast

class transformers.GlmImageImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs] )

构建一个快速 Glm Image 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs] ) <class 'transformers.feature_extraction_utils.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 要预处理的图像。期望单个或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_convert_rgb (bool | None.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • do_resize (bool | None.do_resize) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 描述模型的最大输入维度。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 应用 center_crop 后输出图像的大小。
  • resample (Annotated[Union[PILImageResampling, int, NoneType], None]) — 如果调整图像大小,使用的重采样过滤器。可以是枚举 PILImageResampling 之一。仅当 do_resize 设置为 True 时有效。
  • do_rescale (bool | None.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float | None.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的缩放因子。
  • do_normalize (bool | None.do_normalize) — 是否对图像进行归一化。
  • image_mean (float | list[float] | tuple[float, ...] | None.image_mean) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时有效。
  • image_std (float | list[float] | tuple[float, ...] | None.image_std) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时有效。
  • do_pad (bool | None.do_pad) — 是否填充图像。填充可以填充到批次中的最大大小,或填充到每个图像的固定正方形大小。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 要将图像填充到的 {"height": int, "width" int} 大小。必须大于预处理提供的任何图像大小。如果未提供 pad_size,图像将填充到批次中的最大高度和宽度。仅当 do_pad=True 时应用。
  • do_center_crop (bool | None.do_center_crop) — 是否对图像进行中心裁剪。
  • data_format (str | ~image_utils.ChannelDimension | None.data_format) — 仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (str | ~image_utils.ChannelDimension | None.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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]) — 处理图像的设备。如果未设置,则从输入图像中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt` 则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool | None.disable_grouping) — 是否禁用按大小分组图像以单独处理它们而不是批量处理。如果为 None,则如果图像位于 CPU 上,将设置为 True,否则设置为 False。此选择基于经验观察,详情请参阅此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int | None.image_seq_length) — 用于输入中每张图像的图像标记数。为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。
  • min_pixels (int, optional, defaults to 56 * 56) — 用于调整图像大小的最小像素值。
  • max_pixels (int, optional, defaults to 28 * 28 * 1280) — 用于调整图像大小的最大像素值。
  • patch_size (int, optional, defaults to 14) — 视觉编码器的空间切块大小。
  • temporal_patch_size (int, optional, defaults to 2) — 视觉编码器的时间切块大小。
  • merge_size (int, optional, defaults to 2) — 视觉编码器到 LLM 编码器的合并大小。

返回

<class 'transformers.feature_extraction_utils.BatchFeature'>

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

GlmImageProcessor

class transformers.GlmImageProcessor

< >

( image_processor = None tokenizer = None chat_template = None **kwargs )

参数

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

构建一个 GLM-Image 处理器,它将 GLM-Image 图像处理器和 GLM-Image 分词器封装在一个处理器中。有关更多信息,请参阅 __call__()decode()

GlmImageVisionModel

class transformers.GlmImageVisionModel

< >

( config: GlmImageVisionConfig )

forward

< >

( pixel_values: Tensor grid_thw: Tensor **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) torch.Tensor of shape (total_patches, hidden_size)

参数

  • pixel_values (torch.Tensor of shape (total_patches, num_channels * patch_size * patch_size)) — 打包的像素值。
  • grid_thw (torch.Tensor of shape (num_images, 3)) — 每张图像特征形状的时间、高度和宽度。

返回

torch.Tensor of shape (total_patches, hidden_size)

隐藏状态。

Glm Image Vision Model forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

GlmImageTextModel

class transformers.GlmImageTextModel

< >

( config: GlmImageTextConfig )

参数

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

裸 Glm Image Text Model,输出原始隐藏状态,不带任何特定头部。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None cache_position: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 输入序列标记的索引,在词汇表中。默认情况下会忽略填充。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 用于避免在填充标记索引上执行注意力的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示**未被掩码**的标记,
    • 0 表示**被掩码**的标记。

    什么是注意力掩码?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 位置嵌入中每个输入序列标记的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在先前解码阶段返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    仅允许 Cache 实例作为输入,请参阅我们的 kv cache guide。如果未传入 past_key_values,则默认初始化 DynamicCache

    模型将输出与输入时相同的缓存格式。

    如果使用 past_key_values,则用户应仅输入形状为 (batch_size, unprocessed_length) 的未处理 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, optional) — 如果设置为 True,将返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 描述输入序列中的 token 在序列中的位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。

返回

transformers.modeling_outputs.BaseModelOutputWithPast or tuple(torch.FloatTensor)

返回 transformers.modeling_outputs.BaseModelOutputWithPast 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),包含根据配置(None)和输入而异的各种元素。

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

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

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

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if config.is_encoder_decoder=True in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

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

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

GlmImageTextModel forward 方法,重写了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

GlmImageVQVAE

class transformers.GlmImageVQVAE

< >

( config: GlmImageVQVAEConfig )

参数

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

用于 GlmImage 模型中将图像编码/解码为离散 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_unimplemented

< >

( *input: typing.Any )

定义每次调用时执行的计算。

应由所有子类覆盖。

尽管前向传播的配方需要在该函数中定义,但之后应该调用 Module 实例而不是它,因为前者负责运行注册的钩子,而后者则默默地忽略它们。

GlmImageModel

class transformers.GlmImageModel

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

Glm 图像模型,输出原始隐藏状态,顶部没有特定头部。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None pixel_values: torch.Tensor | None = None image_grid_thw: torch.LongTensor | None = None images_per_sample: torch.LongTensor | None = None rope_deltas: torch.LongTensor | None = None cache_position: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.models.glm_image.modeling_glm_image.GlmImageModelOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 输入序列 token 在词汇表中的索引。默认情况下将忽略填充。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行注意力的掩码。掩码值选择在 [0, 1] 中:

    • 1 表示**未被掩码**的 token,
    • 0 表示**被掩码**的 token。

    什么是注意力掩码?

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

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, optional) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括在解码的先前阶段由模型返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    只允许输入 Cache 实例,请参阅我们的 kv 缓存指南。如果没有传递 past_key_values,将默认初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用 past_key_values,用户应仅输入形状为 (batch_size, unprocessed_length) 的未处理 input_ids(即没有将过去的键值状态提供给此模型的那些 token),而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这将很有用。
  • pixel_values (torch.Tensor of shape (batch_size, num_channels, image_size, image_size), optional) — 对应于输入图像的张量。像素值可以使用 image_processor_class 获取。有关详细信息,请参阅 image_processor_class.__call__processor_class 使用 image_processor_class 处理图像)。
  • image_grid_thw (torch.LongTensor of shape (total_images_in_batch, 3), optional) — LLM 中每张图像的特征形状的时间、高度和宽度。图像在批次中的所有样本中打包。
  • images_per_sample (torch.LongTensor of shape (batch_size,), optional) — 批次中每个样本的图像数量(包括目标网格)。
  • rope_deltas (torch.LongTensor of shape (batch_size, ), optional) — 序列长度和多模态 RoPE 之间的 RoPE 索引差异。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 描述输入序列中的 token 在序列中的位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。

返回

transformers.models.glm_image.modeling_glm_image.GlmImageModelOutputWithPast or tuple(torch.FloatTensor)

返回 transformers.models.glm_image.modeling_glm_image.GlmImageModelOutputWithPast 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),包含根据配置(None)和输入而异的各种元素。

  • last_hidden_state (torch.FloatTensor | None.last_hidden_state, shape (batch_size, sequence_length, hidden_size), 默认为 None) — 模型最后一层的输出的隐藏状态序列。

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

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

  • hidden_states (tuple[torch.FloatTensor] | None.hidden_states, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出,如果模型有嵌入层,+ 每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

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

  • attentions (tuple[torch.FloatTensor] | None.attentions, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

  • rope_deltas (形状为 (batch_size, )torch.LongTensor可选) — 序列长度和多模态 RoPE 之间的 RoPE 索引差异。

GlmImageModel forward 方法,重写了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

get_image_features

< >

( pixel_values: FloatTensor image_grid_thw: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。
  • image_grid_thw (torch.LongTensor of shape (num_images, 3), optional) — LLM 中每张图像的特征形状的时间、高度和宽度。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

返回 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),包含根据配置(GlmImageConfig)和输入而异的各种元素。

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

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列第一个 token(分类 token)在进一步通过用于辅助预训练任务的层后的最后一个隐藏状态。例如,对于 BERT 系列模型,这会返回经过线性层和 tanh 激活函数处理后的分类 token。线性层的权重是通过预训练期间的下一句预测(分类)目标来训练的。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

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

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

GlmImageForConditionalGeneration

class transformers.GlmImageForConditionalGeneration

< >

( config )

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None labels: torch.LongTensor | None = None pixel_values: torch.Tensor | None = None image_grid_thw: torch.LongTensor | None = None images_per_sample: torch.LongTensor | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] )

labels (torch.LongTensor of shape (batch_size, sequence_length), optional): 用于计算掩码语言建模损失的标签。索引应位于 [0, ..., config.vocab_size] 或 -100 之间(参见 input_ids docstring)。索引设置为 -100 的 token 将被忽略(掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 的 token 计算。 image_grid_thw (torch.LongTensor of shape (total_images_in_batch, 3), optional): LLM 中每张图像的特征形状的时间、高度和宽度。图像在批次中的所有样本中打包。 images_per_sample (torch.LongTensor of shape (batch_size,), optional): 批次中每个样本的图像数量(包括目标网格)。

示例

>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, GlmImageForConditionalGeneration

>>> model = GlmImageForConditionalGeneration.from_pretrained("zai-org/GLM-Image")
>>> processor = AutoProcessor.from_pretrained("zai-org/GLM-Image")

>>> messages = [
    {
        "role": "user",
        "content": [
            {"type": "image"},
            {"type": "text", "text": "Add a truck of this photo.<sop>28 40<eop>"},
        ],
    },
]
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."

get_image_features

< >

( pixel_values: FloatTensor image_grid_thw: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。
  • image_grid_thw (torch.LongTensor of shape (num_images, 3), optional) — LLM 中每张图像的特征形状的时间、高度和宽度。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

返回 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),包含根据配置(GlmImageConfig)和输入而异的各种元素。

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

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列第一个 token(分类 token)在进一步通过用于辅助预训练任务的层后的最后一个隐藏状态。例如,对于 BERT 系列模型,这会返回经过线性层和 tanh 激活函数处理后的分类 token。线性层的权重是通过预训练期间的下一句预测(分类)目标来训练的。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

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

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.