Transformers documentation

Voxtral

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2025-07-18에 Hugging Face Transformers에 기여되었습니다.

Voxtral

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

Mistral의 릴리스 블로그 게시물에서 더 자세히 읽을 수 있습니다.

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

주요 기능

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

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

사용

오디오 Instruct 모드

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

➡️ 오디오 + 텍스트 지시

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)

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

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)

➡️ 다중 턴:

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)

➡️ 텍스트만:

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)

➡️ 오디오만:

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)

➡️ 배치 추론!

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)

전사 모드

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

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에 의해 기여되었습니다.

VoxtralConfig

클래스 transformers.VoxtralConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneaudio_token_id: int | None = Noneprojector_hidden_act: str = 'gelu' )

매개변수

  • 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) — 멀티모달 projector에 사용되는 활성화 함수입니다.

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

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

예:

>>> 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_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 51866hidden_size: int = 1280intermediate_size: int = 5120num_hidden_layers: int = 32num_attention_heads: int = 20scale_embedding: bool = Falseactivation_function: str = 'gelu'num_mel_bins: int = 128max_source_positions: int = 1500initializer_range: float = 0.02attention_dropout: float | int = 0.0dropout: float | int = 0.0layerdrop: float | int = 0.0activation_dropout: float | int = 0.0 )

매개변수

  • 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 논문](https://huggingface.co/papers/1909.11556 참조)을 참고하세요.
  • activation_dropout (Union[float, int], 선택 사항, 기본값 0.0) — 완전 연결 레이어 내부 활성화에 적용할 dropout 비율입니다.

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

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

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

< >

( feature_extractortokenizer )

매개변수

  • feature_extractor (WhisperFeatureExtractor) — 피처 추출기는 필수 입력입니다.
  • tokenizer (MistralCommonBackend) — 토크나이저는 필수 입력값입니다.

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

VoxtralProcessor는 WhisperFeatureExtractor와 MistralCommonBackend의 모든 기능을 제공합니다. 자세한 내용은 ~WhisperFeatureExtractor와 ~MistralCommonBackend를 참고하세요.

__call__

< >

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

매개변수

  • text (Union[str, list[str], list[list[str]]], 선택 사항) — 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 혼동을 피하기 위해 is_split_into_words=True를 설정하세요.
  • max_source_positions (int, kwargs, 선택 사항, 기본값 3000) — 시간 차원 방향으로 mel spectrogram features를 분할할 때 청크당 최대 위치 수입니다.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.
  • **kwargs (ProcessingKwargs, 선택) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

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

  1. apply_chat_template apply_chat_template() 메서드.
  2. apply_transcription_request apply_transcription_request() 메서드.

VoxtralEncoder

클래스 transformers.VoxtralEncoder

< >

( config: VoxtralEncoderConfig )

매개변수

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

Whisper 인코더인 Voxtral 인코더

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_featuresattention_mask = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

매개변수

  • input_features (torch.LongTensor, shape (batch_size, feature_size, sequence_length)) — 원시 음성 웨이브폼에서 추출한 mel feature의 float 값입니다. 원시 음성 웨이브폼은 .flac 또는 .wav 오디오 파일을 list[float] 또는 numpy.ndarray 타입의 배열로 로드하여 얻을 수 있으며, 예를 들어 soundfile 라이브러리(pip install soundfile)를 사용할 수 있습니다. input_features 배열을 준비하려면, mel feature 추출, padding 및 torch.FloatTensor 타입의 텐서 변환을 위해 AutoFeatureExtractor를 사용해야 합니다. 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

class transformers.VoxtralModel

< >

( config: VoxtralConfig )

매개변수

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

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

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VoxtralModelOutputWithPast or tuple(torch.FloatTensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • input_features (torch.FloatTensor, shape (batch_size, sequence_length, feature_dim), 선택 사항) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 WhisperFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 WhisperFeatureExtractor.call()를 참조하세요 (VoxtralProcessor는 오디오 처리에 WhisperFeatureExtractor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • past_key_values (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는 past_key_values 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요. past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만 입력해야 하며, 이때의 shape은 (batch_size, unprocessed_length)입니다. shape이 (batch_size, sequence_length)인 전체 input_ids를 입력하지 않습니다.

  • inputs_embeds (torch.FloatTensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대한 더 세밀한 제어가 필요한 경우 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).

반환값

VoxtralModelOutputWithPast 또는 tuple(torch.FloatTensor)

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

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

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

  • last_hidden_state (torch.FloatTensor, 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 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 config.is_encoder_decoder=True인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 past_key_values 참조).

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

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

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

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

  • audio_hidden_states (torch.FloatTensor, 선택 사항) — 투영된 오디오 hidden states입니다.

VoxtralForConditionalGeneration

클래스 transformers.VoxtralForConditionalGeneration

< >

( config: VoxtralConfig )

매개변수

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

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

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

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneinput_features: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.FloatTensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • input_features (torch.FloatTensor, shape (batch_size, sequence_length, feature_dim), 선택 사항) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 WhisperFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 WhisperFeatureExtractor.call()를 참조하세요 (VoxtralProcessor는 오디오 처리에 WhisperFeatureExtractor를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • past_key_values (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는 past_key_values 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요. past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만 입력해야 하며, 이때의 shape은 (batch_size, unprocessed_length)입니다. shape이 (batch_size, sequence_length)인 전체 input_ids를 입력하지 않습니다.

  • inputs_embeds (torch.FloatTensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대한 더 세밀한 제어가 필요한 경우 유용합니다.
  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.vocab_size] 범위 내의 값이거나 -100이어야 합니다(input_ids docstring 참조). 인덱스가 -100으로 설정된 토큰은 무시(마스크)되며, 손실은 [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차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

반환값

CausalLMOutputWithPast 또는 tuple(torch.FloatTensor)

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

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

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

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

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

  • past_key_values (Cache, 선택 사항, use_cache=True가 전달되었거나 config.use_cache=True인 경우 반환됨) — Cache 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

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

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

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

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

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

예:

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

< >

( *args**kwargs )

Update on GitHub