Transformers documentation
GlmImage
该模型于 2026-01-13 贡献至 Hugging Face Transformers。
GlmImage
概述
GLM-Image 是一款采用混合自回归 + 扩散解码器架构的图像生成模型,有效提升了视觉保真度和细粒度细节的上限。在通用图像生成质量方面,它与业界标准的基于 LDM 的方法相当,同时在知识密集型图像生成场景中展现出显著优势。
模型架构:混合自回归 + 扩散解码器设计、
- 自回归生成器:一个从 GLM-4-9B-0414 初始化的 9B 参数模型,其词表经过扩展以纳入视觉标记。该模型首先生成约 256 个标记的紧凑编码,随后扩展至 1K–4K 个标记,对应 1K–2K 的高分辨率图像输出。
- Diffusion Decoder:一个基于单流 DiT 架构的 7B 参数解码器,用于潜在空间图像解码。它配备了 Glyph Encoder 文本模块,显著提升了图像中文字的准确渲染效果。
通过解耦强化学习进行后训练:该模型引入了基于 GRPO 算法的细粒度、模块化反馈策略,显著提升了语义理解和视觉细节质量。
- 自回归模块:提供专注于美学和语义对齐的低频反馈信号,从而提升指令遵循能力和艺术表现力。
- 解码器模块:提供针对细节保真度和文本准确性的高频反馈,从而生成高度逼真的纹理、光照和色彩还原,以及更精确的文本渲染。
GLM-Image 支持在单个模型中同时进行文本生成图像和图像生成图像
文本生成图像:根据文本描述生成高细节图像,在信息密集的场景中表现尤为出色。
图像到图像:支持多种任务,包括图像编辑、风格迁移、多主体一致性,以及针对人物和物体的身份保持生成。
GlmImageForConditionalGeneration是 GLM-Image 模型的自回归部分,完整的图像生成流程请参见此处。
该模型由 Raushan Turganbay 和 Yuxuan Zhang 贡献。
使用示例
使用 GLM-Image 配合图像输入,为 DIT 生成视觉 token。
import torch
from transformers import AutoProcessor, GlmImageForConditionalGeneration
model = GlmImageForConditionalGeneration.from_pretrained(
pretrained_model_name_or_path="zai-org/GLM-Image/vision_language_encoder",
device_map=torch.accelerator.current_accelerator()
)
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
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevq_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 167855image_start_token_id: int = 16384image_end_token_id: int = 16385tie_word_embeddings: bool = False )
参数
- text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。 - vq_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 向量量化模块的配置字典。 - image_token_id (
int,可选,默认为167855) — 用作输入图像占位符的图像 token 索引。 - image_start_token_id (
int,可选,默认为 16384) — 用于编码图像起始位置的图像起始标记索引。 - image_end_token_id (
int,可选,默认为 16385) — 用于编码图像结束位置的图像结束标记索引。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 GlmImageModel 配置的类。它根据指定的参数实例化 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.configGlmImageVisionConfig
class transformers.GlmImageVisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonedepth: int = 40hidden_size: int = 1536hidden_act: str = 'gelu'attention_bias: bool = Trueattention_dropout: float | int = 0.0num_heads: int = 16in_channels: int = 3image_size: int | list[int] | tuple[int, int] = 2048patch_size: int | list[int] | tuple[int, int] = 16spatial_merge_size: int = 1intermediate_size: int = 6144initializer_range: float = 0.02layer_norm_eps: float = 1e-06 )
参数
- depth (
int,可选,默认为40) — 视觉编码器中 Transformer 层的数量。 - hidden_size (
int,可选,默认为1536) — 隐藏表示的维度。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - attention_bias (
bool,可选,默认为True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - num_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - in_channels (
int,可选,默认为3) — 输入通道的数量。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为2048) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - spatial_merge_size (
int,可选,默认为1) — 用于通过合并相邻 patch 来减少视觉 token 数量的空间合并窗口大小。 - intermediate_size (
int,可选,默认为6144) — MLP 表示的维度。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。
这是用于存储 GlmImageModel 配置的类。它根据指定的参数实例化 Glm Image 模型,并定义模型架构。使用默认值实例化配置将生成与 zai-org/GLM-Image 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import GlmImageVisionConfig, GlmImageVisionModel
>>> # Initializing a GlmImageVisionConfig GLM-Image style configuration
>>> configuration = GlmImageVisionConfig()
>>> # Initializing a model (with random weights) from the GLM-Image configuration
>>> model = GlmImageVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configGlmImageTextConfig
class transformers.GlmImageTextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 168064hidden_size: int = 4096intermediate_size: int = 13696num_hidden_layers: int = 40num_attention_heads: int = 32num_key_value_heads: int | None = 2hidden_act: str = 'silu'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Trueattention_dropout: float | int = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonepad_token_id: int = 167841vision_vocab_size: int = 16512attention_bias: bool = Trueeos_token_id: int | list[int] | None = 16385 )
参数
- vocab_size (
int,可选,默认为168064) — 模型的词表大小。定义了input_ids可以表示的不同 token 数量。 - hidden_size (
int,可选,默认为4096) — 隐藏表示的维度。 - intermediate_size (
int,可选,默认为13696) — MLP 表示的维度。 - num_hidden_layers (
int,可选,默认为40) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为32) — Transformer 解码器中每个注意力层的注意力头数量。 - num_key_value_heads (
int, 可选,默认为2) — 这是用于实现 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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为num_attention_heads。 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - max_position_embeddings (
int,可选,默认为131072) — 该模型可能使用的最大序列长度。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - rms_norm_eps (
float,可选,默认为1e-05) — RMS 归一化层使用的 epsilon 值。 - use_cache (
bool,可选,默认为True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当config.is_decoder=True或模型为仅解码器生成式模型时相关。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含rope_theta的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - pad_token_id (
int,可选,默认为167841) — 词表中用于填充的 Token id。 - vision_vocab_size (
int,可选,默认值为 16512) — GlmImage 模型的视觉词汇表大小。定义了调用 GlmImageVisionModel 时传入的inputs_ids所能表示的不同 token 数量。 - attention_bias (
bool,可选,默认为True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。 - eos_token_id (
Union[int, list[int]],可选,默认为16385) — 词汇表中用于表示流结束(end-of-stream)的 token id。
这是用于存储 GlmImageModel 配置的类。它根据指定的参数实例化 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.configGlmImageVQVAEConfig
class transformers.GlmImageVQVAEConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneembed_dim: int = 2048num_embeddings: int = 16384latent_channels: int = 1536in_channels: int = 3initializer_range: float = 0.02 )
这是用于存储 GlmImageModel 配置的类。它根据指定的参数实例化 Glm Image 模型,并定义模型架构。使用默认值实例化配置将生成与 zai-org/GLM-Image 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
GlmImageImageProcessor
class transformers.GlmImageImageProcessor
< source >( **kwargs: *<class 'transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 3136, 'longest_edge': 1003520}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为[0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - min_pixels (
int,kwargs,可选,默认为56 * 56) — 用于调整图像大小的最小像素数。 - max_pixels (
int,kwargs,可选,默认为28 * 28 * 1280) — 用于调整图像尺寸的最大像素数。 - patch_size (
int,kwargs,可选,默认为 14) — 视觉编码器的空间块大小。 - temporal_patch_size (
int, kwargs, 可选,默认为 2) — 视觉编码器的时间补丁大小。 - merge_size (
int,kwargs,可选,默认为 2) — 视觉编码器到 LLM 编码器的合并大小。
构建一个 GlmImageImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.glm_image.image_processing_glm_image.GlmImageImageProcessorKwargs'> ) → ~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。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - min_pixels (
int,kwargs,可选,默认为56 * 56) — 用于调整图像大小的最小像素数。 - max_pixels (
int,kwargs,可选,默认为28 * 28 * 1280) — 用于调整图像尺寸的最大像素数。 - patch_size (
int,kwargs,可选,默认为 14) — 视觉编码器的空间块大小。 - temporal_patch_size (
int, kwargs, 可选,默认为 2) — 视觉编码器的时间补丁大小。 - merge_size (
int,kwargs,可选,默认为 2) — 视觉编码器到 LLM 编码器的合并大小。
返回值
~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,也不应转换为张量的键的列表或集合。
GlmImageImageProcessorPil
class transformers.GlmImageImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.glm_image.image_processing_pil_glm_image.GlmImageImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 3136, 'longest_edge': 1003520}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为[0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - min_pixels (
int,kwargs,可选,默认为56 * 56) — 用于调整图像大小的最小像素数。 - max_pixels (
int,kwargs,可选,默认为28 * 28 * 1280) — 用于调整图像尺寸的最大像素数。 - patch_size (
int,kwargs,可选,默认为 14) — 视觉编码器的空间块大小。 - temporal_patch_size (
int, kwargs, 可选,默认为 2) — 视觉编码器的时间补丁大小。 - merge_size (
int,kwargs,可选,默认为 2) — 视觉编码器到 LLM 编码器的合并大小。
构建一个 GlmImageImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.glm_image.image_processing_pil_glm_image.GlmImageImageProcessorKwargs'> ) → ~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。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - min_pixels (
int,kwargs,可选,默认为56 * 56) — 用于调整图像大小的最小像素数。 - max_pixels (
int,kwargs,可选,默认为28 * 28 * 1280) — 用于调整图像尺寸的最大像素数。 - patch_size (
int,kwargs,可选,默认为 14) — 视觉编码器的空间块大小。 - temporal_patch_size (
int, kwargs, 可选,默认为 2) — 视觉编码器的时间补丁大小。 - merge_size (
int,kwargs,可选,默认为 2) — 视觉编码器到 LLM 编码器的合并大小。
返回值
~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,也不应转换为张量的键的列表或集合。
GlmImageProcessor
class transformers.GlmImageProcessor
< source >( image_processor = Nonetokenizer = Nonechat_template = None**kwargs )
参数
- image_processor(GlmImageProcessor,可选)— 图像处理器是必需的输入。
- tokenizer (PreTrainedTokenizerFast,可选) — tokenizer 是必需的输入。
- chat_template (
str, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
构建一个 GLM-Image 处理器,它将 GLM-Image 图像处理器和 GLM-Image 分词器封装为单一处理器。有关详细信息,请参阅 call() 和 decode()。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] = None**kwargs: *<class 'transformers.models.glm_image.processing_glm_image.GlmImageProcessorKwargs'> ) → BatchFeature
参数
- images (
PIL.Image.Image,np.ndarray,torch.Tensor,List[PIL.Image.Image],List[np.ndarray],List[torch.Tensor]) — 要准备处理的图像或图像批次。每张图像可以是 PIL 图像、NumPy 数组或 PyTorch 张量。同时支持通道在前(channels-first)和通道在后(channels-last)两种格式。 - text (
str,List[str],List[List[str]]) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)形式提供序列,则必须设置is_split_into_words=True(以消除与序列批次的歧义)。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
返回值
一个包含以下字段的 BatchFeature:
- input_ids — 要输入模型的 token id 列表。当
text不为None时返回。 - attention_mask — 一个索引列表,指定模型应关注哪些 token(当
return_attention_mask=True,或当 “attention_mask” 位于self.model_input_names中且text不为None时)。 - pixel_values — 输入模型的像素值。当
images不为None时返回。 - image_grid_thw — LLM 中图像的 3D 网格列表。当
images不为None时返回。
用于为模型准备一条或多条序列和图像的主要方法。如果 text 不为 None,此方法会将 text 和 kwargs 参数转发给 PreTrainedTokenizerFast 的 call() 以编码文本。
GlmImageVisionModel
forward
< source >( pixel_values: Tensorgrid_thw: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → torch.Tensor of shape (total_patches, hidden_size)
GlmImageVisionModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
GlmImageTextModel
class transformers.GlmImageTextModel
< source >( config: GlmImageTextConfig )
参数
- config (GlmImageTextConfig) — 模型配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Glm Image Text Model,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( 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.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → BaseModelOutputWithPast or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- 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]. - 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 (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。
返回值
BaseModelOutputWithPast 或 tuple(torch.FloatTensor)
一个 BaseModelOutputWithPast 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
GlmImageTextModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。如果使用了
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.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 之后的权重,用于在自注意力头中计算加权平均值。
GlmImageVQVAE
class transformers.GlmImageVQVAE
< source >( 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 文档。
GlmImageModel
class transformers.GlmImageModel
< source >( config: GlmImageConfig )
参数
- config (GlmImageConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Glm Image Model,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( 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.FloatTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneimages_per_sample: typing.Optional[torch.LongTensor] = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → GlmImageModelOutputWithPast or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- 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]. - 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 (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 GlmImageImageProcessor 获取像素值。有关详细信息,请参阅 GlmImageImageProcessor.call()(GlmImageProcessor 使用 GlmImageImageProcessor 处理图像)。 - image_grid_thw (
torch.LongTensor,形状为(num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。 - images_per_sample (
torch.LongTensor,形状为(batch_size,),可选) — 批次中每个样本的图像数量(包括目标网格)。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
GlmImageModelOutputWithPast 或 tuple(torch.FloatTensor)
GlmImageModelOutputWithPast 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(GlmImageConfig)和输入。
GlmImageModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。如果使用了
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.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 之后的权重,用于在自注意力头中计算加权平均值。
rope_deltas (
torch.LongTensor,形状为(batch_size, ),可选) — 序列长度与多模态 rope 之间的 rope 索引差值。 该属性已弃用,并将在 v5.20 中移除,请改用model.base_model.rope_deltas。
get_image_features
< source >( pixel_values: FloatTensorimage_grid_thw: typing.Optional[torch.LongTensor] = Noneimages_per_sample: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 GlmImageImageProcessor 获取像素值。有关详细信息,请参阅 GlmImageImageProcessor.call()(GlmImageProcessor 使用 GlmImageImageProcessor 处理图像)。 - image_grid_thw (
torch.LongTensor,形状为(num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。 - images_per_sample(形状为
(batch_size,)的torch.LongTensor,可选) — 批次中每个样本的图像输入数量。
返回值
BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 BaseModelOutputWithPooling 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(GlmImageConfig)和输入。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.FloatTensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后的结果。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测(分类)目标进行训练的。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 之后的权重,用于在自注意力头中计算加权平均值。
GlmImageForConditionalGeneration
forward
< source >( 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.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneimages_per_sample: 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'> )
images_per_sample (torch.LongTensor,形状为 (batch_size,),可选):
批次中每个样本的图像数量(包括目标网格)。
示例:
>>> from PIL import Image
>>> from huggingface_hub.utils 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
< source >( pixel_values: FloatTensorimage_grid_thw: typing.Optional[torch.LongTensor] = Noneimages_per_sample: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 GlmImageImageProcessor 获取像素值。有关详细信息,请参阅 GlmImageImageProcessor.call()(GlmImageProcessor 使用 GlmImageImageProcessor 来处理图像)。 - image_grid_thw (
torch.LongTensor,形状为(num_images, 3),可选) — LLM 中每张图片特征形状的时间、高度和宽度。 - images_per_sample (
torch.LongTensor,形状为(batch_size,),可选) — 批次中每个样本的图像数量(包括目标网格)。
返回值
BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 BaseModelOutputWithPooling 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(GlmImageConfig)和输入。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.FloatTensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后的结果。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测(分类)目标进行训练的。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 之后的权重,用于在自注意力头中计算加权平均值。