# Whisper

[Whisper](https://huggingface.co/papers/2212.04356)는 680,000시간의 라벨이 붙은 오디오 데이터로 사전 학습된 인코더-디코더(시퀀스-투-시퀀스) transformer입니다. 이 규모의 사전 학습 데이터는 영어를 비롯한 여러 언어의 오디오 작업에서 zero-shot 성능을 가능하게 합니다. 디코더는 추가적인 fine-tuning 없이 인코더가 학습한 음성 표현을 텍스트와 같은 유용한 출력으로 매핑할 수 있도록 합니다. Whisper는 설치 후 바로 사용할 수 있습니다.

모든 원본 Whisper 체크포인트는 [Whisper](https://huggingface.co/collections/openai/whisper-release-6501bba2cf999715fd953013) 컬렉션에서 찾을 수 있습니다.

> [!TIP]
> Whisper를 다양한 오디오 작업에 적용하는 방법에 대한 추가 예제는 오른쪽 사이드바의 Whisper 모델에서 확인하세요.
>
> `use_kernels=True`를 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained)에 설정하여 Hub의 최적화 커널로 지원되는 레이어를 대체합니다. 자세한 내용은 [커널 로딩](../kernel_doc/loading_kernels)을 참고하세요.

아래 예제는 [Pipeline](/docs/transformers/main/ko/main_classes/pipelines#transformers.Pipeline) 또는 [AutoModel](/docs/transformers/main/ko/model_doc/auto#transformers.AutoModel) 클래스를 사용하여 음성에서 텍스트로 자동으로 전사하는 방법을 보여줍니다.

```python
from transformers import pipeline

pipeline = pipeline(
    task="automatic-speech-recognition",
    model="openai/whisper-large-v3-turbo",
    device=0
)
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
```

```python
# pip install datasets
from datasets import load_dataset

from transformers import AutoProcessor, WhisperForConditionalGeneration

processor = AutoProcessor.from_pretrained(
    "openai/whisper-large-v3-turbo",
)
model = WhisperForConditionalGeneration.from_pretrained(
    "openai/whisper-large-v3-turbo",
    device_map="auto",
    attn_implementation="sdpa"
)

ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
audio_sample = ds[0]["audio"]

input_features = processor(
    audio_sample["array"],
    sampling_rate=audio_sample["sampling_rate"],
    return_tensors="pt"
).input_features
input_features = input_features.to(model.device, dtype=model.dtype)

predicted_ids = model.generate(input_features, cache_implementation="static")
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
transcription[0]
```

## The input is a single word "Notes".

참고

- Whisper는 추론을 위해 커스텀 `generate`를 사용하므로, 아래 문서를 꼭 확인하세요.
- [WhisperProcessor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperProcessor)는 오디오를 준비하고 예측된 id를 텍스트로 복원하는 데 사용할 수 있습니다.

## WhisperConfig[[transformers.WhisperConfig]]

#### transformers.WhisperConfig[[transformers.WhisperConfig]]

```python
transformers.WhisperConfig(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, 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, is_encoder_decoder: bool = True, vocab_size: int = 51865, num_mel_bins: int = 80, encoder_layers: int = 4, encoder_attention_heads: int = 6, decoder_layers: int = 4, decoder_attention_heads: int = 6, decoder_ffn_dim: int = 1536, encoder_ffn_dim: int = 1536, encoder_layerdrop: float | int = 0.0, decoder_layerdrop: float | int = 0.0, decoder_start_token_id: int = 50257, use_cache: bool = True, activation_function: str = 'gelu', d_model: int = 384, dropout: float | int = 0.0, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, init_std: float = 0.02, scale_embedding: bool = False, max_source_positions: int = 1500, max_target_positions: int = 448, pad_token_id: int | None = 50256, bos_token_id: int | None = 50256, eos_token_id: int | list[int] | None = 50256, suppress_tokens: list | None = None, begin_suppress_tokens: list[int] | tuple[int, ...] | None = (220, 50256), use_weighted_layer_sum: bool = False, classifier_proj_size: int = 256, apply_spec_augment: bool = False, 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, mask_feature_min_masks: int = 0, median_filter_width: int = 7, tie_word_embeddings: bool = True)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/configuration_whisper.py#L50)

**매개변수:**

is_encoder_decoder (`bool`, *선택 사항*, 기본값 `True`) : 모델이 인코더/디코더로 사용되는지 여부.

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

num_mel_bins (`int`, *선택 사항*, 기본값 `80`) : 각 입력 프레임에 사용되는 mel 특징의 수입니다. `AutoFeatureExtractor` 클래스에서 사용된 값과 일치해야 합니다.

encoder_layers (`int`, *선택 사항*, 기본값 `4`) : Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면 `num_layers`와 동일한 값을 사용합니다.

encoder_attention_heads (`int`, *선택 사항*, 기본값 `6`) : Transformer 인코더의 각 어텐션 레이어에 사용할 어텐션 헤드 수입니다.

decoder_layers (`int`, *선택 사항*, 기본값 `4`) : Transformer 디코더의 숨겨진 레이어 수. 설정하지 않으면 `num_layers`와 동일한 값을 사용합니다.

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

decoder_ffn_dim (`int`, *선택 사항*, 기본값 `1536`) : 디코더의 "intermediate"(일반적으로 feed-forward라고도 함) 레이어의 차원.

encoder_ffn_dim (`int`, *선택 사항*, 기본값 `1536`) : 인코더의 "중간"(일반적으로 feed-forward라고도 함) 레이어의 차원.

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

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

decoder_start_token_id (`int`, *선택 사항*, 기본값 `50257`) : 인코더-디코더 모델이 `bos`와 다른 토큰으로 디코딩을 시작하는 경우, 해당 토큰의 id입니다.

use_cache (`bool`, *선택 사항*, 기본값 `True`) : 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음). `config.is_decoder=True`인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다.

activation_function (`str`, *선택 사항*, 기본값 `gelu`) : 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등이 있습니다.

d_model (`int`, *선택 사항*, 기본값 `384`) : 인코더 레이어와 풀러 레이어의 크기입니다.

dropout (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 모든 dropout 레이어에 적용되는 비율입니다.

attention_dropout (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : attention 확률에 적용할 dropout 비율입니다.

activation_dropout (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : 완전 연결 계층 내부 활성화에 적용되는 dropout 비율입니다.

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

scale_embedding (`bool`, *선택 사항*, 기본값 `False`) : 임베딩을 sqrt(d_model)로 나누어 스케일링할지 여부.

max_source_positions (`int`, *선택 사항*, 기본값 1500) : 이 모델이 사용될 수 있는 log-mel filter-bank feature의 최대 시퀀스 길이입니다.

max_target_positions (`int`, *선택 사항*, 기본값 448) : 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다. 혹시 모를 상황에 대비하여 일반적으로 큰 값(예: 512, 1024 또는 2048)으로 설정합니다.

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

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

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

suppress_tokens (`list[int]`, *optional*) : `generate` 함수의 logit processor에서 사용되는 비음성(non-speech) 토큰을 포함하는 목록입니다. NON_SPEECH_TOKENS와 NON_SPEECH_TOKENS_MULTI는 각각 `english-only` 모델과 `multilingual` 모델에 해당합니다.

begin_suppress_tokens (`list[int]`, *선택 사항*, 기본값 `[220,50256]`) : 샘플링 과정의 시작 부분에 억제될 토큰을 포함하는 목록입니다. `" "` (`blank_token_id`) 토큰과 `eos_token_id`로 초기화됩니다.

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

classifier_proj_size (`int`, *선택 사항*, 기본값 256) : 분류를 위한 토큰 평균 풀링 전 투영의 차원. [WhisperForAudioClassification](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperForAudioClassification) 인스턴스를 사용할 때만 관련이 있습니다.

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

mask_time_prob (`float`, *선택 사항*, 기본값 0.05) : 시간 축을 따라 모든 특징 벡터 중 마스킹될 비율(0에서 1 사이). 마스킹 절차는 해당 축에 대해 `mask_time_prob*len(time_axis)/mask_time_length`개의 독립적인 마스킹을 생성합니다. 마스킹될 벡터 스팬의 시작점으로 선택될 각 특징 벡터의 확률로부터 추론한다면, *mask_time_prob*은 `prob_vector_start*mask_time_length`여야 합니다. 겹침으로 인해 실제 마스킹된 벡터의 비율이 감소할 수 있습니다. 이는 `apply_spec_augment == 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_prob*len(feature_axis)/mask_time_length`개의 독립적인 마스크를 생성합니다. 각 feature 벡터가 마스킹될 벡터 스팬의 시작점으로 선택될 확률로부터 추론한다면, *mask_feature_prob*은 `prob_vector_start*mask_feature_length`여야 합니다. 겹침(overlap)으로 인해 실제 마스킹된 벡터의 비율이 감소할 수 있습니다. 이는 `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`인 경우에만 관련이 있습니다.

median_filter_width (`int`, *선택 사항*, 기본값 7) : 토큰 타임스탬프를 계산할 때 크로스 어텐션 출력을 부드럽게 만들기 위해 사용되는 중앙값 필터의 폭입니다. 홀수여야 합니다.

tie_word_embeddings (`bool`, *선택 사항*, 기본값 `True`) : 모델의 `tied_weights_keys` 매핑에 따라 가중치 임베딩을 묶을지 여부.

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

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

예:

```python
>>> from transformers import WhisperConfig, WhisperModel

>>> # Initializing a Whisper tiny style configuration
>>> configuration = WhisperConfig()

>>> # Initializing a model (with random weights) from the tiny style configuration
>>> model = WhisperModel(configuration)

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

## WhisperTokenizer[[transformers.WhisperTokenizer]]

#### transformers.WhisperTokenizer[[transformers.WhisperTokenizer]]

```python
transformers.WhisperTokenizer(vocab: str | dict[str, int] | None = None, merges = None, normalizer_file = None, unk_token = '<|endoftext|>', bos_token = '<|endoftext|>', eos_token = '<|endoftext|>', add_prefix_space = False, language = None, task = None, predict_timestamps = False, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L163)

**매개변수:**

vocab_file (`str`, *선택 사항*) : 어휘 파일의 경로.

merges_file (`str`, *선택 사항*) : merges 파일의 경로.

normalizer_file (`str`, *선택 사항*) : normalizer_file 파일의 경로.

tokenizer_file (`str`, *선택 사항*) : 토크나이저를 로드하는 데 필요한 모든 정보가 포함된 [tokenizers](https://github.com/huggingface/tokenizers) 파일(일반적으로 .json 확장자를 가짐)의 경로

unk_token (`str`, *선택 사항*, 기본값 `"<|endoftext|>"`) : 알려지지 않은 토큰. 어휘에 없는 토큰은 ID로 변환할 수 없으므로 대신 이 토큰으로 설정됩니다.

bos_token (`str`, *선택 사항*, 기본값 `"<|endoftext|>"`) : 시퀀스의 시작 토큰입니다. 생성 시 `decoder_start_token_id`를 사용하여 첫 번째 토큰을 `"<|startoftranscript|>"`로 설정합니다.

eos_token (`str`, *선택 사항*, 기본값 `"<|endoftext|>"`) : 시퀀스 종료 토큰입니다.

add_prefix_space (`bool`, *선택 사항*, 기본값 `False`) : 입력에 공백을 추가할지 여부입니다. 이를 통해 첫 번째 단어를 다른 단어와 동일하게 처리할 수 있습니다. (Whisper 토크나이저는 앞선 공백을 통해 단어의 시작을 감지합니다).

language (`str`, *선택 사항*) : 전사 텍스트의 언어입니다. 다국어 음성 인식 및 음성 번역 작업의 경우, 해당 언어 id 토큰이 시퀀스 시작 부분에 추가됩니다. 예를 들어 스페인어의 경우 `"<|es|>"` 토큰이 시퀀스 시작 부분에 추가됩니다. 이 인수는 다국어 파인튜닝에만 사용해야 합니다.

task (`str`, *선택 사항*) : 시퀀스 시작 부분에 추가할 작업 식별자(있는 경우). 이는 다국어 파인튜닝에 사용해야 하며, 음성 인식에는 `"transcribe"`, 음성 번역에는 `"translate"`를 사용합니다.

predict_timestamps (`bool`, *선택 사항*, 기본값 `False`) : 시퀀스 시작 부분에 `<|notimestamps|>` 토큰을 생략할지 여부.

HuggingFace의 *tokenizers* 라이브러리를 기반으로 하는 "fast" Whisper 토크나이저를 구성합니다.

이 토크나이저는 대부분의 주요 메서드를 포함하는 [PreTrainedTokenizerFast](/docs/transformers/main/ko/main_classes/tokenizer#transformers.TokenizersBackend)에서 상속됩니다. 해당 메서드에 대한 자세한 정보는 이 상위 클래스를 참고하세요.

#### set_prefix_tokens[[transformers.WhisperTokenizer.set_prefix_tokens]]

```python
set_prefix_tokens(language: str | None = None, task: str | None = None, predict_timestamps: bool | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L585)

**매개변수:**

language (`str`, *선택 사항*, 기본값 `None`) : 전사 텍스트의 언어입니다.

task (`str`, *선택 사항*, 기본값 `None`) : 시퀀스 시작 부분에 추가할 작업 식별자(있는 경우).

predict_timestamps (`bool`, *선택 사항*, 기본값 `None`) : 시퀀스 시작 부분에 `<|notimestamps|>` 토큰을 생략할지 여부.

의 시작 부분에 추가되는 prefix 토큰을 재정의합니다. 이 메서드는 단독으로

fine-tuning 시 필요에 따라 prefix 토큰을 업데이트하세요. 예:

```python
>>> # instantiate the tokenizer and set the prefix token to Spanish
>>> tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny", language="spanish")
>>> # now switch the prefix token from Spanish to French
>>> tokenizer.set_prefix_tokens(language="french")
```

#### get_special_tokens_mask[[transformers.WhisperTokenizer.get_special_tokens_mask]]

```python
get_special_tokens_mask(token_ids_0: list, token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L669)

**매개변수:**

token_ids_0 (`list[int]`) : ID 목록.

token_ids_1 (`list[int]`, *선택 사항*) : 시퀀스 쌍을 위한 선택적 두 번째 ID 목록.

already_has_special_tokens (`bool`, *선택 사항*, 기본값 `False`) : 토큰 목록이 이미 모델의 특수 토큰으로 포맷되어 있는지 여부.

**반환값:** `list[int]`

[0, 1] 범위의 정수 목록: 특수 토큰은 1, 시퀀스 토큰은 0.

특수 토큰이 추가되지 않은 토큰 목록에서 시퀀스 ID를 가져옵니다. 이 메서드는 토크나이저의 `prepare_for_model` 메서드를 사용하여 특수 토큰을 추가할 때 호출됩니다.

#### save_vocabulary[[transformers.WhisperTokenizer.save_vocabulary]]

```python
save_vocabulary(save_directory: str, filename_prefix: str | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L555)

#### batch_decode[[transformers.WhisperTokenizer.batch_decode]]

```python
batch_decode(sequences: list[int] | list[list[int]] | np.ndarray | torch.Tensor, skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_utils_base.py#L2933)

**매개변수:**

sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`) : 토큰화된 입력 ID 목록. `__call__` 메서드를 사용하여 얻을 수 있습니다.

skip_special_tokens (`bool`, *선택 사항*, 기본값 `False`) : 디코딩 시 특수 토큰을 제거할지 여부.

clean_up_tokenization_spaces (`bool`, *선택 사항*) : 토큰화 공백을 정리할지 여부입니다. `None`인 경우 기본값으로 `self.clean_up_tokenization_spaces`를 사용합니다.

kwargs (추가 키워드 인자, *선택 사항*) : 기본 모델의 특정 decode 메서드에 전달됩니다.

**반환값:** `list[str]`

디코딩된 문장의 목록입니다.

decode를 호출하여 토큰 ID의 리스트로 된 리스트를 문자열의 리스트로 변환합니다.

이 메서드는 하위 호환성을 위해 제공됩니다. `decode` 메서드가 이제 배치 입력을 네이티브로 처리하므로 `batch_decode` 대신 `decode`를 직접 사용할 수 있습니다.

#### decode[[transformers.WhisperTokenizer.decode]]

```python
decode(token_ids, skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, output_offsets: bool = False, time_precision: float = 0.02, decode_with_timestamps: bool = False, normalize: bool = False, basic_normalize: bool = False, remove_diacritics: bool = False, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L432)

**매개변수:**

token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`) : 토큰화된 입력 ID 목록. `__call__` 메서드를 사용하여 얻을 수 있습니다.

skip_special_tokens (`bool`, *선택 사항*, 기본값 `False`) : 디코딩 시 특수 토큰을 제거할지 여부입니다. 존재하는 경우 이전 토큰(프롬프트 이전)도 제거됩니다.

clean_up_tokenization_spaces (`bool`, *선택 사항*) : 토큰화 공백을 정리할지 여부입니다. `None`인 경우 `tokenizer_config`에서 사용할 수 있는 `self.clean_up_tokenization_spaces` 값이 기본값으로 적용됩니다.

output_offsets (`bool`, *선택 사항*, 기본값 `False`) : 토큰의 오프셋을 출력할지 여부입니다. 이는 모델이 타임스탬프를 예측한 경우에만 설정해야 합니다. 디코딩할 이전 토큰(프롬프트 이전)이 있는 경우, 타임스탬프 토큰을 포함하고 있을 때만 디코딩된 텍스트에 표시됩니다.

time_precision (`float`, *선택 사항*, 기본값 0.02) : 토큰을 시간으로 변환할 때 사용할 시간 비율입니다.

decode_with_timestamps (`bool`, *선택 사항*, 기본값 `False`) : 원시 텍스트에 타임스탬프를 포함하여 디코딩할지 여부.

normalize (`bool`, *선택 사항*, 기본값 `False`) : 디코딩된 텍스트에 영어 텍스트 정규화기를 적용할지 여부. 대상 텍스트가 영어인 경우에만 적용됩니다. 그렇지 않으면 기본 텍스트 정규화기를 적용해야 합니다.

basic_normalize (`bool`, *선택 사항*, 기본값 `False`) : 디코딩된 텍스트에 Basic 텍스트 정규화기를 적용할지 여부입니다. 다국어 대상 텍스트에 적용됩니다.

remove_diacritics (`bool`, *선택 사항*, 기본값 `False`) : Basic 텍스트 정규화기를 적용할 때 음소 부호를 제거할지 여부입니다. 음소 부호를 제거하면 디코딩된 텍스트의 정보가 손상될 수 있으므로 신중하게 사용해야 합니다.

kwargs (추가 키워드 인자, *선택 사항*) : 기본 모델의 특정 decode 메서드에 전달됩니다.

**반환값:** `str`

복호화된 문장.

토크나이저와 어휘를 사용하여 문자열의 id 시퀀스를 변환하며, 특수 토큰 제거 및 토크나이제이션 공간 정리 옵션을 제공합니다.

`self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`를 실행하는 것과 유사합니다.

#### basic_normalize[[transformers.WhisperTokenizer.basic_normalize]]

```python
basic_normalize(text, remove_diacritics = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L546)

`BasicTextNormalizer` 클래스를 사용하여 주어진 문자열을 정규화합니다. 이 클래스는 다국어 텍스트에 대한 일반적인 변환을 수행합니다.

#### normalize[[transformers.WhisperTokenizer.normalize]]

```python
normalize(text)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/tokenization_whisper.py#L538)

`EnglishTextNormalizer` 클래스를 사용하여 주어진 문자열을 정규화합니다. 이 클래스는 영어 텍스트에 대한 일반적인 변환을 수행합니다.

## WhisperFeatureExtractor[[transformers.WhisperFeatureExtractor]]

#### transformers.WhisperFeatureExtractor[[transformers.WhisperFeatureExtractor]]

```python
transformers.WhisperFeatureExtractor(feature_size = 80, sampling_rate = 16000, hop_length = 160, chunk_length = 30, n_fft = 400, padding_value = 0.0, dither = 0.0, return_attention_mask = False, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py#L33)

**매개변수:**

feature_size (`int`, *선택 사항*, 기본값 80) : 추출된 특징의 차원입니다.

sampling_rate (`int`, *선택 사항*, 기본값 16000) : 오디오 파일을 디지털화할 때 사용할 샘플링 주파수입니다. 헤르츠(Hz) 단위로 표시됩니다.

hop_length (`int`, *선택 사항*, 기본값 160) : Mel Frequency 계수를 얻기 위해 사용되는 STFT의 겹치는 윈도우 길이.

chunk_length (`int`, *선택 사항*, 기본값 30) : 더 길거나 더 짧은 오디오 시퀀스를 자르고 패딩하는 데 사용되는 `sampling_rate` 샘플 수의 최대 청크 수입니다.

n_fft (`int`, *선택 사항*, 기본값 400) : 푸리에 변환의 크기.

padding_value (`float`, *선택 사항*, 기본값 0.0) : 오디오를 패딩하는 데 사용되는 패딩 값입니다. 침묵에 해당해야 합니다.

dither (`float`, *선택 사항*, 기본값 0.0) : 디더링을 추가합니다. 즉, 각 프레임에 작은 가우시안 노이즈를 추가합니다. 예를 들어, 0.0001을 사용하면 0.0을 중심으로 표준편차가 0.0001인 정규 분포로 디더링을 추가합니다(원시 음성(raw_speech)의 범위가 [-1,+1]이라고 가정). 값 0.0은 디더링을 하지 않음을 의미합니다. 디더링은 `spectrogram(mel_floor=...)`와 유사한 효과를 냅니다. 신호에 VAD 컷오프가 존재하는 경우, 하드 제로(hard-zero) 구간이 있는 신호의 높은 log_mel_fbank 값을 줄여줍니다.

Whisper feature extractor를 생성합니다.

이 feature extractor는 대부분의 주요 메서드를 포함하는 [SequenceFeatureExtractor](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)를 상속합니다. 해당 메서드에 대한 자세한 내용은 이 상위 클래스를 참고하세요.

이 클래스는 pytorch의 `torch.stft`와 일치해야 하는 `Short Time Fourier Transform`의 사용자 정의 numpy 구현을 사용하여 원시 음성에서 mel-filter bank 특징을 추출합니다.

#### __call__[[transformers.WhisperFeatureExtractor.__call__]]

```python
__call__(raw_speech: numpy.ndarray | list[float] | list[numpy.ndarray] | list[list[float]], truncation: bool = True, pad_to_multiple_of: int | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, return_attention_mask: bool | None = None, padding: str | None = 'max_length', max_length: int | None = None, sampling_rate: int | None = None, do_normalize: bool | None = None, device: str | None = 'cpu', **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/feature_extraction_whisper.py#L193)

**매개변수:**

raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`) : 패딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 numpy 배열, float 값의 리스트, numpy 배열의 리스트, float 값의 리스트의 리스트일 수 있습니다. 스테레오가 아닌 모노 채널 오디오여야 하며, 즉 각 타임스텝당 float 값이 하나만 있어야 합니다.

truncation (`bool`, *선택 사항*, 기본값 `True`) : *max_length*보다 긴 입력 시퀀스를 *max_length*로 잘라내는 truncation을 활성화합니다.

pad_to_multiple_of (`int`, *선택 사항*, 기본값 None) : 설정하면 시퀀스를 제공된 값의 배수로 패딩합니다. 이는 Volta와 같은 컴퓨트 캐피빌리티 `>= 7.5`를 가진 NVIDIA 하드웨어에서 Tensor Cores 사용을 활성화하거나, 시퀀스 길이가 128의 배수일 때 성능 향상을 얻는 TPU에서 특히 유용합니다.

return_tensors (`str` 또는 [TensorType](/docs/transformers/main/ko/internal/file_utils#transformers.TensorType), *optional*) : 설정된 경우, python 정수 목록 대신 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:  - `'pt'`: PyTorch `torch.Tensor` 객체를 반환합니다. - `'np'`: Numpy `np.ndarray` 객체를 반환합니다.

return_attention_mask (`bool`, *선택 사항*) : attention mask를 반환할지 여부입니다. 기본값으로 두면 해당 feature_extractor의 기본 설정에 따라 attention mask를 반환합니다. [attention mask란 무엇인가요?](../glossary#attention-mask)    Whisper 모델의 경우, 미묘한 버그를 방지하기 위해 배치 추론 시 `attention_mask`를 항상 전달해야 합니다.

padding (`str` 또는 [PaddingStrategy](/docs/transformers/main/ko/internal/file_utils#transformers.utils.PaddingStrategy), *선택 사항*, 기본값 `'max_length'`) : 패딩을 활성화하고 제어합니다. 다음 값을 허용합니다: - `'longest'`: 배치 내 가장 긴 시퀀스 길이로 패딩합니다(단일 시퀀스만 제공된 경우 패딩하지 않음). - `'max_length'` (기본값): `max_length` 인수로 지정된 최대 길이로 패딩하거나, 해당 인수가 제공되지 않으면 모델이 허용하는 최대 입력 길이로 패딩합니다. - `'do_not_pad'`: 패딩하지 않음(즉, 서로 다른 길이의 시퀀스를 가진 배치 출력 가능).

max_length (`int`, *선택 사항*) : truncation/padding 매개변수 중 하나가 사용할 최대 길이를 제어합니다. 설정하지 않거나 `None`으로 설정한 경우, truncation/padding 매개변수 중 하나가 최대 길이를 요구하면 미리 정의된 모델 최대 길이를 사용합니다. 모델에 특정 최대 입력 길이가 없는 경우(XLNet 등) 최대 길이로 truncation/padding하는 기능이 비활성화됩니다.

sampling_rate (`int`, *선택 사항*) : `raw_speech` 입력이 샘플링된 샘플링 레이트입니다. 조용한 오류를 방지하고 자동 음성 인식 파이프라인을 허용하기 위해 forward 호출 시 `sampling_rate`를 전달하는 것이 강력히 권장됩니다.

do_normalize (`bool`, *선택 사항*, 기본값 `False`) : 입력을 평균 0, 분산 1로 정규화할지 여부입니다. 정규화는 모델 성능을 크게 향상시키는 데 도움이 될 수 있습니다.

device (`str`, *선택 사항*, 기본값 `'cpu'`) : `_torch_extract_fbank_features` 메서드에서 오디오 신호의 log-mel spectrogram을 계산하는 데 사용할 장치를 지정합니다. (예: "cpu", "cuda")

- ****kwargs** : WhisperFeatureExtractor에서 지원하지 않으며 __call__()에서 무시됩니다.

하나 이상의 시퀀스를 특징화(featurize)하고 모델에 맞게 준비하는 주요 메서드입니다. 구현에서는 PyTorch가 사용 가능한 경우 STFT 계산에 PyTorch를 사용하고, 그렇지 않으면 더 느린 NumPy 기반 방식을 사용합니다.

## WhisperProcessor[[transformers.WhisperProcessor]]

#### transformers.WhisperProcessor[[transformers.WhisperProcessor]]

```python
transformers.WhisperProcessor(feature_extractor, tokenizer)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/processing_whisper.py#L23)

**매개변수:**

feature_extractor (`WhisperFeatureExtractor`) : feature extractor는 필수 입력입니다.

tokenizer (`WhisperTokenizer`) : 토크나이저는 필수 입력입니다.

feature extractor와 tokenizer를 단일 processor로 감싸는 WhisperProcessor를 생성합니다.

[WhisperProcessor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperProcessor)는 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)와 [WhisperTokenizer](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperTokenizer)의 모든 기능을 제공합니다. 자세한 내용은 [~WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)와 [~WhisperTokenizer](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperTokenizer)를 참고하세요.

#### __call__[[transformers.WhisperProcessor.__call__]]

```python
__call__(*args, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/processing_whisper.py#L30)

**매개변수:**

return_tensors (`str` 또는 [TensorType](/docs/transformers/main/ko/internal/file_utils#transformers.TensorType), *optional*) : 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:  - `'pt'`: PyTorch `torch.Tensor` 객체를 반환합니다. - `'np'`: NumPy `np.ndarray` 객체를 반환합니다.

#### from_pretrained[[transformers.WhisperProcessor.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, cache_dir: str | os.PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = 'main', **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1750)

**매개변수:**

pretrained_model_name_or_path (`str` 또는 `os.PathLike`) : 다음 중 하나일 수 있습니다. - huggingface.co의 모델 저장소에 호스팅된 사전 학습된 feature_extractor의 *model id*인 문자열. - [save_pretrained()](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.FeatureExtractionMixin.save_pretrained) 메서드를 사용하여 저장된 feature extractor 파일이 포함된 *디렉터리*의 경로, 예: `./my_model_directory/`. - 저장된 feature extractor JSON *파일*의 경로, 예: `./my_model_directory/preprocessor_config.json`.

- ****kwargs** : [from_pretrained()](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained)와 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`에 함께 전달되는 추가 키워드 인자입니다.

과(와) 연관된 를 초기화합니다.

이 클래스 메서드는 단순히 feature extractor의 [from_pretrained()](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.FeatureExtractionMixin.from_pretrained), image processor의 [ImageProcessingMixin](/docs/transformers/main/ko/internal/image_processing_utils#transformers.ImageProcessingMixin) 및 tokenizer의 `~tokenization_utils_base.PreTrainedTokenizer.from_pretrained` 메서드를 호출합니다. 자세한 내용은 위 메서드들의 docstring을 참고하세요.

#### save_pretrained[[transformers.WhisperProcessor.save_pretrained]]

```python
save_pretrained(save_directory, push_to_hub: bool = False, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L1165)

**매개변수:**

save_directory (`str` 또는 `os.PathLike`) : feature extractor JSON 파일과 tokenizer 파일이 저장될 디렉터리 (존재하지 않으면 생성됩니다).

push_to_hub (`bool`, *선택 사항*, 기본값 `False`) : 모델을 저장한 후 Hugging Face 모델 허브에 푸시할지 여부입니다. `repo_id`를 사용하여 푸시할 저장소를 지정할 수 있으며, 지정하지 않으면 네임스페이스 내 `save_directory`의 이름이 기본값으로 사용됩니다.

kwargs (`dict[str, Any]`, *선택*) : [push_to_hub()](/docs/transformers/main/ko/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) 메서드에 함께 전달되는 추가 키워드 인자입니다.

이 프로세서의 속성(피처 추출기, 토크나이저...)을 지정된 디렉터리에 저장하여 [from_pretrained()](/docs/transformers/main/ko/model_doc/wav2vec2#transformers.Wav2Vec2Processor.from_pretrained) 메서드를 사용해 다시 로드할 수 있도록 합니다.

이 클래스 메서드는 단순히 [save_pretrained()](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.FeatureExtractionMixin.save_pretrained)와 [save_pretrained()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.save_pretrained)를 호출합니다. 자세한 내용은 위 메서드의 docstring을 참고하세요.

#### batch_decode[[transformers.WhisperProcessor.batch_decode]]

```python
batch_decode(*args, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L2005)

이 메서드는 모든 인수를 PreTrainedTokenizer의 [batch_decode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode)로 전달합니다. 자세한 내용은 해당 메서드의 docstring을 참조하세요.

#### decode[[transformers.WhisperProcessor.decode]]

```python
decode(*args, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L2014)

이 메서드는 모든 인수를 PreTrainedTokenizer의 [decode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.decode)로 전달합니다. 자세한 내용은 해당 메서드의 docstring을 참조하세요.

## WhisperModel[[transformers.WhisperModel]]

#### transformers.WhisperModel[[transformers.WhisperModel]]

```python
transformers.WhisperModel(config: WhisperConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L826)

**매개변수:**

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Whisper 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.WhisperModel.forward]]

```python
forward(input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, decoder_inputs_embeds: tuple[torch.Tensor] | None = None, decoder_position_ids: tuple[torch.LongTensor] | None = None, use_cache: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L891)

**매개변수:**

input_features (`torch.Tensor`, shape `(batch_size, sequence_length, feature_dim)`, *선택 사항*) : 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)를 참조하세요 ([WhisperProcessor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperProcessor)는 오디오 처리에 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용합니다).

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

decoder_input_ids (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. [WhisperTokenizer](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [디코더 입력 ID란 무엇인가요?](../glossary#decoder-input-ids) Whisper는 `decoder_input_ids` 생성의 시작 토큰으로 `decoder_start_token_id`를 사용합니다. `past_key_values`를 사용하는 경우, 선택적으로 마지막 `decoder_input_ids`만 입력하면 됩니다(`past_key_values` 참조).

decoder_attention_mask (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 기본 동작: `decoder_input_ids`의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 Causal mask도 사용됩니다. 패딩 동작을 변경하려면 `modeling_whisper._prepare_decoder_attention_mask`를 읽고 필요에 맞게 수정해야 합니다. 기본 전략에 대한 자세한 내용은 [BART 논문](https://huggingface.co/papers/1910.13461)의 다이어그램 1을 참조하세요.

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *선택 사항*) : (`last_hidden_state`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`) `last_hidden_state`의 shape은 `(batch_size, sequence_length, hidden_size)`, *선택 사항*)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/main/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/main/ko/internal/generation_utils#transformers.DynamicCache)가 초기화됩니다. 모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다. `past_key_values`를 사용하는 경우, 이 모델에 과거 key value 상태가 제공되지 않은 `input_ids`(처리되지 않은 항목)만 `(batch_size, unprocessed_length)` 형식으로 입력해야 하며, `(batch_size, sequence_length)` 형식의 모든 `input_ids`를 입력하지 않습니다.

decoder_inputs_embeds (`tuple[torch.Tensor]`, shape `(batch_size, target_sequence_length, hidden_size)`, *선택*) : `decoder_input_ids`를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. `past_key_values`를 사용하는 경우, 선택적으로 마지막 `decoder_inputs_embeds`만 입력하면 됩니다(`past_key_values` 참조). 모델의 내부 임베딩 조회 행렬보다 `decoder_input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요할 때 유용합니다. `decoder_input_ids`와 `decoder_inputs_embeds`가 모두 설정되지 않은 경우, `decoder_inputs_embeds`는 `inputs_embeds`의 값을 사용합니다.

decoder_position_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다. [위치 ID란 무엇인가요?](../glossary#position-ids)

use_cache (`bool`, *선택 사항*) : `True`로 설정하면 `past_key_values` 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(`past_key_values` 참조).

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

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

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

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

- **last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`) -- 모델의 decoder 마지막 레이어 출력의 hidden-state 시퀀스입니다.

  `past_key_values`가 사용되면, `(batch_size, 1, hidden_size)` 형태의 시퀀스의 마지막 hidden-state만 출력됩니다.
- **past_key_values** (`EncoderDecoderCache`, *선택 사항*, `use_cache=True`가 전달되거나 `config.use_cache=True`인 경우 반환됨) -- [EncoderDecoderCache](/docs/transformers/main/ko/internal/generation_utils#transformers.EncoderDecoderCache) 인스턴스입니다. 자세한 내용은 [kv 캐시 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프-어텐션 블록과 크로스-어텐션 블록의 key 및 values)를 포함합니다(입력 `past_key_values` 참조).
- **decoder_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개).

  각 레이어 출력의 decoder hidden-states와 선택적인 초기 embedding 출력
- **decoder_attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor` 튜플이며, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
- **cross_attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.
- **encoder_last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) -- 모델 인코더의 마지막 레이어 출력의 hidden-state 시퀀스입니다.
- **encoder_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와 선택적인 초기 임베딩 출력.
- **encoder_attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩 포함된 `torch.Tensor` 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  인코더의 어텐션 가중치입니다. 어텐션 softmax 이후에 self-attention 헤드에서 가중 평균을 계산하는 데 사용됩니다.

예:
```python
>>> import torch
>>> from transformers import AutoFeatureExtractor, WhisperModel
>>> from datasets import load_dataset

>>> model = WhisperModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 512]
```

#### _mask_input_features[[transformers.WhisperModel._mask_input_features]]

```python
_mask_input_features(input_features: Tensor, attention_mask: typing.Optional[torch.LongTensor] = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L848)

[SpecAugment](https://huggingface.co/papers/1904.08779)에 따라 시간 축 및/또는 특징 축을 따라 추출된 특징을 가립니다.

## WhisperForConditionalGeneration[[transformers.WhisperForConditionalGeneration]]

#### transformers.WhisperForConditionalGeneration[[transformers.WhisperForConditionalGeneration]]

```python
transformers.WhisperForConditionalGeneration(config: WhisperConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L990)

**매개변수:**

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

언어 모델링 헤드가 포함된 Whisper 모델. 자동 음성 인식에 사용할 수 있습니다.

이 모델은 [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.WhisperForConditionalGeneration.forward]]

```python
forward(input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, decoder_input_ids: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, decoder_inputs_embeds: tuple[torch.Tensor] | None = None, decoder_position_ids: tuple[torch.LongTensor] | None = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1034)

**매개변수:**

input_features (`torch.Tensor`, shape `(batch_size, sequence_length, feature_dim)`, *선택 사항*) : 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)를 참조하세요 ([WhisperProcessor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperProcessor)는 오디오 처리에 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용합니다).

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

decoder_input_ids (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. [WhisperTokenizer](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [디코더 입력 ID란 무엇인가요?](../glossary#decoder-input-ids) Whisper는 `decoder_input_ids` 생성의 시작 토큰으로 `decoder_start_token_id`를 사용합니다. `past_key_values`를 사용하는 경우, 선택적으로 마지막 `decoder_input_ids`만 입력하면 됩니다(`past_key_values` 참조).

decoder_attention_mask (`torch.LongTensor`, shape `(batch_size, target_sequence_length)`, *선택 사항*) : 기본 동작: `decoder_input_ids`의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 Causal mask도 사용됩니다. 패딩 동작을 변경하려면 `modeling_whisper._prepare_decoder_attention_mask`를 읽고 필요에 맞게 수정해야 합니다. 기본 전략에 대한 자세한 내용은 [BART 논문](https://huggingface.co/papers/1910.13461)의 다이어그램 1을 참조하세요.

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *선택 사항*) : (`last_hidden_state`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`) `last_hidden_state`의 shape은 `(batch_size, sequence_length, hidden_size)`, *선택 사항*)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/main/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/main/ko/internal/generation_utils#transformers.DynamicCache)가 초기화됩니다. 모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다. `past_key_values`를 사용하는 경우, 이 모델에 과거 key value 상태가 제공되지 않은 `input_ids`(처리되지 않은 항목)만 `(batch_size, unprocessed_length)` 형식으로 입력해야 하며, `(batch_size, sequence_length)` 형식의 모든 `input_ids`를 입력하지 않습니다.

decoder_inputs_embeds (`tuple[torch.Tensor]`, shape `(batch_size, target_sequence_length, hidden_size)`, *선택*) : `decoder_input_ids`를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. `past_key_values`를 사용하는 경우, 선택적으로 마지막 `decoder_inputs_embeds`만 입력하면 됩니다(`past_key_values` 참조). 모델의 내부 임베딩 조회 행렬보다 `decoder_input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요할 때 유용합니다. `decoder_input_ids`와 `decoder_inputs_embeds`가 모두 설정되지 않은 경우, `decoder_inputs_embeds`는 `inputs_embeds`의 값을 사용합니다.

decoder_position_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 각 입력 시퀀스의 토큰 위치 인덱스입니다. `[0, config.n_positions - 1]` 범위에서 선택됩니다. [위치 ID란 무엇인가요?](../glossary#position-ids)

labels (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 언어 모델링 손실을 계산하기 위한 라벨. 인덱스는 `[0, ..., config.vocab_size]` 범위 내이거나 -100이어야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, 손실은 `[0, ..., config.vocab_size]` 범위의 라벨을 가진 토큰에 대해서만 계산됩니다. `sequence_length`는 `config.max_target_positions`보다 작거나 같아야 합니다.

use_cache (`bool`, *선택 사항*) : `True`로 설정하면 `past_key_values` 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(`past_key_values` 참조).

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

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

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택*, `labels`이 제공될 때 반환됨) -- 언어 모델링 손실.
- **logits** (`torch.Tensor`, shape `(batch_size, sequence_length, config.vocab_size)`) -- 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).
- **past_key_values** (`EncoderDecoderCache`, *선택 사항*, `use_cache=True`가 전달되거나 `config.use_cache=True`인 경우 반환됨) -- [EncoderDecoderCache](/docs/transformers/main/ko/internal/generation_utils#transformers.EncoderDecoderCache) 인스턴스입니다. 자세한 내용은 [kv 캐시 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프-어텐션 블록과 크로스-어텐션 블록의 key 및 values)를 포함합니다(입력 `past_key_values` 참조).
- **decoder_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와 초기 임베딩 출력을 더한 값.
- **decoder_attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor` 튜플이며, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
- **cross_attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.
- **encoder_last_hidden_state** (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) -- 모델 인코더의 마지막 레이어 출력의 hidden-state 시퀀스입니다.
- **encoder_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와 초기 임베딩 출력을 더한 값.
- **encoder_attentions** (`tuple(torch.Tensor)`, *선택 사항*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어에 하나씩 포함된 `torch.Tensor` 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  인코더의 어텐션 가중치입니다. 어텐션 softmax 이후에 self-attention 헤드에서 가중 평균을 계산하는 데 사용됩니다.

예:

```python
>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

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

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features

>>> generated_ids = model.generate(inputs=input_features)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
```

#### generate[[transformers.WhisperForConditionalGeneration.generate]]

```python
generate(input_features: typing.Optional[torch.Tensor] = None, generation_config: transformers.generation.configuration_utils.GenerationConfig | None = None, logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None, stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None, prefix_allowed_tokens_fn: collections.abc.Callable[[int, torch.Tensor], list[int]] | None = None, synced_gpus: bool = False, return_timestamps: bool | None = None, task: str | None = None, language: str | list[str] | None = None, is_multilingual: bool | None = None, prompt_ids: typing.Optional[torch.Tensor] = None, prompt_condition_type: str | None = None, condition_on_prev_tokens: bool | None = None, temperature: float | tuple[float, ...] | None = None, compression_ratio_threshold: float | None = None, logprob_threshold: float | None = None, no_speech_threshold: float | None = None, num_segment_frames: int | None = None, attention_mask: typing.Optional[torch.Tensor] = None, time_precision: float = 0.02, time_precision_features: float = 0.01, return_token_timestamps: bool | None = None, return_segments: bool = False, return_dict_in_generate: bool | None = None, force_unique_generate_call: bool | None = None, monitor_progress: collections.abc.Callable[[torch.Tensor], None] | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/generation_whisper.py#L383)

**매개변수:**

input_features (`torch.Tensor`, shape `(batch_size, feature_size, sequence_length)`, *선택 사항*) : 원시 음성 웨이브폼에서 추출된 log-mel 특징의 부동 소수점 값. 원시 음성 웨이브폼은 `.flac` 또는 `.wav` 오디오 파일을 `list[float]`, `numpy.ndarray` 또는 `torch.Tensor` 타입의 배열로 로드하여 얻을 수 있으며, *예를 들어* torchcodec 라이브러리(`pip install torchcodec`) 또는 soundfile 라이브러리(`pip install soundfile`)를 통해 수행할 수 있습니다. `input_features`로 배열을 준비하려면, mel 특징 추출, 패딩 및 `torch.Tensor` 타입의 텐서 변환을 위해 [AutoFeatureExtractor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoFeatureExtractor)를 사용해야 합니다. 자세한 내용은 [__call__()](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)를 참조하세요.

generation_config ([GenerationConfig](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationConfig), *optional*) : 생성 호출의 기본 파라미터화로 사용할 생성 구성입니다. `generation_config`의 속성과 일치하는 `**kwargs`가 generate에 전달되면 해당 속성을 덮어씁니다. `generation_config`가 제공되지 않으면 기본값이 사용되며, 이는 다음 로딩 우선순위를 따릅니다: 1) `generation_config.json` 모델 파일이 존재하는 경우 해당 파일에서; 2) 모델 구성에서. 지정되지 않은 파라미터는 [GenerationConfig](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationConfig)의 기본값을 상속받으므로, 생성을 파라미터화하려면 해당 문서에서 기본값을 확인해야 합니다.

logits_processor (`LogitsProcessorList`, *선택*) : 인자와 generation config에서 생성된 기본 logits processor를 보완하는 사용자 정의 logits processor입니다. 인자 또는 generation config로 이미 생성된 logit processor가 전달되면 오류가 발생합니다. 이 기능은 고급 사용자를 위한 것입니다.

stopping_criteria (`StoppingCriteriaList`, *선택 사항*) : 인자와 generation config에서 기본으로 생성되는 stopping criteria를 보완하는 사용자 정의 stopping criteria입니다. 인자나 generation config로 이미 생성된 stopping criteria가 전달되면 오류가 발생합니다. 이 기능은 고급 사용자를 위해 제공됩니다.

prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`, *선택*) : 지정된 경우, 이 함수는 각 단계에서 beam search를 허용된 토큰으로만 제한합니다. 지정되지 않으면 제약이 적용되지 않습니다. 이 함수는 2개의 인수를 받습니다: 배치 ID `batch_id`와 `input_ids`. 배치 ID `batch_id`와 이전에 생성된 토큰 `inputs_ids`에 조건부인 다음 생성 단계에 허용되는 토큰의 리스트를 반환해야 합니다. 이 인수는 [Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904)에 설명된 바와 같이 접두사에 조건부인 제약 생성에 유용합니다.

synced_gpus (`bool`, *선택 사항*, 기본값 `False`) : `FullyShardedDataParallel` 및 DeepSpeed ZeRO Stage 3과의 데드락을 방지하기 위해 max_length까지 while 루프를 계속 실행할지 여부.

return_timestamps (`bool`, *선택 사항*) : 텍스트와 함께 타임스탬프를 반환할지 여부입니다. 이 설정은 `WhisperTimestampsLogitsProcessor`를 활성화합니다. 30초보다 긴 오디오의 경우 `return_timestamps=True`로 설정해야 합니다.

task (`str`, *선택 사항*) : 생성에 사용할 태스크로, "translate" 또는 "transcribe" 중 하나입니다.

language (`str` 또는 `str` 목록, *선택 사항*) : 생성에 사용할 언어 토큰으로, `<|en|>`, `en` 또는 `english` 형태일 수 있습니다. 배치 생성의 경우 언어 토큰 목록을 전달할 수 있습니다. 모든 가능한 언어 토큰은 `model.generation_config.lang_to_id` 사전에서 찾을 수 있습니다.

is_multilingual (`bool`, *선택 사항*) : 모델이 다국어인지 여부.

prompt_ids (`torch.Tensor`, *선택 사항*) : 텍스트를 `get_prompt_ids()`에 전달하여 생성된 토큰 ID의 Rank-1 텐서로, 각 청크에 프롬프트로 제공됩니다. 이를 통해 전사 작업의 컨텍스트를 제공하거나 "프롬프트 엔지니어링"하여, 예를 들어 맞춤 사전이나 고유명사 등을 더 정확하게 예측할 가능성을 높일 수 있습니다. 이 값은 해당 값을 덮어쓰기 때문에 `decoder_start_token_id`와 함께 사용할 수 없습니다.

prompt_condition_type (`str`, *선택 사항*) : 긴 형식의 전사(long-form transcription)에만 관련이 있습니다. `prompt_ids`의 조건 유형을 지정합니다. 'first-segment'는 첫 번째 세그먼트만 `prompt_ids`에 조건이 적용됨을 의미합니다. 'all-segments'는 각 세그먼트가 `prompt_ids`에 조건이 적용됨을 의미합니다. 'all-segments'의 경우 `condition_on_prev_tokens`를 활성화해야 합니다. 기본값은 'first-segment'입니다. 짧은 형식의 전사(short-term transcription)의 경우 'first-segment'만 가능합니다.

condition_on_prev_tokens (`bool`, *선택 사항*) : 긴 형식의 전사(long-form transcription)에만 관련이 있습니다. 각 세그먼트를 이전 세그먼트에 조건부로 처리할지 여부입니다. [Whisper 논문](https://cdn.openai.com/papers/whisper.pdf)에서 보여주었듯이, 이를 통해 성능을 향상시킬 수 있습니다.

temperature (`float` 또는 `float` 목록, *선택 사항*) : 생성에 사용할 temperature입니다. 단일 `float` 값과 `do_sample=True`를 전달하면 샘플링을 사용한 생성이 활성화됩니다. 긴 형식의 전사(transcription)의 경우, (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)과 같은 float 값 목록을 전달하여 temperature fallback을 활성화할 수 있습니다. [Whisper 논문](https://cdn.openai.com/papers/whisper.pdf)에 제시된 바와 같이, 이를 통해 성능을 향상시킬 수 있습니다.

compression_ratio_threshold (`float`, *선택 사항*) : 긴 형식의 전사(long-form transcription)에만 관련이 있습니다. 정의된 경우 각 세그먼트의 zlib 압축률이 계산됩니다. 특정 세그먼트의 압축률이 `compression_ratio_threshold`보다 높으면 temperature fallback이 활성화됩니다. 생성된 세그먼트가 폐기되고 더 높은 temperature를 사용하여 생성이 반복됩니다. 이 기능의 직관은 압축률이 매우 높은 세그먼트는 반복이 많이 발생한다는 것입니다. temperature를 높여 무작위성을 더 주입함으로써 원치 않는 반복을 줄일 수 있습니다. `compression_ratio_threshold`가 정의되어 있다면 `temperature`가 값의 목록인지 확인하십시오. `compression_ratio_threshold`의 일반적인 값은 1.35입니다. [Whisper 논문](https://cdn.openai.com/papers/whisper.pdf)에서 보여주듯, 이를 통해 성능을 향상시킬 수 있습니다.

logprob_threshold (`float`, *선택 사항*) : 긴 형식의 전사(long-form transcription)에만 관련이 있습니다. 정의된 경우, 각 세그먼트의 평균 로그 확률(log-probability)이 계산됩니다. 특정 세그먼트의 로그 확률이 `logprob_threshold`보다 낮으면 temperature fallback이 활성화됩니다. 생성된 세그먼트가 폐기되고 더 높은 temperature를 사용하여 생성이 반복됩니다. 이 기능의 직관은, 낮은 로그 확률을 가진 세그먼트는 temperature를 높여 더 많은 무작위성을 주입함으로써 개선될 수 있다는 것입니다. `logprob_threshold`가 정의되어 있다면 `temperature`가 값의 목록인지 확인하십시오. `logprob_threshold`의 일반적인 값은 -1.0입니다. [Whisper 논문](https://cdn.openai.com/papers/whisper.pdf)에서 보여준 바와 같이, 이는 성능 향상에 도움이 될 수 있습니다.

no_speech_threshold (`float`, *선택 사항*) : 긴 형식의 전사(long-form transcription)에만 관련이 있습니다. 정의된 경우, "no-speech" 토큰과 `logprob_threshold`가 결합되어 해당 세그먼트가 침묵만 포함하는지 여부를 결정하는 데 사용됩니다. 이 경우 해당 세그먼트의 전사는 건너뜁니다. [Whisper 논문](https://cdn.openai.com/papers/whisper.pdf)에서 보여준 바와 같이, 이를 통해 성능을 향상시킬 수 있습니다.

num_segment_frames (`int`, *선택 사항*) : 단일 세그먼트를 구성하는 프레임 수입니다. 정의되지 않은 경우, `num_segment_frames`는 모델의 스트라이드와 최대 입력 길이의 곱으로 기본 설정됩니다.

attention_mask (`torch.Tensor`, *선택 사항*) : 배치 크기가 1보다 큰 경우 장문 전사(long-form transcription)를 수행할 때 `attention_mask`를 전달해야 합니다.

time_precision (`int`, *선택 사항*, 기본값 0.02) : 출력 토큰의 지속 시간(초). *예를 들어* 0.02는 생성된 토큰이 평균적으로 20ms를 차지한다는 것을 의미합니다.

time_precision_features (`int`, *선택 사항*, 기본값 0.01) : 특징 프레임이 초 단위로 나타내는 지속 시간입니다.

return_token_timestamps (`bool`, *선택 사항*) : 텍스트와 함께 토큰 수준의 타임스탬프를 반환할지 여부입니다. 이 옵션은 `return_timestamps` 옵션과 함께 또는 단독으로 사용할 수 있습니다. 단어 수준의 타임스탬프를 얻으려면 토크나이저를 사용하여 토큰을 단어로 그룹화하세요.

return_segments (`bool`, *선택 사항*, 기본값 `False`) : 모든 세그먼트의 목록을 추가로 반환할지 여부입니다. 이 옵션은 장문 전사(long-form transcription)를 수행할 때만 활성화할 수 있습니다.

return_dict_in_generate (`bool`, *선택 사항*, 기본값 `False`) : 생성된 토큰만 반환하는 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)을 반환할지 여부입니다. 장문 전사(long-form transcription)를 수행할 때 `return_dict_in_generate`는 `return_segments`가 True로 설정된 경우에만 활성화할 수 있습니다. 이 경우 각 세그먼트의 생성 출력물이 해당 세그먼트에 추가됩니다.

force_unique_generate_call (`bool`, *선택 사항*) : 기본 GenerationMixin의 [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate) 메서드에 대한 고유한 호출을 강제할지 여부입니다. 이는 assisted decoding 및 테스트 목적으로 유용하며, [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate)가 한 번만 호출되도록 보장하여 decoder 입력 토큰 ID와 eos 토큰 ID가 반환되도록 합니다.

monitor_progress (`Callable[[torch.Tensor], None]`, *선택 사항*) : 제공된 경우, 이 함수를 호출하여 오디오 전사 진행 상황을 보고할 수 있습니다. 이 함수는 `n`이 배치 크기인 `(n, 2)` 모양의 텐서 인자 `p`를 받습니다. `p[i, 0]`에는 배치 항목 `i`에 대해 현재 전사 중인 오디오 프레임의 인덱스가 포함되어 있습니다. `p[i, 1]`에는 배치 항목 `i`의 총 프레임 수가 포함되어 있습니다. 반환 값은 기대되지 않습니다.

kwargs (`dict[str, Any]`, *선택*) : `generate_config`의 즉석 파라미터화 및/또는 모델의 `forward` 함수로 전달될 추가적인 모델 전용 kwargs입니다. 모델이 인코더-디코더 모델인 경우, 인코더 전용 kwargs에는 접두사를 붙이지 않고 디코더 전용 kwargs에는 *decoder_* 접두사를 붙여야 합니다.

**반환값:** [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput) 또는 `dict[str, Any]` 또는 `torch.LongTensor`

다음 중 하나:
- `return_dict_in_generate=True`이고 (`return_timestamps=False` 또는 `force_unique_generate_call=True`)인 경우, decoder 입력 id와 시퀀스 종료 id를 포함하는 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)
- (`return_dict_in_generate=True`이고 `return_timestamps=True`인 경우) 또는 `return_segments=True` 또는 `return_token_timestamps=True`인 경우 `dict[str, Any]`
- 디코더 입력 id와 시퀀스 종료 id를 제외한 모든 다른 경우, `torch.LongTensor`

가능한 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput) 유형은 다음과 같습니다:
- [GenerateEncoderDecoderOutput](/docs/transformers/main/ko/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput)
- [GenerateBeamEncoderDecoderOutput](/docs/transformers/main/ko/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)

`segments`는 `segment`의 리스트(배치 요소당 하나의 리스트)의 리스트입니다. `segment`는 `start`, `end`, `tokens`, `idxs`, `result` 키를 가진 딕셔너리입니다.
- `start`: 세그먼트의 시작 타임스탬프.
- `end`: 세그먼트의 종료 타임스탬프.
- `tokens`: decoder input ids와 end of sequence id를 제외한 세그먼트의 토큰
- `idxs`: `result`에 포함된 GenerationMixin의 [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate) 기본 호출에서 해당 세그먼트의 `tokens`의 시작(포함) 및 끝(제외) 인덱스.
- `result`: GenerationMixin의 [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate)에 대한 기본 호출의 결과.

`return_timestamps=True`인 경우, `return_dict_in_generate=True`는 기본 GenerationMixin의 [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate) 호출 각각에 적용되며, 출력은 각 `segment`의 `result`에 저장됩니다.

log-mel 입력 특징을 오토레그레시브 방식으로 생성된 토큰 id 시퀀스로 전사하거나 번역합니다.

대부분의 생성 제어 매개변수는 `generation_config`에 설정되며, 전달되지 않으면 모델의 기본 생성 구성으로 설정됩니다. `generation_config`의 항목은 generate()에 해당 매개변수를 전달하여 오버라이드할 수 있습니다. 예를 들어 `.generate(inputs, num_beams=4, do_sample=True)`와 같이 사용할 수 있습니다.

생성 전략 개요와 코드 예제는 [다음 가이드](../generation_strategies)를 참고하세요.

예:

- *긴 형식 전사*: 30초 이상의 오디오를 전사하거나 번역하려면 오디오 파일을 잘리지 않도록 처리하고 모든 mel 특징을 한 번에 전달하여 생성해야 합니다. `return_timestamps=True`를 설정하는 것이 필요합니다.
실제로, 장문 전사(long-form transcription)는 타임스탬프 예측에 기반한 순차적 알고리즘을 사용하며, 압축률 임계값, 로그 확률 임계값, 온도 폴백(temperature fallback)과 같은 휴리스틱을 적용합니다. 이 알고리즘은 [Whisper 원 논문](https://cdn.openai.com/papers/whisper.pdf)의 *3.8. Long-form Transcription* 섹션에 설명되어 있습니다.

```python
>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset, Audio

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
>>> model.cuda()
>>> # load audios > 30 seconds
>>> ds = load_dataset("distil-whisper/meanwhile", "default")["test"]
>>> # resample to 16kHz
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> # take first 8 audios and retrieve array
>>> audio = ds[:8]["audio"]
>>> audio = [x["array"] for x in audio]

>>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio
>>> inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000)
>>> inputs = inputs.to("cuda", torch.float32)

>>> # transcribe audio to ids
>>> generated_ids = model.generate(**inputs, return_timestamps=True)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> transcription[0]
" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
```

`monitor_progress` 콜백은 전사 진행 상황을 모니터링하는 데 사용할 수 있습니다:
```python
>>> from tqdm import tqdm

>>> # prepare inputs like above

>>> # define a callback to monitor the progress of the transcription.
>>> with tqdm(desc="Progress") as pbar:
>>>     def monitor_progress(p_batch):
>>>         i = torch.argmax(p_batch[:, 1])
>>>         p = p_batch[i].detach().cpu()
>>>         pbar.total = int(p[1])
>>>         pbar.n = int(p[0])
>>>         pbar.update()

>>>     # transcribe audio to ids
>>>     generated_ids = model.generate(**inputs, return_timestamps=True, monitor_progress=monitor_progress)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> transcription[0]
Progress:  95%|█████████████████████████████████████████████████████████████████████████████████████████████████▎    | 8497/8901 [00:04<00:00, 2052.79it/s]
" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
```

- *짧은 형식 전사*: 전달된 mel 입력 기능이 30초 이하인 경우, 두 가지 가능성이 있습니다:
  - `return_timestamps=False`: 전체 오디오가 GenerationMixin의 [generate()](/docs/transformers/main/ko/main_classes/text_generation#transformers.GenerationMixin.generate)를 한 번 호출하여 전사됩니다.
  - `return_timestamps=True`: 오디오는 장문 전사와 동일한 로직을 사용하여 전사됩니다.

```python
>>> import torch
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")

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

>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features

>>> generated_ids = model.generate(inputs=input_features)

>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
```

## WhisperForCausalLM[[transformers.WhisperForCausalLM]]

#### transformers.WhisperForCausalLM[[transformers.WhisperForCausalLM]]

```python
transformers.WhisperForCausalLM(config: WhisperConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1171)

**매개변수:**

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

선형 레이어(입력 임베딩과 가중치가 공유됨)로 구성된 언어 모델링 헤드가 위에 있는 Whisper decoder

이 모델은 [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.WhisperForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, encoder_outputs: tuple[torch.Tensor] | None = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1197)

**매개변수:**

input_ids (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : 어휘(input sequence tokens)의 인덱스입니다. 기본적으로 패딩은 무시됩니다. [AutoTokenizer](/docs/transformers/main/ko/model_doc/auto#transformers.AutoTokenizer)를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 [PreTrainedTokenizer.encode()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 및 [PreTrainedTokenizer.__call__()](/docs/transformers/main/ko/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)를 참조하세요. [입력 ID란 무엇인가요?](../glossary#input-ids)

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

encoder_outputs (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 모델이 디코더로 구성된 경우 cross-attention에 사용됩니다.

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/main/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/main/ko/internal/generation_utils#transformers.DynamicCache)가 초기화됩니다. 모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다. `past_key_values`를 사용하는 경우, 이 모델에 과거 key value 상태가 제공되지 않은 `input_ids`(처리되지 않은 항목)만 `(batch_size, unprocessed_length)` 형식으로 입력해야 하며, `(batch_size, sequence_length)` 형식의 모든 `input_ids`를 입력하지 않습니다.

inputs_embeds (`torch.Tensor`, shape `(batch_size, sequence_length, hidden_size)`, *선택 사항*) : `input_ids`를 전달하는 대신 임베디드 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 `input_ids` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 많은 제어가 필요한 경우 유용합니다.

labels (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : masked language modeling loss를 계산하기 위한 라벨. 인덱스는 `[0, ..., config.vocab_size]` 범위 내이거나 -100이어야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, loss는 `[0, ..., config.vocab_size]` 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.

use_cache (`bool`, *선택 사항*) : `True`로 설정하면 `past_key_values` 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(`past_key_values` 참조).

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

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

[WhisperForCausalLM](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperForCausalLM)의 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 가중치입니다.
- **cross_attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어마다 하나씩 포함된 `torch.Tensor`의 튜플로, shape는 `(batch_size, num_heads, sequence_length, sequence_length)`입니다.

  Attention softmax 이후의 cross attention 가중치로, cross-attention 헤드에서 가중 평균을 계산하는 데 사용됩니다.
- **past_key_values** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/main/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(attention 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).

예:

```python
>>> from transformers import WhisperForCausalLM, WhisperForConditionalGeneration, WhisperProcessor
>>> import torch
>>> from datasets import load_dataset

>>> processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")

>>> assistant_model = WhisperForCausalLM.from_pretrained("distil-whisper/distil-large-v2")

>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> sample = ds[0]["audio"]
>>> input_features = processor(
...     sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt"
... ).input_features

>>> predicted_ids = model.generate(input_features, assistant_model=assistant_model)

>>> # decode token ids to text
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
>>> transcription
' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.'
```

## WhisperForAudioClassification[[transformers.WhisperForAudioClassification]]

#### transformers.WhisperForAudioClassification[[transformers.WhisperForAudioClassification]]

```python
transformers.WhisperForAudioClassification(config: WhisperConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1279)

**매개변수:**

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

SUPERB Keyword Spotting와 같은 작업을 위해, 풀링된 출력 위에 선형 레이어를 적용한 시퀀스 분류 헤드를 갖춘 Whisper Encoder 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.WhisperForAudioClassification.forward]]

```python
forward(input_features: typing.Optional[torch.LongTensor] = None, encoder_outputs: tuple[tuple[torch.Tensor]] | None = None, labels: typing.Optional[torch.LongTensor] = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1306)

**매개변수:**

input_features (`torch.LongTensor`, shape `(batch_size, sequence_length, feature_dim)`, *선택 사항*) : 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [WhisperFeatureExtractor.__call__()](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor.__call__)를 참조하세요 ([WhisperProcessor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperProcessor)는 오디오 처리에 [WhisperFeatureExtractor](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperFeatureExtractor)를 사용합니다).

encoder_outputs (`tuple[tuple[torch.Tensor]]`, *선택 사항*) : (`last_hidden_state`, *선택 사항*: `hidden_states`, *선택 사항*: `attentions`) `last_hidden_state`의 shape은 `(batch_size, sequence_length, hidden_size)`, *선택 사항*)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.

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

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

[WhisperForAudioClassification](/docs/transformers/main/ko/model_doc/whisper#transformers.WhisperForAudioClassification)의 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 AutoFeatureExtractor, WhisperForAudioClassification
>>> from datasets import load_dataset

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")
>>> model = WhisperForAudioClassification.from_pretrained("sanchit-gandhi/whisper-medium-fleurs-lang-id")

>>> ds = load_dataset("google/fleurs", "all", split="validation", streaming=True)
>>> sample = next(iter(ds))

>>> inputs = feature_extractor(
...     sample["audio"]["array"], sampling_rate=sample["audio"]["sampling_rate"], return_tensors="pt"
... )
>>> input_features = inputs.input_features

>>> with torch.no_grad():
...     logits = model(input_features).logits

>>> predicted_class_ids = torch.argmax(logits).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]
>>> predicted_label
'Afrikaans'
```

