Transformers documentation

NemotronH Omni

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-09-23 贡献至 Hugging Face Transformers。

FlashAttention

NemotronH Omni

NemotronH Omni 是 NVIDIA 推出的多模态推理模型,它将 NemotronH 混合 Mamba-Transformer 语言模型与 RADIO 视觉编码器以及可选的基于 Parakeet 的音频编码器相结合。图像(和视频)块通过 RADIO tower 和 pixel-shuffle MLP 投影到语言模型的嵌入空间中,对应 <image> / <video> 上下文标记的位置;音频片段以相同方式投影到 <audio> 位置。最终得到一个单一的自回归模型,能够对文本、图像、视频和声音进行联合推理。

以下示例演示了如何使用 AutoModelForImageTextToText 对图像和文本提示进行推理。

AutoModel
from transformers import AutoModelForImageTextToText, AutoProcessor


model_id = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(
    model_id,
    device_map="auto",
    # the Parakeet audio encoder has no flash-attention kernel, so pin that tower to sdpa
    attn_implementation={"": "flash_attention_2", "audio_config": "sdpa"},
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
            },
            {"type": "text", "text": "Describe this image in detail."},
        ],
    }
]
inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

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

NemotronH_Omni_Reasoning_V3_Config

class transformers.NemotronH_Omni_Reasoning_V3_Config

< >

( 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 = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneforce_image_size: int | None = Nonedownsample_ratio: float = 0.5projector_hidden_size: int = 4096vision_hidden_size: int = 1280video_pruning_rate: float = 0.0video_temporal_patch_size: int = 2image_token_id: int | None = Nonevideo_token_id: int | None = Noneaudio_token_id: int | None = None )

参数

  • vision_config (dict 或 RadioConfig,可选) — RADIO 视觉编码器的配置。默认使用默认的 RadioConfig。
  • text_config (dict 或 NemotronHConfig,可选) — NemotronH 语言模型的配置。默认值为默认的 NemotronHConfig。
  • audio_config (dict 或 ParakeetEncoderConfig,可选) — 可选的 Parakeet 声音编码器配置。None 表示禁用音频分支。
  • force_image_size (int, 可选) — 视觉塔所期望的固定输入图像分辨率(以像素为单位)。
  • downsample_ratio (float,可选,默认为 0.5) — 应用于视觉特征的像素重排空间下采样比率。
  • projector_hidden_size (int, 可选,默认为 4096) — 视觉到 LLM 的 MLP 投影器的隐藏层大小。
  • vision_hidden_size (int,可选,默认为 1280) — RADIO 视觉特征的隐藏层大小。
  • video_pruning_rate (float,可选,默认值为 0.0) — Efficient-Video-Sampling 的 token 剪枝率;0.0 表示禁用剪枝。
  • video_temporal_patch_size (int, 可选,默认为 2) — 视频嵌入器将多少帧合并为一个时间补丁。
  • image_token_id (int, 可选) — 在 input_ids 中用作图像上下文占位符的 Token id。
  • video_token_id (int, 可选) — 在 input_ids 中用作视频上下文占位符的 Token id。
  • audio_token_id (int, 可选) — 在 input_ids 中用作音频上下文占位符的 token id。

这是用于存储 Nemotron H OmniModel 配置的类。它根据指定的参数实例化 Nemotron H Omni 模型,并定义模型架构。使用默认值实例化配置将得到与 nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 类似的配置。

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

NemotronH_Omni_Reasoning_V3ImageProcessor

class transformers.NemotronH_Omni_Reasoning_V3ImageProcessor

< >

( **kwargs: *<class 'transformers.models.nemotron_h_omni.image_processing_nemotron_h_omni.NemotronH_Omni_Reasoning_V3ImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • 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.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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (int,kwargs,可选,默认值为 16) — 视觉塔中单个 patch 的边长(以像素为单位)。
  • downsample_ratio (float,kwargs,可选,默认值为 0.5) — 模型应用的像素混洗空间下采样比率;补丁网格的每一边都是其倒数的整数倍。
  • min_num_patches (int,kwargs,可选,默认值为 1024) — 图像被调整大小后,patch_size 补丁的最小数量。
  • max_num_patches (int,kwargs,可选,默认值为 13312) — 图像被调整大小后,patch_size 补丁的最大数量;0 表示禁用该上限。
  • max_model_len (int,kwargs,可选,默认值为 16384) — 语言模型的上下文长度,用于限制单次调用中图像的 patch 预算。

构建一个 NemotronH_Omni_Reasoning_V3ImageProcessor 图像处理器。

预处理

< >

( images**kwargs: *<class 'transformers.models.nemotron_h_omni.image_processing_nemotron_h_omni.NemotronH_Omni_Reasoning_V3ImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (`) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (int,kwargs,可选,默认值为 16) — 视觉塔中单个 patch 的边长(以像素为单位)。
  • downsample_ratio (float,kwargs,可选,默认值为 0.5) — 模型应用的像素混洗空间下采样比率;补丁网格的每一边都是其倒数的整数倍。
  • min_num_patches (int,kwargs,可选,默认值为 1024) — 图像被调整大小后,patch_size 补丁的最小数量。
  • max_num_patches (int,kwargs,可选,默认值为 13312) — 图像被调整大小后,patch_size 补丁的最大数量;0 表示禁用该上限。
  • max_model_len (int,kwargs,可选,默认值为 16384) — 语言模型的上下文长度,用于限制单次调用中图像的 patch 预算。

返回值

~image_processing_base.BatchFeature

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

NemotronH_Omni_Reasoning_V3VideoProcessor

class transformers.NemotronH_Omni_Reasoning_V3VideoProcessor

< >

( **kwargs: *<class 'transformers.models.nemotron_h_omni.video_processing_nemotron_h_omni.NemotronH_Omni_Reasoning_V3VideoProcessorInitKwargs'> )

参数

  • **kwargs (NemotronH_Omni_Reasoning_V3VideoProcessorInitKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持的完整参数列表,请参阅 TypedDict 类。

构建一个 NemotronH_Omni_Reasoning_V3VideoProcessor 视频处理器。

NemotronH_Omni_Reasoning_V3Processor

类 transformers.NemotronH_Omni_Reasoning_V3Processor

< >

( image_processor = Nonevideo_processor = Nonetokenizer = Nonefeature_extractor = Nonechat_template = Noneaudio_sampling_rate: int = 16000audio_subsampling_factor: int = 8audio_hop_length: int = 160video_temporal_patch_dim: int = 2**kwargs )

参数

  • image_processor (NemotronH_Omni_Reasoning_V3ImageProcessor) — 图像处理器是必需的输入。
  • video_processor (NemotronH_Omni_Reasoning_V3VideoProcessor) — 视频处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • feature_extractor (feature_extractor_class) — 特征提取器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • audio_sampling_rate (int,可选,默认为 16000) — 音频波形预期的采样率,单位为 Hz。
  • audio_subsampling_factor (int,可选,默认值为 8) — 声音编码器对 mel 帧进行下采样的因子,用于确定音频占位符序列的长度。
  • audio_hop_length (int,可选,默认为 160) — 连续 mel 帧之间的跳跃长度,以采样点为单位。
  • video_temporal_patch_dim (int, 可选,默认为 2) — 模型的 video embedder 将多少帧合并为一个时间 patch。

构建一个 NemotronH_Omni_Reasoning_V3Processor,它将图像处理器、视频处理器、分词器和特征提取器封装为单一处理器。

NemotronH_Omni_Reasoning_V3Processor 提供了 NemotronH_Omni_Reasoning_V3ImageProcessor、NemotronH_Omni_Reasoning_V3VideoProcessor、tokenizer_class 和 feature_extractor_class 的所有功能。有关更多信息,请参阅 ~NemotronH_Omni_Reasoning_V3ImageProcessor、~NemotronH_Omni_Reasoning_V3VideoProcessor、~tokenizer_class 和 ~feature_extractor_class。

batch_decode

< >

( *args**kwargs )

转发至分词器的 batch_decode()。

decode

< >

( *args**kwargs )

转发到分词器的 decode()。

后处理图像文本到文本

< >

( generated_outputsskip_special_tokens = Trueclean_up_tokenization_spaces = False**kwargs )

将模型生成的 token id 解码为文本。

replace_video_token

< >

( video_inputs: dictvideo_idx: int**kwargs )

将 <video> 展开为每个时间块(tubelet)一个 <img>...</img> 块。

每个块都标注了其所包含帧的时间戳,时间戳之间以 ” 和 ” 连接(管状体中的第一帧为 “Frame”,其余帧为 “frame”)。分词器没有真正的 <video> 标记,因此这些块使用图像标记;模型通过传入的是哪个 pixel_values_* 参数来区分图像和视频。

NemotronH_Omni_Reasoning_V3

class transformers.NemotronH_Omni_Reasoning_V3

< >

( config: NemotronH_Omni_Reasoning_V3_Config )

forward

< >

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

参数

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

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (total_patches, num_channels * patch_size**2),可选) — 图像处理器返回的所有图像的展平补丁,已拼接在一起。
  • image_grid_hw (torch.LongTensor,形状为 (num_images, 2),可选) — pixel_values 中每张图片的 patch 网格 (height, width)。
  • pixel_values_videos (torch.Tensor,形状为 (batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 与输入视频对应的张量。可以使用 NemotronH_Omni_Reasoning_V3VideoProcessor 获取视频的像素值。有关详细信息,请参阅 NemotronH_Omni_Reasoning_V3Processor.call()(NemotronH_Omni_Reasoning_V3Processor 使用 NemotronH_Omni_Reasoning_V3VideoProcessor 来处理视频)。
  • input_features (torch.Tensor,形状为 (batch_size, num_frames, num_mel_bins),可选) — 由处理器生成的梅尔特征,经过编码后分散到音频占位符标记上。
  • input_features_mask(形状为 (batch_size, num_frames) 的 torch.Tensor,可选) — 用于标记每个填充片段中真实 mel 帧的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

    如果使用了 past_key_values,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的全部 input_ids。

  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

CausalLMOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

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

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

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

示例:

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

>>> model = NemotronH_Omni_Reasoning_V3.from_pretrained("nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16")
>>> processor = AutoProcessor.from_pretrained("nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16")

>>> 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]

generate

< >

( inputs: typing.Optional[torch.Tensor] = Nonegeneration_config: transformers.generation.configuration_utils.GenerationConfig | None = Nonelogits_processor: transformers.generation.logits_process.LogitsProcessorList | None = Nonestopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = Noneprefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = Nonesynced_gpus: bool | None = Noneassistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional[ForwardRef('BaseStreamer')] = Nonenegative_prompt_ids: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonecustom_generate: str | collections.abc.Callable | None = None**kwargs ) → ModelOutput or torch.LongTensor

参数

  • inputs(形状因模态而异的 torch.Tensor,可选)— 用作生成提示的序列,或作为编码器的模型输入。如果为 None,该方法将使用 bos_token_id 和批大小 1 对其进行初始化。对于仅解码器模型,inputs 应采用 input_ids 的格式。对于编码器-解码器模型,inputs 可以是 input_ids、input_values、input_features 或 pixel_values 中的任意一种。
  • generation_config (GenerationConfig, 可选) — 用作生成调用基础参数化的生成配置。传递给 generate 且与 generation_config 属性匹配的 **kwargs 将覆盖这些属性。如果未提供 generation_config,则使用默认值,其加载优先级如下:1) 如果存在 generation_config.json 模型文件,则从中加载;2) 从模型配置中加载。请注意,未指定的参数将继承 GenerationConfig 的默认值,应查阅其文档以参数化生成。
  • logits_processor (LogitsProcessorList, 可选) — 自定义的 logits 处理器,用于补充由参数和生成配置构建的默认 logits 处理器。如果传入的 logit 处理器已经由参数或生成配置创建,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList,可选) — 自定义停止条件,用于补充由参数和生成配置构建的默认停止条件。如果传入的停止条件已经由参数或生成配置创建,则会抛出错误。如果你的停止条件依赖于 scores 输入,请确保向 generate 传入 return_dict_in_generate=True, output_scores=True。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], list[int]], 可选) — 如果提供,此函数会在每一步将束搜索限制为仅使用允许的 token。如果未提供,则不施加任何约束。此函数接受 2 个参数:批次 ID batch_id 和 input_ids。它必须返回一个列表,其中包含根据批次 ID batch_id 和之前生成的 token inputs_ids 条件化后,用于下一步生成的允许 token。此参数对于基于前缀的约束生成非常有用,如 Autoregressive Entity Retrieval 中所述。
  • synced_gpus (bool, 可选) — 是否继续执行 while 循环直到达到 max_length。除非被覆盖,否则在使用 FullyShardedDataParallel 或 DeepSpeed ZeRO Stage 3 且涉及多 GPU 时,此标志将设置为 True,以避免某个 GPU 在其他 GPU 之前完成生成时发生死锁。否则,默认为 False。
  • assistant_model (PreTrainedModel, 可选) — 可用于加速生成的辅助模型。辅助模型必须使用完全相同的 tokenizer。当使用辅助模型预测候选 token 的速度远快于从你调用 generate 的模型运行生成时,即可实现加速。因此,辅助模型应小得多。
  • streamer (BaseStreamer,可选) — 用于流式传输生成序列的 Streamer 对象。生成的 token 会通过 streamer.put(token_ids) 传入,由 streamer 负责后续处理。
  • negative_prompt_ids(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选) — 某些处理器(例如 CFG)所需的负面提示。批处理大小必须与输入批处理大小相匹配。这是一个实验性功能,未来版本中可能会发生破坏性的 API 变更。
  • negative_prompt_attention_mask(形状为 (batch_size, sequence_length) 的 torch.LongTensor,可选)— negative_prompt_ids 的 attention_mask。
  • custom_generate (str 或 Callable, 可选) — 以下之一:
    • str(Hugging Face Hub 仓库名称):运行该仓库中 custom_generate/generate.py 定义的自定义 generate 函数,而不是标准的 generate 方法。该仓库会完全替换生成逻辑,且返回类型可能有所不同。
    • str(本地仓库路径):与上述相同,但来自本地路径。本地目录也需要 trust_remote_code=True,因为会执行本地的 custom_generate/generate.py。
    • Callable:generate 将执行常规的输入准备步骤,然后调用提供的可调用对象来运行解码循环。 有关更多信息,请参阅 文档。
  • kwargs (dict[str, Any], 可选) — generation_config 的临时参数设置,和/或将被转发给模型 forward 函数的额外模型特定 kwargs。如果模型是编码器-解码器模型,编码器特定的 kwargs 不应添加前缀,而解码器特定的 kwargs 应以 decoder_ 作为前缀。

返回值

ModelOutput 或 torch.LongTensor

ModelOutput(当 return_dict_in_generate=True 或 config.return_dict_in_generate=True 时)或 torch.LongTensor。

如果模型不是编码器-解码器模型(model.config.is_encoder_decoder=False),可能的 ModelOutput 类型为:

如果模型是编码器-解码器模型(model.config.is_encoder_decoder=True),则可能的 ModelOutput 类型为:

为具有语言建模头的模型生成 token id 序列。

大多数生成控制参数都在 generation_config 中设置,如果未传入该参数,则会使用模型的默认生成配置。你可以通过向 generate() 传入相应参数来覆盖 generation_config 中的任意设置,例如 .generate(inputs, num_beams=4, do_sample=True)。

有关生成策略和代码示例的概述,请参阅以下指南。

Update on GitHub