# 多模态生成

Multimodal (any-to-any) models are language models capable of processing diverse types of input data (e.g., text, images, audio, or video) and generating outputs in any of these modalities. Unlike traditional unimodal or fixed-modality models, they allow flexible combinations of input and output, enabling a single system to handle a wide range of tasks: from text-to-image generation to audio-to-text transcription, image captioning, video understanding, and so on. This task shares many similarities with image-text-to-text, but supports a wider range of input and output modalities.

在本指南中，我们将简要介绍任意到任意（any-to-any）模型，并展示如何使用 Transformers 进行推理。与通常仅限于视觉-语言任务的视觉 LLM 不同，全模态（omni-modal）模型可以接受任意模态组合（例如文本、图像、音频、视频）作为输入，并生成不同模态的输出，例如文本或图像。

让我们从安装依赖项开始：

```bash
pip install -q transformers accelerate flash_attn
```

让我们初始化模型和处理器。

```python
from transformers import AutoProcessor, AutoModelForMultimodalLM
import torch

model = AutoModelForMultimodalLM.from_pretrained(
    "Qwen/Qwen2.5-Omni-3B",
    device_map="auto",
    attn_implementation="flash_attention_2",
)

processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-Omni-3B")
```

这些模型通常包含一个 [聊天模板](../chat_templating)，用于跨模态组织对话。输入可以在单轮中混合图像、文本、音频或其他支持的格式。输出也可能有所不同（例如，文本生成或音频生成），具体取决于配置。

以下是一个示例，提供“文本 + 音频”输入并请求文本响应。

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

接下来，我们将调用处理器的 [apply_chat_template()](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) 方法，对其输出以及图像输入进行预处理。

```python
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(model.device)
```

现在，我们可以将预处理后的输入传递给模型。

```python
with torch.no_grad():
    generated_ids = model.generate(**inputs, max_new_tokens=100, generation_mode="text")
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
print(generated_texts)
```

## Pipeline

最快的入门方式是使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) API。指定 `"any-to-any"` 任务以及您想要使用的模型。

```python
from transformers import pipeline
pipe = pipeline("any-to-any", model="mistralai/Voxtral-Mini-3B-2507")
```

以下示例使用聊天模板来格式化文本输入，并将音频模态作为多模态数据。

```python
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?"},
         ],
     },
 ]
```

将经过聊天模板格式化的文本和图像传入 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline)，并设置 `return_full_text=False` 以从生成的输出中移除输入。

```python
outputs = pipe(text=messages, max_new_tokens=20, return_full_text=False)
outputs[0]["generated_text"]
```

任意到任意流水线也支持使用任意到任意模型生成音频或图像。为此，您需要设置 `generation_mode` 参数。请别忘了将视频采样设置为所需的 FPS，否则整个视频将在不进行采样的情况下被加载。以下是一个示例代码：

```python
import soundfile as sf
pipe = pipeline("any-to-any", model="Qwen/Qwen2.5-Omni-3B")
messages = [
    {
        "role": "user",
        "content": [
            {"type": "video", "path": "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/Cooking_cake.mp4"},
            {"type": "text", "text": "Describe this video."},
        ],
    },
]
output = pipe(text=messages, fps=1, load_audio_from_video=True, max_new_tokens=20, generation_mode="audio")
sf.write("generated_audio.wav", out[0]["generated_audio"])
```

