Transformers documentation

オーディオテキストからテキストへ

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

and get access to the augmented documentation experience

to get started

オーディオテキストからテキストへ

Audio-text-to-text models accept both audio and text as inputs and generate text as output. They combine audio understanding with language generation, enabling tasks like audio question answering (e.g., “What is being said in this clip?”), audio reasoning (e.g., “What emotion does the speaker convey?”), and spoken dialogue understanding. Unlike traditional automatic speech recognition (ASR) models that only transcribe speech into text, audio-text-to-text models can reason about the audio content, follow complex instructions, and produce contextual responses based on what they hear.

以下の例では、モデルとプロセッサを読み込み、テキストプロンプト付きの音声ファイルを渡して応答を生成する方法を示しています。ここでは、モデルに音声録音を文字起こしするように指示しています。

from transformers import AudioFlamingo3ForConditionalGeneration, AutoProcessor

model_id = "nvidia/audio-flamingo-3-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AudioFlamingo3ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

conversation = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Transcribe the input speech."},
            {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/WhDJDIviAOg_120_10.mp3"},
        ],
    }
]

inputs = processor.apply_chat_template(
    conversation,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
).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(decoded_outputs)
## ["The transcription of the audio is 'summer follows spring the days grow longer and the nights are warm'."]

このガイドでは、次の方法について説明します:

  1. LoRAを使用して、AudioCapsデータセットでAudio Flamingo 3をファインチューニングし、オーディオキャプショニングを行います。
  2. ファインチューニングしたモデルを推論に使用します。

このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、タスクページを参照することをお勧めします。

開始前に、必要なライブラリがすべてインストールされていることを確認してください。

pip install transformers datasets peft accelerate

Hugging Face アカウントにログインして、モデルをアップロードし、コミュニティと共有できるようにすることを推奨します。プロンプトが表示されたら、ログイン用のトークンを入力してください:

>>> from huggingface_hub import notebook_login
>>> notebook_login()

AudioCaps データセットを読み込む

🤗 Datasets ライブラリからAudioCapsデータセットをストリーミングモードで読み込むことから始めます。このデータセットには説明的なキャプション付きの音声クリップが含まれており、音声キャプション付けタスクに最適です。

>>> from datasets import load_dataset, Audio
>>> dataset = load_dataset("OpenSound/AudioCaps", split="train", streaming=True)

Audio Flamingo の Whisper feature extractor に 16kHz が必須であるため、audio 列を 16kHz にキャストします:

>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))

ストリーミングデータセットでは、.take()と.skip()を使用して、データセットを学習用とテスト用に分割します:

>>> train_dataset = dataset.take(1000)
>>> eval_dataset = dataset.skip(1000).take(100)

例を見てみましょう:

>>> next(iter(train_dataset))
{'audiocap_id': 91139, 'youtube_id': 'r1nicOVtvkQ', 'start_time': 130, 'caption': 'A woman talks nearby as water pours', 'audio_length': 480000, 'audio': <datasets.features._torchcodec.AudioDecoder object at ...>}

データセットには以下が含まれます:

  • audio: 音声波形
  • caption: 音声の説明テキスト

前処理

オーディオとテキストの両方の入力を処理するために、Audio Flamingo のプロセッサを読み込みます:

>>> from transformers import AutoProcessor
>>> processor = AutoProcessor.from_pretrained("nvidia/audio-flamingo-3-hf")

Audio Flamingo が期待する形式に音声とテキストのペアを処理するデータコラテーターを作成します。このコラテーターは、直接音声配列を使用するチャットテンプレート形式を使用します。

>>> class AudioFlamingo3DataCollator:
...     """Data collator for Audio Flamingo 3 audio captioning training."""
...
...     def __init__(self, processor):
...         self.processor = processor
...
...     def __call__(self, features):
...         conversations = []
...
...         for feature in features:
...             # Build conversation format for Audio Flamingo
...             # Audio is passed directly as an array, no base64 encoding needed
...             sample = [
...                 {
...                     "role": "user",
...                     "content": [
...                         {"type": "text", "text": "Describe the audio."},
...                         {"type": "audio", "audio": feature["audio"].get_all_samples().data[0].numpy()},
...                     ],
...                 },
...                 {
...                     "role": "assistant",
...                     "content": [{"type": "text", "text": feature["caption"]}],
...                 }
...             ]
...             conversations.append(sample)
...
...         # Apply chat template and format labels for training
...         return self.processor.apply_chat_template(
...             conversations,
...             tokenize=True,
...             add_generation_prompt=False,
...             return_dict=True,
...             output_labels=True,  # Automatically creates labels for training
...         )

データコラテーターをインスタンス化します:

>>> data_collator = AudioFlamingo3DataCollator(processor)

学習

Trainer を用いたモデルのファインチューニングに慣れていない場合は、こちらの基本的なチュートリアルをご覧ください!

Audio Flamingo モデルを読み込みます。効率的なメモリ使用のために、bfloat16 精度と device_map="auto" を使用します:

>>> from transformers import AudioFlamingo3ForConditionalGeneration
>>> import torch
>>> model = AudioFlamingo3ForConditionalGeneration.from_pretrained(
...     "nvidia/audio-flamingo-3-hf",
...     torch_dtype=torch.bfloat16,
...     device_map="auto",
... )

LoRAを設定

LoRA(Low-Rank Adaptation)は、追加のパラメータを少数のみ学習させることで、効率的なファインチューニングを可能にします。LoRAを設定して、言語モデルのattention層とfeed-forward層を対象にしてください。

>>> from peft import LoraConfig, get_peft_model
>>> lora_config = LoraConfig(
...     r=16,  # LoRA rank
...     lora_alpha=32,  # LoRA scaling factor
...     target_modules=[
...         # Language model attention
...         "q_proj",
...         "k_proj",
...         "v_proj",
...         "o_proj",
...         # Feed-forward layers
...         "gate_proj",
...         "up_proj",
...         "down_proj",
...     ],
...     lora_dropout=0.05,
...     bias="none",
...     task_type="CAUSAL_LM",
... )
>>> model = get_peft_model(model, lora_config)
>>> model.print_trainable_parameters()
trainable params: 44,302,336 || all params: 8,311,517,696 || trainable%: 0.5330

LoRAは、モデル全体ではなく少数の適応器パラメータのみを更新することで、メモリ使用量と学習時間を大幅に削減します。この設定では、言語モデルのattention層とfeed-forward層を対象とし、音声エンコーダーは凍結したままにすることで、単一のGPUでのファインチューニングを可能にしています。

トレーニングのセットアップ

TrainingArguments で学習ハイパーパラメータを定義します。ストリーミングデータセットを使用しているため、エポックではなく max_steps を使用することに注意してください。

>>> from transformers import TrainingArguments, Trainer
>>> training_args = TrainingArguments(
...     output_dir="audio-flamingo-3-hf-lora-finetuned",
...     per_device_train_batch_size=4,
...     per_device_eval_batch_size=4,
...     gradient_accumulation_steps=4,
...     learning_rate=1e-4,
...     max_steps=500,  # Use max_steps with streaming datasets
...     bf16=True,
...     logging_steps=10,
...     eval_steps=100,
...     save_steps=250,
...     save_total_limit=2,  # Keep only the latest 2 checkpoints
...     save_only_model=True,  # Skip saving optimizer state to save disk space
...     eval_strategy="steps",
...     save_strategy="steps",
...     remove_unused_columns=False,
...     dataloader_num_workers=0,  # Must be 0 for streaming datasets
...     gradient_checkpointing=True,
...     report_to="none",
... )

モデル、データセット、データコラクターとともに、学習引数をTrainerに渡します:

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=train_dataset,
...     eval_dataset=eval_dataset,
...     data_collator=data_collator,
... )
>>> trainer.train()

LoRA アダプターとプロセッサーを保存します:

>>> trainer.save_model()
>>> processor.save_pretrained("audio-flamingo-3-hf-lora-finetuned")
['audio-flamingo-3-hf-lora-finetuned/processor_config.json']

トレーニングが完了したら、モデルを Hub に共有します:

>>> trainer.push_to_hub()

推論

モデルのファインチューニングが完了したので、音声キャプショニングに使用できます。

ファインチューニング済みのモデルとプロセッサを読み込みます:

>>> from transformers import AudioFlamingo3ForConditionalGeneration, AutoProcessor
>>> from peft import PeftModel
>>> import torch
>>> base_model = AudioFlamingo3ForConditionalGeneration.from_pretrained(
...     "nvidia/audio-flamingo-3-hf",
...     torch_dtype=torch.bfloat16,
...     device_map="auto",
... )
>>> model = PeftModel.from_pretrained(base_model, "audio-flamingo-3-hf-lora-finetuned")
>>> processor = AutoProcessor.from_pretrained("audio-flamingo-3-hf-lora-finetuned")

推論用のオーディオサンプルを読み込みます:

>>> from datasets import load_dataset, Audio
>>> dataset = load_dataset("OpenSound/AudioCaps", split="test", streaming=True)
>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
>>> sample = next(iter(dataset))
>>> audio = sample["audio"]
>>> audio_array = audio.get_all_samples().data[0].numpy() if hasattr(audio, "get_all_samples") else audio["array"]

会話形式で入力を用意します:

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "text", "text": "Describe the audio."},
...             {"type": "audio", "audio": audio_array},
...         ],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
... ).to(device=model.device, dtype=model.dtype)

レスポンスを生成します:

>>> with torch.no_grad():
...     output_ids = model.generate(**inputs, max_new_tokens=100)
>>> # Decode only the generated tokens
>>> input_len = inputs["input_ids"].shape[1]
>>> response = processor.tokenizer.decode(output_ids[0][input_len:], skip_special_tokens=True)
>>> print(response)
## A sewing machine is running while people are talking

パイプライン

For quick inference, use the Pipeline API with an any-to-any model. The example below uses Voxtral, which accepts audio and text inputs and generates text. See the any-to-any task guide for more examples.

from transformers import pipeline

pipe = pipeline("any-to-any", model="mistralai/Voxtral-Mini-3B-2507")

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "audio",
                "url": "https://huggingface.co/datasets/raushan-testing-hf/audio-test/resolve/main/glass-breaking-151256.mp3",
            },
            {"type": "text", "text": "What do you hear in this audio?"},
        ],
    },
]

outputs = pipe(text=messages, max_new_tokens=100, return_full_text=False)
print(outputs[0]["generated_text"])

さらに詳しく

Update on GitHub