# Çok modlu sohbet şablonları

Çok modlu sohbet modelleri, metnin yanı sıra görüntü, ses veya video gibi girdileri kabul eder. Çok modlu bir sohbet geçmişindeki `content` anahtarı, farklı türlerde birden çok öğe içeren bir listedir. Bu, `content` anahtarı tek bir dize olan yalnızca metin tabanlı sohbet modellerinden farklıdır.

Aynı şekilde [Tokenizer](./fast_tokenizers) sınıfı yalnızca metin tabanlı modeller için sohbet şablonlarını ve tokenizasyonu ele alırken, [Processor](./processors) sınıfı çok modlu modeller için ön işleme, tokenizasyon ve sohbet şablonlarını ele alır. [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) yöntemleri neredeyse aynıdır.

Bu kılavuz, yüksek seviyeli [ImageTextToTextPipeline](/docs/transformers/main/tr/main_classes/pipelines#transformers.ImageTextToTextPipeline) ile ve daha düşük seviyede [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) ile [generate()](/docs/transformers/main/tr/main_classes/text_generation#transformers.GenerationMixin.generate) yöntemlerini kullanarak multimodal modellerle sohbet etmenin nasıl yapılacağını gösterecektir.

## ImageTextToTextPipeline

[ImageTextToTextPipeline](/docs/transformers/main/tr/main_classes/pipelines#transformers.ImageTextToTextPipeline), “sohbet modu”na sahip yüksek düzeyde bir görüntü ve metin üretim sınıfıdır. Konuşmacı bir model algılandığında ve sohbet istemi [doğru biçimlendirildiğinde](./llm_tutorial#prompt-format) sohbet modu etkinleştirilir.

Sohbet geçmişindeki `content` anahtarına görsel ve metin blokları ekleyin.

```py
messages = [
    {
        "role": "system",
        "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
      "role": "user",
      "content": [
            {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
            {"type": "text", "text": "What are these?"},
        ],
    },
]
```

Bir [ImageTextToTextPipeline](/docs/transformers/main/tr/main_classes/pipelines#transformers.ImageTextToTextPipeline) oluşturun ve sohbeti ona iletin. Büyük modeller için [device_map="auto"](./models#big-model-inference) ayarlamak, modelin daha hızlı yüklenmesine yardımcı olur ve onu otomatik olarak en hızlı kullanılabilir cihaza yerleştirir. Veri türünü [auto](./models#model-data-type) olarak ayarlamak da bellek tasarrufu sağlamaya ve hızı artırmaya yardımcı olur.

```python
import torch
from transformers import pipeline

pipe = pipeline("image-text-to-text", model="Qwen/Qwen2.5-VL-3B-Instruct", device_map="auto", dtype="auto")
out = pipe(text=messages, max_new_tokens=128)
print(out[0]['generated_text'][-1]['content'])
```

```text
Ahoy, me hearty! These be two feline friends, likely some tabby cats, taking a siesta on a cozy pink blanket. They're resting near remote controls, perhaps after watching some TV or just enjoying some quiet time together. Cats sure know how to find comfort and relaxation, don't they?
```

Korsan jargonundan modern Amerikan İngilizcesine kademeli geçiş dışında (zaten **sadece** 3B parametreli bir model), bu doğru!

## `apply_chat_template` kullanımı

[Sadece metin modelleri](./chat_templating) gibi, multimodal modeller için sohbet mesajlarını hazırlamak üzere [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) yöntemini kullanın. Bu yöntem, görüntüler ve diğer medya türleri dahil olmak üzere sohbet mesajlarının tokenizasyonunu ve biçimlendirmesini yönetir. Oluşan girdiler, üretim için modele iletilir.

```python
from transformers import AutoProcessor, AutoModelForImageTextToText

model = AutoModelForImageTextToText.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct", device_map="auto", torch_dtype="auto")
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct")

messages = [
    {
      "role": "system",
      "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
      "role": "user",
      "content": [
            {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
            {"type": "text", "text": "What are these?"},
        ],
    },
]
```

Girdi içeriğini belirteçleştirmek için `messages` değerini [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) fonksiyonuna iletin. Metin modellerinden farklı olarak, `apply_chat_template` çıktısı, belirteçlenmiş metnin yanı sıra ön işlenmiş görüntü verisini içeren bir `pixel_values` anahtarı da içerir.

```py
processed_chat = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt")
print(list(processed_chat.keys()))
```

```text
['input_ids', 'attention_mask', 'pixel_values', 'image_grid_thw']
```

Bu girdileri [generate()](/docs/transformers/main/tr/main_classes/text_generation#transformers.GenerationMixin.generate) işlevine iletin.

```python
out = model.generate(**processed_chat.to(model.device), max_new_tokens=128)
print(processor.decode(out[0]))
```

Çözümlenmiş çıktı, kullanıcı mesajını ve görsel bilgilerini içeren yer tutucu jetonları da dahil olmak üzere bugüne kadarki tüm sohbeti içerir. Kullanıcıya göstermeden önce çıktıdaki önceki sohbeti kırpmanız gerekebilir.

## Video girdileri

Bazı görme modelleri video girdilerini de destekler. Mesaj biçimi, önceki bölümde açıklanan görüntü girdileri için kullanılan biçime çok benzer.

- İçerik `"type"` alanı, içeriğin bir video olduğunu belirtmek için `"video"` olmalıdır.
- Videolar için bir video bağlantısı (`"url"`) veya bir dosya yolu (`"path"`) olabilir. Videolar [torchcodec](https://meta-pytorch.org/torchcodec/stable/index.html) ile çözümlenir. torchcodec kullanılamıyorsa ve eski bir torchvision sürümünde iseniz, çözümleme torchvision'a geri düşer.
- Bir URL veya dosya yolundan video yüklemenin yanı sıra, çözümlenmiş video verilerini doğrudan da iletebilirsiniz. Bu, video karelerini bellekte başka bir yerde önceden işlediyseniz veya çözdüyseniz faydalıdır. Dosyalara kaydetmenize veya bir URL'de saklamanıza gerek yoktur.

> [!TIP]
> [PyAV](https://pyav.basswood-io.com/docs/stable/) ve [Decord](https://github.com/dmlc/decord) kullanılabilir, ancak yalnızca videoyu kendiniz çözümlerseniz ve `load_video(backend=...)` ile arka ucu açıkça belirtirseniz.

```python
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration

model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"
model = LlavaOnevisionForConditionalGeneration.from_pretrained(model_id)
processor = AutoProcessor.from_pretrained(model_id)

messages = [
    {
      "role": "system",
      "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
      "role": "user",
      "content": [
            {"type": "video", "url": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4"},
            {"type": "text", "text": "What do you see in this video?"},
        ],
    },
]
```

### Örnek: Çözümlenmiş video nesnelerini iletme

```python
import numpy as np

video_object1 = np.random.randint(0, 255, size=(16, 224, 224, 3), dtype=np.uint8),

messages = [
    {
        "role": "system",
        "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": video_object1},
            {"type": "text", "text": "What do you see in this video?"}
        ],
    },
]
```

Mevcut (`"load_video()"`) işlevini de bir video yüklemek, videoyu bellekte düzenlemek ve mesajlarda iletmek için kullanabilirsiniz.

```python

# Make sure a video backend library (torchcodec, pyav, or decord) is available.
from transformers.video_utils import load_video

# load a video file in memory for testing
video_object2, _ = load_video(
    "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4"
)

messages = [
    {
        "role": "system",
        "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": video_object2},
            {"type": "text", "text": "What do you see in this video?"}
        ],
    },
]
```

Girdi içeriğini belirteçleştirmek için `messages` değerini [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) fonksiyonuna iletin. Örnekleme sürecini kontrol eden, [apply_chat_template()](/docs/transformers/main/tr/main_classes/processors#transformers.ProcessorMixin.apply_chat_template) fonksiyonuna dahil edilecek birkaç ek parametre vardır.

`num_frames` parametresi, videodan eşit aralıklarla örneklenen kare sayısını kontrol eder. Her checkpoint, ön eğitimi sırasında kullanılan maksimum kare sayısına sahiptir ve bu sayıyı aşmak, üretim kalitesini önemli ölçüde düşürebilir. Hem model kapasitesine hem de donanım kaynaklarınıza uygun bir kare sayısı seçmek önemlidir. `num_frames` belirtilmezse, video herhangi bir kare örneklemesi yapılmadan tamamen yüklenir.

```python
processed_chat = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    num_frames=32,
)
print(processed_chat.keys())
```

Bu girdiler artık [generate()](/docs/transformers/main/tr/main_classes/text_generation#transformers.GenerationMixin.generate) içinde kullanılmaya hazırdır.

Daha uzun videolarda, `fps` parametresi ile daha iyi temsil için daha fazla kare örneklemek daha iyi olabilir. Bu parametre, saniyede kaç kare çıkarılacağını belirler. Örneğin, bir video 10 saniye uzunluğundaysa ve `fps=2` ise, model 20 kare örnekler. Başka bir deyişle, her 10 saniyede 2 kare eşit aralıklarla örneklenir.

```py
processed_chat = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    fps=16,
)
print(processed_chat.keys())
```

Videolar, tam video dosyası yerine görüntüler olarak saklanan örneklenmiş kareler kümesi olarak da var olabilir.

Bu durumda, bir görüntü dosya yolu listesi iletin ve işlemci bunları otomatik olarak bir videoya birleştirir. Tüm görüntülerin aynı boyutta olduğundan emin olun, çünkü bunların aynı videodan geldiği varsayılır.

```py
frames_paths = ["/path/to/frame0.png", "/path/to/frame5.png", "/path/to/frame10.png"]
messages = [
    {
        "role": "system",
        "content": [{"type": "text", "text": "You are a friendly chatbot who always responds in the style of a pirate"}],
    },
    {
      "role": "user",
      "content": [
            {"type": "video", "path": frames_paths},
            {"type": "text", "text": "What do you see in this video?"},
        ],
    },
]

processed_chat = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
)
print(processed_chat.keys())
```

