# 멀티모달 생성

Multimodal (any-to-any) 모델은 텍스트, 이미지, 오디오, 비디오 등 다양한 유형의 입력 데이터를 처리하고 이러한 모달리티 중 하나로 출력을 생성할 수 있는 언어 모델입니다. 기존의 단일 모달리티 또는 고정 모달리티 모델과 달리, 입력과 출력의 유연한 조합을 허용하여 단일 시스템으로 텍스트-이미지 생성, 오디오-텍스트 전사, 이미지 캡셔닝, 비디오 이해 등 폭넓은 작업을 처리할 수 있습니다. 이 작업은 이미지-텍스트-텍스트와 많은 유사점을 공유하지만, 더 넓은 범위의 입력 및 출력 모달리티를 지원합니다.

이 가이드에서는 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 template](../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/v5.25.0/ko/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/v5.25.0/ko/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")
```

아래 예시는 텍스트 입력을 포맷팅하기 위해 chat templates를 사용하며, 오디오 모달리티를 멀티모달 데이터로 사용합니다.

```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/v5.25.0/ko/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"]
```

Any-to-any pipeline also supports generating audio or images with any-to-any models. For that you need to set `generation_mode` parameter. Do not forget to set video sampling to the desired FPS, otherwise the whole video will be loaded without sampling. Here is an example code:

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

