Transformers documentation

Voxtral

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2025年7月18日にHugging Face Transformersに貢献されました。

Voxtral

Voxtral は Ministral 3B と Mistral Small 3B のアップグレード版であり、音声入力への対応により言語処理機能を拡張しています。音声文字起こし、翻訳、音声理解などのタスクに対応するように設計されています。

Mistralのリリースブログ記事で詳細を読むことができます。

モデルは2つのチェックポイントで利用できます:

主な機能

VoxtralはMinistral-3Bをベースに、音声処理機能を追加したモデルです:

  • 文字起こしモード: 音声の文字起こしに特化したモードが含まれています。デフォルトでは、Voxtral が話されている言語を自動検出し、それに合わせて文字起こしを行います。
  • 長文脈: 32kトークンのコンテキストウィンドウにより、Voxtralは文字起こしで最大30分間、より広範な音声理解で最大40分間の音声を処理できます。
  • 統合された Q&A と要約: 個別の ASR や言語モデルに依存せずに、オーディオを直接クエリし、構造化された要約を生成できます。
  • 多言語対応: 言語を自動検出し、英語、スペイン語、フランス語、ポルトガル語、ヒンディー語、ドイツ語、オランダ語、イタリア語など、広く話されている複数の言語で優れたパフォーマンスを発揮します。
  • 音声による関数呼び出し: 検出されたユーザーの意図に基づき、音声入力から直接関数やワークフローをトリガーできます。
  • テキスト機能: Ministral-3B基盤モデルの優れたテキスト処理性能を維持しています。

使用方法

Audio 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]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • audio_token_id (int, 省略可) — 入力音声のプレースホルダーとして使用される音声トークンのインデックスです。
  • projector_hidden_act (str、任意、デフォルトは gelu) — マルチモーダルプロジェクターで使用する活性化関数です。

これはVoxtralModelの設定を保存するための設定クラスです。指定された引数に基づいてVoxtralモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、mistralai/Voxtral-Mini-3B-2507と類似した設定が得られます。

設定オブジェクトは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

class 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 デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 20) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • 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 フィルターバンク特徴量の最大シーケンス長です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • attention_dropout (Union[float, int]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。
  • 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と類似した設定が得られます。

設定オブジェクトは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) — トークナイザーは必須の入力です。

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) — 時間軸に沿ってメルスペクトログラム特徴を分割する際の、チャンクあたりの最大ポジション数。
  • return_mm_token_type_ids (bool, kwargs) — マルチモーダルプレースホルダトークンの位置を示すマルチモーダルトークンタイプIDを返すかどうか。
  • return_text_replacement_offsets (bool, kwargs) — 各マルチモーダルプレースホルダーとその置換文字列の文字オフセットを返すかどうかを指定します。
  • 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)) — 生の音声波形から抽出されたメル特徴量の浮動小数点値。生の音声波形は、.flac または .wav 形式のオーディオファイルを list[float] 型または numpy.ndarray 型の配列として読み込むことで取得できます。例えば、soundfile ライブラリ(pip install soundfile)を使用します。input_features として配列を準備するには、メル特徴量の抽出、パディング、および torch.Tensor 型への変換を行うために 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

クラス 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.Tensor] = 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.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VoxtralModelOutputWithPast or tuple(torch.Tensor)

パラメータ

  • input_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。

    インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

  • input_features (torch.Tensor、形状 (batch_size, sequence_length, feature_dim)、任意) — 入力音声特徴に対応するテンソルです。音声特徴は WhisperFeatureExtractor を使用して取得できます。詳細は WhisperFeatureExtractor.call() を参照してください(VoxtralProcessor は音声の処理に WhisperFeatureExtractor を使用します)。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • position_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲 [0, config.n_positions - 1].

    ポジションIDとは?

  • past_key_values (~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返した past_key_values であり、 use_cache=True または config.use_cache=True.

    入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。 past_key_values が渡されない場合、デフォルトで DynamicCache が初期化されます。

    モデルは、入力として与えられたのと同じキャッシュ形式を出力します。

    past_key_values を使用する場合、すべての input_ids(形状 (batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理の input_ids(形状 (batch_size, unprocessed_length))のみを入力することになります。

  • inputs_embeds (torch.Tensor、形状 (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)や入力に応じて、さまざまな要素で構成されます。

VoxtralModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • last_hidden_state (torch.Tensor、形状 (batch_size, sequence_length, hidden_size)) — モデルの最終層の出力における隠れ状態のシーケンス。

    past_key_valuesが使用されている場合、出力されるのは、形状(batch_size, 1, hidden_size)のシーケンスの最後の隠れ状態のみです。

  • past_key_values (Cache、任意、use_cache=True が渡された場合または config.use_cache=True の場合に返されます) — Cache のインスタンスです。詳細については、kv cache ガイドを参照してください。

    自己アテンションブロック(および config.is_encoder_decoder=True の場合、クロスカレンションブロック)の事前計算済みヒドゥンステート(キーとバリュー)を保持します。これらは逐次デコーディングを高速化するために使用できます(past_key_values 入力参照)。

  • hidden_states (tuple(torch.Tensor)、optional、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)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.Tensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

  • audio_hidden_states (torch.Tensor、任意) — 投影されたオーディオの隠れ状態。

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.Tensor] = 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.Tensor] = 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.Tensor)

パラメータ

  • input_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。

    インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

  • input_features (torch.Tensor、形状 (batch_size, sequence_length, feature_dim)、任意) — 入力音声特徴に対応するテンソルです。音声特徴は WhisperFeatureExtractor を使用して取得できます。詳細は WhisperFeatureExtractor.call() を参照してください(VoxtralProcessor は音声の処理に WhisperFeatureExtractor を使用します)。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • position_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲 [0, config.n_positions - 1].

    ポジションIDとは?

  • past_key_values (~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返した past_key_values であり、 use_cache=True または config.use_cache=True.

    入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。 past_key_values が渡されない場合、デフォルトで DynamicCache が初期化されます。

    モデルは、入力として与えられたのと同じキャッシュ形式を出力します。

    past_key_values を使用する場合、すべての input_ids(形状 (batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理の input_ids(形状 (batch_size, unprocessed_length))のみを入力することになります。

  • inputs_embeds (torch.Tensor、形状 (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.Tensor)

torch.Tensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)または CausalLMOutputWithPast。設定(VoxtralConfig)と入力に応じて、さまざまな要素で構成されます。

VoxtralForConditionalGenerationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • loss (torch.Tensor、形状 (1,)、任意、labels が指定された場合に返されます) — 言語モデリングの損失(次のトークンの予測用)。

  • logits (torch.Tensor、形状 (batch_size, sequence_length, config.vocab_size)) — 言語モデリングヘッドの予測スコア(SoftMax 適用前の各語彙トークンのスコア)。

  • past_key_values (Cache、任意、use_cache=True が渡された場合または config.use_cache=True の場合に返されます) — Cache のインスタンスです。詳細については、kv cache ガイドを参照してください。

    逐次デコーディングを高速化するために使用できる(past_key_values 入力参照)、事前計算済みの隠れ状態(自己注意ブロックのキーとバリュー)が含まれます。

  • hidden_states (tuple(torch.Tensor)、optional、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)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.Tensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

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