# WavLM

## 개요

WavLM 모델은 Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei가 [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://huggingface.co/papers/2110.13900)에서 제안했습니다.

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

*자기 지도 학습(SSL)은 음성 인식에서 큰 성공을 거두었지만, 다른 음성 처리 작업에 대한 탐색은 제한적이었습니다. 음성 신호는 화자 신원, 부언어 정보, 발화 내용 등 다양한 측면의 정보를 포함하므로, 모든 음성 작업을 위한 범용 표현을 학습하는 것은 어려운 과제입니다. 이 논문에서는 풀스택 다운스트림 음성 작업을 해결하기 위한 새로운 사전 학습 모델인 WavLM을 제안합니다. WavLM은 HuBERT 프레임워크를 기반으로 구축되었으며, 발화 내용 모델링과 화자 신원 보존에 모두 중점을 둡니다. 먼저, Transformer 구조에 게이트드 상대 위치 편향을 적용하여 인식 작업에서의 성능을 향상시켰습니다. 화자 구분 능력을 높이기 위해, 추가적으로 겹치는 발화문을 비지도 방식으로 생성하여 모델 학습 과정에 통합하는 발화 혼합 학습 전략을 제안합니다. 마지막으로, 학습 데이터셋을 6만 시간에서 9.4만 시간으로 확장했습니다. WavLM Large는 SUPERB 벤치마크에서 최첨단 성능을 달성했으며, 각 대표 벤치마크에서 다양한 음성 처리 작업에 대해 상당한 성능 향상을 가져왔습니다.*

관련 체크포인트는 https://huggingface.co/models?other=wavlm에서 찾을 수 있습니다.

이 모델은 [patrickvonplaten](https://huggingface.co/patrickvonplaten)님이 기여했습니다. 저자의 코드는 [여기](https://github.com/microsoft/unilm/tree/master/wavlm)에서 찾을 수 있습니다.

## 사용 팁

- WavLM은 음성 신호의 원시 파형에 해당하는 float 배열을 입력으로 받는 음성 모델입니다. 특징 추출에는 [Wav2Vec2Processor](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.Wav2Vec2Processor)를 사용하세요.
- WavLM 모델은 connectionist temporal classification(CTC)을 사용하여 fine-tune할 수 있으며, 모델 출력을 [Wav2Vec2CTCTokenizer](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.Wav2Vec2CTCTokenizer)를 사용하여 디코딩해야 합니다.
- WavLM은 화자 인증, 화자 식별, 화자 분리 작업에서 특히 뛰어난 성능을 보입니다.

## 리소스

- [오디오 분류 작업 가이드](../tasks/audio_classification)
- [자동 음성 인식 작업 가이드](../tasks/asr)

## WavLMConfig[[transformers.WavLMConfig]]

#### transformers.WavLMConfig[[transformers.WavLMConfig]]

```python
transformers.WavLMConfig(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, is_encoder_decoder: bool = False, 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, vocab_size: int = 32, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout: float | int = 0.1, activation_dropout: float | int = 0.1, attention_dropout: float | int = 0.1, feat_proj_dropout: float | int = 0.0, final_dropout: float | int = 0.1, layerdrop: float | int = 0.1, initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, feat_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 = False, num_conv_pos_embeddings: int = 128, num_conv_pos_embedding_groups: int = 16, num_buckets: int = 320, max_bucket_distance: int = 800, do_stable_layer_norm: bool = False, apply_spec_augment: bool = True, 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, num_codevectors_per_group: int = 320, num_codevector_groups: int = 2, contrastive_logits_temperature: float = 0.1, num_negatives: int = 100, codevector_dim: int = 256, proj_codevector_dim: int = 256, diversity_loss_weight: float = 0.1, ctc_loss_reduction: str = 'mean', ctc_zero_infinity: bool = False, use_weighted_layer_sum: bool = False, classifier_proj_size: int = 256, tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500), tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1), tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1), xvector_output_dim: int = 512, num_ctc_classes: int = 80, pad_token_id: int | None = 0, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, add_adapter: bool = False, adapter_kernel_size: int = 3, adapter_stride: int = 2, num_adapter_layers: int = 3, output_hidden_size: int | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/configuration_wavlm.py#L27)

**매개변수:**

vocab_size (`int`, *선택 사항*, 기본값 `32`) : 모델의 어휘 크기입니다. `input_ids`로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.

hidden_size (`int`, *선택 사항*, 기본값 `768`) : 숨겨진 표현의 차원.

num_hidden_layers (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 숨겨진 레이어 수입니다.

num_attention_heads (`int`, *선택 사항*, 기본값 `12`) : Transformer decoder의 각 attention layer에 사용되는 attention head의 수입니다.

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`) : attention 확률에 적용할 dropout 비율입니다.

feat_proj_dropout (`float`, *선택 사항*, 기본값 0.0) : feature encoder 출력의 dropout 확률입니다.

final_dropout (`float`, *선택 사항*, 기본값 0.1) : [WavLMForCTC](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForCTC)의 최종 투영 레이어에 대한 dropout 확률입니다.

layerdrop (`Union[float, int]`, *선택 사항*, 기본값 `0.1`) : LayerDrop 확률입니다. 자세한 내용은 [LayerDrop 논문](see https://huggingface.co/papers/1909.11556)을 참고하세요.

initializer_range (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

layer_norm_eps (`float`, *선택 사항*, 기본값 `1e-05`) : layer normalization 레이어에서 사용되는 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, `선택 사항`, 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"`을(를) 지원합니다.

conv_dim (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(512, 512, 512, 512, 512, 512, 512)`) : 특징 인코더의 각 1D 합성곱 레이어의 입력 및 출력 채널 수를 정의하는 정수 튜플입니다. *conv_dim*의 길이는 1D 합성곱 레이어의 수를 정의합니다.

conv_stride (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(5, 2, 2, 2, 2, 2, 2)`) : 특징 인코더의 각 1D 컨볼루션 레이어의 스트라이드를 정의하는 정수 튜플입니다. *conv_stride*의 길이는 컨볼루션 레이어의 수를 정의하며 *conv_dim*의 길이와 일치해야 합니다.

conv_kernel (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(10, 3, 3, 3, 3, 3, 3)`) : 특징 인코더의 각 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 컨볼루션 위치 임베딩 레이어의 그룹 수.

num_buckets (`int`, *선택 사항*, 기본값 320) : 각 attention layer에 사용할 버킷의 수

max_bucket_distance (`int`, *선택 사항*, 기본값 800) : 최대 버킷 거리

do_stable_layer_norm (`bool`, *선택 사항*, 기본값 `False`) : Transformer 인코더의 *안정적인* layer norm 아키텍처를 적용할지 여부. `do_stable_layer_norm is True`는 attention 레이어 전에 layer norm을 적용하는 것을 의미하고, `do_stable_layer_norm is False`는 attention 레이어 후에 layer norm을 적용하는 것을 의미합니다.

apply_spec_augment (`bool`, *선택 사항*, 기본값 `True`) : feature encoder의 출력에 *SpecAugment* 데이터 증강을 적용할지 여부. 참고로 [SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition](https://huggingface.co/papers/1904.08779)를 확인하세요.

mask_time_prob (`float`, *optional*, 기본값 0.05) : 시간 축을 따라 각 특징 벡터가 마스킹될 벡터 스팬의 시작점으로 선택될 확률입니다. 시간 축을 따라 대략 `mask_time_prob * sequence_length // mask_time_length`개의 특징 벡터가 마스킹됩니다. 이는 `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 벡터가 마스킹될 벡터 스팬의 시작점으로 선택될 확률입니다. 대략 `mask_time_prob * hidden_size // mask_time_length`개의 feature 벡터가 time 축을 따라 마스킹됩니다. 이는 `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 축을 따라 벡터가 확장되는 길이.

num_codevectors_per_group (`int`, *선택 사항*, 기본값 320) : 각 양자화 코드북(그룹)의 항목 수

num_codevector_groups (`int`, *선택 사항*, 기본값 2) : product codevector quantization을 위한 codevector 그룹 수.

contrastive_logits_temperature (`float`, *선택 사항*, 기본값 0.1) : 대조적 손실(contrastive loss)의 온도 *kappa*입니다.

num_negatives (`int`, *선택 사항*, 기본값 100) : 대조적 손실에 사용할 음의 샘플 수.

codevector_dim (`int`, *선택 사항*, 기본값 256) : 양자화된 특징 벡터의 차원입니다.

proj_codevector_dim (`int`, *선택 사항*, 기본값 256) : 양자화된 특징과 transformer 특징 모두의 최종 투영 차원입니다.

diversity_loss_weight (`int`, *선택 사항*, 기본값 0.1) : 코드북 다양성 손실 구성 요소의 가중치입니다.

ctc_loss_reduction (`str`, *선택 사항*, 기본값 `mean`) : `torch.nn.CTCLoss`의 출력에 적용할 리덕션을 지정합니다. 학습 시에만 관련이 있습니다.

ctc_zero_infinity (`bool`, *선택 사항*, 기본값 `False`) : `torch.nn.CTCLoss`의 무한 손실과 관련 그래디언트를 0으로 설정할지 여부입니다. 무한 손실은 주로 입력이 대상과 정렬하기에 너무 짧을 때 발생합니다. [WavLMForCTC](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForCTC) 인스턴스를 학습하는 경우에만 관련이 있습니다.

use_weighted_layer_sum (`bool`, *선택 사항*, 기본값 `False`) : 학습된 가중치를 사용하여 레이어 출력의 가중 평균을 사용할지 여부. [WavLMForSequenceClassification](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForSequenceClassification) 인스턴스를 사용할 때만 관련이 있습니다.

classifier_proj_size (`int`, *선택 사항*, 기본값 256) : 분류를 위한 토큰 평균 풀링 전에 투영의 차원.

tdnn_dim (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(512, 512, 512, 512, 1500)`) : *XVector* 모델의 *TDNN* 모듈에서 각 1D 컨볼루션 레이어의 출력 채널 수를 정의하는 정수 튜플입니다. *tdnn_dim*의 길이는 *TDNN* 레이어의 수를 정의합니다.

tdnn_kernel (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(5, 3, 3, 1, 1)`) : *XVector* 모델의 *TDNN* 모듈에서 각 1D 컨볼루션 레이어의 커널 크기를 정의하는 정수 튜플입니다. *tdnn_kernel*의 길이는 *tdnn_dim*의 길이와 일치해야 합니다.

tdnn_dilation (`tuple[int]` 또는 `list[int]`, *선택 사항*, 기본값은 `(1, 2, 3, 1, 1)`) : *XVector* 모델의 *TDNN* 모듈에서 각 1D 컨볼루션 레이어의 팽창 계수를 정의하는 정수 튜플입니다. *tdnn_dilation*의 길이는 *tdnn_dim*의 길이와 일치해야 합니다.

xvector_output_dim (`int`, *선택 사항*, 기본값 512) : *XVector* 임베딩 벡터의 차원입니다.

num_ctc_classes (`int`, *선택 사항*, 기본값 80) : 음소 수준 CTC 손실에 사용할 클래스 수(음소 토큰 및 blank 토큰)를 지정합니다. [UniSpeechForPreTraining](/docs/transformers/main/ko/model_doc/unispeech#transformers.UniSpeechForPreTraining) 인스턴스를 사용할 때만 관련이 있습니다.

pad_token_id (`int`, *선택 사항*, 기본값 `0`) : 어휘에서 패딩에 사용되는 토큰 ID입니다.

bos_token_id (`int`, *선택 사항*, 기본값 `1`) : 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.

eos_token_id (`Union[int, list[int]]`, *선택*, 기본값 `2`) : 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

add_adapter (`bool`, *선택 사항*, 기본값 `False`) : Wav2Vec2 Encoder 위에 합성곱 신경망을 쌓을지 여부입니다. SpeechEncoderDecoder 모델에서 Wav2Vec2를 워밍 스타트하는 데 매우 유용할 수 있습니다.

adapter_kernel_size (`int`, *선택 사항*, 기본값 3) : 어댑터 네트워크의 컨볼루션 레이어 커널 크기. `add_adapter is True`인 경우에만 관련이 있습니다.

adapter_stride (`int`, *선택 사항*, 기본값 2) : 어댑터 네트워크의 컨볼루션 레이어 스트라이드. `add_adapter is True`인 경우에만 관련이 있습니다.

num_adapter_layers (`int`, *optional*, 기본값 3) : 어댑터 네트워크에서 사용할 컨볼루션 레이어의 수입니다. `add_adapter is True`인 경우에만 관련이 있습니다.

output_hidden_size (`int`, *선택 사항*) : 인코더 출력 레이어의 차원입니다. 정의되지 않으면 기본값은 *hidden-size*입니다. `add_adapter is True`인 경우에만 관련이 있습니다.

이것은 WavLMModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Wavlm 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [microsoft/wavlm-base](https://huggingface.co/microsoft/wavlm-base)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:

```python

```

예:

```python
>>> from transformers import WavLMConfig, WavLMModel

>>> # Initializing a WavLM facebook/wavlm-base-960h style configuration
>>> configuration = WavLMConfig()

>>> # Initializing a model (with random weights) from the facebook/wavlm-base-960h style configuration
>>> model = WavLMModel(configuration)

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

## WavLMModel[[transformers.WavLMModel]]

#### transformers.WavLMModel[[transformers.WavLMModel]]

```python
transformers.WavLMModel(config: WavLMConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L951)

**매개변수:**

config ([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Wavlm Model입니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.WavLMModel.forward]]

```python
forward(input_values: typing.Optional[torch.Tensor], attention_mask: typing.Optional[torch.Tensor] = None, mask_time_indices: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1025)

**매개변수:**

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](/docs/transformers/main/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 [Wav2Vec2Processor.__call__()](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.Wav2Vec2Processor.__call__)를 참조하세요.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

mask_time_indices (`torch.BoolTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 대조적 손실을 위해 추출된 특징을 가리기 위한 인덱스입니다. 학습 모드일 때, 모델은 *config.proj_codevector_dim* 공간에서 가려진 추출된 특징을 예측하도록 학습합니다.

**반환값:** [Wav2Vec2BaseModelOutput](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.modeling_outputs.Wav2Vec2BaseModelOutput) 또는 `tuple(torch.Tensor)`

구성([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig))과 입력에 따라 다양한 요소를 포함하는 [Wav2Vec2BaseModelOutput](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.modeling_outputs.Wav2Vec2BaseModelOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[WavLMModel](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMModel)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.
- **extract_features** (`torch.Tensor`, shape `(batch_size, sequence_length, conv_dim[-1])`) -- 모델의 마지막 컨볼루션 레이어에서 추출된 특징 벡터의 시퀀스.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`일 때 반환) -- shape가 `(batch_size, sequence_length, hidden_size)`인 `torch.Tensor`의 튜플 (임베딩 출력 1개 + 각 레이어 출력 1개).

  각 레이어의 출력에서 모델의 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 가중치입니다.

## WavLMForCTC[[transformers.WavLMForCTC]]

#### transformers.WavLMForCTC[[transformers.WavLMForCTC]]

```python
transformers.WavLMForCTC(config: WavLMConfig, target_lang: str | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1076)

**매개변수:**

config ([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

target_lang (`str`, *선택 사항*) : 어댑터 가중치의 언어 ID입니다. 어댑터 가중치는 adapter..safetensors 또는 adapter..bin 형식으로 저장됩니다. 어댑터를 사용하는 [WavLMForCTC](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForCTC) 인스턴스를 사용할 때만 관련이 있습니다. 기본값은 'eng'입니다.

`language modeling` 헤드가 위에 있는 Connectionist Temporal Classification(CTC)용 WavLM 모델.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.WavLMForCTC.forward]]

```python
forward(input_values: typing.Optional[torch.Tensor], attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1145)

**매개변수:**

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](/docs/transformers/main/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 [Wav2Vec2Processor.__call__()](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.Wav2Vec2Processor.__call__)를 참조하세요.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

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](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.CausalLMOutput) 또는 `tuple(torch.Tensor)`

구성([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig))과 입력에 따라 다양한 요소를 포함하는 [CausalLMOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.CausalLMOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[WavLMForCTC](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForCTC)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(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 가중치입니다.

예:

```python
>>> from transformers import AutoProcessor, WavLMForCTC
>>> 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("microsoft/wavlm-base")
>>> model = WavLMForCTC.from_pretrained("microsoft/wavlm-base")

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

## WavLMForSequenceClassification[[transformers.WavLMForSequenceClassification]]

#### transformers.WavLMForSequenceClassification[[transformers.WavLMForSequenceClassification]]

```python
transformers.WavLMForSequenceClassification(config: WavLMConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1203)

**매개변수:**

config ([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

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

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.WavLMForSequenceClassification.forward]]

```python
forward(input_values: typing.Optional[torch.Tensor], attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1236)

**매개변수:**

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](/docs/transformers/main/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 `WavLMProcessor.__call__`를 참조하세요.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 오차)이 계산되고, `config.num_labels > 1`인 경우 분류 손실(교차 엔트로피)이 계산됩니다.

**반환값:** [SequenceClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) 또는 `tuple(torch.Tensor)`

구성([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig))과 입력에 따라 다양한 요소를 포함하는 [SequenceClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[WavLMForSequenceClassification](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForSequenceClassification)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(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 가중치입니다.

단일 레이블 분류의 예시:

```python
>>> import torch
>>> from transformers import AutoTokenizer, WavLMForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/wavlm-base")
>>> model = WavLMForSequenceClassification.from_pretrained("microsoft/wavlm-base")

>>> 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 = WavLMForSequenceClassification.from_pretrained("microsoft/wavlm-base", num_labels=num_labels)

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

다중 레이블 분류의 예시:

```python
>>> import torch
>>> from transformers import AutoTokenizer, WavLMForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/wavlm-base")
>>> model = WavLMForSequenceClassification.from_pretrained("microsoft/wavlm-base", 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 = WavLMForSequenceClassification.from_pretrained(
...     "microsoft/wavlm-base", 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
```

## WavLMForAudioFrameClassification[[transformers.WavLMForAudioFrameClassification]]

#### transformers.WavLMForAudioFrameClassification[[transformers.WavLMForAudioFrameClassification]]

```python
transformers.WavLMForAudioFrameClassification(config: WavLMConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1296)

**매개변수:**

config ([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

Wavlm 모델은 화자 분리(Speaker Diarization)와 같은 작업을 위해 프레임 분류 헤드를 최상단에 배치합니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.WavLMForAudioFrameClassification.forward]]

```python
forward(input_values: typing.Optional[torch.Tensor], attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1328)

**매개변수:**

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](/docs/transformers/main/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 `WavLMProcessor.__call__`를 참조하세요.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 오차)이 계산되고, `config.num_labels > 1`인 경우 분류 손실(교차 엔트로피)이 계산됩니다.

**반환값:** [TokenClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) 또는 `tuple(torch.Tensor)`

구성([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig))과 입력에 따라 다양한 요소를 포함하는 [TokenClassifierOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[WavLMForAudioFrameClassification](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForAudioFrameClassification)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`가 제공될 때 반환됨) -- 분류 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.num_labels)`) -- 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 가중치입니다.

예:

```python
>>> from transformers import AutoFeatureExtractor, WavLMForAudioFrameClassification
>>> 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

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base")
>>> model = WavLMForAudioFrameClassification.from_pretrained("microsoft/wavlm-base")

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

>>> probabilities = torch.sigmoid(logits[0])
>>> # labels is a one-hot array of shape (num_frames, num_speakers)
>>> labels = (probabilities > 0.5).long()
>>> labels[0].tolist()
...
```

## WavLMForXVector[[transformers.WavLMForXVector]]

#### transformers.WavLMForXVector[[transformers.WavLMForXVector]]

```python
transformers.WavLMForXVector(config: WavLMConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1419)

**매개변수:**

config ([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

WavLM 모델은 화자 인증과 같은 작업을 위해 XVector 특징 추출 헤드를 최상단에 배치하여 사용합니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.WavLMForXVector.forward]]

```python
forward(input_values: typing.Optional[torch.Tensor], attention_mask: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wavlm/modeling_wavlm.py#L1469)

**매개변수:**

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](/docs/transformers/main/ko/model_doc/auto#transformers.AutoProcessor)를 사용해야 합니다. 자세한 내용은 `WavLMProcessor.__call__`를 참조하세요.

attention_mask (`torch.Tensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크입니다. `[0, 1]`에서 선택된 마스크 값: - **마스크되지 않은** 토큰은 1, - **마스크된** 토큰은 0. [attention 마스크란?](../glossary#attention-mask)

labels (`torch.LongTensor`, shape `(batch_size,)`, *선택 사항*) : 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨. 인덱스는 `[0, ..., config.num_labels - 1]` 범위에 있어야 합니다. `config.num_labels == 1`인 경우 회귀 손실(평균 제곱 오차)이 계산되고, `config.num_labels > 1`인 경우 분류 손실(교차 엔트로피)이 계산됩니다.

**반환값:** [XVectorOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.XVectorOutput) 또는 `tuple(torch.Tensor)`

구성([WavLMConfig](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMConfig))과 입력에 따라 다양한 요소를 포함하는 [XVectorOutput](/docs/transformers/main/ko/main_classes/output#transformers.modeling_outputs.XVectorOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[WavLMForXVector](/docs/transformers/main/ko/model_doc/wavlm#transformers.WavLMForXVector)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*, `labels`가 제공될 때 반환됨) -- 분류 손실.
- **logits** (shape `(batch_size, config.xvector_output_dim)`인 `torch.Tensor`) -- AMSoftmax 적용 전 분류 hidden states.
- **embeddings** (`torch.Tensor`, shape `(batch_size, config.xvector_output_dim)`) -- 벡터 유사도 기반 검색에 사용되는 발화 임베딩.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`일 때 반환) -- shape가 `(batch_size, sequence_length, hidden_size)`인 `torch.Tensor`의 튜플 (임베딩 출력 1개 + 각 레이어 출력 1개).

  각 레이어의 출력에서 모델의 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 가중치입니다.

예:

```python
>>> from transformers import AutoFeatureExtractor, WavLMForXVector
>>> 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

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base")
>>> model = WavLMForXVector.from_pretrained("microsoft/wavlm-base")

>>> # audio file is decoded on the fly
>>> inputs = feature_extractor(
...     [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True
... )
>>> with torch.no_grad():
...     embeddings = model(**inputs).embeddings

>>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu()

>>> # the resulting embeddings can be used for cosine similarity-based retrieval
>>> cosine_sim = torch.nn.CosineSimilarity(dim=-1)
>>> similarity = cosine_sim(embeddings[0], embeddings[1])
>>> threshold = 0.7  # the optimal threshold is dataset-dependent
>>> if similarity < threshold:
...     print("Speakers are not the same!")
>>> round(similarity.item(), 2)
...
```

