Transformers documentation

CohereAsr

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

and get access to the augmented documentation experience

to get started

该模型于 2026-03-26 贡献至 Hugging Face Transformers。

CohereAsr

概述

Cohere ASR 是 Cohere 于 2026 年 3 月 26 日发布的基于 Conformer 的编码器-解码器语音识别模型,参数量为 20 亿。

该模型由 Eustache Le Bihan 贡献。

用法

短文本转录

from transformers import AutoProcessor, CohereAsrForConditionalGeneration
from transformers.audio_utils import load_audio


revision = "refs/pr/6"
processor = AutoProcessor.from_pretrained("CohereLabs/cohere-transcribe-03-2026", revision=revision)
model = CohereAsrForConditionalGeneration.from_pretrained("CohereLabs/cohere-transcribe-03-2026", device_map="auto", revision=revision)

audio = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
    sampling_rate=16000,
)

inputs = processor(audio, sampling_rate=16000, return_tensors="pt", language="en").to(model.device)
inputs.to(model.device, dtype=model.dtype)

outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True)
print(text)

标点控制

传入 punctuation=False 以获取不带标点符号的小写输出。

inputs_pnc = processor(audio, sampling_rate=16000, return_tensors="pt", language="en", punctuation=True).to(model.device)
inputs_nopnc = processor(audio, sampling_rate=16000, return_tensors="pt", language="en", punctuation=False).to(model.device)

长文本转录

对于时长超过特征提取器 max_audio_clip_s 的音频,特征提取器会自动将波形切分为多个片段。 处理器会使用返回的 audio_chunk_index 来重新组装各片段的转录结果。

audio_long = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3",
    sampling_rate=16000,
)

inputs = processor(audio=audio_long, return_tensors="pt", language="en", sampling_rate=16000).to(model.device)
audio_chunk_index = inputs.get("audio_chunk_index")
inputs.to(model.device, dtype=model.dtype)

outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True, audio_chunk_index=audio_chunk_index, language="en")
print(text)

批量推理

可以在单次调用中处理多个音频文件。当批次中混合了短音频和长音频时,处理器会负责分块和重组。

audio_short = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
    sampling_rate=16000,
)
audio_long = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3",
    sampling_rate=16000,
)

inputs = processor([audio_short, audio_long], sampling_rate=16000, return_tensors="pt", language="en").to(model.device)
audio_chunk_index = inputs.get("audio_chunk_index")
inputs.to(model.device, dtype=model.dtype)

outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(
    outputs, skip_special_tokens=True, audio_chunk_index=audio_chunk_index, language="en"
)
print(text)

非英语转录

指定要转录的语言代码,支持 14 种语言中的任意一种。

audio_es = load_audio(
    "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/fleur_es_sample.wav",
    sampling_rate=16000,
)

inputs = processor(audio_es, sampling_rate=16000, return_tensors="pt", language="es", punctuation=True).to(model.device)
inputs.to(model.device, dtype=model.dtype)

outputs = model.generate(**inputs, max_new_tokens=256)
text = processor.decode(outputs, skip_special_tokens=True)
print(text)

CohereAsrConfig

class transformers.CohereAsrConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Trueencoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevocab_size: int = 16384hidden_size: int = 1024num_hidden_layers: int = 8num_attention_heads: int = 8num_key_value_heads: int | None = Noneintermediate_size: int = 4096hidden_act: str = 'relu'max_position_embeddings: int = 1024pad_token_id: int | None = 2eos_token_id: int | None = 3bos_token_id: int | None = 4use_cache: bool = Trueinitializer_range: float = 0.02attention_dropout: float | int = 0.0attention_bias: bool = Truedecoder_start_token_id: int | None = Nonetie_word_embeddings: bool = Falsehead_dim: int | None = None )

参数

  • is_encoder_decoder (bool,可选,默认为 True) — 指示该模型是否用作编码器/解码器。
  • encoder_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 编码器骨干网络的配置对象或字典。
  • vocab_size (int,可选,默认为 16384) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • num_hidden_layers (int,可选,默认为 8) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • intermediate_size (int,可选,默认为 4096) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 1024) — 该模型可能使用的最大序列长度。
  • pad_token_id (int,可选,默认为 2) — 词表中用于填充的 token id。
  • eos_token_id (int, 可选,默认为 3) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • bos_token_id (int,可选,默认为 4) — 词汇表中用于表示流起始的 token id。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool,可选,默认为 True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。
  • decoder_start_token_id (int, 可选) — 如果编码器-解码器模型使用不同于 bos 的 token 开始解码,则指定该 token 的 id。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • head_dim (int,可选) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads

这是用于存储 CohereAsrModel 配置的类。它根据指定的参数实例化 Cohere Asr 模型,并定义模型架构。使用默认值实例化配置将得到与 CohereLabs/cohere-transcribe-03-2026 类似的配置。

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

示例:

>>> from transformers import CohereAsrForConditionalGeneration, CohereAsrConfig

>>> configuration = CohereAsrConfig()
>>> model = CohereAsrForConditionalGeneration(configuration)
>>> configuration = model.config

CohereAsrFeatureExtractor

class transformers.CohereAsrFeatureExtractor

< >

( feature_size = 128sampling_rate = 16000hop_length = 160n_fft = 512win_length = 400preemphasis = 0.97padding_value = 0.0dither = 1e-05max_audio_clip_s = 35.0overlap_chunk_second = 5.0min_energy_window_samples = 1600**kwargs )

参数

  • feature_size (int,可选,默认为 128) — 提取特征的维度。
  • sampling_rate (int,可选,默认为 16000) — 音频文件应被数字化时的采样率,以赫兹 (Hz) 为单位。
  • hop_length (int,可选,默认为 160) — 用于获取梅尔频率系数的 STFT 中重叠窗口的长度。
  • n_fft (int,可选,默认为 512) — 傅里叶变换的大小。
  • win_length (int,可选,默认为 400) — 用于 STFT 计算的窗口长度。
  • preemphasis (float,可选,默认为 0.97) — 预加重滤波器系数。0.0 表示不使用预加重滤波器。
  • padding_value (float,可选,默认为 0.0) — 用于填充音频的填充值。该值应对应静音。
  • dither (float, 可选,默认为 1e-05) — 在特征提取前添加的确定性抖动噪声量。每个样本以其有效波形长度作为随机种子,从而保证抖动噪声与批次组成无关。设置为 0.0 可禁用该功能。
  • max_audio_clip_s (float,可选,默认值为 35.0) — 单个音频片段的最大时长(秒)。时长超过 max_audio_clip_s - overlap_chunk_second 的音频将在基于能量的边界处进行切分。
  • overlap_chunk_second (float,可选,默认值为 5.0) — 用于分割长音频时,边界搜索窗口的时长(以秒为单位)。这并非块之间的实际重叠部分,而是定义了从块边界向前搜索静音分割点的范围。
  • min_energy_window_samples (int,可选,默认为 1600) — 用于在拆分音频块时寻找最安静点的滑动窗口的样本大小。

构建一个 CohereAsr 特征提取器。

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

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

__call__

< >

( raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]]truncation: bool = Falsepad_to_multiple_of: int | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonereturn_attention_mask: bool | None = Nonepadding: str | None = 'longest'max_length: int | None = Nonesampling_rate: int | None = Nonedo_normalize: bool | None = Nonedevice: str | None = 'cpu'return_token_timestamps: bool | None = None**kwargs )

参数

  • 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)— 如果设置,则将序列填充为所提供值的倍数。

    这在启用 NVIDIA 硬件(计算能力 >= 7.5,即 Volta 架构)上的 Tensor Cores 使用时尤为有用,或者在 TPU 上使用时也特别有益,因为 TPU 在序列长度为 128 的倍数时性能更佳。

  • return_attention_mask (bool, 可选) — 是否返回注意力掩码。如果保持默认值,则根据特定 feature_extractor 的默认设置返回注意力掩码。

    什么是注意力掩码?

    对于 CohereAsr 模型,在进行批量推理时,始终应传入 attention_mask,以避免出现细微的 bug。

  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:
    • 'tf':返回 TensorFlow tf.constant 对象。
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 Numpy np.ndarray 对象。
  • sampling_rate (int, 可选) — raw_speech 输入所使用的采样率。强烈建议在 forward 调用时传入 sampling_rate,以避免静默错误并支持自动语音识别流水线。
  • padding_value (float,可选,默认为 0.0) — 用于填充 padding 值/向量的数值。
  • do_normalize (bool,可选,默认为 False) — 是否对输入进行零均值单位方差归一化。归一化可以显著提升模型性能。
  • device (str,可选,默认为 'cpu') — 指定在 _torch_extract_fbank_features 方法中计算音频信号的 log-mel 频谱图时所使用的设备。(例如,“cpu”、“cuda”)
  • return_token_timestamps (bool, 可选, 默认值为 None) — 已弃用。请改用 return_attention_mask ,从中可以推断出帧数。

    是否返回输入 raw_speech 的帧数。 这些 num_frames 可供模型用于计算词级时间戳。

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

CohereAsrProcessor

class transformers.CohereAsrProcessor

< >

( feature_extractortokenizer )

参数

  • feature_extractor(CohereAsrFeatureExtractor)— 特征提取器是必需的输入。
  • tokenizer (TokenizersBackend) — 分词器是必需的输入。

构造一个 CohereAsrProcessor,它将特征提取器和分词器封装为单个处理器。

CohereAsrProcessor 提供了 CohereAsrFeatureExtractor 和 TokenizersBackend 的所有功能。有关更多信息,请参阅 ~CohereAsrFeatureExtractor 和 ~TokenizersBackend。

__call__

< >

( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]language: strtext: str | list[str] | list[list[str]] | None = Nonepunctuation: bool = Truesampling_rate: int | None = None**kwargs: *<class 'transformers.models.cohere_asr.processing_cohere_asr.CohereAsrProcessorKwargs'> )

参数

  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • language (str) — 用于构建解码器提示的语言代码(例如 "en"、"es"、"fr")。处理器会构建完整的解码器提示,并随音频特征一起返回 decoder_input_ids。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • punctuation (bool,默认为 True) — 是否在解码器提示中启用标点符号。
  • sampling_rate (int, 可选) — 输入音频的采样率,单位为 Hz。该值应与特征提取器所期望的采样率一致(默认为 16000 Hz)。如果提供了该参数,则会将其与处理器所期望的采样率进行校验,若两者不匹配则抛出错误。如果未提供,则会发出警告并假定使用默认采样率。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

CohereAsrPreTrainedModel

类 transformers.CohereAsrPreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

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

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

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

forward

( *args**kwargs )

点分路径(例如 torch.float32)的模拟值:属性访问链和调用行为如同透传装饰器,repr 返回点分路径,将其用作基类时会替换为普通的 type 基类(PEP 560 __mro_entries__),因此真实的子类保留正常的元类,且 inspect.signature 读取的是它们真实的 __init__,而非模拟对象的。

CohereAsrModel

class transformers.CohereAsrModel

< >

( config: CohereAsrConfig )

参数

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

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

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

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

forward

< >

( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: tuple[tuple[torch.Tensor]] | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | None = Nonedecoder_inputs_embeds: tuple[torch.Tensor] | None = Nonedecoder_position_ids: tuple[torch.LongTensor] | None = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqModelOutput or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, audio_length)) — 原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取原始语音波形,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组处理为 input_features,应使用 AutoFeatureExtractor 进行填充并将其转换为 torch.Tensor 类型的张量。
  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • 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.EncoderDecoderCache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

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

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

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

  • 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, target_sequence_length)) — 输入序列中每个 token 在位置嵌入中的位置索引。 用于计算直至 config.decoder_config.max_position_embeddings 的位置嵌入。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

Seq2SeqModelOutput 或 tuple(torch.Tensor)

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

CohereAsrModel 的 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 实例。更多详情,请参阅我们的 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 之后的注意力权重,用于在自注意力头中计算加权平均值。

示例:

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

>>> model = CohereAsrModel.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> 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, 288]

CohereAsrForConditionalGeneration

类 transformers.CohereAsrForConditionalGeneration

< >

( config: CohereAsrConfig )

参数

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

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

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

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

forward

< >

( input_features: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: tuple[tuple[torch.Tensor]] | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | None = Nonedecoder_inputs_embeds: tuple[torch.Tensor] | None = Nonedecoder_position_ids: tuple[torch.LongTensor] | None = Noneuse_cache: bool | None = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqLMOutput or tuple(torch.Tensor)

参数

  • input_features (torch.Tensor,形状为 (batch_size, audio_length)) — 原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取原始语音波形,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组处理为 input_features,应使用 AutoFeatureExtractor 进行填充并将其转换为 torch.Tensor 类型的张量。
  • attention_mask (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充(padding)标记索引执行注意力机制的掩码。掩码值取自 [0, 1]:1 表示未屏蔽的标记,0 表示被屏蔽的标记。什么是注意力掩码? [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor 形状为 (batch_size, target_sequence_length), ,可选) — 解码器输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取索引。详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是解码器输入 ID?

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

    什么是解码器输入 ID?

  • decoder_attention_mask(形状为 (batch_size, target_sequence_length) 的 torch.LongTensor,可选) — 用于避免对特定 token 索引执行注意力的掩码。默认情况下,会使用因果掩码,以确保模型只能查看之前的输入来预测未来。
  • 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.EncoderDecoderCache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 past_key_values 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

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

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

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

  • 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, target_sequence_length)) — 输入序列中每个 token 在位置嵌入中的位置索引。 用于计算直至 config.decoder_config.max_position_embeddings 的位置嵌入。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。

返回值

Seq2SeqLMOutput 或 tuple(torch.Tensor)

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

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

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

  • loss(形状为 (1,) 的 torch.Tensor,可选,在提供 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 实例。更多详情,请参阅我们的 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 之后的注意力权重,用于在自注意力头中计算加权平均值。

示例:

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

>>> processor = AutoProcessor.from_pretrained("UsefulSensors/cohere_asr-tiny")
>>> model = CohereAsrForConditionalGeneration.from_pretrained("UsefulSensors/cohere_asr-tiny")

>>> 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(input_features, max_new_tokens=100)

>>> 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.'
Update on GitHub