Transformers documentation

LASR

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

and get access to the augmented documentation experience

to get started

该模型于 2020-05-16 在 HF papers 上发布,并于 2025-12-05 贡献至 Hugging Face Transformers。

SDPA

LASR

概述

LASR 是 MedASR 背后的架构,MedASR 是 Google Health AI 推出的一个针对医疗听写进行预训练的语音转文本模型。它基于 Conformer 架构,旨在为开发者构建包含医学术语的听写工具(例如放射科听写)提供一个起点。MedASR 在医疗音频上表现良好,但在处理其训练数据之外的术语时可能会遇到困难,例如非标准药物名称或时间引用(日期、时间或持续时间)。

用法

基本用法

Pipeline
AutoModel
from transformers import pipeline


pipe = pipeline("automatic-speech-recognition", model="google/medasr")
out = pipe("path/to/audio.mp3")
print(out)

训练

以下示例准备了一个音频和文本批次,将其通过 LASR/MedASR 模型,并计算训练损失。

from datasets import Audio, load_dataset

from transformers import AutoModelForCTC, AutoProcessor


# Load processor and model
processor = AutoProcessor.from_pretrained("google/medasr")
model = AutoModelForCTC.from_pretrained("google/medasr", device_map="auto")

# Load a small example dataset and prepare batch
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
speech_samples = [el["array"] for el in ds["audio"][:5]]
text_samples = [el for el in ds["text"][:5]]

# Passing `text` to the processor will prepare the `labels`
inputs = processor(audio=speech_samples, text=text_samples, sampling_rate=processor.feature_extractor.sampling_rate)
inputs.to(device, dtype=model.dtype)

outputs = model(**inputs)
outputs.loss.backward()

LasrTokenizer

class transformers.LasrTokenizer

< >

( eos_token = '</s>'unk_token = '<unk>'pad_token = '<pad>'_spm_precompiled_charsmap = Noneextra_ids = 100additional_special_tokens = Nonevocab = Nonevocab_file = None**kwargs )

参数

  • vocab_file (str, 可选) — 包含实例化分词器所需词汇表的 SentencePiece 文件(通常具有 .spm 扩展名)。
  • eos_token (str, 可选, 默认为 "</s>") — 序列结束标记。在构建包含特殊标记的序列时,序列结束使用的并非此标记,而是 sep_token。

    在构建包含特殊标记的序列时,序列末尾使用的并不是这个标记。 实际使用的是 sep_token。

  • unk_token (str,可选,默认为 "<unk>") — 未知标记。不在词汇表中的标记无法转换为 ID,因此会被设置为该标记。
  • pad_token (str,可选,默认为 "<pad>") — 用于填充的标记,例如在对长度不同的序列进行批处理时。
  • extra_ids (int,可选,默认为 100) — 向词表中添加一定数量的额外 id,用作哨兵。这些 token 可以通过 “id{%d}>” 进行访问,其中 “{%d}” 是 0 到 extra_ids-1 之间的数字。可以通过调用 get_sentinel_tokens 方法获取这些 token,通过调用 get_sentinel_token_ids 方法获取 token id
  • additional_special_tokens (list[str],可选) — 分词器使用的额外特殊标记。
  • vocab (str、dict 或 list,可选) — 自定义词表字典。如果未提供,将使用特殊标记创建一个最小词表。

构建一个 LASR 分词器(基于 HuggingFace 的 tokenizers 库)。基于 Unigram。

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

get_sentinel_token_ids

< >

( )

获取哨兵令牌的令牌 ID。

get_sentinel_tokens

< >

( )

从 additional_special_tokens 中获取哨兵标记(extra_id 标记)的列表。

LasrFeatureExtractor

class transformers.LasrFeatureExtractor

< >

( feature_size = 128sampling_rate = 16000hop_length = 160n_fft = 512win_length = 400padding_value = 0.0**kwargs )

参数

  • feature_size (int,可选,默认为 128) — 提取特征的维度。
  • sampling_rate (int,可选,默认为 16000) — 音频文件应被数字化时的采样率,以赫兹 (Hz) 为单位。
  • hop_length (int,可选,默认为 160) — 用于获取梅尔频率系数的 STFT 中重叠窗口的长度。
  • n_fft (int,可选,默认为 512) — 傅里叶变换的大小。
  • win_length (int,可选,默认为 400) — 用于 STFT 计算的窗口长度。
  • padding_value (float,可选,默认为 0.0) — 用于填充音频的填充值。该值应对应静音。

构建 LASR 特征提取器。

该特征提取器继承自 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 的默认设置返回注意力掩码。

    什么是注意力掩码?

    对于 Parakeet 模型,在进行批量推理时,始终应传入 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 的实现。

LasrProcessor

class transformers.LasrProcessor

< >

( feature_extractortokenizer )

参数

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

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

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

__call__

< >

( audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor']]text: str | list[str] | list[list[str]] | None = Nonesampling_rate: int | None = None**kwargs: *<class 'transformers.models.lasr.processing_lasr.LasrProcessorKwargs'> )

参数

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

batch_decode

< >

( *args**kwargs )

此方法会将其所有参数转发给 PreTrainedTokenizer 的 batch_decode()。有关更多信息,请参阅该方法的文档字符串。

decode

< >

( *args**kwargs )

此方法会将其所有参数转发给 PreTrainedTokenizer 的 decode()。有关更多信息,请参阅该方法的文档字符串。

LasrEncoderConfig

class transformers.LasrEncoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 512num_hidden_layers: int = 17num_attention_heads: int = 8intermediate_size: int = 2048hidden_act: str = 'silu'attention_bias: bool = Falseconvolution_bias: bool = Falseconv_kernel_size: int = 32subsampling_conv_channels: int = 256num_mel_bins: int = 128subsampling_conv_kernel_size: int = 5subsampling_conv_stride: int = 2dropout: float | int = 0.1dropout_positions: float | int = 0.0layerdrop: float | int = 0.1activation_dropout: float | int = 0.1attention_dropout: float | int = 0.1max_position_embeddings: int = 10000initializer_range: float = 0.02layer_norm_eps: float = 1e-06feed_forward_residual_weights: list[float] | tuple[float, ...] = (1.5, 0.5)conv_residual_weights: list[float] | tuple[float, ...] = (2.0, 1.0)batch_norm_momentum: float = 0.01rope_parameters: dict | None = None )

参数

  • hidden_size (int,可选,默认为 512) — 隐藏表示的维度。
  • num_hidden_layers (int,可选,默认为 17) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 2048) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • convolution_bias (bool,可选,默认为 False) — 是否在 conformer 的卷积模块中使用偏置。
  • conv_kernel_size (int, 可选,默认为 32) — Conformer 块中卷积层的卷积核大小。
  • subsampling_conv_channels (int, 可选,默认为 256) — 下采样卷积层的通道数。
  • num_mel_bins (int, 可选,默认为 128) — 每个输入帧使用的 mel 特征数量。应与 AutoFeatureExtractor 类中使用的值相对应。
  • subsampling_conv_kernel_size (int,可选,默认值为 5) — 下采样卷积层的卷积核大小。
  • subsampling_conv_stride (int,可选,默认为 2) — 下采样卷积层的步长。
  • dropout (Union[float, int],可选,默认为 0.1) — 所有 dropout 层的比率。
  • dropout_positions (float,可选,默认值为 0.0) — 输入序列中位置的 dropout 比率。
  • layerdrop (Union[float, int],可选,默认为 0.1) — LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • activation_dropout (Union[float, int],可选,默认为 0.1) — 全连接层内部激活值的 dropout 比率。
  • attention_dropout (Union[float, int],可选,默认为 0.1) — 注意力概率的 dropout 比率。
  • max_position_embeddings (int,可选,默认为 10000) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • feed_forward_residual_weights (tuple[float, float],可选,默认为 [1.5, 0.5]) — 前馈层的残差权重。
  • conv_residual_weights (tuple[float, float],可选,默认为 [2.0, 1.0]) — 卷积层的残差权重。
  • batch_norm_momentum (float,可选,默认值为 0.01) — 批归一化层的动量
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。

这是用于存储 LasrModel 配置的类。它根据指定的参数实例化 Lasr 模型,并定义模型架构。使用默认值实例化配置将生成与 google/medasr 类似的配置。

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

示例:

>>> from transformers import LasrEncoderModel, LasrEncoderConfig

>>> # Initializing a `LasrEncoder` configuration
>>> configuration = LasrEncoderConfig()

>>> # Initializing a model from the configuration
>>> model = LasrEncoderModel(configuration)

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

此配置类基于 Google Health AI 的 LasrEncoder 架构。您可以在 google/medasr 中找到更多详细信息和预训练模型。

LasrCTCConfig

class transformers.LasrCTCConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 512ctc_loss_reduction: str = 'mean'ctc_zero_infinity: bool = Trueencoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepad_token_id: int = 0 )

参数

  • vocab_size (int,可选,默认为 512) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • ctc_loss_reduction (str,可选,默认为 "mean") — 指定应用于 torch.nn.CTCLoss 输出的归约方式。仅在训练 LasrForCTC 实例时相关。
  • ctc_zero_infinity (bool,可选,默认为 True) — 是否将 torch.nn.CTCLoss 的无穷大损失及其相关梯度置零。无穷大损失主要出现在输入过短、无法与目标对齐的情况下。仅在训练 LasrForCTC 实例时相关。
  • encoder_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 编码器骨干网络的配置对象或字典。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。

这是用于存储 LasrModel 配置的类。它根据指定的参数实例化 Lasr 模型,并定义模型架构。使用默认值实例化配置将生成与 google/medasr 类似的配置。

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

示例:

>>> from transformers import LasrForCTC, LasrCTCConfig
>>> # Initializing a Lasr configuration
>>> configuration = LasrCTCConfig()
>>> # Initializing a model from the configuration
>>> model = LasrForCTC(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
This configuration class is based on the Lasr CTC architecture from Google Health AI. You can find more details and pre-trained models at [google/medasr](https://huggingface.co/google/medasr).

LasrEncoder

class transformers.LasrEncoder

< >

( config: LasrEncoderConfig )

参数

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

基于 Conformer 架构的 LasrEncoder 模型](https://arxiv.org/abs/2005.08100)。

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

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

forward

< >

( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneoutput_attention_mask: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LasrEncoderModelOutput or tuple(torch.Tensor)

参数

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

    什么是注意力掩码?

  • output_attention_mask (bool,可选) — 是否返回输出注意力掩码。

返回值

LasrEncoderModelOutput 或 tuple(torch.Tensor)

LasrEncoderModelOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(None)和输入而定的各种元素。

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

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

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

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

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

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

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

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

  • attention_mask(形状为 (batch_size, sequence_length) 的 torch.Tensor,可选)— 用于在序列压缩后避免对填充(padding)标记索引执行注意力机制的掩码。由于序列长度可能与输入序列长度不同,因此会返回该掩码。掩码值取自 [0, 1]:

    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

示例:

>>> from transformers import AutoProcessor, LasrEncoder
>>> from datasets import load_dataset, Audio

>>> model_id = "google/medasr"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> encoder = ParakeetEncoder.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"])
>>> encoder_outputs = encoder(**inputs)

>>> print(encoder_outputs.last_hidden_state.shape)

LasrForCTC

class transformers.LasrForCTC

< >

( config: LasrCTCConfig )

参数

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

带有连接主义时间分类(CTC)头的 Lasr 编码器。

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

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

forward

< >

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

参数

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

    什么是注意力掩码?

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

返回值

CausalLMOutput 或 tuple(torch.Tensor)

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

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

示例:

>>> from transformers import AutoProcessor, LasrForCTC
>>> from datasets import load_dataset, Audio

>>> model_id = "nvidia/lasr-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = LasrForCTC.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> outputs = model(**inputs)

>>> print(outputs.loss)

generate

< >

( input_features: Tensorattention_mask: typing.Optional[torch.Tensor] = Nonereturn_dict_in_generate: bool = Falsecompile_config: transformers.generation.configuration_utils.CompileConfig | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

示例:

>>> from transformers import AutoProcessor, LasrForCTC
>>> from datasets import load_dataset, Audio

>>> model_id = "google/medasr"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = LasrForCTC.from_pretrained(model_id)

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> predicted_ids = model.generate(**inputs)
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)

>>> print(transcription)
Update on GitHub