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

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.

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

```python
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](https://huggingface.co/datasets/OpenSound/AudioCaps)データセットで[Audio Flamingo 3](https://huggingface.co/nvidia/audio-flamingo-3-hf)をファインチューニングし、オーディオキャプショニングを行います。
2. ファインチューニングしたモデルを推論に使用します。

> [!TIP]
> このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、[タスクページ](https://huggingface.co/tasks/audio-text-to-text)を参照することをお勧めします。

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

```bash
pip install transformers datasets peft accelerate
```

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

```py
>>> from huggingface_hub import notebook_login
>>> notebook_login()
```

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

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

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

Audio FlamingoのWhisper feature extractorに必要とされる16kHzに、audioカラムをキャストします:

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

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

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

例を見てみましょう:

```py
>>> 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 のプロセッサを読み込みます:

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

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

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

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

```py
>>> data_collator = AudioFlamingo3DataCollator(processor)
```

## 学習

> [!TIP]
> [Trainer](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer)によるモデルのファインチューニングに慣れていない場合は、[こちら](../training)の基本的なチュートリアルをご覧ください!

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

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

### LoRAを設定

[LoRA](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora)（Low-Rank Adaptation）は、追加のパラメータをわずかな数だけ学習させることで、効率的なファインチューニングを可能にします。LoRAを設定して、言語モデルのattention層とfeed-forward層を対象にしてください：

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

```

> [!TIP]
> LoRAは、モデル全体ではなく少数のアダプタパラメータのみを更新することで、メモリ使用量と学習時間を大幅に削減します。この設定は、言語モデルのattention層とfeed-forward層を対象とし、オーディオエンコーダは凍結したままにします。これにより、単一のGPUでのファインチューニングが可能になります。

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

[TrainingArguments](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.TrainingArguments) で学習ハイパーパラメータを定義します。ストリーミングデータセットを使用しているため、エポックではなく`max_steps`を使用することに注意してください。

```py
>>> 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](/docs/transformers/v5.23.0/ja/main_classes/trainer#transformers.Trainer)に渡します:

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

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

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

```

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

```py
>>> trainer.push_to_hub()
```

## 推論

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

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

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

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

```py
>>> 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"]
```

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

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

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

```py
>>> 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](/docs/transformers/v5.23.0/ja/main_classes/pipelines#transformers.Pipeline) API with an `any-to-any` model. The example below uses [Voxtral](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507), which accepts audio and text inputs and generates text. See the [any-to-any task guide](./any_to_any) for more examples.

```python
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"])
```

## さらに詳しく

- [Audio-text-to-text タスクのページ](https://huggingface.co/tasks/audio-text-to-text)では、モデルの種類、ユースケース、データセットについて説明しています。
- LoRAの設定オプションやその他のアダプター手法の詳細については、[PEFTのドキュメント](https://huggingface.co/docs/peft)を参照してください。
- モデル固有の詳細や機能については、[Audio Flamingo 3 モデルカード](https://huggingface.co/nvidia/audio-flamingo-3-hf)を参照してください。

