Transformers documentation

Nemotron 3.5 Transcribe

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-10-28 贡献至 Hugging Face Transformers。

Nemotron 3.5 Transcribe

FlashAttention SDPA

概述

Nemotron 3.5 Transcribe 是一款用于多语言转录、带说话人归属的转录、语音翻译以及音频问答的音频语言模型。语音识别编码器与 Nemotron 3 Diarization 模型读取相同的频谱图,它们的输出被投影到 Nemotron-H 语言模型中。编码器上的词级时间戳头输出词级别的时间信息。

用法

转录

from transformers import AutoModelForMultimodalLM, AutoProcessor


model_id = "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B"
samples = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

inputs = processor.apply_transcription_request(samples + "en-Alice_woman.wav").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=256)
print(processor.decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True))

批量转录

from transformers import AutoModelForMultimodalLM, AutoProcessor


model_id = "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B"
samples = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

audio = [samples + "en-Alice_woman.wav", samples + "diarization_example.mp3"]
speaker_attributed_prompt = (
    "Transcribe this audio with punctuation and capitalization. Include all spoken words and verbal fillers. Write "
    "numbers in their standard written form. Put speaker tags <spk:0> <spk:1> <spk:2> <spk:3> on the transcription."
)
prompt = [None, speaker_attributed_prompt]

inputs = processor.apply_transcription_request(audio, prompt=prompt).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1024)
texts = processor.decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=False)
print([text.replace(processor.tokenizer.pad_token, "") for text in texts])

说话人归属转录

from transformers import AutoModelForMultimodalLM, AutoProcessor


model_id = "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B"
samples = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

prompt = (
    "Transcribe this audio with punctuation and capitalization. Include all spoken words and verbal fillers. Write "
    "numbers in their standard written form. Put speaker tags <spk:0> <spk:1> <spk:2> <spk:3> on the transcription."
)
conversation = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": prompt},
            {"type": "audio", "path": samples + "diarization_example.mp3"},
        ],
    }
]

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    enable_thinking=False,
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1024)
text = processor.decode(outputs[0, inputs.input_ids.shape[1] :], skip_special_tokens=False)
print(text)

extract_speaker_dict() 将输出拆分为每个说话人轮次对应的一个字典:

for turn in processor.extract_speaker_dict(text):
    print(turn)
{'Speaker': 0, 'Content': "To celebrate the release of Nematron three Dierization, we invited ... from NVIDIA."}
{'Speaker': 1, 'Content': "Hi everybody, thanks for having me. I'm Jane, a pocket voice from QTie."}
{'Speaker': 2, 'Content': "Nice to meet you Chris and Jane. I'm Serena, the Queen three Voice."}
...

单词时间戳

需要 torchaudio 和 scipy。

from transformers import AutoModelForMultimodalLM, AutoProcessor


model_id = "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B"
samples = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForMultimodalLM.from_pretrained(model_id, device_map="auto")

prompt = (
    "Transcribe this audio with punctuation and capitalization. Include all spoken words and verbal fillers. Write "
    "numbers in their standard written form. Put speaker tags <spk:0> <spk:1> <spk:2> <spk:3> on the transcription."
)

inputs = processor.apply_transcription_request(samples + "diarization_example.mp3", prompt=prompt).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=1024, return_word_timestamp_logits=True)
texts = processor.decode(outputs.sequences[:, inputs.input_ids.shape[1] :], skip_special_tokens=False)
timestamps = processor.align_word_timestamps(
    texts,
    outputs.word_timestamp_logits,
    inputs.input_features_mask,
    outputs.speaker_logits,
)
print(timestamps[0]["chunks"][:3])

要对未生成的转录文本进行对齐:

input_features_mask = inputs.input_features_mask
audio_outputs = model.get_audio_features(inputs.input_features, input_features_mask)
word_timestamp_logits = model.get_word_timestamp_logits(audio_outputs.asr_last_hidden_state, input_features_mask)
timestamps = processor.align_word_timestamps(
    ["<spk:0> To celebrate the ..."],
    word_timestamp_logits,
    input_features_mask,
    audio_outputs.speaker_logits,
)

Nemotron3_5TranscribeConfig

class transformers.Nemotron3_5TranscribeConfig

< >

( 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 = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_token_id: int = 131072word_timestamp_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )

参数

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 音频骨干网络的配置对象或字典。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • audio_token_id (int,可选,默认值为 131072) — 用作音频嵌入占位符的音频 token 索引。原始检查点将其附加在语言模型词表之后,且不包含对应的嵌入行:它先作为 token 0 进行嵌入,随后被音频嵌入替换。
  • word_timestamp_config (Union[dict, Nemotron3_5TranscribeWordTimestampConfig], 可选) — 词级时间戳编码器和头部的配置,用于从语音识别编码器状态中预测对齐的分词器片段。

这是用于存储 Nemotron3 5 TranscribeModel 配置的类。它根据指定的参数实例化 Nemotron3 5 Transcribe 模型,并定义模型架构。使用默认值实例化配置将得到与 nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B 类似的配置。

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

示例:

>>> from transformers import Nemotron3_5TranscribeForConditionalGeneration, Nemotron3_5TranscribeConfig

>>> # Initializing a Nemotron3_5Transcribe configuration
>>> configuration = Nemotron3_5TranscribeConfig()

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

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

Nemotron3_5TranscribeAsrAudioConfig

class transformers.Nemotron3_5TranscribeAsrAudioConfig

< >

( 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 = Nonehidden_size: int = 1280intermediate_size: int = 5120num_hidden_layers: int = 32num_attention_heads: int = 10num_key_value_heads: int | None = Nonehidden_act: str = 'gelu'max_position_embeddings: int = 5000initializer_range: float = 0.02rope_parameters: dict | None = Noneattention_dropout: float | int = 0.0num_mel_bins: int = 128subsampling_factor: int = 8 )

参数

  • hidden_size (int,可选,默认为 1280) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 5120) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 32) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 10) — 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,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 5000) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • num_mel_bins (int, 可选,默认为 128) — 每个输入帧使用的 mel 特征数量。应与 AutoFeatureExtractor 类中使用的值相对应。
  • subsampling_factor (int,可选,默认为 8) — 堆叠到单个编码器帧中的连续频谱帧数。

这是用于存储 Nemotron3 5 TranscribeModel 配置的类。它根据指定的参数实例化 Nemotron3 5 Transcribe 模型,并定义模型架构。使用默认值实例化配置将得到与 nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B 类似的配置。

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

示例:

>>> from transformers import Nemotron3_5TranscribeAsrAudioModel, Nemotron3_5TranscribeAsrAudioConfig

>>> # Initializing a Nemotron3_5TranscribeAsrAudioModel configuration
>>> configuration = Nemotron3_5TranscribeAsrAudioConfig()

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

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

Nemotron3_5TranscribeAudioConfig

class transformers.Nemotron3_5TranscribeAudioConfig

< >

( 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 = Noneasr_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonediarization_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonespeaker_activity_threshold: float = 0.5 )

参数

  • asr_config (Union[dict, Nemotron3_5TranscribeAsrAudioConfig],可选) — 语音识别编码器的配置。
  • diarization_config (Union[dict, Nemotron3DiarizationConfig], 可选) — 说话人分离模型的配置,该模型的说话人活动会被添加到语音识别编码器的输出中。
  • speaker_activity_threshold (float,可选,默认值为 0.5) — 当说话人的概率高于此阈值时,该说话人在编码器帧中被视为处于活跃状态。

这是用于存储 Nemotron3 5 TranscribeModel 配置的类。它根据指定的参数实例化 Nemotron3 5 Transcribe 模型,并定义模型架构。使用默认值实例化配置将得到与 nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B 类似的配置。

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

示例:

>>> from transformers import Nemotron3_5TranscribeAudioModel, Nemotron3_5TranscribeAudioConfig

>>> # Initializing a Nemotron3_5TranscribeAudioModel configuration
>>> configuration = Nemotron3_5TranscribeAudioConfig()

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

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

Nemotron3_5TranscribeWordTimestampConfig

class transformers.Nemotron3_5TranscribeWordTimestampConfig

< >

( 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 = Nonehidden_size: int = 1280intermediate_size: int = 640num_hidden_layers: int = 2num_attention_heads: int = 16num_key_value_heads: int | None = Nonehidden_act: str = 'gelu'max_position_embeddings: int = 5000initializer_range: float = 0.02rope_parameters: dict | None = Noneattention_dropout: float | int = 0.0vocab_size: int = 23863blank_token_id: int = 23862residual_scale: float = 0.1upsampling_factor: int = 2 )

参数

  • hidden_size (int,可选,默认为 1280) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 640) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 2) — Transformer 解码器中的隐藏层数。
  • num_attention_heads (int,可选,默认为 16) — 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,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 5000) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • vocab_size (int,可选,默认值为 23863) — 词元时间戳头的类别数:即其对齐分词器的各个片段,再加上一个空白符。
  • blank_token_id (int,可选,默认为 23862) — 对齐分词器中空白类别的索引,位于各片段之后。
  • residual_scale (float, 可选,默认为 0.1) — 在分类器之前,添加到语音识别编码器状态中的 Transformer 输出的缩放比例。
  • upsampling_factor (int,可选,默认为 2) — 每个编码器帧对应的头部帧数,由 Transformer 之前的转置卷积生成:2 表示从 80 ms 的编码器帧生成 40 ms 的帧。

这是用于存储 Nemotron3 5 TranscribeModel 配置的类。它根据指定的参数实例化 Nemotron3 5 Transcribe 模型,并定义模型架构。使用默认值实例化配置将得到与 nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B 类似的配置。

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

示例:

>>> from transformers import Nemotron3_5TranscribeConfig, Nemotron3_5TranscribeWordTimestampConfig

>>> # Initializing a Nemotron3_5TranscribeWordTimestamp configuration
>>> configuration = Nemotron3_5TranscribeWordTimestampConfig()

>>> # Using it as the word timestamp head of the model
>>> model_configuration = Nemotron3_5TranscribeConfig(word_timestamp_config=configuration)

Nemotron3_5TranscribeProcessor

class transformers.Nemotron3_5TranscribeProcessor

< >

( feature_extractortokenizeralignment_tokenizerchat_template = Noneaudio_token = '<|audio|>'default_transcription_prompt = 'Audio transcription. Language: as spoken. Wording: verbatim, including fillers and repetitions. Formatting: punctuation and capitalization. Output: transcript only.'subsampling_factor = 8 )

参数

  • feature_extractor (feature_extractor_class) — 特征提取器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • alignment_tokenizer (PreTrainedTokenizerFast) — 词时间戳头的词表:23,862 个 SentencePiece BPE 片段,其中该头的类别 23,862 为 CTC 空白符。仅由 align_word_timestamps() 使用,保存在 alignment_tokenizer/ 子文件夹中。在文本前添加一个空格,以复现任意文本(包括以标签开头的文本)的原始 SentencePiece id:alignment_tokenizer.encode(" " + text, add_special_tokens=False)。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • audio_token (str, 可选,默认为 "<|audio|>") — 在聊天模板中用于表示音频输入的特殊标记。
  • default_transcription_prompt (str, 可选) — apply_transcription_request() 使用的默认提示。
  • subsampling_factor (int,可选,默认为 8) — 每个音频 token 对应的频谱帧数,与 Nemotron3_5TranscribeAsrAudioConfig.subsampling_factor 保持一致。频谱会被填充为该值的整数倍。

构建一个 Nemotron3_5TranscribeProcessor,它将特征提取器、分词器和对齐分词器封装为单一处理器。

Nemotron3_5TranscribeProcessor 提供了 feature_extractor_class、tokenizer_class 和 {alignment_tokenizer_class} 的所有功能。有关更多信息,请参阅 ~feature_extractor_class、~tokenizer_class 和 ~{alignment_tokenizer_class}。

__call__

< >

( text: str | list[str]audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = Noneoutput_labels: bool | None = False**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → BatchFeature

参数

  • text (Union[str, list[str]]) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True 以避免与批量输入产生歧义。
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • output_labels (bool,可选,默认值=False) — 是否返回用于训练的标签。
  • 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 类。

返回值

BatchFeature

一个包含分词文本(input_ids、attention_mask)和音频特征(input_features、input_features_mask)的字典。

apply_transcription_request

< >

( audio: typing.Union[str, list[str], numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]prompt: str | list[str] | None = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → BatchFeature

参数

  • audio (str, list[str], np.ndarray, torch.Tensor, list[np.ndarray], list[torch.Tensor]) — 要转录的音频。字符串会被解释为本地路径或 URL,并由聊天模板加载器自动加载;NumPy 数组和 PyTorch 张量会被直接传递。
  • prompt (str 或 list[str],可选) — 包含在用户轮次中的自定义提示。列表的长度必须与批次相同。当为 None 时, 每个样本使用 default_transcription_prompt。
  • **kwargs — 转发给 apply_chat_template() 的额外关键字参数(例如 text_kwargs、audio_kwargs 等)。 除非传入 enable_thinking=True,否则思考功能处于禁用状态(聊天模板默认启用该功能)。

返回值

BatchFeature

Processor 的输出可直接传入 Nemotron3_5TranscribeForConditionalGeneration.generate()。

为自动语音识别准备输入,而无需手动编写默认转录提示。

apply_chat_template

< >

( conversation: list[dict[str, str]] | list[list[dict[str, str]]]chat_template: str | None = Nonetools: list[dict] | None = Nonedocuments: list[dict[str, str]] | None = Noneadd_generation_prompt: bool = Falsecontinue_final_message: bool | str = Falsereturn_assistant_tokens_mask: bool = Falsetokenize: bool = Falsereturn_tensors: str | transformers.utils.generic.TensorType | None = 'auto'return_dict: bool = Falseload_audio_from_video: bool = Falseprocessor_kwargs: dict | None = Nonesanitize_control_tokens: bool = False**kwargs )

参数

  • conversation (Union[list[Dict, [str, str]], list[list[dict[str, str]]]]) — 要格式化的对话。
  • chat_template (Optional[str],可选) — 用于格式化对话的 Jinja 模板。如果未提供,则使用分词器的聊天模板。
  • sanitize_control_tokens (bool,默认为 False) — 是否将对话、工具、文档以及作为 **kwargs 传入的模板变量中发现的控制标记编码为纯文本,从而防止用户输入写入这些标记或 mm 占位符。 请参阅分词器的 apply_chat_template。 需要 tokenize=True。

与分词器上的 apply_chat_template 方法类似,该方法将 Jinja 模板应用于输入对话,将其转换为单个可分词的字符串。

输入应遵循以下格式,其中每条消息的内容是一个列表,包含文本以及可选的图像或视频输入。也可以提供图像、视频、URL 或本地路径,当 return_dict=True 时,这些内容将用于构建 pixel_values。如果未提供,则只会获得格式化后的文本,以及可选的标记化文本。

conversation = [ { “role”: “user”, “content”: [ {“type”: “image”, “url”: “https://www.ilankelman.org/stopsigns/australia.jpg”}, {“type”: “text”, “text”: “Please describe this image in detail.”}, ], }, ]

extract_speaker_dict

< >

( text: str | list[str] ) → list[dict] for a single text, list[list[dict]] for a batch

参数

  • text (str 或 list[str]) — 单条文本或文本批次,使用 skip_special_tokens=False 进行解码:<spk:N> 说话人标签属于特殊标记。从文本结束标记开始的所有内容均会被丢弃。

返回值

单个文本为 list[dict],批次为 list[list[dict]]

每个说话人轮次对应一个字典,其中包含其 <spk:N> 标签的 "Speaker" 索引 N 以及其 "Content"。没有标签的文本被视为单个轮次,其 "Speaker": None;如果存在标签,则第一个标签之前的文本同样被视为单个轮次。

VibeVoiceAsrProcessor.extract_speaker_dict() 将带有说话人归属的转录文本拆分为说话人轮次,格式与 VibeVoiceAsrProcessor.extract_speaker_dict() 相同,但不包含时间戳,因为该模型不预测时间戳。

示例:

>>> processor.extract_speaker_dict("<spk:0> Hi, how are you? <spk:1> Fine, thanks.<|im_end|>")
[{'Speaker': 0, 'Content': 'Hi, how are you?'}, {'Speaker': 1, 'Content': 'Fine, thanks.'}]

align_word_timestamps

< >

( transcriptions: str | list[str]word_timestamp_logits: torch.Tensorinput_features_mask: torch.Tensorspeaker_logits: torch.Tensor | None = Nonelanguage: str | list[str | None] | None = Nonespeaker_activity_threshold: float = 0.5max_word_duration: float = 1.0max_word_frames: int = 12 ) → dict or list[dict]

参数

  • transcriptions(str 或 list[str])— 每条录音的生成文本,使用 skip_special_tokens=False 进行解码,以保留 <spk:N> 标签。
  • word_timestamp_logits(形状为 (batch_size, num_frames * upsampling_factor, vocab_size) 的 torch.Tensor)— 词时间戳头的 logits(即 generate(..., return_word_timestamp_logits=True) 或 model.get_word_timestamp_logits(...) 返回的 word_timestamp_logits),其中最后一个类别为 CTC 空白。每个编码器帧对应的帧数,即该头的 upsampling_factor,可从其形状中读取。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 每条录音中有效频谱帧的掩码,由处理器返回:其数量决定了录音的时长,进而决定头部帧的时间步长。
  • speaker_logits (torch.Tensor,形状为 (batch_size, num_frames * subsampling_factor, num_speakers),可选) — 说话人分离模型的 logits(即 generate(..., return_word_timestamp_logits=True) 或 get_audio_features 返回的 speaker_logits)。如果未提供,每条转录文本将被视为单一说话人进行对齐,且不会返回说话人分离结果。
  • language (str 或 list[str | None],可选) — 转录文本的语言,可为所有转录文本指定一种语言,或为每条转录文本分别指定一种语言;当值为 None 时,将根据脚本自动检测: "zh" 和 "ja" 按字符对齐,"th" 不受支持。
  • speaker_activity_threshold (float,可选,默认值为 0.5) — 说话人处于活跃状态的判定概率阈值。
  • max_word_duration (float,可选,默认值为 1.0) — 对齐单词的最大时长,单位为秒。
  • max_word_frames (int, 可选,默认为 12) — 对齐到说话人分离片段的单词的最大偏移量和持续时间,以不超过 80 毫秒的编码器帧为单位。

返回值

dict 或 list[dict]

用于录音(或转录列表中的每个录音),作为语音识别流水线的单词时间戳,"chunks" (每个单词包含 {"text", "timestamp", "speaker"},其中 timestamp = (start, end),单位为秒,按时间排序; speaker 为单词标签的 N,在第一个标签之前为 None,在无标签的转录中为 0), "diarization"(每个说话人分离说话人的 {"speaker", "timestamp"} 活动片段), "speaker_tag_to_diarization_speaker"(未匹配的标签为 None)以及 "failed_speakers"(无法对齐其单词的标签,缺失于 "chunks" 中)。

对生成转录文本中的每个词进行时间戳标注,并将其归属到对应的说话人:每个 <spk:N> 标签内的词会在词时间戳头中说话人分离结果与该标签匹配的说话人处于活跃状态的帧上进行强制对齐(torchaudio.functional.forced_align),然后对齐到该说话人的说话人分离片段。此功能移植自 NeMo 的 MultiSpeakerSOTWordTimestampAligner,并在其使用近似方法处理长录音的地方采用了精确搜索。

示例:

>>> inputs = processor.apply_transcription_request(audio, prompt=speaker_attributed_prompt).to(model.device)
>>> outputs = model.generate(**inputs, return_word_timestamp_logits=True, max_new_tokens=500)
>>> transcriptions = processor.decode(
...     outputs.sequences[:, inputs.input_ids.shape[1] :], skip_special_tokens=False
... )
>>> timestamps = processor.align_word_timestamps(
...     transcriptions, outputs.word_timestamp_logits, inputs.input_features_mask, outputs.speaker_logits
... )
>>> timestamps[0]["chunks"][0]  # {'text': ..., 'timestamp': (..., ...), 'speaker': 0}

Nemotron3_5TranscribeAsrAudioModel

class transformers.Nemotron3_5TranscribeAsrAudioModel

< >

( config: Nemotron3_5TranscribeAsrAudioConfig )

参数

Nemotron 3.5 Transcribe 语音识别编码器:在 Nemotron 3 Diarization 音频编码器的基础上,对每个注意力头的查询和键进行归一化,并在每个头的一部分上应用旋转位置嵌入。

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

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

forward

< >

( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 feature_extractor_class 获取音频特征。有关详细信息,请参阅 feature_extractor_class.__call__(processor_class 使用 feature_extractor_class 来处理音频)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • position_ids (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

返回值

BaseModelOutput 或 tuple(torch.Tensor)

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

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

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

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

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

Nemotron3_5TranscribeAudioModel

class transformers.Nemotron3_5TranscribeAudioModel

< >

( config: Nemotron3_5TranscribeAudioConfig )

参数

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

Nemotron 3.5 Transcribe 音频模型:语音识别编码器和说话人分离模型在相同的频谱图上并行运行,并将说话人活动添加到语音识别编码器的输出中。

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

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

forward

< >

( input_features: Tensorinput_features_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Nemotron3_5TranscribeAudioModelOutput or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, feature_sequence_length, num_mel_bins)) — 对数梅尔频谱图,填充至 config.subsampling_factor 帧的整数倍。与原始实现一致,长度超过 config.diarization_config.chunk_length 个编码器帧的音频将以带上下文的分块方式进行编码。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor,可选) — 有效频谱帧的掩码。填充必须位于右侧。

返回值

Nemotron3_5TranscribeAudioModelOutput 或 tuple(torch.Tensor)

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

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

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

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

  • pooler_output(形状为 (num_audio_tokens, text_config.hidden_size) 的 torch.Tensor,可选)— 按批次顺序排列的每条录音中有效编码器帧的投影音频嵌入:即用于替换提示中音频令牌的嵌入。由 get_audio_features 返回。

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

  • asr_last_hidden_state(形状为 (batch_size, num_frames, audio_config.hidden_size) 的 torch.Tensor)— 语音识别编码器的输出,位于其归一化和说话人嵌入之前:get_word_timestamp_logits() 的输入。

  • speaker_logits(形状为 (batch_size, feature_sequence_length, audio_config.num_speakers) 的 torch.Tensor)— 说话人分离模型的 logits,每个频谱图帧对应一帧。

Nemotron3_5TranscribeWordTimestampModel

class transformers.Nemotron3_5TranscribeWordTimestampModel

< >

( config: Nemotron3_5TranscribeWordTimestampConfig )

参数

Nemotron 3.5 Transcribe 的 transformer 中的词级时间戳头。Nemotron3_5TranscribeForConditionalGeneration.word_timestamp_head 会对其输出进行分类。

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

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

forward

< >

( inputs_embeds: Tensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

  • inputs_embeds(形状为 (batch_size, num_frames, hidden_size) 的 torch.Tensor)— 语音识别编码器状态,位于音频模型的 asr_norm 和说话人嵌入之前。
  • attention_mask (torch.Tensor,形状为 (batch_size, num_frames),可选) — 有效编码器帧的掩码。

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

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

返回 num_frames * upsampling_factor 帧。

Nemotron3_5TranscribeModel

class transformers.Nemotron3_5TranscribeModel

< >

( config: Nemotron3_5TranscribeConfig )

参数

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

Nemotron 3.5 Transcribe 模型(语音识别编码器与说话人分离模型并行,线性投影器以及 Nemotron-H 语言模型),不包含语言建模头。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = 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 = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Nemotron3_5TranscribeModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 feature_extractor_class 获取音频特征。有关详细信息,请参阅 feature_extractor_class.__call__(processor_class 使用 feature_extractor_class 来处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

Nemotron3_5TranscribeModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

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

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

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

  • audio_hidden_states (torch.Tensor,可选) — 投影后的音频隐藏状态。

get_audio_features

< >

( input_features: Tensorinput_features_mask: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor) — 从原始语音波形中提取的梅尔特征的浮点值。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充的特征索引执行注意力机制的掩码。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

此方法用于从输入特征(对数梅尔频谱图)中获取音频嵌入,即推断音频编码器和多模态投影器。

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

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

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

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

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

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

get_word_timestamp_hidden_states

< >

( asr_last_hidden_state: Tensorinput_features_mask: Tensor )

参数

  • asr_last_hidden_state (torch.Tensor,形状为 (batch_size, num_frames, audio_config.hidden_size)) — 语音识别编码器在归一化和说话人嵌入之前的输出,即 get_audio_features() 针对 input_features_mask 返回的结果。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 有效频谱帧的掩码。填充必须位于右侧。

在语音识别编码器的状态上运行单词时间戳编码器,按编码器的块进行处理:即单词时间戳头进行分类的状态。

Nemotron3_5TranscribeForConditionalGeneration

类 transformers.Nemotron3_5TranscribeForConditionalGeneration

< >

( config: Nemotron3_5TranscribeConfig )

参数

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

Nemotron 3.5 Transcribe 模型(语音识别编码器与说话人分离模型并行,线性投影器以及 Nemotron-H 语言模型)并带有语言建模头。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = 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 = 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'> ) → Nemotron3_5TranscribeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • input_features (torch.Tensor,形状为 (batch_size, sequence_length, feature_dim),可选) — 与输入音频特征对应的张量。可以使用 feature_extractor_class 获取音频特征。有关详细信息,请参阅 feature_extractor_class.__call__(processor_class 使用 feature_extractor_class 来处理音频)。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 用于避免对填充特征索引执行注意力机制的掩码。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

    什么是位置 ID?

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

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

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

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

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

返回值

Nemotron3_5TranscribeCausalLMOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数。

  • past_key_values(Cache,可选,在传入 use_cache=True 或 config.use_cache=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 之后的权重,用于在自注意力头中计算加权平均值。

  • audio_hidden_states (torch.Tensor,可选) — 音频编码器投影后的隐藏状态。

示例:

>>> from transformers import Nemotron3_5TranscribeForConditionalGeneration, AutoProcessor

>>> model_id = "nvidia/audio-flamingo-3-hf"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = Nemotron3_5TranscribeForConditionalGeneration.from_pretrained(model_id, device_map="auto")

get_audio_features

< >

( input_featuresinput_features_mask**kwargs )

参数

  • input_features (`of shape(batch_size, sequence_length, feature_dim)) -- The tensors corresponding to the input audio features. Audio features can be obtained using feature_extractor_class. See feature_extractor_class.call for details (processor_classusesfeature_extractor_class` for processing audios).
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 有效频谱帧的掩码。填充必须位于右侧。

示例:

get_word_timestamp_logits

< >

( asr_last_hidden_state: Tensorinput_features_mask: Tensor )

参数

  • asr_last_hidden_state (torch.Tensor,形状为 (batch_size, num_frames, audio_config.hidden_size)) — 语音识别编码器在归一化和说话人嵌入之前的输出,即 get_audio_features() 针对 input_features_mask 返回的结果。
  • input_features_mask(形状为 (batch_size, feature_sequence_length) 的 torch.Tensor)— 有效频谱帧的掩码。填充必须位于右侧。

语音识别编码器状态中单词时间戳头的 Logits,align_word_timestamps() 会将其转换为单词时间。

示例:

Update on GitHub