Transformers documentation

Video-text-to-text

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Video-text-to-text

Video-text-to-text, còn được gọi là mô hình ngôn ngữ video, là các mô hình có khả năng xử lý video và tạo ra văn bản. Những mô hình này có thể giải quyết nhiều tác vụ khác nhau, từ trả lời câu hỏi về video đến mô tả video.

Các mô hình này có kiến trúc gần như giống với các mô hình image-text-to-text, ngoại trừ một số thay đổi để chấp nhận dữ liệu video, vì dữ liệu video về cơ bản là các khung hình ảnh có sự phụ thuộc theo thời gian. Một số mô hình image-text-to-text nhận vào nhiều hình ảnh, nhưng điều này đơn lẻ là chưa đủ để một mô hình có thể chấp nhận video.

Hơn nữa, các mô hình video-văn-bản-thành-văn-bản thường được huấn luyện với tất cả các phương thức thị giác. Mỗi ví dụ có thể chứa video, nhiều video, hình ảnh và nhiều hình ảnh. Một số mô hình trong số này cũng có thể nhận đầu vào xen kẽ. Ví dụ, bạn có thể tham chiếu đến một video cụ thể bên trong một chuỗi văn bản bằng cách thêm một token video vào văn bản như “What is happening in this video? <video>“.

Lưu ý rằng các mô hình này xử lý video không có âm thanh. Ngược lại, các mô hình Any-to-any có thể xử lý video có chứa âm thanh.

Trong hướng dẫn này, chúng tôi cung cấp một cái nhìn tổng quan ngắn gọn về video LM và cho thấy cách sử dụng chúng với Transformers để suy luận.

Để bắt đầu, có nhiều loại LM video khác nhau:

  • các mô hình cơ sở được sử dụng để tinh chỉnh
  • các mô hình chat được tinh chỉnh cho hội thoại
  • các mô hình được tinh chỉnh theo hướng dẫn

Hướng dẫn này tập trung vào suy luận với một mô hình được tinh chỉnh theo chỉ thị, llava-hf/llava-onevision-qwen2-0.5b-ov-hf, có thể nhận dữ liệu xen kẽ. Ngoài ra, bạn có thể thử llava-interleave-qwen-0.5b-hf nếu phần cứng của bạn không cho phép chạy mô hình 7B.

Hãy bắt đầu cài đặt các phụ thuộc.

pip install -q transformers accelerate flash_attn torchcodec

Hãy khởi tạo mô hình và bộ xử lý.

from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
import torch
model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"

device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
processor = AutoProcessor.from_pretrained(model_id, device=device)

model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map="auto", dtype=torch.float16)

Chúng ta sẽ suy luận với hai video, cả hai đều có mèo.

Video là chuỗi các khung hình. Tùy thuộc vào giới hạn phần cứng, việc giảm mẫu là cần thiết. Nếu số khung hình sau khi giảm mẫu quá ít, chất lượng dự đoán sẽ thấp.

Các mô hình video-text-to-text có bộ xử lý (processor) với video processor được trừu tượng hóa bên trong. Bạn có thể truyền các đối số liên quan đến suy luận video vào hàm apply_chat_template().

Bạn có thể tìm hiểu thêm về bộ xử lý video tại đây.

Chúng ta có thể định nghĩa lịch sử trò chuyện của mình, truyền vào video với một URL như bên dưới.

messages = [
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4"},
            {"type": "text", "text": "Describe what is happening in this video."},
        ],
    }
]

Bạn có thể tiền xử lý video bằng cách truyền vào messages, đặt do_sample_frames thành True và truyền vào num_frames. Ở đây, chúng ta lấy mẫu 10 khung hình.

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    num_frames=10,
    do_sample_frames=True
)
inputs.to(model.device)

Các đầu vào bao gồm input_ids cho văn bản đã được token hóa, pixel_values_videos cho 10 khung hình và attention_mask cho các token.

Bây giờ chúng ta có thể suy luận với các đầu vào đã tiền xử lý và giải mã chúng.

generated_ids = model.generate(**inputs, max_new_tokens=128)
input_length = len(inputs["input_ids"][0])
output_text = processor.batch_decode(
    generated_ids[:, input_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False
)
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text[0])

#"The video features a fluffy, long-haired cat with a mix of brown and white fur, lying on a beige carpeted floor. The cat's eyes are wide open, and its whiskers are prominently visible. The cat appears to be in a relaxed state, with its head slightly"

Bạn cũng có thể xen kẽ nhiều video với văn bản trực tiếp trong chat template như bên dưới.

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Here's a video."},
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4"},
            {"type": "text", "text": "Here's another video."},
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_2.mp4"},
            {"type": "text", "text": "Describe similarities in these videos."},
        ],
    }
]

Việc suy luận vẫn giống như ví dụ trước đó.

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    num_frames=100,
    do_sample_frames=True
)
inputs.to(model.device)

generated_ids = model.generate(**inputs, max_new_tokens=50)
input_length = len(inputs["input_ids"][0])
output_text = processor.batch_decode(
    generated_ids[:, input_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
#['Both videos feature a cat with a similar appearance, characterized by a fluffy white coat with black markings, a pink nose, and a pink tongue. The cat\'s eyes are wide open, and it appears to be in a state of alertness or excitement. ']
Update on GitHub