# Voxtral

Voxtral은 [Ministral 3B 및 Mistral Small 3B](https://mistral.ai/news/ministraux)의 업그레이드 버전으로, 오디오 입력 지원을 통해 언어 처리 기능을 확장했습니다. 음성 전사, 번역, 오디오 이해와 같은 작업을 처리하도록 설계되었습니다.

Mistral의 [릴리스 블로그 게시물](https://mistral.ai/news/voxtral)에서 더 자세히 읽을 수 있습니다.

모델은 두 개의 체크포인트로 제공됩니다:

- 3B: [mistralai/Voxtral-Mini-3B-2507](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507)
- 24B: [mistralai/Voxtral-Small-24B-2507](https://huggingface.co/mistralai/Voxtral-Small-24B-2507)

## 주요 기능

Voxtral은 Ministral-3B를 기반으로 오디오 처리 기능을 추가하여 구성됩니다:

- **전사 모드**: 음성 전사를 위한 전용 모드를 포함합니다. 기본적으로 Voxtral은 발화 언어를 감지하고 그에 따라 전사합니다.
- **긴 형식 컨텍스트**: 32k 토큰 컨텍스트 윈도우를 갖춘 Voxtral은 전사 작업의 경우 최대 30분, 보다 폭넓은 오디오 이해 작업의 경우 최대 40분까지의 오디오를 처리할 수 있습니다.
- **통합 Q&A 및 요약**: 별도의 ASR 및 언어 모델에 의존하지 않고 오디오를 직접 쿼리하고 구조화된 요약을 생성할 수 있습니다.
- **다국어 지원**: 영어, 스페인어, 프랑스어, 포르투갈어, 힌디어, 독일어, 네덜란드어, 이탈리아어 등 여러 주요 언어에서 언어를 자동으로 감지하고 우수한 성능을 발휘합니다.
- **음성을 통한 함수 호출**: 감지된 사용자 의도에 따라 음성 입력으로 함수나 워크플로를 직접 트리거할 수 있습니다.
- **텍스트 기능**: Ministral-3B 기반 모델의 강력한 텍스트 처리 성능을 유지합니다.

## 사용

### 오디오 Instruct 모드

모델은 다중 턴 및 다중 오디오 상호작용을 포함한 오디오-텍스트 지시를 지원하며, 모든 처리는 배치 단위로 수행됩니다.

➡️ 오디오 + 텍스트 지시

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/eustlb/audio-samples/resolve/main/dude_where_is_my_car.wav",
            },
            {"type": "text", "text": "What can you tell me about this audio?"},
        ],
    }
]

inputs = processor.apply_chat_template(conversation)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated response:")
print("=" * 80)
print(decoded_outputs[0])
print("=" * 80)
```

➡️ 다중 오디오 + 텍스트 지시

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3",
            },
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3",
            },
            {"type": "text", "text": "What sport and what nursery rhyme are referenced?"},
        ],
    }
]

inputs = processor.apply_chat_template(conversation)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated response:")
print("=" * 80)
print(decoded_outputs[0])
print("=" * 80)
```

➡️ 다중 턴:

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3",
            },
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
            },
            {"type": "text", "text": "Describe briefly what you can hear."},
        ],
    },
    {
        "role": "assistant",
        "content": "The audio begins with the speaker delivering a farewell address in Chicago, reflecting on his eight years as president and expressing gratitude to the American people. The audio then transitions to a weather report, stating that it was 35 degrees in Barcelona the previous day, but the temperature would drop to minus 20 degrees the following day.",
    },
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav",
            },
            {"type": "text", "text": "Ok, now compare this new audio with the previous one."},
        ],
    },
]

inputs = processor.apply_chat_template(conversation)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated response:")
print("=" * 80)
print(decoded_outputs[0])
print("=" * 80)
```

➡️ 텍스트만:

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "What if a cyber brain could possibly generate its own ghost, and create a soul all by itself?",
            },
        ],
    }
]

inputs = processor.apply_chat_template(conversation)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated response:")
print("=" * 80)
print(decoded_outputs[0])
print("=" * 80)
```

➡️ 오디오만:

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav",
            },
        ],
    }
]

inputs = processor.apply_chat_template(conversation)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated response:")
print("=" * 80)
print(decoded_outputs[0])
print("=" * 80)
```

➡️ 배치 추론!

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

conversations = [
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3",
                },
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3",
                },
                {
                    "type": "text",
                    "text": "Who's speaking in the speech and what city's weather is being discussed?",
                },
            ],
        }
    ],
    [
        {
            "role": "user",
            "content": [
                {
                    "type": "audio",
                    "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3",
                },
                {"type": "text", "text": "What can you tell me about this audio?"},
            ],
        }
    ],
]

inputs = processor.apply_chat_template(conversations)
inputs = inputs.to(model.device)

outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated responses:")
print("=" * 80)
for decoded_output in decoded_outputs:
    print(decoded_output)
    print("=" * 80)
```

### 전사 모드

모델을 사용하여 오디오를 전사합니다(영어, 스페인어, 프랑스어, 포르투갈어, 힌디어, 독일어, 네덜란드어, 이탈리아어에서 최첨단 성능을 발휘)! 또한 자동 언어 감지를 지원합니다.

```python
from transformers import AutoProcessor, VoxtralForConditionalGeneration

repo_id = "mistralai/Voxtral-Mini-3B-2507"

processor = AutoProcessor.from_pretrained(repo_id)
model = VoxtralForConditionalGeneration.from_pretrained(repo_id, device_map="auto")

# set the language if already known for better accuracy
inputs = processor.apply_transcription_request(language="en", audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", model_id=repo_id)

# # but you can also let the model detect the language automatically
# inputs = processor.apply_transcription_request(audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", model_id=repo_id)

inputs = inputs.to(model.device)
outputs = model.generate(**inputs, max_new_tokens=500)
decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)

print("\nGenerated responses:")
print("=" * 80)
for decoded_output in decoded_outputs:
    print(decoded_output)
    print("=" * 80)
```

이 모델은 [Eustache Le Bihan](https://huggingface.co/eustlb)에 의해 기여되었습니다.

## VoxtralConfig[[transformers.VoxtralConfig]]

#### transformers.VoxtralConfig[[transformers.VoxtralConfig]]

```python
transformers.VoxtralConfig(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, audio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, audio_token_id: int | None = None, projector_hidden_act: str = 'gelu')
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/configuration_voxtral.py#L76)

**매개변수:**

audio_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 오디오 백본의 config 객체 또는 사전입니다.

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 텍스트 백본의 config 객체 또는 사전입니다.

audio_token_id (`int`, *선택 사항*) : 입력 오디오의 자리표시자로 사용되는 오디오 토큰 인덱스입니다.

projector_hidden_act (`str`, *선택 사항*, 기본값 `gelu`) : 멀티모달 프로젝터에 사용되는 활성화 함수입니다.

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

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

예:

```python
>>> from transformers import VoxtralForConditionalGeneration, VoxtralConfig

>>> # Initializing a Voxtral configuration
>>> configuration = VoxtralConfig(audio_token_id=24, projector_hidden_act="gelu")

>>> # Initializing a 3B model with random weights
>>> model = VoxtralForConditionalGeneration(configuration)

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

## VoxtralEncoderConfig[[transformers.VoxtralEncoderConfig]]

#### transformers.VoxtralEncoderConfig[[transformers.VoxtralEncoderConfig]]

```python
transformers.VoxtralEncoderConfig(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 = 51866, hidden_size: int = 1280, intermediate_size: int = 5120, num_hidden_layers: int = 32, num_attention_heads: int = 20, scale_embedding: bool = False, activation_function: str = 'gelu', num_mel_bins: int = 128, max_source_positions: int = 1500, initializer_range: float = 0.02, attention_dropout: float | int = 0.0, dropout: float | int = 0.0, layerdrop: float | int = 0.0, activation_dropout: float | int = 0.0)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/configuration_voxtral.py#L25)

**매개변수:**

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

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

intermediate_size (`int`, *선택 사항*, 기본값 `5120`) : MLP 표현의 차원.

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

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

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

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

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

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

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

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

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

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

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

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

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

```python
>>> from transformers import VoxtralEncoderConfig, VoxtralEncoder

>>> # Initializing a VoxtralEncoderConfig
>>> configuration = VoxtralEncoderConfig()

>>> # Initializing a VoxtralEncoder (with random weights)
>>> model = VoxtralEncoder(configuration)

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

## VoxtralProcessor[[transformers.VoxtralProcessor]]

#### transformers.VoxtralProcessor[[transformers.VoxtralProcessor]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/processing_voxtral.py#L63)

**매개변수:**

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

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

feature extractor와 tokenizer를 단일 프로세서로 감싸는 VoxtralProcessor를 생성합니다.

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

#### __call__[[transformers.VoxtralProcessor.__call__]]

```python
__call__(text: str | list[str] | list[list[str]] | None, **kwargs: *<class 'transformers.models.voxtral.processing_voxtral.VoxtralProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/processing_voxtral.py#L224)

**매개변수:**

text (`Union[str, list[str], list[list[str]]]`, *선택*) : 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 혼동을 피하기 위해 `is_split_into_words=True`를 설정하세요.

max_source_positions (`int`, *kwargs*, *선택 사항*, 기본값 `3000`) : 멜 스펙트로그램 특징을 시간 차원별로 분할할 때 청크당 최대 위치 수.

return_mm_token_type_ids (`bool`, *kwargs*) : 멀티모달 플레이스홀더 토큰의 위치를 나타내는 멀티모달 토큰 타입 ID를 반환할지 여부.

return_text_replacement_offsets (`bool`, *kwargs*) : 각 멀티모달 플레이스홀더 및 그 대체 문자열의 문자 오프셋을 반환할지 여부.

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

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/ko/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

모델 입력으로 제공될 텍스트를 준비하는 메서드입니다. 이 메서드는 `text` 인수를 MistralCommonBackend의 `__call__()`로 전달하여 텍스트를 인코딩합니다. 자세한 내용은 해당 메서드의 docstring을 참고하세요. 이 메서드는 오디오를 지원하지 않습니다. 오디오를 준비하려면 다음을 사용하세요:
1. `apply_chat_template` `apply_chat_template()` 메서드.
2. `apply_transcription_request` `apply_transcription_request()` 메서드.

## VoxtralEncoder[[transformers.VoxtralEncoder]]

#### transformers.VoxtralEncoder[[transformers.VoxtralEncoder]]

```python
transformers.VoxtralEncoder(config: VoxtralEncoderConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L237)

**매개변수:**

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

Whisper 인코더인 Voxtral 인코더

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/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.VoxtralEncoder.forward]]

```python
forward(input_features, attention_mask = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L287)

**매개변수:**

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

attention_mask (`torch.Tensor`)`, *optional*) : Voxtral does not support masking of the `input_features`, this argument is preserved for compatibility, but it is not used. By default the silence in the input log mel spectrogram are ignored.

## VoxtralModel[[transformers.VoxtralModel]]

#### transformers.VoxtralModel[[transformers.VoxtralModel]]

```python
transformers.VoxtralModel(config: VoxtralConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L379)

**매개변수:**

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

Whisper 인코더, 멀티모달 프로젝터, Llama 언어 모델로 구성되며 언어 모델링 헤드가 없는 Voxtral 모델.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/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.VoxtralModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L434)

**매개변수:**

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

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

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

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

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/v5.23.0/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` 인덱스를 관련 벡터로 변환하는 방식에 대해 더 많은 제어가 필요한 경우 유용합니다.

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

**반환값:** `VoxtralModelOutputWithPast` 또는 `tuple(torch.Tensor)`

`VoxtralModelOutputWithPast` 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우)로, [VoxtralConfig](/docs/transformers/v5.23.0/ko/model_doc/voxtral#transformers.VoxtralConfig) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

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

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

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 `config.is_encoder_decoder=True`인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).
- **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 가중치입니다.
- **audio_hidden_states** (`torch.Tensor`, *선택 사항*) -- 투영된 오디오 히든 상태입니다.

## VoxtralForConditionalGeneration[[transformers.VoxtralForConditionalGeneration]]

#### transformers.VoxtralForConditionalGeneration[[transformers.VoxtralForConditionalGeneration]]

```python
transformers.VoxtralForConditionalGeneration(config: VoxtralConfig)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L485)

**매개변수:**

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

Whisper 인코더, 멀티모달 프로젝터, Llama 언어 모델로 구성된 Voxtral 모델입니다.

이 모델은 [PreTrainedModel](/docs/transformers/v5.23.0/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.VoxtralForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, input_features: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = 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, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L497)

**매개변수:**

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

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

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

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

past_key_values (`~cache_utils.Cache`, *선택*) : 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)입니다. 일반적으로 `use_cache=True` 또는 `config.use_cache=True`일 때 모델이 디코딩의 이전 단계에서 반환한 `past_key_values`로 구성됩니다. 입력으로 [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스만 허용되며, [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요. `past_key_values`가 전달되지 않으면 기본적으로 [DynamicCache](/docs/transformers/v5.23.0/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` 참조).

logits_to_keep (`Union[int, torch.Tensor]`, *선택 사항*, 기본값 `0`) : `int`인 경우, 마지막 `logits_to_keep` 토큰에 대한 logits를 계산합니다. `0`인 경우, 모든 `input_ids`에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. `torch.Tensor`인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 packed tensor 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

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

config ([VoxtralConfig](/docs/transformers/v5.23.0/ko/model_doc/voxtral#transformers.VoxtralConfig)) 및 입력에 따라 다양한 요소를 포함하는 [CausalLMOutputWithPast](/docs/transformers/v5.23.0/ko/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 또는 `torch.Tensor`의 튜플 (`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[VoxtralForConditionalGeneration](/docs/transformers/v5.23.0/ko/model_doc/voxtral#transformers.VoxtralForConditionalGeneration)의 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** (`Cache`, *선택 사항*, `use_cache=True`가 전달되었거나 `config.use_cache=True`인 경우 반환됨) -- [Cache](/docs/transformers/v5.23.0/ko/internal/generation_utils#transformers.Cache) 인스턴스입니다. 자세한 내용은 [kv cache 가이드](https://huggingface.co/docs/transformers/en/kv_cache)를 참조하세요.

  순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value)를 포함합니다(입력 `past_key_values` 참조).
- **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 VoxtralForConditionalGeneration, AutoProcessor
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> repo_id = "mistralai/Voxtral-Mini-3B-2507"

>>> processor = AutoProcessor.from_pretrained(repo_id)
>>> model = VoxtralForConditionalGeneration.from_pretrained(repo_id, dtype=torch.bfloat16, device_map=device)

>>> conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav",
            },
            {"type": "text", "text": "What can you tell me about this audio?"},
        ],
    }
]

>>> inputs = processor.apply_chat_template(conversation)
>>> inputs = inputs.to(device, dtype=torch.bfloat16)

>>> outputs = model.generate(**inputs, max_new_tokens=30)
>>> processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
["This audio is a humorous conversation between two friends, likely in English, where one of them is trying to figure out what the other's tattoo says."]
```

#### get_audio_features[[transformers.VoxtralForConditionalGeneration.get_audio_features]]

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

[소스](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/voxtral/modeling_voxtral.py#L494)

