Transformers documentation

Apertus 1.5

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

and get access to the augmented documentation experience

to get started

该模型于 2026-11-16 贡献至 Hugging Face Transformers。

Apertus 1.5

概述

Apertus 1.5 是来自 Swiss AI Initiative 的多模态模型,可接受文本、图像和音频输入并生成文本。它在 Apertus 语言模型的基础上,引入了 EMU3.5 vision tokenizer 和用于音频的 WavTokenizer。EMU3.5 vision tokenizer 是一个仅处理图像的 VQGAN,其编码器与 Chameleon 的相同,而 Emu3 tokenizer 则额外添加了用于视频的时间层。它通过计算与码本的最大内积来分配编码,而不是使用最小 L2 距离。

媒体分词器将图像和音频转换为离散标记,语言骨干网络在共享的输入词汇表中与文本一起处理这些标记。输出词汇表仅包含文本标记。该集成包括媒体编码器和量化器;它不支持图像或音频生成,也不支持训练视觉分词器。

使用示例

使用处理器的聊天模板来准备包含图像和音频的对话。它会自动加载所引用的媒体、对音频进行重采样,并构建模型输入。

from transformers import AutoModelForMultimodalLM, AutoProcessor

model = AutoModelForMultimodalLM.from_pretrained(
    "swiss-ai/Apertus-v1.5-8B", device_map="auto"
)
processor = AutoProcessor.from_pretrained("swiss-ai/Apertus-v1.5-8B")

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"},
            {"type": "audio", "url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/belinda.wav"},
            {"type": "text", "text": "Describe the image and transcribe the audio."},
        ],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)

generated = model.generate(**inputs, max_new_tokens=128)
print(processor.decode(generated[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))

使用注意事项

  • 分词器精度:两种媒体分词器都需要 float32 以实现稳定的代码分配。在加载半精度语言骨干网络时,from_pretrained 会保留此精度。请避免将整个模型转换为较低精度,或在混合精度自动转换下运行分词器。如果要对模型进行量化,请确保后端排除这两种媒体分词器。
  • 输出词表:如果设置了 text_config.output_vocab_size,则返回的 logits 仅覆盖该大小;否则覆盖 text_config.vocab_size。仅用于输入的多模态 token 无法被生成。在训练标签中,使用 -100 对这些 token 进行掩码,并将生成约束限制在输出词表内的 token。

Apertus1p5Config

类 transformers.Apertus1p5Config

< >

( 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.models.apertus1p5.configuration_apertus1p5.Apertus1p5TextConfig | None = Nonevision_config: dict | transformers.models.apertus1p5.configuration_apertus1p5.Apertus1p5VisionTokenizerConfig | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 131079audio_token_id: int = 131085image_token_offset: int = 131272audio_token_offset: int = 262344tie_word_embeddings: bool = False )

参数

  • text_config (Union[dict, ~models.apertus1p5.configuration_apertus1p5.Apertus1p5TextConfig], 可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~models.apertus1p5.configuration_apertus1p5.Apertus1p5VisionTokenizerConfig], 可选) — 视觉骨干网络的配置对象或字典。
  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 音频骨干网络的配置对象或字典。
  • image_token_id (int,可选,默认为 131079) — 用作输入图像占位符的图像标记索引。
  • audio_token_id (int,可选,默认为 131085) — 用作输入音频占位符的音频 token 索引。
  • image_token_offset (int,可选,默认为 131272) — 将视觉码本索引 i 映射到 <|visual token i|> 的词表 id 的偏移量。
  • audio_token_offset (int,可选,默认为 262344) — 将音频码本索引 i 映射到 <|audio token i|> 的词表 id 的偏移量。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 Apertus1p5Model 配置的类。它根据指定的参数实例化 Apertus1P5 模型,并定义模型架构。使用默认值实例化配置将得到与 swiss-ai/Apertus-v1.5-8B 类似的配置。

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

示例:

>>> from transformers import Apertus1p5Config, Apertus1p5ForConditionalGeneration

>>> # Initializing a configuration (Apertus 1.5 backbone + vision/audio tokenizer defaults)
>>> configuration = Apertus1p5Config()

>>> # Initializing a model (with random weights) from the configuration
>>> model = Apertus1p5ForConditionalGeneration(configuration)

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

Apertus1p5TextConfig

类 transformers.Apertus1p5TextConfig

< >

( 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 = 266752hidden_size: int = 4096intermediate_size: int = 14336num_hidden_layers: int = 32num_attention_heads: int = 32num_key_value_heads: int | None = Nonehidden_act: str = 'xielu'max_position_embeddings: int = 65536initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = 3bos_token_id: int | None = 1eos_token_id: int | list[int] | None = 2tie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | int = 0.0output_vocab_size: int | None = None )

参数

  • vocab_size (int, 可选, 默认为 266752) — 模型的词汇表大小。定义了 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, 可选) — 这是用于实现 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,可选,默认为 xielu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 65536) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float,可选,默认为 1e-05) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int,可选,默认为 3) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 1) — 词汇表中用于表示流起始的 token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 2) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • output_vocab_size (int, 可选) — 从输出投影中剪枝多模态 token 行后,保留的 LM-head 行数;保留的输出 id 为 0..output_vocab_size - 1。None 表示未对 head 进行剪枝(vocab_size 行)。输入嵌入始终使用 vocab_size,而返回的 logits 使用 LM-head 的宽度,无论是否包含 labels。发布的检查点 使用 tie_word_embeddings=False,以将剪枝后的 head 与输入嵌入保持分离。

这是用于存储 Apertus1p5Model 配置的类。它根据指定的参数实例化 Apertus1P5 模型,并定义模型架构。使用默认值实例化配置将得到与 swiss-ai/Apertus-v1.5-8B 类似的配置。

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

示例:

>>> from transformers import Apertus1p5TextConfig, Apertus1p5TextForCausalLM

>>> # Initializing an Apertus 1.5 text configuration (extended vocabulary, optionally pruned output head)
>>> configuration = Apertus1p5TextConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = Apertus1p5TextForCausalLM(configuration)

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

Apertus1p5VisionTokenizerConfig

类 transformers.Apertus1p5VisionTokenizerConfig

< >

( 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 = 131072embed_dim: int = 256latent_channels: int = 256in_channels: int = 3base_channels: int = 256channel_multiplier: list[int] | tuple[int, ...] = (1, 1, 2, 2, 4)num_res_blocks: int = 4attn_resolutions: list[int] | tuple[int, ...] = (16,)resolution: int = 256dropout: float = 0.0 )

参数

  • codebook_size (int, 可选, 默认为 131072) — IBQ 码本中的条目数量。
  • embed_dim (int,可选,默认为 256) — 码本向量的维度(quant_conv 之后的量化器输入)。
  • latent_channels (int,可选,默认为 256) — 编码器输出的通道数(在 quant_conv 之前)。
  • in_channels (int,可选,默认为 3) — 输入通道的数量。
  • base_channels (int, 可选, 默认为 256) — 编码器的基础通道数;各阶段的宽度为 base_channels * channel_multiplier[stage]。
  • channel_multiplier (list[int],可选,默认为 (1, 1, 2, 2, 4)) — 每个编码器阶段的通道缩放因子。阶段数为 len(channel_multiplier),由此得到的空间下采样因子为 2**(len(channel_multiplier) - 1)(默认为 16)。
  • num_res_blocks (int,可选,默认为 4) — 每个编码器阶段的残差块数量。
  • attn_resolutions (list[int],可选,默认为 (16,)) — 插入注意力块的特征图分辨率(相对于 resolution 大小的输入)。
  • resolution (int,可选,默认为 256) — 用于(静态地,与 attn_resolutions 一起)决定哪些编码器阶段包含注意力块的参考输入分辨率。不会限制实际的输入尺寸。
  • dropout (float, 可选,默认为 0.0) — 残差块内部的 Dropout。

这是用于存储 Apertus1p5Model 配置的类。它根据指定的参数实例化 Apertus1P5 模型,并定义模型架构。使用默认值实例化配置将得到与 swiss-ai/Apertus-v1.5-8B 类似的配置。

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

示例:

>>> from transformers import Apertus1p5VisionTokenizerConfig, Apertus1p5VisionTokenizerModel

>>> # Initializing a vision tokenizer configuration (Apertus 1.5 defaults)
>>> configuration = Apertus1p5VisionTokenizerConfig()

>>> # Initializing the encode-only tokenizer (with random weights) from the configuration
>>> model = Apertus1p5VisionTokenizerModel(configuration)

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

Apertus1p5Processor

类 transformers.Apertus1p5Processor

< >

( image_processor = Nonefeature_extractor = Nonetokenizer = Nonechat_template = None**kwargs )

参数

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

构建用于文本、图像和音频的 Apertus 1.5 处理器。

__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 = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置 do_rescale=False。
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • return_mm_token_type_ids (bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。
  • return_text_replacement_offsets (bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

Apertus1p5ImageProcessor

类 transformers.Apertus1p5ImageProcessor

< >

( **kwargs: *<class 'transformers.models.apertus1p5.image_processing_apertus1p5.Apertus1p5ImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (dict, kwargs, 可选,默认为 {"min_pixels" -- 128 * 128, "max_pixels": 1400 * 1400}): 最小和最大像素面积。图像会被调整大小至大约此面积范围内。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • spatial_factor (int,kwargs,可选,默认为 16) — 两个输出维度均会舍入为该因子的倍数(即视觉分词器的下采样因子); 每个 spatial_factor x spatial_factor 的图像块对应一个离散编码。

使用训练管道的缩放策略构建 Apertus 1.5 图像处理器。

预处理

< >

( 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.apertus1p5.image_processing_apertus1p5.Apertus1p5ImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (dict, kwargs, 可选,默认为 {"min_pixels" -- 128 * 128, "max_pixels": 1400 * 1400}): 最小和最大像素面积。图像会被调整大小至大约此面积范围内。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • spatial_factor (int,kwargs,可选,默认为 16) — 两个输出维度均会舍入为该因子的倍数(即视觉分词器的下采样因子); 每个 spatial_factor x spatial_factor 的图像块对应一个离散编码。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

Apertus1p5VisionTokenizerModel

类 transformers.Apertus1p5VisionTokenizerModel

< >

( config: Apertus1p5VisionTokenizerConfig )

参数

Apertus 1.5 使用的仅编码 EMU3.5 视觉分词器:一个与 Chameleon 相同的 2D VQGAN 编码器,后接一个量化器,该量化器选择内积最大的码本条目。它返回硬码本索引;请在 float32 下运行以实现稳定的码分配(Apertus 1.5 会自动执行此操作)。

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

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

encode

< >

( pixel_values: Tensor ) → Apertus1p5VisionTokenizerEncoderOutput

参数

  • pixel_values(形状为 (batch_size, channels, height, width) 的 torch.Tensor)— 归一化到 [-1, 1] 的 RGB 图像。

返回值

Apertus1p5VisionTokenizerEncoderOutput

image_tokens 中的离散图像-代码网格。

将图像分词为离散码本索引的网格。

Apertus1p5TextModel

类 transformers.Apertus1p5TextModel

< >

( config: Apertus1p5TextConfig )

参数

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

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

该模型继承自 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] = Nonecache: 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?

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

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

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

    如果使用 cache,用户应仅输入未处理的 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,则会返回 cache 键值状态,可用于加速解码(参见 cache)。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

Apertus1p5TextForCausalLM

类 transformers.Apertus1p5TextForCausalLM

< >

( config: Apertus1p5TextConfig )

参数

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

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

该模型继承自 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] = Nonecache: 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?

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

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

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

    如果使用 cache,用户应仅输入未处理的 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),可选) — 目标 token id。-100 表示忽略该位置;其他值必须在物理 LM-head 范围内。 对于经过剪枝的 head,请使用 -100 来屏蔽多模态/仅输入 id。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • 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)

labels 存在与否,Logits 均使用物理 LM-head 宽度(若已设置,则为 config.output_vocab_size,否则为 config.vocab_size)。

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

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

Apertus1p5Model

类 transformers.Apertus1p5Model

< >

( config: Apertus1p5Config )

参数

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

未添加任何特定头部的裸 Apertus1P5 模型,输出原始隐藏状态。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.Tensor] = Noneinput_values: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: 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'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • image_sizes(形状为 (batch_size, 2) 的 torch.Tensor,可选) — 批次中各图像的尺寸,每张图像表示为 (height, width)。
  • input_values (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 processor_class.__call__。
  • padding_mask (torch.Tensor,形状为 (num_clips, max_length),可选) — 右侧填充掩码,有效样本为 1,填充部分为 0,使用 input_values 时必填。
  • 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?

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

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

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

    如果使用 cache,用户应仅输入未处理的 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,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

Apertus1p5ForConditionalGeneration

类 transformers.Apertus1p5ForConditionalGeneration

< >

( config: Apertus1p5Config )

参数

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

用于基于其他模态(例如图像-文本到文本生成)进行 token 生成的 Apertus1P5 模型。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_sizes: typing.Optional[torch.Tensor] = Noneinput_values: typing.Optional[torch.Tensor] = Nonepadding_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: 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(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor,可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • image_sizes(形状为 (batch_size, 2) 的 torch.Tensor,可选) — 批次中各图像的尺寸,每张图像表示为 (height, width)。
  • input_values (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 processor_class.__call__。
  • padding_mask (torch.Tensor,形状为 (num_clips, max_length),可选) — 音频样本掩码:有效样本为 1,右侧填充为 0。使用 input_values 时必填。
  • 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?

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

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

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

    如果使用 cache,用户应仅输入未处理的 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,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — [0, output_vocab_size) 范围内的下一词元标签(若未设置,则为 [0, text_config.vocab_size))。 对于仅作为输入的多模态词元以及其他需要忽略的位置,请使用 -100。
  • 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)

Logits 的宽度为 text_config.output_vocab_size,若未设置则为 text_config.vocab_size,无论是否包含 labels。

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

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

get_image_features

< >

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

参数

返回值

Apertus1p5VisionTokenizerModelOutput 或 tuple(torch.Tensor)

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

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

  • pooler_output (tuple[torch.Tensor],可选) — 每个输入图像对应一个形状为 (num_tokens, hidden_size) 的图像 token 嵌入张量。

  • 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 (list[torch.LongTensor],可选) — 每个输入图像对应一个扁平的共享词汇表 token id 张量:其 (height // factor) * (width // factor) 个编码按行优先顺序排列,并加上 config.image_token_offset 作为偏移,其中 factor 是视觉分词器的 spatial_scale_factor(默认为 16)。

示例:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Apertus1p5ForConditionalGeneration

>>> model = Apertus1p5ForConditionalGeneration.from_pretrained("swiss-ai/Apertus-v1.5-8B")
>>> processor = AutoProcessor.from_pretrained("swiss-ai/Apertus-v1.5-8B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]

get_audio_features

< >

( input_values: Tensorpadding_mask: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Apertus1p5AudioTokenizerModelOutput or tuple(torch.Tensor)

参数

  • input_values (torch.Tensor,形状为 (batch_size, sequence_length)) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 Apertus1p5Processor.call()。
  • padding_mask(形状为 (num_clips, max_length) 的 torch.Tensor)— 掩码,有效样本为 1,填充为 0,由特征提取器返回。

返回值

Apertus1p5AudioTokenizerModelOutput 或 tuple(torch.Tensor)

Apertus1p5AudioTokenizerModelOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(Apertus1p5Config)和输入而定的各种元素。

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

  • pooler_output (tuple[torch.Tensor],可选) — 每个输入片段一个形状为 (num_tokens, hidden_size) 的音频 token 嵌入张量。

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

  • audio_tokens (list[torch.LongTensor],可选) — 每个输入片段对应一个包含 ceil(num_valid_samples / hop_length) 个共享词汇表 token id 的张量,并偏移 config.audio_token_offset。

示例:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Apertus1p5ForConditionalGeneration

>>> model = Apertus1p5ForConditionalGeneration.from_pretrained("swiss-ai/Apertus-v1.5-8B")
>>> processor = AutoProcessor.from_pretrained("swiss-ai/Apertus-v1.5-8B")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Update on GitHub