Transformers 文档

耳语

Whisper

概述

Whisper模型是由Alec Radford、Jong Wook Kim、Tao Xu、Greg Brockman、Christine McLeavey和Ilya Sutskever在通过大规模弱监督实现鲁棒语音识别中提出的。

论文的摘要如下:

我们研究了仅通过预测互联网上大量音频转录本来训练的语音处理系统的能力。当扩展到680,000小时的多语言和多任务监督时,生成的模型在标准基准测试中表现出色,并且通常与之前完全监督的结果相媲美,但在零样本转移设置中无需任何微调。与人类相比,这些模型接近其准确性和鲁棒性。我们正在发布模型和推理代码,以作为进一步研究鲁棒语音处理的基础。

该模型由Arthur Zucker贡献。该模型的Tensorflow版本由amyeroberts贡献。 原始代码可以在这里找到。

快速使用

你可以在不到4行代码中运行Whisper,并在不到一分钟内完成转录!

# pip install transformers torch

import torch
from transformers import pipeline

whisper = pipeline("automatic-speech-recognition", "openai/whisper-large-v3", torch_dtype=torch.float16, device="cuda:0")

transcription = whisper("<audio_file.mp3>")

print(transcription["text"])

瞧!您可以根据需要,使用相同的管道在Hugging Face Hub上交换任何Whisper检查点的模型。

额外提示:你可以将 "cuda" 替换为 "mps",使其在 Mac 上无缝运行。

使用提示

  • 该模型通常表现良好,无需任何微调。

  • 该架构遵循经典的编码器-解码器架构,这意味着它依赖于generate()函数进行推理。

  • 可以使用WhisperProcessor来为模型准备音频,并将预测的ID解码回文本。

  • 要转换模型和处理器,我们建议使用以下方法:

python src/transformers/models/whisper/convert_openai_to_hf.py --checkpoint_path "" --pytorch_dump_folder_path "Arthur/whisper-3" --convert_preprocessor True

脚本将自动从OpenAI检查点确定所有必要的参数。需要安装一个tiktoken库来执行将OpenAI分词器转换为tokenizers版本的操作。

推理

以下是使用预训练的Whisper模型转录音频样本的逐步指南:

>>> from datasets import load_dataset
>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration

>>> # Select an audio file and read it:
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> audio_sample = ds[0]["audio"]

>>> # Load the Whisper model in Hugging Face format:
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

>>> # Use the model and processor to transcribe the audio:
>>> input_features = processor(
...     audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt"
... ).input_features

>>> # Generate token ids
>>> predicted_ids = model.generate(input_features)

>>> # Decode token ids to text
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)

>>> transcription[0]
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

Whisper 兼容以下针对短格式和长格式生成的优化:

例如,以下代码片段启用了SDPA和torch.compile,以实现高达5倍的推理速度提升:

>>> from datasets import load_dataset
>>> from transformers import WhisperProcessor, WhisperForConditionalGeneration

>>> # Select an audio file and read it:
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> audio_sample = ds[0]["audio"]

>>> # Load the Whisper model with SDPA attention
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", attn_implementation="sdpa")

>>> # Enable static cache and compile the forward pass
>>> model.generation_config.cache_implementation = "static"
>>> model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)

>>> # Use the model and processor to transcribe the audio:
>>> input_features = processor(
...     audio_sample["array"], sampling_rate=audio_sample["sampling_rate"], return_tensors="pt"
... ).input_features

>>> # Compile the forward pass
>>> for _ in range(2):
>>>     model.generate(input_features)

>>> # Generate token ids using compiled graph (fast!)
>>> predicted_ids = model.generate(input_features)

>>> # Decode token ids to text
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)

>>> transcription[0]
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

有关每个优化的更多详细信息,请参阅上面链接的文档。

资源

一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用Whisper。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将对其进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

pip install -U openai-whisper
python convert_hf_to_openai.py \
    --checkpoint openai/whisper-tiny \
    --whisper_dump_path whisper-tiny-openai.pt

WhisperConfig

transformers.WhisperConfig

< >

( vocab_size = 51865 num_mel_bins = 80 encoder_layers = 4 encoder_attention_heads = 6 decoder_layers = 4 decoder_attention_heads = 6 decoder_ffn_dim = 1536 encoder_ffn_dim = 1536 encoder_layerdrop = 0.0 decoder_layerdrop = 0.0 decoder_start_token_id = 50257 use_cache = True is_encoder_decoder = True activation_function = 'gelu' d_model = 384 dropout = 0.0 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 scale_embedding = False max_source_positions = 1500 max_target_positions = 448 pad_token_id = 50256 bos_token_id = 50256 eos_token_id = 50256 suppress_tokens = None begin_suppress_tokens = [220, 50256] use_weighted_layer_sum = False classifier_proj_size = 256 apply_spec_augment = False mask_time_prob = 0.05 mask_time_length = 10 mask_time_min_masks = 2 mask_feature_prob = 0.0 mask_feature_length = 10 mask_feature_min_masks = 0 median_filter_width = 7 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 51865) — Whisper 模型的词汇表大小。定义了可以通过调用 WhisperModel 时传递的 decoder_input_ids 表示的不同标记的数量
  • num_mel_bins (int, 可选, 默认为 80) — 每个输入特征使用的mel特征数量。应与WhisperProcessor类中使用的值相对应。
  • encoder_layers (int, optional, defaults to 4) — 编码器层数.
  • decoder_layers (int, optional, defaults to 4) — 解码器层数.
  • encoder_attention_heads (int, optional, defaults to 6) — Transformer编码器中每个注意力层的注意力头数量。
  • decoder_attention_heads (int, optional, defaults to 6) — Transformer解码器中每个注意力层的注意力头数量。
  • encoder_ffn_dim (int, optional, 默认为 1536) — 编码器中“中间”(通常称为前馈)层的维度。
  • decoder_ffn_dim (int, optional, defaults to 1536) — 解码器中“中间”(通常称为前馈)层的维度。
  • encoder_layerdrop (float, 可选, 默认为 0.0) — 编码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。
  • decoder_layerdrop (float, 可选, 默认为 0.0) — 解码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。
  • decoder_start_token_id (int, 可选, 默认为 50257) — 对应于“<|startoftranscript|>”标记,当没有提供decoder_input_idsgenerate函数时,会自动使用该标记。它用于根据任务指导模型的生成过程。
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。
  • is_encoder_decoder (bool, optional, defaults to True) — 模型是否用作编码器/解码器。
  • activation_function (str, optional, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""silu""gelu_new"
  • d_model (int, optional, 默认为 384) — 层的维度。
  • dropout (float, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的丢弃比率。
  • activation_dropout (float, optional, defaults to 0.0) — 全连接层内部激活的丢弃比例。
  • init_std (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • scale_embedding (bool, optional, defaults to False) — 通过除以 sqrt(d_model) 来缩放嵌入。
  • max_source_positions (int, optional, 默认为 1500) — 该模型可能使用的对数梅尔滤波器组特征的最大序列长度。
  • max_target_positions (int, optional, 默认为 448) — 该模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • pad_token_id (int, optional, 默认为 50256) — 填充标记 id.
  • bos_token_id (int, optional, 默认为 50256) — 流的开始标记 id.
  • eos_token_id (int, 可选, 默认为 50256) — 流结束标记的ID.
  • suppress_tokens (List[int], 可选) — 一个包含非语音标记的列表,这些标记将由generate函数中的logit处理器使用。NON_SPEECH_TOKENS和NON_SPEECH_TOKENS_MULTI分别对应于仅英语多语言模型。
  • begin_suppress_tokens (List[int], 可选, 默认为 [220,50256]) — 一个包含在采样过程开始时将被抑制的令牌的列表。初始化为 " " (blank_token_id) 和 eos_token_id 的令牌
  • use_weighted_layer_sum (bool, 可选, 默认为 False) — 是否使用带有学习权重的层输出的加权平均。仅在使用 WhisperForAudioClassification 实例时相关。
  • classifier_proj_size (int, 可选, 默认为 256) — 分类前用于标记平均池化的投影维度。仅在使用的实例为 WhisperForAudioClassification 时相关。
  • apply_spec_augment (bool, 可选, 默认为 False) — 是否对特征编码器的输出应用 SpecAugment 数据增强。有关参考,请参见 SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition.
  • mask_time_prob (float, 可选, 默认值为 0.05) — 沿时间轴的所有特征向量将被掩码的百分比(介于 0 和 1 之间)。掩码过程生成 mask_time_prob*len(time_axis)/mask_time_length 个独立的掩码。如果从每个特征向量被选为要掩码的向量跨度的起始点的概率来推理,mask_time_prob 应为 prob_vector_start*mask_time_length。请注意,重叠可能会减少实际被掩码的向量的百分比。这仅在 apply_spec_augment == True 时相关。
  • mask_time_length (int, optional, 默认为 10) — 沿时间轴的向量跨度长度。
  • mask_time_min_masks (int, 可选, 默认为 2), — 沿时间轴生成的每个时间步长的最小掩码数量,长度为 mask_feature_length,与 mask_feature_prob 无关。仅在“mask_time_prob*len(time_axis)/mask_time_length < mask_time_min_masks”时相关
  • mask_feature_prob (float, optional, 默认为 0.0) — 沿特征轴的所有特征向量中将被掩码的百分比(介于 0 和 1 之间)。掩码过程生成 mask_feature_prob*len(feature_axis)/mask_time_length 个独立的掩码覆盖该轴。如果从每个特征向量被选为要掩码的向量跨度的起始点的概率来推理,mask_feature_prob 应为 prob_vector_start*mask_feature_length。注意,重叠可能会减少实际被掩码的向量的百分比。这仅在 apply_spec_augment is True 时相关。
  • mask_feature_length (int, optional, defaults to 10) — 沿特征轴的向量跨度长度。
  • mask_feature_min_masks (int, 可选, 默认为 0), — 每次在特征轴上生成的长度为 mask_feature_length 的最小掩码数量,无论 mask_feature_prob 如何。仅当 mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks 时相关。
  • median_filter_width (int, 可选, 默认为 7) — 用于平滑交叉注意力输出的中值滤波器的宽度,当计算令牌时间戳时使用。 应该是一个奇数。

这是用于存储WhisperModel配置的配置类。它用于根据指定的参数实例化一个Whisper模型,定义模型架构。使用默认值实例化配置将产生类似于Whisper openai/whisper-tiny架构的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import WhisperConfig, WhisperModel

>>> # Initializing a Whisper tiny style configuration
>>> configuration = WhisperConfig()

>>> # Initializing a model (with random weights) from the tiny style configuration
>>> model = WhisperModel(configuration)

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

WhisperTokenizer

transformers.WhisperTokenizer

< >

( vocab_file merges_file normalizer_file = None errors = 'replace' unk_token = '<|endoftext|>' bos_token = '<|endoftext|>' eos_token = '<|endoftext|>' pad_token = None add_prefix_space = False language = None task = None predict_timestamps = False **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件的路径。
  • normalizer_file (str, optional) — normalizer_file 文件的路径。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • unk_token (str, optional, defaults to "<|endoftext|>") — 未知的标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • bos_token (str, optional, 默认为 "<|endoftext|>") — 序列的开始标记。在生成时,decoder_start_token_id 用于将第一个标记设置为 "<|startoftranscript|>".
  • eos_token (str, optional, defaults to "<|endoftext|>") — 序列结束标记。
  • pad_token (str, optional) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。
  • 语言 (str, 可选) — 转录文本的语言。对应的语言ID标记会附加到序列的开头,用于多语言语音识别和语音翻译任务,例如对于西班牙语,标记 "<|es|>"会附加到序列的开头。这应仅用于多语言微调。
  • 任务 (str, 可选) — 任务标识符,用于在序列的开头附加(如果有)。这应该用于多语言微调,使用 "transcribe" 进行语音识别,使用 "translate" 进行语音翻译。
  • predict_timestamps (bool, 可选, 默认为 False) — 是否在序列开始时省略 <|notimestamps|> 标记。

构建一个Whisper分词器。

这个分词器继承自PreTrainedTokenizer,其中包含了一些主要方法。用户应参考超类以获取有关这些方法的更多信息。

set_prefix_tokens

< >

( 语言: str = None 任务: str = None 预测时间戳: bool = None )

参数

  • 语言 (str, 可选, 默认为 None) — 转录文本的语言。
  • 任务 (str, 可选, 默认为 None) — 任务标识符,用于在序列开头附加(如果有)。
  • predict_timestamps (bool, 可选, 默认为 None) — 是否在序列开始时省略 <|notimestamps|> 标记。

覆盖附加到标签序列开头的前缀标记。此方法可以单独使用来

根据需要更新前缀标记以进行微调。示例:

>>> # instantiate the tokenizer and set the prefix token to Spanish
>>> tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny", language="spanish")
>>> # now switch the prefix token from Spanish to French
>>> tokenizer.set_prefix_tokens(language="french")

build_inputs_with_special_tokens

< >

( token_ids_0 token_ids_1 = 无 )

通过附加eos_token_id从序列构建模型输入。

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 是否已经为模型格式化了包含特殊标记的标记列表。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 第一个标记化的序列.
  • token_ids_1 (List[int], optional) — 第二个标记化序列。

返回

List[int]

令牌类型ID。

创建与传递的序列相对应的令牌类型ID。什么是令牌类型ID?

如果模型有特殊的构建方式,应该在子类中重写。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

batch_decode

< >

( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) List[str]

参数

  • sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, 可选, 默认为 False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs (额外的关键字参数,可选) — 将被传递给底层模型的特定解码方法。

返回

List[str]

解码后的句子列表。

通过调用decode将token id的列表列表转换为字符串列表。

解码

< >

( token_ids skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None output_offsets: bool = False time_precision: float = 0.02 decode_with_timestamps: bool = False normalize: bool = False basic_normalize: bool = False remove_diacritics: bool = False **kwargs ) str

参数

  • token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化的输入ID列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, 可选, 默认为 False) — 是否在解码过程中移除特殊标记。如果存在,将移除之前的标记(预提示)。
  • clean_up_tokenization_spaces (bool, 可选) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces(在tokenizer_config中可用)。
  • output_offsets (bool, 可选, 默认为 False) — 是否输出标记的偏移量。只有在模型预测了时间戳时才应设置此选项。如果有之前的标记(预提示)需要解码,它们只有在包含时间戳标记时才会出现在解码的文本中。
  • time_precision (float, optional, 默认为 0.02) — 从标记转换为时间的时间比率。
  • decode_with_timestamps (bool, 可选, 默认为 False) — 是否在解码时包含原始文本中的时间戳。
  • normalize (bool, 可选, 默认为 False) — 是否对解码后的文本应用英文文本规范化器。仅当目标文本为英文时适用。否则,应应用基本文本规范化器。
  • basic_normalize (bool, 可选, 默认为 False) — 是否对解码后的文本应用基本文本规范化器。适用于多语言目标文本。
  • remove_diacritics (bool, 可选, 默认为 False) — 是否在应用基本文本规范化时去除变音符号。去除变音符号可能会破坏解码文本中的信息,因此应谨慎使用。
  • kwargs (额外的关键字参数,可选) — 将被传递给底层模型的特定解码方法。

返回

str

解码后的句子。

使用分词器和词汇表将字符串中的ID序列转换为文本,可选择移除特殊标记并清理分词空格。

类似于执行 self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))

basic_normalize

< >

( text remove_diacritics = 假 )

使用BasicTextNormalizer类对给定字符串进行规范化,该类对多语言文本执行常见的转换。

normalize

< >

( 文本 )

使用EnglishTextNormalizer类对给定的字符串进行规范化,该类对英文文本执行常见的转换。

WhisperTokenizerFast

transformers.WhisperTokenizerFast

< >

( vocab_file = None merges_file = None normalizer_file = None tokenizer_file = None unk_token = '<|endoftext|>' bos_token = '<|endoftext|>' eos_token = '<|endoftext|>' add_prefix_space = False language = None task = None predict_timestamps = False **kwargs )

参数

  • vocab_file (str, optional) — 词汇表文件的路径。
  • merges_file (str, optional) — 合并文件的路径。
  • normalizer_file (str, optional) — normalizer_file 文件的路径。
  • tokenizer_file (str, 可选) — 指向tokenizers文件的路径(通常具有.json扩展名),该文件包含加载分词器所需的所有内容。
  • unk_token (str, optional, defaults to "<|endoftext|>") — 未知的标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • bos_token (str, optional, defaults to "<|endoftext|>") — 序列开始的标记。在生成时,decoder_start_token_id用于将第一个标记设置为 "<|startoftranscript|>".
  • eos_token (str, 可选, 默认为 "<|endoftext|>") — 序列结束标记。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(Whisper 分词器通过前面的空格检测词的开头)。
  • 语言 (str, 可选) — 转录文本的语言。对应的语言ID标记会附加到序列的开头,用于多语言语音识别和语音翻译任务,例如对于西班牙语,标记 "<|es|>"会附加到序列的开头。这应仅用于多语言微调。
  • 任务 (str, 可选) — 任务标识符,用于在序列的开头附加(如果有)。这应该用于多语言微调,其中"transcribe"用于语音识别,"translate"用于语音翻译。
  • predict_timestamps (bool, 可选, 默认为 False) — 是否在序列开始时省略 <|notimestamps|> 标记。

构建一个“快速”的Whisper分词器(由HuggingFace的tokenizers库支持)。

这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。

set_prefix_tokens

< >

( 语言: str = None 任务: str = None 预测时间戳: bool = None )

参数

  • 语言 (str, 可选, 默认为 None) — 转录文本的语言。
  • 任务 (str, 可选, 默认为 None) — 任务标识符,用于在序列的开头附加(如果有的话)。
  • predict_timestamps (bool, 可选, 默认为 None) — 是否在序列开始时省略 <|notimestamps|> 标记。

覆盖附加到标签序列开头的前缀标记。此方法可以单独使用来

根据需要更新前缀标记以进行微调。示例:

>>> # instantiate the tokenizer and set the prefix token to Spanish
>>> tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny", language="spanish")
>>> # now switch the prefix token from Spanish to French
>>> tokenizer.set_prefix_tokens(language="french")

build_inputs_with_special_tokens

< >

( token_ids_0 token_ids_1 = 无 )

通过附加eos_token_id从序列构建模型输入。

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 令牌列表是否已经用模型的特殊令牌格式化。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 第一个标记化的序列.
  • token_ids_1 (List[int], optional) — 第二个标记化序列.

返回

List[int]

令牌类型ID。

创建与传递的序列相对应的令牌类型ID。什么是令牌类型ID?

如果模型有特殊的构建方式,应该在子类中重写。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

batch_decode

< >

( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) List[str]

参数

  • sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, 可选) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs (额外的关键字参数, 可选) — 将被传递给底层模型的特定解码方法.

返回

List[str]

解码后的句子列表。

通过调用decode将token id的列表列表转换为字符串列表。

解码

< >

( token_ids skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None output_offsets: bool = False time_precision: float = 0.02 decode_with_timestamps: bool = False normalize: bool = False basic_normalize: bool = False remove_diacritics: bool = False **kwargs ) str

参数

  • token_ids (Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, 默认为 False) — 是否在解码过程中移除特殊标记。如果存在,将移除之前的标记(预提示)。
  • clean_up_tokenization_spaces (bool, 可选) — 是否清理分词后的空格。如果为None,将默认为 self.clean_up_tokenization_spaces(在tokenizer_config中可用)。
  • output_offsets (bool, 可选, 默认为 False) — 是否输出标记的偏移量。只有在模型预测了时间戳时才应设置此选项。如果有之前的标记(预提示)需要解码,它们只有在包含时间戳标记时才会出现在解码后的文本中。
  • time_precision (float, optional, 默认为 0.02) — 从令牌转换为时间的时间比率。
  • decode_with_timestamps (bool, 可选, 默认为 False) — 是否在解码时包含原始文本中的时间戳。
  • normalize (bool, 可选, 默认为 False) — 是否对解码后的文本应用英文文本规范化器。仅当目标文本为英文时适用。否则,应应用基本文本规范化器。
  • basic_normalize (bool, 可选, 默认为 False) — 是否对解码后的文本应用基本文本规范化。适用于多语言目标文本。
  • remove_diacritics (bool, 可选, 默认为 False) — 是否在应用基本文本规范化时去除变音符号。去除变音符号可能会破坏解码文本中的信息,因此应谨慎使用。
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

str

解码后的句子。

使用分词器和词汇表将字符串中的ID序列转换为文本,可选择移除特殊标记并清理分词空格。

类似于执行 self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))

basic_normalize

< >

( text remove_diacritics = 假 )

使用BasicTextNormalizer类对给定字符串进行规范化,该类对多语言文本执行常见的转换。

normalize

< >

( 文本 )

使用EnglishTextNormalizer类对给定的字符串进行规范化,该类对英文文本执行常见的转换。

WhisperFeatureExtractor

transformers.WhisperFeatureExtractor

< >

( feature_size = 80 sampling_rate = 16000 hop_length = 160 chunk_length = 30 n_fft = 400 padding_value = 0.0 return_attention_mask = False **kwargs )

参数

  • feature_size (int, optional, defaults to 80) — 提取特征的特征维度。
  • sampling_rate (int, optional, defaults to 16000) — 音频文件应被数字化的采样率,以赫兹(Hz)表示。
  • hop_length (int, optional, defaults to 160) — 用于获取梅尔频率系数的STFT的重叠窗口的长度。
  • chunk_length (int, 可选, 默认为 30) — 用于修剪和填充较长或较短音频序列的sampling_rate样本的最大块数。
  • n_fft (int, optional, 默认为 400) — 傅里叶变换的大小.
  • padding_value (float, optional, defaults to 0.0) — 用于填充音频的填充值。应该对应于静音部分。

构建一个Whisper特征提取器。

此特征提取器继承自SequenceFeatureExtractor,其中包含 大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

该类使用自定义的numpy实现从原始语音中提取梅尔滤波器组特征,该实现应与pytorch的torch.stft等效。

__call__

< >

( raw_speech: typing.Union[numpy.ndarray, typing.List[float], typing.List[numpy.ndarray], typing.List[typing.List[float]]] truncation: bool = True pad_to_multiple_of: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_attention_mask: typing.Optional[bool] = None padding: typing.Optional[str] = 'max_length' max_length: typing.Optional[int] = None sampling_rate: typing.Optional[int] = None do_normalize: typing.Optional[bool] = None device: typing.Optional[str] = 'cpu' return_token_timestamps: typing.Optional[bool] = None **kwargs )

参数

  • raw_speech (np.ndarray, List[float], List[np.ndarray], List[List[float]]) — 要填充的序列或序列批次。每个序列可以是numpy数组、浮点值列表、numpy数组列表或浮点值列表的列表。必须是单声道音频,而不是立体声,即每个时间步长只有一个浮点数。
  • 截断 (bool, 可选, 默认为 True) — 激活截断功能,将超过 max_length 的输入序列截断至 max_length.
  • pad_to_multiple_of (int, optional, defaults to None) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用,或者对于TPUs来说,序列长度为128的倍数是有益的。

  • return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractor’s default.

    什么是注意力掩码?

    对于Whisper模型,attention_mask应始终在批量推理时传递,以避免细微的错误。

  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • sampling_rate (int, optional) — raw_speech 输入被采样的采样率。强烈建议在前向调用时传递 sampling_rate 以防止静默错误并允许自动语音识别 管道。
  • padding_value (float, optional, defaults to 0.0) — 用于填充填充值/向量的值。
  • do_normalize (bool, 可选, 默认为 False) — 是否对输入进行零均值单位方差归一化。归一化可以显著提高模型的性能。
  • device (str, optional, defaults to 'cpu') — 指定用于计算音频信号的log-mel频谱图的设备,在 _torch_extract_fbank_features 方法中使用。(例如,“cpu”,“cuda”)
  • return_token_timestamps (bool, optional, defaults to None) — 是否返回输入 raw_speech 的帧数。 这些 num_frames 可以被模型用来计算单词级别的时间戳。

用于特征化并为一个或多个序列准备模型的主要方法。如果可用,实现使用PyTorch进行STFT计算,否则使用较慢的基于NumPy的方法。

WhisperProcessor

transformers.WhisperProcessor

< >

( feature_extractor tokenizer )

参数

  • feature_extractor (WhisperFeatureExtractor) — 一个 WhisperFeatureExtractor 的实例。特征提取器是一个必需的输入。
  • tokenizer (WhisperTokenizer) — 一个 WhisperTokenizer 的实例。tokenizer 是一个必需的输入。

构建一个Whisper处理器,它将Whisper特征提取器和Whisper分词器封装到一个单一的处理器中。

WhisperProcessor 提供了 WhisperFeatureExtractorWhisperTokenizer 的所有功能。更多信息请参见 call()decode()

__call__

< >

( *args **kwargs )

audio参数转发给WhisperFeatureExtractor的call(),并将text参数转发给call()。请参考上述两个方法的文档字符串以获取更多信息。

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs )

参数

  • pretrained_model_name_or_path (stros.PathLike) — 这可以是以下之一:
    • 一个字符串,表示托管在 huggingface.co 上的模型仓库中的预训练特征提取器的 模型 id
    • 一个路径,指向使用 save_pretrained() 方法保存的特征提取器文件的 目录,例如 ./my_model_directory/
    • 一个路径或 URL,指向保存的特征提取器 JSON 文件,例如 ./my_model_directory/preprocessor_config.json
  • **kwargs — 传递给from_pretrained()~tokenization_utils_base.PreTrainedTokenizer.from_pretrained的额外关键字参数.

实例化一个与预训练模型关联的处理器。

这个类方法只是简单地调用了特征提取器 from_pretrained(),图像处理器 ImageProcessingMixin 和分词器 ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained 方法。请参考上述方法的文档字符串以获取更多信息。

save_pretrained

< >

( save_directory push_to_hub: bool = False **kwargs )

参数

  • save_directory (str or os.PathLike) — 将保存特征提取器 JSON 文件和分词器文件的目录(如果目录不存在,将会创建)。
  • push_to_hub (bool, 可选, 默认为 False) — 是否在保存后将你的模型推送到 Hugging Face 模型中心。你可以通过 repo_id 指定你想要推送到的仓库(默认情况下会使用你命名空间中的 save_directory 名称)。
  • kwargs (Dict[str, Any], 可选) — 传递给 push_to_hub() 方法的额外关键字参数。

保存此处理器(特征提取器、分词器等)的属性到指定目录,以便可以使用from_pretrained()方法重新加载。

这个类方法只是调用了 save_pretrained()save_pretrained()。请参考上述方法的文档字符串以获取更多信息。

batch_decode

< >

( *args **kwargs )

此方法将其所有参数转发给WhisperTokenizer的batch_decode()。请参考该方法的文档字符串以获取更多信息。

解码

< >

( *args **kwargs )

此方法将其所有参数转发给WhisperTokenizer的decode()。请参考该方法的文档字符串以获取更多信息。

Pytorch
Hide Pytorch content

WhisperModel

transformers.WhisperModel

< >

( config: WhisperConfig )

参数

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

裸的Whisper模型输出原始的隐藏状态,没有任何特定的头部。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_features: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Union[transformers.cache_utils.EncoderDecoderCache, typing.Tuple[torch.FloatTensor], NoneType] = None decoder_inputs_embeds: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_position_ids: typing.Optional[typing.Tuple[torch.LongTensor]] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.Seq2SeqModelOutputtuple(torch.FloatTensor)

参数

  • input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing SpecAugment data augmentation on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用WhisperTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    Whisper 使用 decoder_start_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择仅输入最后一个 decoder_input_ids(参见 past_key_values)。

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读 modeling_whisper._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见BART论文中的图1。

  • head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽交叉注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。
  • past_key_values (EncoderDecoderCache or tuple(tuple(torch.FloatTensor)), optional) — Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and in the cross-attention blocks (2). The past_key_values are returned when use_cache=True is passed or when config.use_cache=True

    允许两种格式:

    • An EncoderDecoderCache instance;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递decoder_input_ids。如果使用了past_key_values,则可以选择仅输入最后一个decoder_inputs_embeds(参见past_key_values)。如果您希望对如何将decoder_input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。

返回

transformers.modeling_outputs.Seq2SeqModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(WhisperConfig)和输入。

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

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

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可选, 当传递了 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

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

    解码器每层输出的隐藏状态加上可选的初始嵌入输出。

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

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

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

    解码器交叉注意力层的注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。

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

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

    编码器每层输出的隐藏状态加上可选的初始嵌入输出。

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

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

WhisperModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import torch
>>> from transformers import AutoFeatureExtractor, WhisperModel
>>> from datasets import load_dataset

>>> model = WhisperModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 512]

_mask_input_features

< >

( input_features: FloatTensor attention_mask: typing.Optional[torch.LongTensor] = None )

根据SpecAugment,沿时间轴和/或特征轴提取的特征进行掩码处理。

WhisperForConditionalGeneration

transformers.WhisperForConditionalGeneration

< >

( config: WhisperConfig )

参数

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

带有语言建模头的Whisper模型。可用于自动语音识别。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_features: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Union[transformers.cache_utils.EncoderDecoderCache, typing.Tuple[torch.FloatTensor], NoneType] = None decoder_inputs_embeds: typing.Optional[typing.Tuple[torch.FloatTensor]] = None decoder_position_ids: typing.Optional[typing.Tuple[torch.LongTensor]] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing SpecAugment data augmentation on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用WhisperTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    Whisper 使用 decoder_start_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择仅输入最后一个 decoder_input_ids(参见 past_key_values)。

  • decoder_attention_mask (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读 modeling_whisper._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见BART论文中的图1。

  • head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽交叉注意力模块中选定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (EncoderDecoderCache or tuple(tuple(torch.FloatTensor)), optional) — Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and in the cross-attention blocks (2). The past_key_values are returned when use_cache=True is passed or when config.use_cache=True

    允许两种格式:

    • An EncoderDecoderCache instance;
    • Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递decoder_input_ids。如果使用了past_key_values,则可以选择仅输入最后一个decoder_inputs_embeds(参见past_key_values)。如果您希望对如何将decoder_input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算语言建模损失的标签。索引应在 [0, ..., config.vocab_size] 或 -100(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。sequence_length 应小于或等于 config.max_target_positions.

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(WhisperConfig)和输入。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失。

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

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

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

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

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

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

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

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

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

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

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

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

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

WhisperForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features

>>> generated_ids = model.generate(inputs=input_features)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

生成

< >

( input_features: typing.Optional[torch.Tensor] = None generation_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = None logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None prefix_allowed_tokens_fn: typing.Optional[typing.Callable[[int, torch.Tensor], typing.List[int]]] = None synced_gpus: bool = False return_timestamps: typing.Optional[bool] = None task: typing.Optional[str] = None language: typing.Union[str, typing.List[str], NoneType] = None is_multilingual: typing.Optional[bool] = None prompt_ids: typing.Optional[torch.Tensor] = None prompt_condition_type: typing.Optional[str] = None condition_on_prev_tokens: typing.Optional[bool] = None temperature: typing.Union[float, typing.Tuple[float, ...], NoneType] = None compression_ratio_threshold: typing.Optional[float] = None logprob_threshold: typing.Optional[float] = None no_speech_threshold: typing.Optional[float] = None num_segment_frames: typing.Optional[int] = None attention_mask: typing.Optional[torch.Tensor] = None time_precision: float = 0.02 time_precision_features: float = 0.01 return_token_timestamps: typing.Optional[bool] = None return_segments: bool = False return_dict_in_generate: typing.Optional[bool] = None **kwargs ) ModelOutputtorch.LongTensorDict[str, Any]

参数

  • input_features (torch.Tensor of shape (batch_size, feature_size, sequence_length), optional) — Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call() for details.
  • generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which had the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation.
  • logits_processor (LogitsProcessorList, 可选) — 自定义的logits处理器,用于补充从参数和生成配置中构建的默认logits处理器。如果传递了一个已经通过参数或生成配置创建的logit处理器,则会抛出错误。此功能面向高级用户。
  • stopping_criteria (StoppingCriteriaList, 可选) — 自定义停止标准,补充了由参数和生成配置构建的默认停止标准。如果传递了一个已经由参数或生成配置创建的停止标准,则会抛出错误。此功能面向高级用户。
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], optional) — If provided, this function constraints the beam search to allowed tokens only at each step. If not provided no constraint is applied. This function takes 2 arguments: the batch ID batch_id and input_ids. It has to return a list with the allowed tokens for the next generation step conditioned on the batch ID batch_id and the previously generated tokens inputs_ids. This argument is useful for constrained generation conditioned on the prefix, as described in Autoregressive Entity Retrieval.
  • synced_gpus (bool, 可选, 默认为 False) — 是否继续运行while循环直到达到max_length(需要避免与 FullyShardedDataParallel 和 DeepSpeed ZeRO Stage 3 发生死锁)。
  • return_timestamps (bool, optional) — 是否返回带有文本的时间戳。这将启用 WhisperTimestampsLogitsProcessor.
  • 任务 (str, 可选) — 用于生成的任务,可以是“翻译”或“转录”。model.config.forced_decoder_ids 将相应更新。
  • 语言 (strstr 列表, 可选) — 用于生成的语言标记,可以是 <|en|>, enenglish 的形式。对于 批量生成,可以传递语言标记的列表。你可以在 model.generation_config.lang_to_id 字典中找到所有可能的语言 标记。
  • is_multilingual (bool, optional) — 模型是否为多语言的。
  • prompt_ids (torch.Tensor, optional) — 通过将文本传递给get_prompt_ids()创建的令牌ID的Rank-1张量,该张量作为提示提供给每个块。这可以用于提供或“提示工程”一个转录的上下文,例如自定义词汇或专有名词,以使其更有可能正确预测这些单词。它不能与decoder_start_token_id一起使用,因为它会覆盖此值。
  • prompt_condition_type (str, 可选) — 仅适用于长文本转录。prompt_ids的条件类型。'first-segment' 表示只有第一个片段受 prompt_ids 影响。'all-segments' 表示每个片段都受 prompt_ids 影响。确保为 'all-segments' 启用 condition_on_prev_tokens。 默认为 'first-segment'。对于短文本转录,只有 'first-segment' 是可能的。
  • condition_on_prev_tokens (bool, 可选) — 仅适用于长文本转录。是否将每个片段基于前一个片段进行条件化。 如Whisper论文所示,这有助于提高性能。
  • temperature (floatfloat 列表, 可选) — 用于生成的温度。传递一个单一的 float 值和 do_sample=True 会激活 使用采样的生成。对于长文本转录,可以通过传递 一个浮点值列表(如 (0.0, 0.2, 0.4, 0.6, 0.8, 1.0))来激活温度回退。如 the Whisper paper 所示,这可以帮助提高 性能。
  • compression_ratio_threshold (float, optional) — Only relevant for long-form transcription. If defined, the zlib compression rate of each segment will be computed. If the compression rate of a segment is higher than compression_ratio_threshold, temperature fallback is activated: the generated segment is discarded and the generation is repeated using a higher temperature. The intuition behind this feature is that segments with very high compression rates suffer from a lot of repetition. The unwanted repetition can be reduced by injecting more randomness by increasing the temperature. If compression_ratio_threshold is defined make sure that temperature is a list of values. A common value for compression_ratio_threshold is 1.35. As shown in the the Whisper paper, this can help to improve performance.
  • logprob_threshold (float, optional) — Only relevant for long-form transcription. If defined, the average log-probability of each segment will be computed. If the log-probability of a given segment is lower than logprob_threshold, temperature fallback is activated: the generated segment is discarded and the generation is repeated using a higher temperature. The intuition behind this feature is that segments of low log-probability can be improved by injecting more randomness by increasing the temperature. If logprob_threshold is defined make sure that temperature is a list of values. A common value for logprob_threshold is -1.0. As shown in the the Whisper paper, this can help to improve performance.
  • no_speech_threshold (float, 可选) — 仅适用于长格式转录。如果定义,将使用“无语音”标记与logprob_threshold结合 来确定一个片段是否仅包含静音。在这种情况下,该片段的转录 将被跳过。 如Whisper论文所示,这有助于提高 性能。
  • num_segment_frames (int, 可选) — 单个段由多少帧组成。如果未定义,num_segment_frames 默认为模型的步幅乘以最大输入长度。
  • attention_mask (torch.Tensor, 可选) — attention_mask 在使用批量大小大于1进行长文本转录时需要传递。
  • time_precision (int, optional, 默认为 0.02) — 输出标记的持续时间,以秒为单位。例如,0.02 表示生成的标记平均占 20 毫秒。
  • time_precision_features (int, optional, defaults to 0.01) — 特征帧表示的持续时间,单位为秒。
  • return_token_timestamps (bool, 可选) — 是否返回带有文本的令牌级时间戳。这可以与return_timestamps选项一起使用,也可以单独使用。要获取单词级时间戳,请使用分词器将令牌分组为单词。
  • return_segments (bool, 可选, 默认为 False) — 是否额外返回所有片段的列表。请注意,此选项只能在执行长格式转录时启用。
  • return_dict_in_generate (bool, 可选, 默认为 False) — 是否返回一个 ModelOutput 而不是仅仅返回生成的标记。 请注意,在进行长文本转录时,return_dict_in_generate 只能在 return_segments 设置为 True 时启用。在这种情况下,每个片段的生成输出会被添加到每个片段中。
  • kwargs (Dict[str, Any], 可选) — generate_config 的临时参数化和/或额外的模型特定 kwargs,这些参数将被转发到模型的 forward 函数。如果模型是编码器-解码器模型,编码器特定的 kwargs 不应加前缀,而解码器特定的 kwargs 应加上 decoder_ 前缀。

返回

ModelOutputtorch.LongTensorDict[str, Any]

一个 ModelOutput(如果 return_dict_in_generate=True 或当 config.return_dict_in_generate=True)或一个 torch.FloatTensor 或当 return_segments=True 时的片段字典。

如果传入的输入大于 30 秒 / 大于 3000 个梅尔输入特征并且 return_segments=True,则返回一个生成的序列 ID 字典,称为 sequences 和每个生成片段的列表。

否则,如果传入的输入小于等于 30 秒 / 大于等于 3000 个梅尔输入特征,可能的 ModelOutput 类型为:

否则,只返回生成的输出序列 ID。

将log-mel输入特征转录或翻译为自回归生成的标记ID序列。

大多数生成控制参数都在generation_config中设置,如果没有传递,将设置为模型的默认生成配置。您可以通过将相应的参数传递给generate()来覆盖任何generation_config,例如.generate(inputs, num_beams=4, do_sample=True)

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

示例:

  • 长文本转录: 要转录或翻译超过30秒的音频,处理音频文件时不进行截断,并一次性传递所有mel特征以生成。
>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset, Audio

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
>>> model.cuda()
>>> # load audios > 30 seconds
>>> ds = load_dataset("distil-whisper/meanwhile", "default")["test"]
>>> # resample to 16kHz
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> # take first 8 audios and retrieve array
>>> audio = ds[:8]["audio"]
>>> audio = [x["array"] for x in audio]

>>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio
>>> inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000)
>>> inputs = inputs.to("cuda", torch.float32)

>>> # transcribe audio to ids
>>> generated_ids = model.generate(**inputs)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> transcription[0]
" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
  • 短格式转录:如果传递的mel输入特征小于30秒,整个音频将通过一次调用generate进行转录。
>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features

>>> generated_ids = model.generate(inputs=input_features)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

WhisperForCausalLM

transformers.WhisperForCausalLM

< >

( config )

参数

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

带有语言建模头的Whisper解码器(线性层,其权重与输入嵌入绑定)。

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[torch.FloatTensor]] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.CausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。默认情况下,如果您提供了填充,它将被忽略。可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入ID?
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 用于避免在填充标记索引上执行注意力机制的掩码。掩码值在 [0, 1] 中选择:
  • encoder_outputs (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。
  • head_mask (torch.Tensor 形状为 (decoder_layers, decoder_attention_heads), 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽交叉注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding. If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length).
  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算掩码语言建模损失的标签。索引应在 [0, ..., config.vocab_size] 或 -100 之间(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略 (掩码),损失仅针对标签在 [0, ..., config.vocab_size] 之间的标记计算。
  • use_cache (bool, optional) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码 (参见 past_key_values)。
    • 1 表示 未屏蔽 的标记,
    • 0 表示 屏蔽 的标记。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。

返回

transformers.modeling_outputs.CausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(WhisperConfig)和输入的各种元素。

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

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

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

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

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

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

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

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

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 由长度为 config.n_layerstorch.FloatTensor 元组组成的元组,每个元组包含自注意力和交叉注意力层的缓存键、值状态,如果模型用于编码器-解码器设置。仅在 config.is_decoder = True 时相关。

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

示例:

>>> from transformers import WhisperForCausalLM, WhisperForConditionalGeneration, WhisperProcessor
>>> import torch
>>> from datasets import load_dataset

>>> processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")

>>> assistant_model = WhisperForCausalLM.from_pretrained("distil-whisper/distil-large-v2")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> sample = ds[0]["audio"]
>>> input_features = processor(
...     sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt"
... ).input_features

>>> predicted_ids = model.generate(input_features, assistant_model=assistant_model)

>>> # decode token ids to text
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.'

WhisperForAudioClassification

transformers.WhisperForAudioClassification

< >

( config )

参数

  • input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

Whisper 编码器模型,顶部带有序列分类头(在池化输出上的线性层),用于诸如 SUPERB 关键词检测等任务。

前进

< >

( input_features: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_features (torch.FloatTensor of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the mel features, padding and conversion into a tensor of type torch.FloatTensor. See call()
  • head_mask (torch.Tensor of shape (encoder_layers, encoder_attention_heads), optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层输出的隐藏状态序列。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.SequenceClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(WhisperConfig)和输入。

  • loss(形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回)— 分类(或回归,如果 config.num_labels==1)损失。

  • logits(形状为 (batch_size, config.num_labels)torch.FloatTensor)— 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

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

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

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

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

WhisperForAudioClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import torch
>>> from transformers import AutoFeatureExtractor, WhisperForAudioClassification
>>> from datasets import load_dataset

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
>>> model = WhisperForAudioClassification.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")

>>> ds = load_dataset("google/fleurs", "all", split="validation", streaming=True)
>>> sample = next(iter(ds))

>>> inputs = feature_extractor(
...     sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="pt"
... )
>>> input_features = inputs.input_features

>>> with torch.no_grad():
...     logits = model(input_features).logits

>>> predicted_class_ids = torch.argmax(logits).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]
>>> predicted_label
'Afrikaans'
TensorFlow
Hide TensorFlow content

TFWhisperModel

transformers.TFWhisperModel

< >

( config: WhisperConfig **kwargs )

参数

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

裸的Whisper模型输出原始的隐藏状态,没有任何特定的头部。 该模型继承自TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

调用

< >

( input_features: TFModelInputType | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None decoder_position_ids: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None decoder_head_mask: np.ndarray | tf.Tensor | None = None cross_attn_head_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None decoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFSeq2SeqModelOutput or tuple(tf.Tensor)

参数

  • input_features (tf.Tensor of shape (batch_size, feature_size, sequence_length)) — Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of type tf.Tensor. See call()
  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用SpeechToTextTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    SpeechToText 使用 eos_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

  • decoder_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读 modeling_whisper._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • head_mask (tf.Tensor 形状为 (encoder_layers, encoder_attention_heads), 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在 [0, 1] 中选择的掩码值:
    • 1 表示头 未被屏蔽,
    • 0 表示头 被屏蔽.
  • decoder_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • cross_attn_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于屏蔽交叉注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(tf.Tensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(tf.Tensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(tf.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

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

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 decoder_input_ids。如果使用了 past_key_values,则可以选择仅输入最后一个 decoder_inputs_embeds(参见 past_key_values)。如果您希望对如何将 decoder_input_ids 索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_tf_outputs.TFSeq2SeqModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或一个 tf.Tensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(WhisperConfig)和输入的各种元素。

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

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

  • past_key_values (List[tf.Tensor]可选,当传递了 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstf.Tensor 列表,每个张量的形状为 (2, batch_size, num_heads, sequence_length, embed_size_per_head)

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

  • decoder_hidden_states (tuple(tf.Tensor)可选,当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)tf.Tensor 元组(一个用于嵌入的输出,一个用于每层的输出)。

    解码器每层输出的隐藏状态加上初始嵌入输出。

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

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

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

    解码器的交叉注意力层的注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (tf.Tensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(tf.Tensor)可选,当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)tf.Tensor 元组(一个用于嵌入的输出,一个用于每层的输出)。

    编码器每层输出的隐藏状态加上初始嵌入输出。

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

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

TFWhisperModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import tensorflow as tf
>>> from transformers import TFWhisperModel, AutoFeatureExtractor
>>> from datasets import load_dataset

>>> model = TFWhisperModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="tf")
>>> input_features = inputs.input_features
>>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 512]

TFWhisperForConditionalGeneration

transformers.TFWhisperForConditionalGeneration

< >

( config: WhisperConfig **kwargs )

参数

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

带有语言建模头的Whisper模型。可用于自动语音识别。 该模型继承自TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。

该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。

调用

< >

( input_features: TFModelInputType | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None decoder_position_ids: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None decoder_head_mask: np.ndarray | tf.Tensor | None = None cross_attn_head_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None decoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]] = None labels: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

参数

  • input_features (tf.Tensor of shape (batch_size, feature_size, sequence_length)) — Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the AutoFeatureExtractor should be used for extracting the fbank features, padding and conversion into a tensor of type tf.Tensor. See call()
  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用SpeechToTextTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    SpeechToText 使用 eos_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

  • decoder_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该阅读 modeling_whisper._prepare_decoder_attention_mask 并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • head_mask (tf.Tensor 形状为 (encoder_layers, encoder_attention_heads), 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在 [0, 1] 中选择的掩码值:
    • 1 表示头 未被屏蔽,
    • 0 表示头 被屏蔽.
  • decoder_head_mask (tf.Tensor of shape (decoder_layers, decoder_attention_heads), optional) — 用于在解码器中取消选择注意力模块的头部。在 [0, 1] 中选择的掩码值:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • cross_attn_head_mask (tf.Tensor 形状为 (decoder_layers, decoder_attention_heads), 可选) — 用于屏蔽交叉注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(tf.Tensor), 可选的) — 元组由 (last_hidden_state, 可选的: hidden_states, 可选的: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选的) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(tf.Tensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(tf.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head).

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

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 decoder_input_ids。如果使用了 past_key_values,则可以选择仅输入最后一个 decoder_inputs_embeds(参见 past_key_values)。如果您希望对如何将 decoder_input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (tf.Tensor 形状为 (batch_size, sequence_length), 可选) — 用于计算语言建模损失的标签。索引应在 [0, ..., config.vocab_size] 范围内 或为 -100(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记计算。

返回

transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (WhisperConfig) 和输入。

  • loss (tf.Tensor 形状为 (n,), 可选, 其中 n 是非掩码标签的数量,当提供 labels 时返回) — 语言建模损失。

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

  • past_key_values (List[tf.Tensor], 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstf.Tensor 列表,每个张量的形状为 (2, batch_size, num_heads, sequence_length, embed_size_per_head))。

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

  • decoder_hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

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

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

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

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

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

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

TFWhisperForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> import tensorflow as tf
>>> from transformers import AutoProcessor, TFWhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="tf")
>>> input_features = inputs.input_features

>>> generated_ids = model.generate(input_features=input_features)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
JAX
Hide JAX content

FlaxWhisperModel

transformers.FlaxWhisperModel

< >

( config: WhisperConfig input_shape: typing.Tuple[int] = None seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

参数

  • config (WhisperConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16().

裸的Whisper模型转换器输出原始隐藏状态,没有任何特定的头部。 该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。该模型也是一个Flax Linen flax.nn.Module子类。将其用作常规的Flax模块,并参考Flax文档以了解与一般使用和行为相关的所有事项。 最后,该模型支持固有的JAX特性,例如:

__call__

< >

( input_features: 数组 decoder_input_ids: 数组 attention_mask: 可选的[jax.Array] = None decoder_attention_mask: 可选的[jax.Array] = None position_ids: 可选的[jax.Array] = None decoder_position_ids: 可选的[jax.Array] = None output_attentions: 可选的[bool] = None output_hidden_states: 可选的[bool] = None return_dict: 可选的[bool] = None train: bool = False params: 字典 = None dropout_rng: = None ) transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutputtuple(torch.FloatTensor)

参数

  • input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call()
  • attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper 不支持对 input_features 进行掩码处理,此参数为兼容性保留,但 未被使用。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation.
  • decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。如果您想更改填充行为,应根据您的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。
  • position_ids (numpy.ndarray 形状为 (batch_size, sequence_length), 可选) — Whisper 在编码器中不使用 position_ids,因为 input_features 的大小始终相同且不使用掩码,但保留此参数以保持兼容性。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围为 [0, config.max_position_embeddings - 1].
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(WhisperConfig)和输入。

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

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

  • past_key_values (tuple(tuple(jnp.ndarray)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

  • decoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入输出,一个用于每层的输出)。

    解码器每层输出的隐藏状态加上初始嵌入输出。

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

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

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

    解码器交叉注意力层的注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入输出,一个用于每层的输出)。

    编码器每层输出的隐藏状态加上初始嵌入输出。

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

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

FlaxWhisperPreTrainedModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxWhisperModel

>>> tokenizer = AutoTokenizer.from_pretrained("openai/whisper-tiny")
>>> model = FlaxWhisperModel.from_pretrained("openai/whisper-tiny")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state

FlaxWhisperForConditionalGeneration

transformers.FlaxWhisperForConditionalGeneration

< >

( config: WhisperConfig input_shape: typing.Tuple[int] = None seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

参数

  • config (WhisperConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16().

带有语言建模头的Whisper模型。 该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。该模型也是一个Flax Linen flax.nn.Module子类。将其作为常规的Flax模块使用,并参考Flax文档以了解与一般使用和行为相关的所有事项。 最后,该模型支持固有的JAX特性,例如:

__call__

< >

( input_features: 数组 decoder_input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_attention_mask: 可选的[jax.Array] = 无 position_ids: 可选的[jax.Array] = 无 decoder_position_ids: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call()
  • attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper 不支持对 input_features 进行掩码处理,此参数为兼容性保留,但 未被使用。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation.
  • decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。如果您想更改填充行为,应根据需要进行修改。有关默认策略的更多信息,请参见论文中的图1。
  • position_ids (numpy.ndarray 形状为 (batch_size, sequence_length), 可选) — Whisper 在编码器中不使用 position_ids,因为 input_features 的大小始终相同且不使用掩码,但保留此参数以确保兼容性。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围在 [0, config.max_position_embeddings - 1] 之间。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个元组 torch.FloatTensor(如果传递了 return_dict=False 或当 config.return_dict=False 时)包含各种 元素,取决于配置(WhisperConfig)和输入。

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

  • past_key_valuestuple(tuple(jnp.ndarray))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回)— 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量和 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

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

  • decoder_hidden_statestuple(jnp.ndarray)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回)— 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentionstuple(jnp.ndarray)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回)— 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

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

  • cross_attentionstuple(jnp.ndarray)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回)— 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state(形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray可选)— 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_statestuple(jnp.ndarray)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回)— 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentionstuple(jnp.ndarray)可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回)— 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

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

FlaxWhisperPreTrainedModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

转录示例:

>>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", from_pt=True)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="np")
>>> input_features = inputs.input_features
>>> generated_ids = model.generate(input_ids=input_features)
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'

FlaxWhisperForAudioClassification

transformers.FlaxWhisperForAudioClassification

< >

( config: WhisperConfig input_shape: typing.Tuple[int] = None seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

参数

  • config (WhisperConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
  • dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) — The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and jax.numpy.bfloat16 (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given dtype. Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters. If you wish to change the dtype of the model parameters, see to_fp16() and to_bf16().

带有音频分类头的Whisper模型。 该模型继承自FlaxPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。该模型也是一个Flax Linen flax.nn.Module子类。将其作为常规的Flax模块使用,并参考Flax文档以了解与一般使用和行为相关的所有事项。 最后,该模型支持固有的JAX特性,例如:

__call__

< >

( input_features: 数组 attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 **kwargs ) transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_features (numpy.ndarray of shape (batch_size, feature_size, sequence_length)) — Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a .flac or .wav audio file into an array of type List[float] or a numpy.ndarray, e.g. via the soundfile library (pip install soundfile). To prepare the array into input_features, the WhisperFeatureExtractor should be used for extracting the features, padding and conversion into a tensor of type numpy.ndarray. See call()
  • attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) — Whisper 不支持对 input_features 进行掩码处理,此参数为兼容性保留,但 未被使用。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_input_ids (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using WhisperTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details. What are decoder input IDs? Whisper uses the decoder_start_token_id as the starting token for decoder_input_ids generation.
  • decoder_attention_mask (numpy.ndarray of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。如果您想更改填充行为,应根据您的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。
  • position_ids (numpy.ndarray 形状为 (batch_size, sequence_length), 可选) — Whisper 在编码器中不使用 position_ids,因为 input_features 的大小始终相同且不使用掩码,但保留此参数以保持兼容性。默认情况下,输入的对数梅尔频谱图中的静音部分会被忽略。
  • decoder_position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) — 每个解码器输入序列标记在位置嵌入中的位置索引。选择范围为 [0, config.max_position_embeddings - 1].
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxSequenceClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(WhisperConfig)和输入。

  • logits (jnp.ndarray 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

  • hidden_states (tuple(jnp.ndarray), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 jnp.ndarray 组成的元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 jnp.ndarray 组成的元组(每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

FlaxWhisperForAudioClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

转录示例:

>>> import jax.numpy as jnp
>>> from transformers import AutoFeatureExtractor, FlaxWhisperForAudioClassification
>>> from datasets import load_dataset

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
>>> model = FlaxWhisperForAudioClassification.from_pretrained(
...     "sanchit-gandhi/whisper-medium-fleurs-lang-id", from_pt=True
... )
>>> ds = load_dataset("google/fleurs", "all", split="validation", streaming=True, trust_remote_code=True)

>>> sample = next(iter(ds))

>>> inputs = feature_extractor(
...     sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="np"
... )
>>> input_features = inputs.input_features

>>> logits = model(input_features).logits

>>> predicted_class_ids = jnp.argmax(logits).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]
>>> predicted_label
'af_za'
< > Update on GitHub