# Whisper

[Whisper](https://huggingface.co/papers/2212.04356) 是一个在 680,000 小时带标签音频数据上预训练的编码器-解码器（序列到序列）Transformer。如此规模的预训练数据使其能够在英语及许多其他语言的音频任务上实现零样本性能。解码器使 Whisper 能够将编码器学习到的语音表示映射为有用的输出（例如文本），而无需额外的微调。Whisper 开箱即用。

您可以在 [Whisper](https://huggingface.co/collections/openai/whisper-release-6501bba2cf999715fd953013) 集合中找到所有原始的 Whisper 检查点。

> [!TIP]
> 点击右侧边栏中的 Whisper 模型，以查看更多将 Whisper 应用于不同音频任务的示例。
>
> 在 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 中设置 `use_kernels=True`，即可用 Hub 上的优化内核替换受支持的层。有关详细信息，请参阅 [加载内核](../kernel_doc/loading_kernels)。

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类自动将语音转录为文本。

```python
from transformers import pipeline

pipeline = pipeline(
    task="automatic-speech-recognition",
    model="openai/whisper-large-v3-turbo",
    device=0
)
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
```

```python
# pip install datasets
from datasets import load_dataset

from transformers import AutoProcessor, WhisperForConditionalGeneration

processor = AutoProcessor.from_pretrained(
    "openai/whisper-large-v3-turbo",
)
model = WhisperForConditionalGeneration.from_pretrained(
    "openai/whisper-large-v3-turbo",
    device_map="auto",
    attn_implementation="sdpa"
)

ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
audio_sample = ds[0]["audio"]

input_features = processor(
    audio_sample["array"],
    sampling_rate=audio_sample["sampling_rate"],
    return_tensors="pt"
).input_features
input_features = input_features.to(model.device, dtype=model.dtype)

predicted_ids = model.generate(input_features, cache_implementation="static")
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
transcription[0]
```

## 备注

- Whisper 在推理时依赖于自定义的 `generate`，请务必查看下方的文档。
- [WhisperProcessor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperProcessor) 可用于准备音频，并将预测的 id 解码回文本。

## WhisperConfig[[transformers.WhisperConfig]]

#### transformers.WhisperConfig[[transformers.WhisperConfig]]

```python
transformers.WhisperConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, vocab_size: int = 51865, num_mel_bins: int = 80, encoder_layers: int = 4, encoder_attention_heads: int = 6, decoder_layers: int = 4, decoder_attention_heads: int = 6, decoder_ffn_dim: int = 1536, encoder_ffn_dim: int = 1536, encoder_layerdrop: float | int = 0.0, decoder_layerdrop: float | int = 0.0, decoder_start_token_id: int = 50257, use_cache: bool = True, activation_function: str = 'gelu', d_model: int = 384, dropout: float | int = 0.0, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, init_std: float = 0.02, scale_embedding: bool = False, max_source_positions: int = 1500, max_target_positions: int = 448, pad_token_id: int | None = 50256, bos_token_id: int | None = 50256, eos_token_id: int | list[int] | None = 50256, suppress_tokens: list | None = None, begin_suppress_tokens: list[int] | tuple[int, ...] | None = (220, 50256), use_weighted_layer_sum: bool = False, classifier_proj_size: int = 256, apply_spec_augment: bool = False, mask_time_prob: float | int = 0.05, mask_time_length: int = 10, mask_time_min_masks: int = 2, mask_feature_prob: float | int = 0.0, mask_feature_length: int = 10, mask_feature_min_masks: int = 0, median_filter_width: int = 7, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/configuration_whisper.py#L50)

**参数：**

is_encoder_decoder (`bool`，*可选*，默认为 `True`)：模型是否用作编码器/解码器。

vocab_size (`int`，*可选*，默认值为 `51865`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

num_mel_bins (`int`，*可选*，默认为 `80`)：每个输入帧使用的 mel 特征数量。应与 `AutoFeatureExtractor` 类中使用的值相对应。

encoder_layers (`int`，*可选*，默认为 `4`)：Transformer 编码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

encoder_attention_heads (`int`，*可选*，默认为 `6`)：Transformer 编码器中每个注意力层的注意力头数量。

decoder_layers (`int`，*可选*，默认为 `4`)：Transformer 解码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

decoder_attention_heads (`int`，*可选*，默认为 `6`)：Transformer 解码器中每个注意力层的注意力头数量。

decoder_ffn_dim (`int`，*可选*，默认为 `1536`)：解码器中“中间”（通常称为前馈）层的维度。

encoder_ffn_dim (`int`, *可选*，默认为 `1536`)：编码器中“中间”（通常称为前馈）层的维度。

encoder_layerdrop (`Union[float, int]`，*可选*，默认为 `0.0`)：编码器的 LayerDrop 概率。有关更多详细信息，请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。

decoder_layerdrop (`Union[float, int]`，*可选*，默认值为 `0.0`)：解码器的 LayerDrop 概率。有关更多详细信息，请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。

decoder_start_token_id (`int`，*可选*，默认为 `50257`)：如果编码器-解码器模型以不同于 `bos` 的 token 开始解码，则该 token 的 id。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

activation_function (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

d_model (`int`，*可选*，默认为 `384`)：编码器层和池化层的大小。

dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：所有 dropout 层的比率。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

activation_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：全连接层内部激活值的 dropout 比率。

init_std (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

scale_embedding (`bool`，*可选*，默认为 `False`)：是否通过将嵌入除以 sqrt(d_model) 来对其进行缩放。

max_source_positions (`int`，*可选*，默认值为 1500)：该模型可能使用的 log-mel 滤波器组特征的最大序列长度。

max_target_positions (`int`, *可选*，默认为 448)：该模型可能使用的最大序列长度。通常建议将其设置为一个较大的值以防万一（例如 512、1024 或 2048）。

pad_token_id (`int`，*可选*，默认为 `50256`)：词表中用于填充的 Token ID。

bos_token_id (`int`，*可选*，默认为 `50256`)：词汇表中用于表示流开始的 Token ID。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `50256`)：词汇表中用于表示流结束（end-of-stream）的 Token ID。

suppress_tokens (`list[int]`, *可选*) : 一个列表，包含将在 `generate` 函数的 logit processor 中使用的非语音 token。NON_SPEECH_TOKENS 和 NON_SPEECH_TOKENS_MULTI 分别对应 `english-only` 和 `multilingual` 模型。

begin_suppress_tokens (`list[int]`, *可选*, 默认为 `[220,50256]`) : 一个列表，包含在采样过程开始时将被抑制的 token。初始化为 `" "` (`blank_token_id`) 和 `eos_token_id` 的 token。

use_weighted_layer_sum (`bool`，*可选*，默认为 `False`)：是否使用具有学习权重的层输出加权平均。仅在使用 [WhisperForAudioClassification](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperForAudioClassification) 实例时相关。

classifier_proj_size (`int`，*可选*，默认为 256)：用于分类的 token 平均池化之前投影的维度。仅在使用 [WhisperForAudioClassification](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperForAudioClassification) 实例时相关。

apply_spec_augment (`bool`, *可选*, 默认为 `False`) : 是否对特征编码器的输出应用 *SpecAugment* 数据增强。参考 [SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition](https://huggingface.co/papers/1904.08779)。

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`，*可选*，默认为 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`, *可选*，默认为 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_prob (`Union[float, int]`，*可选*，默认为 `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` 为 `True` 时，此参数才相关。

mask_feature_length (`int`，*可选*，默认为 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)：用于在计算 token 时间戳时平滑交叉注意力输出的中值滤波器的宽度。应为奇数。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 WhisperModel 配置的类。它根据指定的参数实例化 Whisper 模型，并定义模型架构。使用默认值实例化配置将得到与 [openai/whisper-tiny](https://huggingface.co/openai/whisper-tiny) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

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

#### transformers.WhisperTokenizer[[transformers.WhisperTokenizer]]

```python
transformers.WhisperTokenizer(vocab: str | dict[str, int] | None = None, merges = None, normalizer_file = None, unk_token = '<|endoftext|>', bos_token = '<|endoftext|>', eos_token = '<|endoftext|>', add_prefix_space = False, language = None, task = None, predict_timestamps = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L163)

**参数：**

vocab_file (`str`, *可选*) : 词汇表文件的路径。

merges_file (`str`, *可选*) : 合并文件的路径。

normalizer_file (`str`, *可选*) : normalizer_file 文件的路径。

tokenizer_file (`str`, *可选*) : [tokenizers](https://github.com/huggingface/tokenizers) 文件的路径（通常扩展名为 .json），其中包含加载分词器所需的所有内容。

unk_token (`str`，*可选*，默认为 `"<|endoftext|>"`)：未知标记。词汇表中不存在的标记无法转换为 ID，因此会被设置为该标记。

bos_token (`str`，*可选*，默认为 `"<|endoftext|>"`)：序列起始标记。生成时，`decoder_start_token_id` 用于将第一个标记设置为 `"<|startoftranscript|>"`。

eos_token (`str`，*可选*，默认为 `"<|endoftext|>"`)：序列结束标记。

add_prefix_space (`bool`，*可选*，默认为 `False`)：是否要在输入前添加一个初始空格。这允许将开头的单词视为与其他单词相同。（Whisper 分词器通过前面的空格来检测单词的开头）。

language (`str`, *可选*) : 转录文本的语言。对于多语言语音识别和语音翻译任务，对应的语言 id token 会被添加到序列的开头，例如对于西班牙语，token `"<|es|>"` 会被添加到序列的开头。此参数仅应用于多语言微调。

task (`str`, *可选*) : 要附加在序列开头的任务标识符（如果有的话）。这应用于多语言微调，语音识别使用 `"transcribe"`，语音翻译使用 `"translate"`。

predict_timestamps (`bool`，*可选*，默认为 `False`)：是否省略序列开头的 `<|notimestamps|>` 标记。

构建一个“快速” Whisper 分词器（由 HuggingFace 的 *tokenizers* 库提供支持）。

该分词器继承自 [PreTrainedTokenizerFast](/docs/transformers/main/zh/main_classes/tokenizer#transformers.TokenizersBackend)，后者包含了大部分主要方法。用户应参考该父类以获取有关这些方法的更多信息。

#### set_prefix_tokens[[transformers.WhisperTokenizer.set_prefix_tokens]]

```python
set_prefix_tokens(language: str | None = None, task: str | None = None, predict_timestamps: bool | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L585)

**参数：**

language (`str`，*可选*，默认为 `None`)：转录文本的语言。

task (`str`, *可选*, 默认为 `None`) : 要附加在序列开头的任务标识符（如果有的话）。

predict_timestamps (`bool`, *可选*, 默认为 `None`) : 是否省略序列开头的 `<|notimestamps|>` 标记。

覆盖添加到标签序列开头的 prefix tokens。此方法可以单独用于

在微调时，根据需要更新前缀标记。示例：

```python
>>> # 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")
```

#### get_special_tokens_mask[[transformers.WhisperTokenizer.get_special_tokens_mask]]

```python
get_special_tokens_mask(token_ids_0: list, token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L669)

**参数：**

token_ids_0 (`list[int]`) : ID 列表。

token_ids_1 (`list[int]`, *可选*) : 用于序列对的可选第二个 ID 列表。

already_has_special_tokens (`bool`，*可选*，默认为 `False`)：标记列表是否已使用模型的特殊标记进行格式化。

**返回：** `list[int]`

一个整数列表，取值范围为 [0, 1]：1 表示特殊标记，0 表示序列标记。

从未添加特殊标记的标记列表中获取序列 ID。当使用分词器的 `prepare_for_model` 方法添加特殊标记时，会调用此方法。

#### save_vocabulary[[transformers.WhisperTokenizer.save_vocabulary]]

```python
save_vocabulary(save_directory: str, filename_prefix: str | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L555)

#### batch_decode[[transformers.WhisperTokenizer.batch_decode]]

```python
batch_decode(sequences: list[int] | list[list[int]] | np.ndarray | torch.Tensor, skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_utils_base.py#L2933)

**参数：**

sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`) : 标记化输入 ID 的列表。可通过 `__call__` 方法获取。

skip_special_tokens (`bool`，*可选*，默认为 `False`)：是否在解码过程中移除特殊标记。

clean_up_tokenization_spaces (`bool`，*可选*)：是否清理分词空格。如果为 `None`，则默认为 `self.clean_up_tokenization_spaces`。

kwargs （额外的关键字参数，*可选*）：将传递给底层模型特定的解码方法。

**返回：** `list[str]`

解码后的句子列表。

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

此方法是为了向后兼容而提供的。`decode` 方法现在原生支持批量输入，因此您可以直接使用 `decode` 而无需使用 `batch_decode`。

#### decode[[transformers.WhisperTokenizer.decode]]

```python
decode(token_ids, skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = 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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L432)

**参数：**

token_ids (`Union[int, list[int], np.ndarray, torch.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`)：是否输出 token 的偏移量。仅当模型预测了时间戳时才应设置此项。如果存在需要解码的前置 token（提示词之前），只有当它们包含时间戳 token 时，才会出现在解码后的文本中。

time_precision (`float`, *可选*, 默认值为 0.02) : 用于将 token 转换为时间的比率。

decode_with_timestamps (`bool`，*可选*，默认为 `False`)：是否解码包含在原始文本中的时间戳。

normalize (`bool`, *可选*, 默认为 `False`) : 是否对解码后的文本应用英文文本规范化器。仅当目标文本为英文时适用。否则，应应用基础文本规范化器。

basic_normalize (`bool`, *可选*, 默认为 `False`) : 是否对解码后的文本应用 Basic 文本规范化器。适用于多语言目标文本。

remove_diacritics (`bool`, *可选*，默认为 `False`) : 是否在对文本应用 Basic 文本规范化器时移除变音符号。移除变音符号可能会破坏解码文本中的信息，因此应谨慎使用。

kwargs （额外的关键字参数，*可选*）：将传递给底层模型特定的解码方法。

**返回：** `str`

解码后的句子。

使用分词器和词汇表将字符串中的 id 序列进行转换，并可选择移除特殊标记以及清理分词空格。

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

#### basic_normalize[[transformers.WhisperTokenizer.basic_normalize]]

```python
basic_normalize(text, remove_diacritics = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L546)

使用 `BasicTextNormalizer` 类对给定字符串进行归一化，该类会对多语言文本执行常见的转换操作。

#### normalize[[transformers.WhisperTokenizer.normalize]]

```python
normalize(text)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L538)

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

## WhisperFeatureExtractor[[transformers.WhisperFeatureExtractor]]

#### transformers.WhisperFeatureExtractor[[transformers.WhisperFeatureExtractor]]

```python
transformers.WhisperFeatureExtractor(feature_size = 80, sampling_rate = 16000, hop_length = 160, chunk_length = 30, n_fft = 400, padding_value = 0.0, dither = 0.0, return_attention_mask = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py#L33)

**参数：**

feature_size (`int`，*可选*，默认为 80)：提取特征的维度。

sampling_rate (`int`，*可选*，默认值为 16000)：音频文件应被数字化采样的采样率，单位为赫兹（Hz）。

hop_length (`int`, *可选*，默认为 160)：用于获取梅尔频率系数的 STFT 的重叠窗口长度。

chunk_length (`int`，*可选*，默认为 30)：用于裁剪和填充较长或较短音频序列时，所使用的最大 `sampling_rate` 样本块数。

n_fft (`int`，*可选*，默认为 400)：傅里叶变换的大小。

padding_value (`float`, *可选*, 默认值为 0.0) : 用于填充音频的填充值。应对应静音。

dither (`float`, *可选*，默认为 0.0)：添加抖动。换句话说，为每一帧添加少量高斯噪声。例如，使用 0.0001 可添加以 0.0 为中心、标准差为 0.0001 的正态分布抖动（假设 raw_speech 的范围为 [-1,+1]）。值 0.0 表示不添加抖动。抖动的作用类似于 `spectrogram(mel_floor=...)`。当信号中存在 VAD 截断时，它可以降低具有硬零部分的信号的高 log_mel_fbank 值。

构建 Whisper 特征提取器。

此特征提取器继承自 [SequenceFeatureExtractor](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)，后者包含了大部分主要方法。有关这些方法的更多信息，请参阅该父类。

此类使用自定义的 numpy 实现的`Short Time Fourier Transform`从原始语音中提取 mel 滤波器组特征，其结果应与 pytorch 的`torch.stft`等效。

#### __调用__[[transformers.WhisperFeatureExtractor.__call__]]

```python
__call__(raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]], truncation: bool = True, pad_to_multiple_of: int | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_attention_mask: bool | None = None, padding: str | None = 'max_length', max_length: int | None = None, sampling_rate: int | None = None, do_normalize: bool | None = None, device: str | None = 'cpu', **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py#L193)

**参数：**

raw_speech (`np.ndarray`、`list[float]`、`list[np.ndarray]`、`list[list[float]]`)：需要填充的序列或序列批次。每个序列可以是 numpy 数组、浮点值列表、numpy 数组列表或浮点值列表的列表。必须是单声道音频，而非立体声，即每个时间步仅包含一个浮点值。

truncation (`bool`, *可选*, 默认为 `True`) : 启用截断，将长度超过 *max_length* 的输入序列截断为 *max_length*。

pad_to_multiple_of (`int`, *可选*，默认为 None) : 如果设置，则将序列填充为所提供值的倍数。 这对于在计算能力 `>= 7.5` (Volta) 的 NVIDIA 硬件上启用 Tensor Cores 的使用特别有用，或者对于受益于序列长度为 128 的倍数的 TPU 也很有用。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回张量而不是 Python 整数列表。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 Numpy `np.ndarray` 对象。

return_attention_mask (`bool`, *可选*) : 是否返回注意力掩码。如果保持默认值，将根据特定 feature_extractor 的默认设置返回注意力掩码。  [什么是注意力掩码？](../glossary#attention-mask)    对于 Whisper 模型，在进行批量推理时，始终应传入 `attention_mask`，以避免细微的 bug。

padding (`str` 或 [PaddingStrategy](/docs/transformers/main/zh/internal/file_utils#transformers.utils.PaddingStrategy)，*可选*，默认为 `'max_length'`)：启用并控制填充。接受以下值： - `'longest'`：填充至批次中最长的序列（如果仅提供单个序列，则不进行填充）。 - `'max_length'`（默认）：填充至参数 `max_length` 指定的最大长度，或者如果未提供该参数，则填充至模型可接受的最大输入长度。 - `'do_not_pad'`：不进行填充（即可以输出包含不同长度序列的批次）。

max_length (`int`, *可选*) : 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 `None`，当截断/填充参数需要最大长度时，将使用预定义的最大模型长度。如果模型没有特定的最大输入长度（例如 XLNet），则禁用截断/填充至最大长度的功能。

sampling_rate (`int`, *可选*) : `raw_speech` 输入的采样率。强烈建议在 forward 调用时传入 `sampling_rate`，以防止静默错误并支持自动语音识别流水线。

do_normalize (`bool`，*可选*，默认为 `False`)：是否对输入进行零均值单位方差归一化。归一化可以显著提升模型性能。

device (`str`, *可选*, 默认为 `'cpu'`) : 指定在 `_torch_extract_fbank_features` 方法中计算音频信号的 log-mel 频谱图时所使用的设备。(例如，"cpu"、"cuda")

- ****kwargs** : 不受 WhisperFeatureExtractor 的 __call__() 支持，将被忽略。

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

## WhisperProcessor[[transformers.WhisperProcessor]]

#### transformers.WhisperProcessor[[transformers.WhisperProcessor]]

```python
transformers.WhisperProcessor(feature_extractor, tokenizer)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/processing_whisper.py#L23)

**参数：**

feature_extractor (`WhisperFeatureExtractor`)：特征提取器是必需的输入。

tokenizer (`WhisperTokenizer`)：分词器是必需的输入。

构建一个 WhisperProcessor，它将特征提取器和分词器封装为单一处理器。

[WhisperProcessor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperProcessor) 提供了 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 和 [WhisperTokenizer](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperTokenizer) 的所有功能。有关更多信息，请参阅 [~WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 和 [~WhisperTokenizer](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperTokenizer)。

#### __调用__[[transformers.WhisperProcessor.__call__]]

```python
__call__(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/processing_whisper.py#L30)

**参数：**

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

#### from_pretrained[[transformers.WhisperProcessor.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, cache_dir: str | os.PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = 'main', **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1750)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`) : 可以是以下之一： - 一个字符串，即托管在 huggingface.co 模型仓库中的预训练 feature_extractor 的 *model id*。 - 指向一个 *目录* 的路径，该目录包含使用 [save_pretrained()](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin.save_pretrained) 方法保存的 feature extractor 文件，例如 `./my_model_directory/`。 - 指向已保存的 feature extractor JSON *file* 的路径，例如 `./my_model_directory/preprocessor_config.json`。

- ****kwargs** : 同时传递给 [from_pretrained()](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained) 和 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained` 的额外关键字参数。

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

此类的该方法只是调用了特征提取器的 [from_pretrained()](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained)、图像处理器 [ImageProcessingMixin](/docs/transformers/main/zh/internal/image_processing_utils#transformers.ImageProcessingMixin) 以及分词器的 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained` 方法。有关更多信息，请参阅上述方法的文档字符串。

#### save_pretrained[[transformers.WhisperProcessor.save_pretrained]]

```python
save_pretrained(save_directory, push_to_hub: bool = False, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1165)

**参数：**

save_directory (`str` 或 `os.PathLike`) : 用于保存特征提取器 JSON 文件和分词器文件的目录（如果该目录不存在，则会自动创建）。

push_to_hub (`bool`，*可选*，默认为 `False`)：是否在保存模型后将其推送到 Hugging Face 模型库。您可以通过 `repo_id` 指定要推送到的仓库（默认使用您命名空间中 `save_directory` 的名称）。

kwargs (`dict[str, Any]`，*可选*)：传递给 [push_to_hub()](/docs/transformers/main/zh/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 方法的额外关键字参数。

将此处理器的属性（特征提取器、分词器……）保存到指定目录中，以便使用 [from_pretrained()](/docs/transformers/main/zh/model_doc/wav2vec2#transformers.Wav2Vec2Processor.from_pretrained) 方法重新加载。

此类的该方法只是调用了 [save_pretrained()](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.FeatureExtractionMixin.save_pretrained) 和 [save_pretrained()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.save_pretrained)。有关更多信息，请参阅上述方法的文档字符串。

#### batch_decode[[transformers.WhisperProcessor.batch_decode]]

```python
batch_decode(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L2005)

此方法将其所有参数转发给 PreTrainedTokenizer 的 [batch_decode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode)。有关更多信息，请参阅该方法的文档字符串。

#### decode[[transformers.WhisperProcessor.decode]]

```python
decode(*args, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L2014)

此方法将其所有参数转发给 PreTrainedTokenizer 的 [decode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.decode)。有关更多信息，请参阅该方法的文档字符串。

## WhisperModel[[transformers.WhisperModel]]

#### transformers.WhisperModel[[transformers.WhisperModel]]

```python
transformers.WhisperModel(config: WhisperConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L826)

**参数：**

config ([WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.WhisperModel.forward]]

```python
forward(input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, decoder_inputs_embeds: tuple[torch.Tensor] | None = None, decoder_position_ids: tuple[torch.LongTensor] | None = None, use_cache: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L891)

**参数：**

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)（[WhisperProcessor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperProcessor) 使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 来处理音频）。

attention_mask (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。 [什么是注意力掩码？](../glossary#attention-mask)

decoder_input_ids (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 解码器输入序列中词元在词汇表中的索引。 可以使用 [WhisperTokenizer](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是解码器输入 ID？](../glossary#decoder-input-ids)  Whisper 使用 `decoder_start_token_id` 作为 `decoder_input_ids` 生成的起始词元。 如果使用 `past_key_values`，则只需输入最后几个 `decoder_input_ids`（参见 `past_key_values`）。

decoder_attention_mask (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 默认行为：生成一个忽略 `decoder_input_ids` 中填充标记的张量。默认情况下也会使用因果掩码。 如果您想更改填充行为，请阅读 `modeling_whisper._prepare_decoder_attention_mask` 并根据需要修改。有关默认策略的更多信息，请参阅 [BART 论文](https://huggingface.co/papers/1910.13461) 中的图 1。

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *可选*) : 元组由 (`last_hidden_state`, *可选*: `hidden_states`, *可选*: `attentions`) 组成。`last_hidden_state` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

decoder_inputs_embeds (`tuple[torch.Tensor]`，形状为 `(batch_size, target_sequence_length, hidden_size)`，*可选*)：可选地，您可以选择直接传入嵌入表示，而不是传入 `decoder_input_ids`。如果使用了 `past_key_values`，则可选地只需输入最后一段 `decoder_inputs_embeds`（参见 `past_key_values`）。如果您希望比模型内部的嵌入查找矩阵更精细地控制将 `decoder_input_ids` 索引转换为对应向量的方式，这将非常有用。如果 `decoder_input_ids` 和 `decoder_inputs_embeds` 均未设置，则 `decoder_inputs_embeds` 将取 `inputs_embeds` 的值。

decoder_position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

**返回：** [Seq2SeqModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) 或 `tuple(torch.Tensor)`

一个 [Seq2SeqModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqModelOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig)）和输入。

[WhisperModel](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`EncoderDecoderCache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [EncoderDecoderCache](/docs/transformers/main/zh/internal/generation_utils#transformers.EncoderDecoderCache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  解码器在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **decoder_attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器交叉注意力层在注意力 softmax 之后的注意力权重，用于在交叉注意力头中计算加权平均值。
- **encoder_last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  编码器每层输出处的隐藏状态，以及可选的初始嵌入输出。
- **encoder_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：
```python
>>> 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[[transformers.WhisperModel._mask_input_features]]

```python
_mask_input_features(input_features: Tensor, attention_mask: typing.Optional[torch.LongTensor] = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L848)

根据 [SpecAugment](https://huggingface.co/papers/1904.08779)，掩码沿时间轴和/或特征轴提取特征。

## WhisperForConditionalGeneration[[transformers.WhisperForConditionalGeneration]]

#### transformers.WhisperForConditionalGeneration[[transformers.WhisperForConditionalGeneration]]

```python
transformers.WhisperForConditionalGeneration(config: WhisperConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L990)

**参数：**

config ([WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有语言建模头的 Whisper 模型。可用于自动语音识别。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.WhisperForConditionalGeneration.forward]]

```python
forward(input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, decoder_inputs_embeds: tuple[torch.Tensor] | None = None, decoder_position_ids: tuple[torch.LongTensor] | None = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1034)

**参数：**

input_features (`torch.Tensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)（[WhisperProcessor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperProcessor) 使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 来处理音频）。

attention_mask (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。 [什么是注意力掩码？](../glossary#attention-mask)

decoder_input_ids (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 解码器输入序列中词元在词汇表中的索引。 可以使用 [WhisperTokenizer](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperTokenizer) 获取索引。 有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。  [什么是解码器输入 ID？](../glossary#decoder-input-ids)  Whisper 使用 `decoder_start_token_id` 作为 `decoder_input_ids` 生成的起始词元。 如果使用 `past_key_values`，则只需输入最后几个 `decoder_input_ids`（参见 `past_key_values`）。

decoder_attention_mask (`torch.LongTensor`，形状为 `(batch_size, target_sequence_length)`，*可选*) : 默认行为：生成一个忽略 `decoder_input_ids` 中填充标记的张量。默认情况下也会使用因果掩码。 如果您想更改填充行为，请阅读 `modeling_whisper._prepare_decoder_attention_mask` 并根据需要修改。有关默认策略的更多信息，请参阅 [BART 论文](https://huggingface.co/papers/1910.13461) 中的图 1。

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *可选*) : 元组由 (`last_hidden_state`, *可选*: `hidden_states`, *可选*: `attentions`) 组成。`last_hidden_state` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

decoder_inputs_embeds (`tuple[torch.Tensor]`，形状为 `(batch_size, target_sequence_length, hidden_size)`，*可选*)：可选地，您可以选择直接传入嵌入表示，而不是传入 `decoder_input_ids`。如果使用了 `past_key_values`，则可选地只需输入最后一段 `decoder_inputs_embeds`（参见 `past_key_values`）。如果您希望比模型内部的嵌入查找矩阵更精细地控制将 `decoder_input_ids` 索引转换为对应向量的方式，这将非常有用。如果 `decoder_input_ids` 和 `decoder_inputs_embeds` 均未设置，则 `decoder_inputs_embeds` 将取 `inputs_embeds` 的值。

decoder_position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 用于计算语言建模损失的标签。索引应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引设置为 `-100` 的标记将被忽略（被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的标记进行计算。`sequence_length` 应小于或等于 `config.max_target_positions`。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

**返回：** [Seq2SeqLMOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqLMOutput) 或 `tuple(torch.Tensor)`

一个 [Seq2SeqLMOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.Seq2SeqLMOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig)）和输入。

[WhisperForConditionalGeneration](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，在提供 `labels` 时返回) -- 语言建模损失。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`EncoderDecoderCache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）-- 它是一个 [EncoderDecoderCache](/docs/transformers/main/zh/internal/generation_utils#transformers.EncoderDecoderCache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  解码器在每一层输出处的隐藏状态，以及初始嵌入输出。
- **decoder_attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器交叉注意力层在注意力 softmax 之后的注意力权重，用于在交叉注意力头中计算加权平均值。
- **encoder_last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  编码器在每一层输出处的隐藏状态，以及初始嵌入输出。
- **encoder_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：

```python
>>> 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.'
```

#### generate[[transformers.WhisperForConditionalGeneration.generate]]

```python
generate(input_features: typing.Optional[torch.Tensor] = None, generation_config: transformers.generation.configuration_utils.GenerationConfig | None = None, logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None, stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None, prefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = None, synced_gpus: bool = False, return_timestamps: bool | None = None, task: str | None = None, language: str | list[str] | None = None, is_multilingual: bool | None = None, prompt_ids: typing.Optional[torch.Tensor] = None, prompt_condition_type: str | None = None, condition_on_prev_tokens: bool | None = None, temperature: float | tuple[float, ...] | None = None, compression_ratio_threshold: float | None = None, logprob_threshold: float | None = None, no_speech_threshold: float | None = None, num_segment_frames: int | None = None, attention_mask: typing.Optional[torch.Tensor] = None, time_precision: float = 0.02, time_precision_features: float = 0.01, return_token_timestamps: bool | None = None, return_segments: bool = False, return_dict_in_generate: bool | None = None, force_unique_generate_call: bool | None = None, monitor_progress: collections.abc.Callable[[torch.Tensor], None] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/generation_whisper.py#L383)

**参数：**

input_features (`torch.Tensor`，形状为 `(batch_size, feature_size, sequence_length)`，*可选*) : 从原始语音波形中提取的 log-mel 特征的浮点值。原始语音波形可以通过将 `.flac` 或 `.wav` 音频文件加载为 `list[float]`、`numpy.ndarray` 或 `torch.Tensor` 类型的数组来获取，*例如* 使用 torchcodec 库（`pip install torchcodec`）或 soundfile 库（`pip install soundfile`）。要将该数组准备为 `input_features`，应使用 [AutoFeatureExtractor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoFeatureExtractor) 来提取 mel 特征、进行填充并转换为 `torch.Tensor` 类型的张量。有关详细信息，请参阅 [__call__()](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)。

generation_config ([GenerationConfig](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig), *可选*) : 用作生成调用基础参数化的生成配置。传递给 generate 且与 `generation_config` 属性匹配的 `**kwargs` 将覆盖这些属性。如果未提供 `generation_config`，则将使用默认值，其加载优先级如下：1) 如果存在，则从 `generation_config.json` 模型文件加载；2) 从模型配置加载。请注意，未指定的参数将继承 [GenerationConfig](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig) 的默认值，应查阅其文档以参数化生成。

logits_processor (`LogitsProcessorList`, *可选*) : 用于补充由参数和生成配置构建的默认 logits 处理器的自定义 logits 处理器。如果传入的 logit 处理器已经由参数或生成配置创建，则会抛出错误。此功能面向高级用户。

stopping_criteria (`StoppingCriteriaList`，*可选*)：自定义停止条件，用于补充由参数和生成配置构建的默认停止条件。如果传入的停止条件已经由参数或生成配置创建，则会抛出错误。此功能面向高级用户。

prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`，*可选*)：如果提供，此函数会在每一步将 beam search 限制为仅允许特定的 token。如果未提供，则不施加任何约束。此函数接受 2 个参数：batch ID `batch_id` 和 `input_ids`。它必须返回一个列表，其中包含根据 batch ID `batch_id` 和之前生成的 token `inputs_ids` 条件化后，下一步生成所允许的 token。此参数对于基于前缀的约束生成非常有用，如 [Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904) 中所述。

synced_gpus (`bool`，*可选*，默认为 `False`)：是否继续运行 while 循环直到 max_length（用于避免与 `FullyShardedDataParallel` 和 DeepSpeed ZeRO Stage 3 发生死锁）。

return_timestamps (`bool`, *可选*) : 是否随文本一起返回时间戳。这将启用 `WhisperTimestampsLogitsProcessor`。对于时长超过 30 秒的音频，必须设置 `return_timestamps=True`。

task (`str`, *可选*) : 用于生成的任务，可以是 "translate" 或 "transcribe"。

language (`str` 或 `str` 列表，*可选*) : 用于生成的语言标记，可以是 `<|en|>`、`en` 或 `english` 的形式。对于批量生成，可以传入语言标记列表。您可以在 `model.generation_config.lang_to_id` 字典中找到所有可能的语言标记。

is_multilingual (`bool`, *可选*) : 模型是否为多语言模型。

prompt_ids (`torch.Tensor`, *可选*) : 通过将文本传入 `get_prompt_ids()` 创建的 token ID 秩为 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 论文](https://cdn.openai.com/papers/whisper.pdf)所示，这有助于提升性能。

temperature (`float` 或 `float` 列表，*可选*) : 生成时使用的温度。传入单个 `float` 值并设置 `do_sample=True` 即可启用基于采样的生成。对于长文本转录，可以通过传入浮点数列表（例如 (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)）来启用温度回退机制。如[Whisper 论文](https://cdn.openai.com/papers/whisper.pdf)所示，这有助于提升性能。

compression_ratio_threshold (`float`, *可选*) : 仅适用于长文本转录。如果已定义，将计算每个片段的 zlib 压缩率。如果某个片段的压缩率高于 `compression_ratio_threshold`，则会激活温度回退机制：丢弃生成的片段，并使用更高的温度重新生成。该功能背后的直觉是，压缩率非常高的片段往往存在大量重复。通过提高温度来注入更多随机性，可以减少这种不需要的重复。如果定义了 `compression_ratio_threshold`，请确保 `temperature` 是一个值列表。`compression_ratio_threshold` 的常用值为 1.35。如 [Whisper 论文](https://cdn.openai.com/papers/whisper.pdf) 所示，这有助于提升性能。

logprob_threshold (`float`, *可选*) : 仅适用于长文本转录。如果已定义，将计算每个片段的平均对数概率。如果某个片段的对数概率低于 `logprob_threshold`，则会激活温度回退机制：丢弃已生成的片段，并使用更高的温度重新生成。该功能背后的直觉是，通过对数概率较低的片段可以通过提高温度来注入更多随机性，从而得到改善。如果定义了 `logprob_threshold`，请确保 `temperature` 是一个值列表。`logprob_threshold` 的常用值为 -1.0。如 [Whisper 论文](https://cdn.openai.com/papers/whisper.pdf) 所示，这有助于提升性能。

no_speech_threshold (`float`, *可选*) : 仅适用于长文本转录。如果已定义，则“no-speech”标记与 `logprob_threshold` 结合使用，以判断某个片段是否仅包含静音。在这种情况下，将跳过该片段的转录。如 [Whisper 论文](https://cdn.openai.com/papers/whisper.pdf) 所示，这有助于提升性能。

num_segment_frames (`int`, *可选*) : 单个片段包含的帧数。如果未定义，`num_segment_frames` 默认为模型的步长乘以最大输入长度。

attention_mask (`torch.Tensor`, *可选*) : 当使用大于 1 的批处理大小进行长文本转录时，必须传入 `attention_mask`。

time_precision (`int`, *可选*，默认为 0.02)：输出 token 的持续时间（以秒为单位）。*例如*，0.02 表示生成的 token 平均占用 20 毫秒。

time_precision_features (`int`，*可选*，默认值为 0.01)：特征帧所代表的时间长度（以秒为单位）。

return_token_timestamps (`bool`, *可选*) : 是否随文本返回 token 级时间戳。此选项可与 `return_timestamps` 选项一起使用，也可单独使用。要获取词级时间戳，请使用分词器将 token 分组为词。

return_segments (`bool`，*可选*，默认为 `False`)：是否额外返回所有片段的列表。请注意，此选项仅在执行长文本转录时才能启用。

return_dict_in_generate (`bool`，*可选*，默认为 `False`)：是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是仅返回生成的 token。请注意，在进行长文本转录时，只有当 `return_segments` 设置为 True 时，才能启用 `return_dict_in_generate`。在这种情况下，每个片段的生成输出会被添加到对应的片段中。

force_unique_generate_call (`bool`, *可选*) : 是否强制对底层 GenerationMixin 的 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 方法进行一次唯一调用。这在辅助解码和测试场景中非常有用，可确保仅调用一次 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)，从而返回解码器输入 token ids 和 eos token ids。

monitor_progress (`Callable[[torch.Tensor], None]`, *可选*) : 如果提供，可以调用此函数来报告音频转录的进度。该函数接受一个形状为 `(n, 2)` 的张量参数 `p`，其中 `n` 是批处理大小。`p[i, 0]` 包含批处理项 `i` 当前正在转录的音频帧索引。`p[i, 1]` 包含批处理项 `i` 的总帧数。不期望有返回值。

kwargs (`dict[str, Any]`, *可选*) : 用于临时配置 `generate_config` 和/或额外的模型特定 kwargs，这些参数将被转发到模型的 `forward` 函数。如果模型是编码器-解码器模型，编码器特定的 kwargs 不应添加前缀，而解码器特定的 kwargs 应以 *decoder_* 作为前缀。

**返回：** [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 或 `dict[str, Any]` 或 `torch.LongTensor`

以下之一：
- 当 `return_dict_in_generate=True` 且（`return_timestamps=False` 或 `force_unique_generate_call=True`）时，返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput)，其中包含解码器输入 id 和序列结束 id。
- 当（`return_dict_in_generate=True` 且 `return_timestamps=True`）或 `return_segments=True` 或 `return_token_timestamps=True` 时，类型为 `dict[str, Any]`。
- `torch.LongTensor` 在所有其他情况下，不包括解码器输入 id 和序列结束 id。

可能的 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 类型包括：
- [GenerateEncoderDecoderOutput](/docs/transformers/main/zh/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput)
- [GenerateBeamEncoderDecoderOutput](/docs/transformers/main/zh/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)

`segments` 是一个列表的列表（每个批次元素对应一个列表），其中包含 `segment`。`segment` 是一个字典，其键为 `start`、`end`、`tokens`、`idxs` 和 `result`。
- `start`：片段的起始时间戳。
- `end`：片段的结束时间戳。
- `tokens`：该段的 token，不包含解码器输入 id 和序列结束 id。
- `idxs`：该段落在底层调用 GenerationMixin 的 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)（存在于 `result` 中）时，`tokens` 的起始（包含）和结束（不包含）索引。
- `result`：对 GenerationMixin 的 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 进行底层调用后返回的结果。

当 `return_timestamps=True` 时，`return_dict_in_generate=True` 会应用于底层 GenerationMixin 的 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 的每次调用，输出结果存储在每个 `segment` 的 `result` 中。

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

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

有关生成策略和代码示例的概述，请参阅[以下指南](../generation_strategies)。

示例：

- *长音频转录*：要转录或翻译时长超过 30 秒的音频，请对音频文件进行无截断处理，并将所有 mel 特征一次性传入 generate。必须设置 `return_timestamps=True`。
实际上，长文本转录使用一种基于时间戳预测的序列算法，并采用诸如压缩比阈值、对数概率阈值和温度回退等启发式方法。该算法在[Whisper 原始论文](https://cdn.openai.com/papers/whisper.pdf)的*3.8. 长文本转录*一节中有详细描述。

```python
>>> 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, return_timestamps=True)

>>> 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."
```

可以使用 `monitor_progress` 回调来监控转录的进度：
```python
>>> from tqdm import tqdm

>>> # prepare inputs like above

>>> # define a callback to monitor the progress of the transcription.
>>> with tqdm(desc="Progress") as pbar:
>>>     def monitor_progress(p_batch):
>>>         i = torch.argmax(p_batch[:, 1])
>>>         p = p_batch[i].detach().cpu()
>>>         pbar.total = int(p[1])
>>>         pbar.n = int(p[0])
>>>         pbar.update()

>>>     # transcribe audio to ids
>>>     generated_ids = model.generate(**inputs, return_timestamps=True, monitor_progress=monitor_progress)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> transcription[0]
Progress:  95%|█████████████████████████████████████████████████████████████████████████████████████████████████▎    | 8497/8901 [00:04<00:00, 2052.79it/s]
" 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 秒，则有两种可能：
  - `return_timestamps=False`：整个音频将通过一次对 GenerationMixin 的 [generate()](/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 调用进行转录。
  - `return_timestamps=True`：音频将使用与长音频转录相同的逻辑进行转录。

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

#### transformers.WhisperForCausalLM[[transformers.WhisperForCausalLM]]

```python
transformers.WhisperForCausalLM(config: WhisperConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1171)

**参数：**

config ([WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有语言建模头（线性层，其权重与输入嵌入共享）的 Whisper 解码器。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.WhisperForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, encoder_outputs: tuple[torch.Tensor] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1197)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

encoder_outputs (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：编码器最后一层输出的隐藏状态序列。如果模型被配置为解码器，则用于交叉注意力。

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

**返回：** [CausalLMOutputWithCrossAttentions](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) 或 `tuple(torch.Tensor)`

一个 [CausalLMOutputWithCrossAttentions](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig)）和输入。

[WhisperForCausalLM](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperForCausalLM) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  在注意力 softmax 之后的交叉注意力权重，用于在交叉注意力头中计算加权平均值。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

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

示例：

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

#### transformers.WhisperForAudioClassification[[transformers.WhisperForAudioClassification]]

```python
transformers.WhisperForAudioClassification(config: WhisperConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1279)

**参数：**

config ([WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Whisper Encoder 模型，顶部带有序列分类头（在池化输出上应用线性层），用于 SUPERB 关键词检测等任务。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.WhisperForAudioClassification.forward]]

```python
forward(input_features: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, labels: typing.Optional[torch.LongTensor] = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1306)

**参数：**

input_features (`torch.LongTensor`，形状为 `(batch_size, sequence_length, feature_dim)`，*可选*) : 与输入音频特征对应的张量。可以使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 获取音频特征。有关详细信息，请参阅 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)（[WhisperProcessor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperProcessor) 使用 [WhisperFeatureExtractor](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperFeatureExtractor) 来处理音频）。

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *可选*) : 元组由 (`last_hidden_state`, *可选*: `hidden_states`, *可选*: `attentions`) 组成。`last_hidden_state` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*)：用于计算序列分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels == 1`，则计算回归损失（均方损失）；如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

**返回：** [SequenceClassifierOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) 或 `tuple(torch.Tensor)`

一个 [SequenceClassifierOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[WhisperConfig](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperConfig)）和输入。

[WhisperForAudioClassification](/docs/transformers/main/zh/model_doc/whisper#transformers.WhisperForAudioClassification) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels)` 的 `torch.Tensor`）-- 分类（或当 config.num_labels==1 时为回归）得分（SoftMax 之前）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：

```python
>>> 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'
```

