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

멀티모달 생성

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

이 가이드에서는 any-to-any 모델에 대해 간략히 소개하고, Transformers를 사용하여 추론을 수행하는 방법을 보여 줍니다. 비전 LLM은 일반적으로 비전-언어 작업으로 제한되는 반면, omni-modal 모델은 텍스트, 이미지, 오디오, 비디오와 같은 임의의 모달리티 조합을 입력으로 받아들이고, 텍스트나 이미지와 같은 다양한 모달리티로 출력을 생성할 수 있습니다.

의존성을 설치하는 것으로 시작해 보겠습니다:

pip install -q transformers accelerate flash_attn

모델과 프로세서를 초기화해 보겠습니다.

from transformers import AutoProcessor, AutoModelForMultimodalLM, infer_device
import torch

device = torch.device(infer_device())
model = AutoModelForMultimodalLM.from_pretrained(
    "Qwen/Qwen2.5-Omni-3B",
    dtype=torch.bfloat16,
    attn_implementation="flash_attention_2",
).to(device)

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

이러한 모델은 일반적으로 chat template을 포함하여 여러 모달리티에 걸친 대화를 구조화합니다. 입력은 단일 턴에서 이미지, 텍스트, 오디오 또는 기타 지원되는 형식을 혼합할 수 있습니다. 출력도 구성에 따라 달라질 수 있습니다(예: 텍스트 생성 또는 오디오 생성).

아래는 “텍스트 + 오디오” 입력을 제공하고 텍스트 응답을 요청하는 예시입니다.

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() 메서드를 호출하여 출력과 이미지 입력을 전처리합니다.

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
)

이제 전처리된 입력을 모델에 전달할 수 있습니다.

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

Pipeline

가장 빠르게 시작하는 방법은 Pipeline API를 사용하는 것입니다. "any-to-any" 작업과 사용하려는 모델을 지정하세요.

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

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

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에 전달하고, return_full_text=False를 설정하여 생성된 출력에서 입력을 제거합니다.

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:

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"])
Update on GitHub