Transformers documentation

HuBERT

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-06-14 在 HF papers 上发布,并于 2021-06-16 贡献至 Hugging Face Transformers。

FlashAttention SDPA

HuBERT

HuBERT 是一种自监督语音模型,它通过聚类对齐的目标标签来构建类似 BERT 的预测损失,并且仅在掩码区域上应用该预测损失,从而迫使模型在连续输入上同时学习声学建模和语言建模。该模型解决了以下挑战:每个话语中包含多个声音单元、预训练阶段没有词表,以及声音单元长度可变且缺乏显式分段。

您可以在 HuBERT 集合中找到所有原始的 HuBERT 检查点。

该模型由 patrickvonplaten 贡献。

点击右侧边栏中的 HuBERT 模型,以查看将 HuBERT 应用于不同音频任务的更多示例。

以下示例演示了如何使用 Pipeline 或 AutoModel 类自动将语音转录为文本。

Pipeline
AutoModel
from transformers import pipeline


pipeline = pipeline(
    task="automatic-speech-recognition",
    model="facebook/hubert-large-ls960-ft",
    device=0
)

pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")

量化

量化通过以较低精度表示权重来降低大模型的内存负担。 有关更多可用的量化后端,请参阅 量化 概述。

以下示例使用 bitsandbytes 将权重量化为 4 位。

import torch
from datasets import load_dataset

from transformers import AutoModelForCTC, AutoProcessor, BitsAndBytesConfig


bnb_config = BitsAndBytesConfig(
    load_in_8bit=True,
    llm_int8_threshold=6.0
)

dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation").sort("id")
sampling_rate = dataset.features["audio"].sampling_rate

processor = AutoProcessor.from_pretrained("facebook/hubert-base-ls960")
model = AutoModelForCTC.from_pretrained("facebook/hubert-base-ls960", quantization_config=bnb_config, device_map="auto", attn_implementation="sdpa")

inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt").to(model.device)
with torch.no_grad():
    logits = model(**inputs).logits
predicted_ids = torch.argmax(logits, dim=-1)

transcription = processor.batch_decode(predicted_ids)
print(transcription[0])

备注

  • HuBERT 模型期望原始音频输入为以 16kHz 采样的 1D 浮点数组。

HubertConfig

class transformers.HubertConfig

< >

( 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 = 32hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout: float | int = 0.1activation_dropout: float | int = 0.1attention_dropout: float | int = 0.1feat_proj_layer_norm: bool = Truefeat_proj_dropout: float | int = 0.0final_dropout: float | int = 0.1layerdrop: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-05feat_extract_norm: str = 'group'feat_extract_activation: str = 'gelu'conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)conv_bias: bool = Falsenum_conv_pos_embeddings: int = 128num_conv_pos_embedding_groups: int = 16conv_pos_batch_norm: bool = Falsedo_stable_layer_norm: bool = Falseapply_spec_augment: bool = Truemask_time_prob: float | int = 0.05mask_time_length: int = 10mask_time_min_masks: int = 2mask_feature_prob: float | int = 0.0mask_feature_length: int = 10mask_feature_min_masks: int = 0ctc_loss_reduction: str = 'sum'ctc_zero_infinity: bool = Falseuse_weighted_layer_sum: bool = Falseclassifier_proj_size: int = 256pad_token_id: int | None = 0bos_token_id: int | None = 1eos_token_id: int | list[int] | None = 2 )

参数

  • vocab_size (int,可选,默认为 32) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout (Union[float, int],可选,默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • activation_dropout (Union[float, int],可选,默认为 0.1) — 全连接层内部激活值的 dropout 比率。
  • attention_dropout (Union[float, int],可选,默认为 0.1) — 注意力概率的 dropout 比率。
  • feat_proj_layer_norm (bool,可选,默认为 True) — 是否对特征编码器的输出应用 LayerNorm。
  • feat_proj_dropout (float, 可选,默认值为 0.0) — 特征编码器输出的 dropout 概率。
  • final_dropout (float,可选,默认值为 0.1) — Wav2Vec2ForCTC 最终投影层的 dropout 概率。
  • layerdrop (Union[float, int],可选,默认为 0.1) — LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • feat_extract_norm (str,可选,默认为 "group") — 应用于特征编码器中一维卷积层的归一化方式。取值为 "group",表示仅对第一个一维卷积层应用组归一化;或取值为 "layer",表示对所有的一维卷积层应用层归一化。
  • feat_extract_activation (str, optional, defaults to “gelu”) -- The non-linear activation function (function or string) in the 1D convolutional layers of the feature extractor. If string, “gelu”, “relu”, “selu”and“gelu_new”` are supported.
  • conv_dim (tuple[int],可选,默认为 (512, 512, 512, 512, 512, 512, 512)) — 一个整数元组,用于定义特征编码器中每个一维卷积层的输入和输出通道数。conv_dim 的长度决定了一维卷积层的数量。
  • conv_stride (tuple[int],可选,默认为 (5, 2, 2, 2, 2, 2, 2)) — 一个整数元组,用于定义特征编码器中每个一维卷积层的步长。conv_stride 的长度决定了卷积层的数量,并且必须与 conv_dim 的长度相匹配。
  • conv_kernel (tuple[int],可选,默认为 (10, 3, 3, 3, 3, 3, 3)) — 一个整数元组,用于定义特征编码器中每个一维卷积层的卷积核大小。conv_kernel 的长度决定了卷积层的数量,并且必须与 conv_dim 的长度一致。
  • conv_bias (bool,可选,默认为 False) — 一维卷积层是否包含偏置。
  • num_conv_pos_embeddings (int,可选,默认为 128) — 卷积位置嵌入的数量。定义一维卷积位置嵌入层的核大小。
  • num_conv_pos_embedding_groups (int,可选,默认为 16) — 一维卷积位置嵌入层的组数。
  • conv_pos_batch_norm (bool,可选,默认为 False) — 是否在 conv_pos 中使用 batch norm 代替 weight norm
  • do_stable_layer_norm (bool, 可选,默认为 False) — 是否对 Transformer 编码器应用 stable 层归一化架构。do_stable_layer_norm is True 表示在注意力层之前应用层归一化,而 do_stable_layer_norm is False 表示在注意力层之后应用层归一化。
  • apply_spec_augment (bool,可选,默认为 True) — 是否对特征编码器的输出应用 SpecAugment 数据增强。参考 SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition。
  • mask_time_prob (float, optional, defaults to 0.05) — Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking procedure generates ”mask_time_problen(time_axis)/mask_time_length” independent masks over the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector span to be masked, mask_time_prob should be `prob_vector_startmask_time_length. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if apply_spec_augment is 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, optional, defaults to 0.0) — Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The masking procedure generates ”mask_feature_problen(feature_axis)/mask_time_length” independent masks over the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector span to be masked, mask_feature_prob should be `prob_vector_startmask_feature_length. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if 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” 时相关。
  • ctc_loss_reduction (str,可选,默认为 "sum") — 指定应用于 torch.nn.CTCLoss 输出的归约方式。仅在训练 HubertForCTC 实例时相关。
  • ctc_loss_reduction (str,可选,默认为 sum) — 指定应用于 torch.nn.CTCLoss 输出的归约方式。仅在训练时相关。
  • ctc_zero_infinity (bool,可选,默认为 False) — 是否将 torch.nn.CTCLoss 的无穷大损失及其相关梯度置零。无穷大损失主要出现在输入过短、无法与目标对齐的情况下。仅在训练 HubertForCTC 实例时相关。
  • use_weighted_layer_sum (bool,可选,默认为 False) — 是否使用带有学习权重的层输出加权平均。仅在使用 HubertForSequenceClassification 实例时相关。
  • classifier_proj_size (int,可选,默认为 256) — 用于分类的 token 平均池化之前投影的维度。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 1) — 词汇表中用于表示流起始的 token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 2) — 词汇表中用于表示流结束(end-of-stream)的 token id。

这是用于存储 HubertModel 配置的类。它根据指定的参数实例化 Hubert 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/hubert-base-ls960 类似的配置。

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

示例:

>>> from transformers import HubertModel, HubertConfig

>>> # Initializing a Hubert facebook/hubert-base-ls960 style configuration
>>> configuration = HubertConfig()

>>> # Initializing a model from the facebook/hubert-base-ls960 style configuration
>>> model = HubertModel(configuration)

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

HubertModel

class transformers.HubertModel

< >

( config: HubertConfig )

参数

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

裸的 Hubert 模型,输出原始隐藏状态,顶部没有添加任何特定的头。

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

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

forward

< >

( input_values: typing.Optional[torch.Tensor]attention_mask: typing.Optional[torch.Tensor] = Nonemask_time_indices: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutput or tuple(torch.Tensor)

参数

  • input_values (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 Wav2Vec2Processor.call()。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • mask_time_indices (torch.BoolTensor,形状为 (batch_size, sequence_length),可选) — 用于对比损失中掩码提取特征的索引。在训练模式下,模型学习在 config.proj_codevector_dim 空间中预测被掩码的提取特征。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

BaseModelOutput 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

示例:

>>> from transformers import AutoProcessor, HubertModel
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("facebook/hubert-large-ls960-ft")
>>> model = HubertModel.from_pretrained("facebook/hubert-large-ls960-ft")


>>> def map_to_array(example):
...     example["speech"] = example["audio"]["array"]
...     return example


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

>>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values  # Batch size 1
>>> hidden_states = model(input_values).last_hidden_state

HubertForCTC

class transformers.HubertForCTC

< >

( config: HubertConfigtarget_lang: str | None = None )

参数

  • config (HubertConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
  • target_lang (str, 可选) — 适配器权重的语言 ID。适配器权重以 adapter.<lang>.safetensors 或 adapter.<lang>.bin 格式存储。仅在使用带有适配器的 HubertForCTC 实例时相关。默认使用 ‘eng’。

在 Hubert 模型顶部添加 language modeling 头,用于连接主义时间分类(CTC)。

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

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

forward

< >

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

参数

  • input_values (torch.Tensor,形状为 (batch_size, sequence_length),可选) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 Wav2Vec2Processor.call()。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • labels (torch.LongTensor,形状为 (batch_size, target_length),可选) — 用于连接时序分类的标签。请注意,target_length 必须小于或等于输出 logits 的序列长度。索引的取值范围为 [-100, 0, ..., config.vocab_size - 1]。 所有设置为 -100 的标签都会被忽略(即被掩码),损失仅针对 [0, ..., config.vocab_size - 1] 范围内的标签进行计算。

返回值

CausalLMOutput 或 tuple(torch.Tensor)

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

HubertForCTC 的 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, HubertForCTC
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> processor = AutoProcessor.from_pretrained("facebook/hubert-base-ls960")
>>> model = HubertForCTC.from_pretrained("facebook/hubert-base-ls960")

>>> # audio file is decoded on the fly
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> predicted_ids = torch.argmax(logits, dim=-1)

>>> # transcribe speech
>>> transcription = processor.batch_decode(predicted_ids)
>>> transcription[0]
...

>>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="pt").input_ids

>>> # compute loss
>>> loss = model(**inputs).loss
>>> round(loss.item(), 2)
...

HubertForSequenceClassification

class transformers.HubertForSequenceClassification

< >

( config: HubertConfig )

参数

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

在 Hubert 模型顶部添加一个序列分类头(在池化输出上应用一个线性层),用于 SUPERB 关键词检测等任务。

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

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

forward

< >

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

参数

  • input_values (torch.Tensor,形状为 (batch_size, sequence_length)) — 输入原始语音波形的浮点值。可以通过将 .flac 或 .wav 音频文件加载为 list[float]、numpy.ndarray 或 torch.Tensor 类型的数组来获取这些值,例如 使用 torchcodec 库(pip install torchcodec)或 soundfile 库(pip install soundfile)。要将该数组准备为 input_values,应使用 AutoProcessor 进行填充并转换为 torch.Tensor 类型的张量。详情请参见 HubertProcessor.__call__。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

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

返回值

SequenceClassifierOutput 或 tuple(torch.Tensor)

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

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

单标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, HubertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/hubert-base-ls960")
>>> model = HubertForSequenceClassification.from_pretrained("facebook/hubert-base-ls960")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = HubertForSequenceClassification.from_pretrained("facebook/hubert-base-ls960", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

多标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, HubertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/hubert-base-ls960")
>>> model = HubertForSequenceClassification.from_pretrained("facebook/hubert-base-ls960", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = HubertForSequenceClassification.from_pretrained(
...     "facebook/hubert-base-ls960", num_labels=num_labels, problem_type="multi_label_classification"
... )

>>> labels = torch.sum(
...     torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).loss
Update on GitHub