Transformers documentation

SEW-D

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

이 모델은 2021-09-14에 HF papers에 게시되었으며, 2021-10-15에 Hugging Face Transformers에 기여되었습니다.

SEW-D

개요

SEW-D(Squeezed and Efficient Wav2Vec with Disentangled attention)는 Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi가 음성 인식 무감독 사전 학습의 성능-효율 트레이드오프에서 제안했습니다.

해당 논문의 초록은 다음과 같습니다:

이 논문은 자동 음성 인식(ASR)을 위한 사전 학습 모델의 성능-효율성 트레이드오프에 대한 연구입니다. wav2vec 2.0에 초점을 맞추고, 모델 성능과 효율성 모두에 영향을 미치는 여러 아키텍처 설계를 형식화했습니다. 이러한 관찰을 종합하여, 다양한 학습 설정에서 성능과 효율성 두 측면 모두에서 상당한 개선을 보여주는 사전 학습 모델 아키텍처인 SEW(Squeezed and Efficient Wav2vec)를 소개합니다. 예를 들어, LibriSpeech의 100h-960h 반지도 학습 설정에서 SEW는 wav2vec 2.0 대비 1.9배의 추론 속도 향상을 달성하면서 단어 오류율을 13.5% 상대적으로 줄였습니다. 유사한 추론 시간에서 SEW는 모델 크기에 따라 단어 오류율을 25-50% 줄였습니다.

이 모델은 anton-l님이 기여했습니다.

사용 팁

  • SEW-D는 음성 신호의 원시 파형에 해당하는 float 배열을 입력으로 받는 음성 모델입니다.
  • SEWDForCTC는 connectionist temporal classification(CTC)을 사용하여 fine-tuning되며, 모델 출력을 Wav2Vec2CTCTokenizer를 사용하여 디코딩해야 합니다.

리소스

SEWDConfig

class transformers.SEWDConfig

< >

( 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 = 3072squeeze_factor: int = 2max_position_embeddings: int = 512position_buckets: int = 256share_att_key: bool = Truerelative_attention: bool = Truepos_att_type: list[str] | tuple[str, ...] = ('p2c', 'c2p')norm_rel_ebd: str = 'layer_norm'hidden_act: str = 'gelu_python'hidden_dropout: float | int = 0.1activation_dropout: float | int = 0.1attention_dropout: float | int = 0.1feat_proj_dropout: float | int = 0.0final_dropout: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-07feature_layer_norm_eps: float = 1e-05feat_extract_norm: str = 'group'feat_extract_activation: str = 'gelu'conv_dim: list[int] | tuple[int, ...] = (64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)conv_stride: list[int] | tuple[int, ...] = (5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)conv_kernel: list[int] | tuple[int, ...] = (10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)conv_bias: bool = Falsenum_conv_pos_embeddings: int = 128num_conv_pos_embedding_groups: int = 16apply_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 = 'mean'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로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 768) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 12) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • intermediate_size (int, 선택 사항, 기본값 3072) — MLP 표현의 차원입니다.
  • squeeze_factor (int, 선택 사항, 기본값 2) — 인코더 이후 시퀀스 길이의 다운샘플링 계수 및 트랜스포머 이후 업샘플링 계수입니다.
  • max_position_embeddings (int, 선택 사항, 기본값 512) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • position_buckets (int, 선택 사항, 기본값 256) — 상대 위치 임베딩의 최대 크기입니다.
  • share_att_key (bool, 선택 사항, 기본값 True) — c2p 및 p2c와 attention key를 공유할지 여부.
  • relative_attention (bool, 선택, 기본값 True) — 상대 위치 인코딩을 사용할지 여부입니다.
  • pos_att_type (tuple[str], 선택 사항, 기본값 ("p2c", "c2p")) — 상대 위치 주의력(relative position attention)의 유형입니다. ("p2c", "c2p")의 조합으로 사용할 수 있으며, 예를 들어 ("p2c"), ("p2c", "c2p"), ("p2c", "c2p") 등이 있습니다.
  • norm_rel_ebd (str, 선택 사항, 기본값 "layer_norm") — 상대 임베딩에 layer norm을 사용할지 여부(사용 시 "layer_norm")
  • hidden_act (str, 선택 사항, 기본값 gelu_python) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "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) — Attention 확률에 적용할 dropout 비율입니다.
  • feat_proj_dropout (float, 선택 사항, 기본값 0.0) — 피처 인코더 출력의 dropout 확률입니다.
  • final_dropout (float, 선택 사항, 기본값 0.1) — SEWDForCTC의 최종 투영 레이어에 적용할 dropout 확률입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-07) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • feature_layer_norm_eps (float, 선택 사항, 기본값 1e-5) — 피처 인코더 이후의 레이어 정규화에 사용되는 epsilon입니다.
  • feat_extract_norm (str, 선택 사항, 기본값 "group") — feature encoder의 1D convolutional layer에 적용할 norm입니다. 첫 번째 1D convolutional layer에만 group normalization을 적용하려면 "group", 모든 1D convolutional layer에 layer normalization을 적용하려면 "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] 또는 list[int], 선택 사항, 기본값 (64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)) — 피처 인코더의 각 1D 컨볼루션 레이어의 입력 및 출력 채널 수를 정의하는 정수 튜플입니다. conv_dim의 길이는 1D 컨볼루션 레이어의 수를 정의합니다.
  • conv_stride (tuple[int] 또는 list[int], 선택 사항, 기본값 (5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)) — 피처 인코더의 각 1D 컨볼루션 레이어의 스트라이드를 정의하는 정수 튜플입니다. conv_stride의 길이는 컨볼루션 레이어의 수를 정의하며, conv_dim의 길이와 일치해야 합니다.
  • conv_kernel (tuple[int] 또는 list[int], 선택 사항, 기본값은 (10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)) — 피처 인코더의 각 1D 컨볼루션 레이어의 커널 크기를 정의하는 정수 튜플입니다. conv_kernel의 길이는 컨볼루션 레이어의 수를 정의하며, conv_dim의 길이와 일치해야 합니다.
  • conv_bias (bool, 선택 사항, 기본값 False) — 1D 컨볼루션 레이어에 bias가 있는지 여부.
  • num_conv_pos_embeddings (int, 선택 사항, 기본값 128) — 컨볼루션 위치 임베딩의 개수입니다. 1차원 컨볼루션 위치 임베딩 레이어의 커널 크기를 정의합니다.
  • num_conv_pos_embedding_groups (int, 선택 사항, 기본값 16) — 1D 합성곱 위치 임베딩 레이어의 그룹 수.
  • apply_spec_augment (bool, 선택 사항, 기본값 True) — feature encoder의 출력에 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_prob와 무관하게, 시간축의 각 시간 단계에서 mask_feature_length 길이의 최소 마스크 수입니다. "mask_time_prob*len(time_axis)/mask_time_length < mask_time_min_masks"인 경우에만 관련이 있습니다.
  • mask_feature_prob (float, 선택 사항, 기본값 0.0) — feature 축을 따라 모든 feature 벡터 중 마스킹될 비율(0에서 1 사이). 마스킹 절차는 해당 축에 대해 ”mask_feature_problen(feature_axis)/mask_time_length”개의 독립적인 마스크를 생성합니다. 마스킹될 벡터 스팬의 시작점으로 선택될 각 feature 벡터의 확률로 추론한다면, 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) — feature 축을 따라 마스킹될 모든 feature 벡터의 비율(0에서 1 사이). 마스킹 절차는 해당 축에 대해 mask_feature_prob*len(feature_axis)/mask_time_length개의 독립적인 마스크를 생성합니다. 각 feature 벡터가 마스킹될 벡터 스팬의 시작점으로 선택될 확률로부터 추론한다면, mask_feature_prob는 prob_vector_start*mask_feature_length여야 합니다. 겹침(overlap)으로 인해 실제 마스킹된 벡터의 비율이 감소할 수 있습니다. 이는 apply_spec_augment가 True인 경우에만 관련이 있습니다.
  • mask_feature_length (int, 선택 사항, 기본값 10) — feature 축을 따라 벡터가 확장되는 길이입니다.
  • mask_feature_min_masks (int, 선택 사항, 기본값 0), — mask_feature_prob와 무관하게, 각 시간 단계마다 feature 축을 따라 생성되는 mask_feature_length 길이의 mask의 최소 개수입니다. “mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks”인 경우에만 관련이 있습니다.
  • diversity_loss_weight (int, 선택 사항, 기본값 0.1) — 코드북 다양성 손실 구성 요소의 가중치입니다.
  • ctc_loss_reduction (str, 선택 사항, 기본값 mean) — torch.nn.CTCLoss의 출력에 적용할 reduction 방식을 지정합니다. 학습 시에만 관련이 있습니다.
  • ctc_zero_infinity (bool, 선택 사항, 기본값 False) — torch.nn.CTCLoss의 무한 손실과 관련 그래디언트를 0으로 설정할지 여부입니다. 무한 손실은 주로 입력이 대상과 정렬될 수 없을 정도로 너무 짧을 때 발생합니다. SEWDForCTC 인스턴스를 학습하는 경우에만 관련이 있습니다.
  • use_weighted_layer_sum (bool, 선택 사항, 기본값 False) — 학습된 가중치를 사용하여 레이어 출력의 가중 평균을 사용할지 여부입니다. Wav2Vec2ForSequenceClassification 인스턴스를 사용할 때만 관련이 있습니다.
  • classifier_proj_size (int, 선택 사항, 기본값 256) — 분류를 위한 토큰 평균 풀링 전에 투영되는 차원.
  • pad_token_id (int, 선택 사항, 기본값 0) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항, 기본값 1) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택 사항, 기본값 2) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

이것은 Sew DModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Sew D 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 BAAI/seggpt-vit-large와 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import SEWDConfig, SEWDModel

>>> # Initializing a SEW-D asapp/sew-d-tiny-100k style configuration
>>> configuration = SEWDConfig()

>>> # Initializing a model (with random weights) from the asapp/sew-d-tiny-100k style configuration
>>> model = SEWDModel(configuration)

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

SEWDModel

class transformers.SEWDModel

< >

( config: SEWDConfig )

매개변수

  • config (SEWDConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

특정 헤드가 없는 맨 Sew D 모델은 원시 hidden-states를 출력합니다.

이 모델은 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] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)

매개변수

  • input_values (torch.Tensor of shape (batch_size, sequence_length), optional) — 입력 원시 음성 파형의 부동 소수점 값. .flac 또는 .wav 오디오 파일을 list[float], numpy.ndarray 또는 torch.Tensor 타입의 배열로 로드하여 값을 얻을 수 있습니다. 예를 들어 torchcodec 라이브러리(pip install torchcodec) 또는 soundfile 라이브러리(pip install soundfile)를 통해 수행할 수 있습니다. input_values 배열을 준비하려면 패딩 및 torch.Tensor 타입의 텐서 변환을 위해 AutoProcessor를 사용해야 합니다. 자세한 내용은 Wav2Vec2Processor.call()를 참조하세요.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • mask_time_indices (torch.BoolTensor, shape (batch_size, sequence_length), 선택 사항) — contrastive loss를 위해 추출된 features를 mask할 인덱스입니다. training mode일 때, 모델은 config.proj_codevector_dim 공간에서 mask된 추출 features를 예측하도록 학습합니다.

반환값

BaseModelOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 BaseModelOutput (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(SEWDConfig)과 입력에 따라 다양한 요소를 포함합니다.

SEWDModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

SEWDForCTC

class transformers.SEWDForCTC

< >

( config: SEWDConfigtarget_lang: str | None = None )

매개변수

  • config (SEWDConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
  • target_lang (str, 선택 사항) — 어댑터 가중치의 언어 ID입니다. 어댑터 가중치는 adapter..safetensors 또는 adapter..bin 형식으로 저장됩니다. 어댑터를 사용하는 SEWDForCTC 인스턴스를 사용할 때만 관련이 있습니다. 기본값은 ‘eng’입니다.

language modeling 헤드가 위에 있는 Connectionist Temporal Classification(CTC)용 SEW-D 모델.

이 모델은 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 of shape (batch_size, sequence_length), optional) — 입력 원시 음성 파형의 부동 소수점 값. .flac 또는 .wav 오디오 파일을 list[float], numpy.ndarray 또는 torch.Tensor 타입의 배열로 로드하여 값을 얻을 수 있습니다. 예를 들어 torchcodec 라이브러리(pip install torchcodec) 또는 soundfile 라이브러리(pip install soundfile)를 통해 수행할 수 있습니다. input_values 배열을 준비하려면 패딩 및 torch.Tensor 타입의 텐서 변환을 위해 AutoProcessor를 사용해야 합니다. 자세한 내용은 Wav2Vec2Processor.call()를 참조하세요.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • labels (torch.LongTensor, shape (batch_size, target_length), 선택 사항) — Connectionist temporal classification에 사용할 라벨입니다. 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인 경우에도 동일합니다. 구성(SEWDConfig)과 입력에 따라 다양한 요소를 포함합니다.

SEWDForCTC의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 언어 모델링 손실(다음 토큰 예측용).

  • logits (torch.Tensor, shape (batch_size, sequence_length, config.vocab_size)) — 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> from transformers import AutoProcessor, SEWDForCTC
>>> 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("BAAI/seggpt-vit-large")
>>> model = SEWDForCTC.from_pretrained("BAAI/seggpt-vit-large")

>>> # 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)
...

SEWDForSequenceClassification

class transformers.SEWDForSequenceClassification

< >

( config: SEWDConfig )

매개변수

  • config (SEWDConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

SUPERB Keyword Spotting와 같은 작업을 위해, 풀링된 출력 위에 시퀀스 분류 헤드(선형 레이어)를 적용한 SEWD 모델

이 모델은 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, shape (batch_size, sequence_length)) — 입력 원시 음성 파형의 부동소수점 값. .flac 또는 .wav 오디오 파일을 list[float] 타입의 배열, numpy.ndarray 또는 torch.Tensor로 로드하여 값을 얻을 수 있습니다. 예를 들어 torchcodec 라이브러리(pip install torchcodec) 또는 soundfile 라이브러리(pip install soundfile)를 사용할 수 있습니다. 배열을 input_values로 준비하려면 패딩 및 torch.Tensor 타입의 텐서 변환을 위해 AutoProcessor를 사용해야 합니다. 자세한 내용은 SEWDProcessor.__call__를 참조하세요.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • labels (torch.LongTensor, shape (batch_size,), 선택 사항) — 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다. config.num_labels == 1인 경우 회귀 손실(Mean-Square loss)이 계산되고, config.num_labels > 1인 경우 분류 손실(Cross-Entropy)이 계산됩니다.

반환값

SequenceClassifierOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 SequenceClassifierOutput입니다. return_dict=False가 전달되거나 config.return_dict=False인 경우, 구성(SEWDConfig)과 입력에 따라 다양한 요소로 구성됩니다.

SEWDForSequenceClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.

  • logits (torch.Tensor, shape (batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

단일 레이블 분류의 예시:

>>> import torch
>>> from transformers import AutoTokenizer, SEWDForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("BAAI/seggpt-vit-large")
>>> model = SEWDForSequenceClassification.from_pretrained("BAAI/seggpt-vit-large")

>>> 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 = SEWDForSequenceClassification.from_pretrained("BAAI/seggpt-vit-large", num_labels=num_labels)

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

다중 레이블 분류의 예시:

>>> import torch
>>> from transformers import AutoTokenizer, SEWDForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("BAAI/seggpt-vit-large")
>>> model = SEWDForSequenceClassification.from_pretrained("BAAI/seggpt-vit-large", 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 = SEWDForSequenceClassification.from_pretrained(
...     "BAAI/seggpt-vit-large", 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