Chat UniVi
Chat-UniViは統一視覚表現の大規模言語モデルで、画像と動画の内容を同時に理解できます。
ダウンロード数 12.10k
リリース時間 : 9/28/2023
モデル概要
Chat-UniViは動的視覚マーキングセットによって画像と動画を統一表現し、大規模言語モデルが両方の視覚メディアの理解タスクを同時に処理できるようにします。
モデル特徴
統一視覚表現
動的視覚マーキングセットを採用し、画像と動画を統一表現することで、空間的詳細と時間的関係を同時に捕捉
共同トレーニング戦略
画像と動画を含む混合データセットでトレーニングを行い、両メディアのタスクに直接適用可能
補完的学習効果
画像と動画の共同トレーニングにより補完的学習効果が得られ、単一メディア専用モデルよりも優れた性能
モデル能力
動画内容理解
画像内容理解
マルチモーダル対話
視覚的質問応答
動画説明生成
画像説明生成
使用事例
内容理解
動画内容要約
動画内容のテキスト説明と要約を自動生成
動画中のキーイベントと時間的関係を正確に捕捉可能
画像内容分析
画像中のオブジェクト、シーン、関係を理解
画像内容と空間的関係を詳細に記述可能
インテリジェントインタラクション
マルチモーダル対話システム
視覚内容に基づく自然言語対話
ユーザーの質問を理解し、視覚内容に基づいて適切な回答を提供可能
🚀 Chat-UniVi: 統一視覚表現による画像と動画理解を備えた大規模言語モデル
Chat-UniViは、画像と動画の統一視覚表現を用いて、大規模言語モデルに画像と動画の理解能力を付与するモデルです。このモデルは、画像と動画を含む混合データセットで学習されており、画像と動画の両方を扱うタスクに直接適用できます。
📄 ライセンス
Llama 2は、LLAMA 2 Community Licenseの下でライセンスされています。 Copyright (c) Meta Platforms, Inc. All Rights Reserved.
✨ 主な機能
💡 画像と動画の統一視覚表現
一連の動的視覚トークンを用いて、画像と動画を統一的に表現します。この表現フレームワークにより、モデルは限られた数の視覚トークンを効率的に利用して、画像に必要な空間的詳細と動画に必要な包括的な時間的関係を同時に捉えることができます。
🔥 共同学習戦略による画像と動画の理解
Chat-UniViは、画像と動画の両方を含む混合データセットで学習されているため、何らの変更も必要とせずに、両方のメディアを扱うタスクに直接適用できます。
🤗 高い性能と画像と動画の相補的学習
広範な実験結果から、Chat-UniViは統一モデルとして、既存の画像または動画専用の手法を上回る性能を発揮することが示されています。
💻 使用例
基本的な使用法
動画理解の推論
import torch
import os
from ChatUniVi.constants import *
from ChatUniVi.conversation import conv_templates, SeparatorStyle
from ChatUniVi.model.builder import load_pretrained_model
from ChatUniVi.utils import disable_torch_init
from ChatUniVi.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
from PIL import Image
from decord import VideoReader, cpu
import numpy as np
def _get_rawvideo_dec(video_path, image_processor, max_frames=MAX_IMAGE_LENGTH, image_resolution=224, video_framerate=1, s=None, e=None):
# speed up video decode via decord.
if s is None:
start_time, end_time = None, None
else:
start_time = int(s)
end_time = int(e)
start_time = start_time if start_time >= 0. else 0.
end_time = end_time if end_time >= 0. else 0.
if start_time > end_time:
start_time, end_time = end_time, start_time
elif start_time == end_time:
end_time = start_time + 1
if os.path.exists(video_path):
vreader = VideoReader(video_path, ctx=cpu(0))
else:
print(video_path)
raise FileNotFoundError
fps = vreader.get_avg_fps()
f_start = 0 if start_time is None else int(start_time * fps)
f_end = int(min(1000000000 if end_time is None else end_time * fps, len(vreader) - 1))
num_frames = f_end - f_start + 1
if num_frames > 0:
# T x 3 x H x W
sample_fps = int(video_framerate)
t_stride = int(round(float(fps) / sample_fps))
all_pos = list(range(f_start, f_end + 1, t_stride))
if len(all_pos) > max_frames:
sample_pos = [all_pos[_] for _ in np.linspace(0, len(all_pos) - 1, num=max_frames, dtype=int)]
else:
sample_pos = all_pos
patch_images = [Image.fromarray(f) for f in vreader.get_batch(sample_pos).asnumpy()]
patch_images = torch.stack([image_processor.preprocess(img, return_tensors='pt')['pixel_values'][0] for img in patch_images])
slice_len = patch_images.shape[0]
return patch_images, slice_len
else:
print("video path: {} error.".format(video_path))
if __name__ == '__main__':
# Model Parameter
model_path = "Chat-UniVi/Chat-UniVi" # or "Chat-UniVi/Chat-UniVi-13B"、"Chat-UniVi/Chat-UniVi-v1.5"
video_path = ${video_path}
# The number of visual tokens varies with the length of the video. "max_frames" is the maximum number of frames.
# When the video is long, we will uniformly downsample the video to meet the frames when equal to the "max_frames".
max_frames = 100
# The number of frames retained per second in the video.
video_framerate = 1
# Input Text
qs = "Describe the video."
# Sampling Parameter
conv_mode = "simple"
temperature = 0.2
top_p = None
num_beams = 1
disable_torch_init()
model_path = os.path.expanduser(model_path)
model_name = "ChatUniVi"
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, None, model_name)
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
if mm_use_im_patch_token:
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
if mm_use_im_start_end:
tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
model.resize_token_embeddings(len(tokenizer))
vision_tower = model.get_vision_tower()
if not vision_tower.is_loaded:
vision_tower.load_model()
image_processor = vision_tower.image_processor
if model.config.config["use_cluster"]:
for n, m in model.named_modules():
m = m.to(dtype=torch.bfloat16)
# Check if the video exists
if video_path is not None:
video_frames, slice_len = _get_rawvideo_dec(video_path, image_processor, max_frames=max_frames, video_framerate=video_framerate)
cur_prompt = qs
if model.config.mm_use_im_start_end:
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN * slice_len + DEFAULT_IM_END_TOKEN + '\n' + qs
else:
qs = DEFAULT_IMAGE_TOKEN * slice_len + '\n' + qs
conv = conv_templates[conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(
0).cuda()
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
keywords = [stop_str]
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
with torch.inference_mode():
output_ids = model.generate(
input_ids,
images=video_frames.half().cuda(),
do_sample=True,
temperature=temperature,
top_p=top_p,
num_beams=num_beams,
output_scores=True,
return_dict_in_generate=True,
max_new_tokens=1024,
use_cache=True,
stopping_criteria=[stopping_criteria])
output_ids = output_ids.sequences
input_token_len = input_ids.shape[1]
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
if n_diff_input_output > 0:
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
outputs = outputs.strip()
if outputs.endswith(stop_str):
outputs = outputs[:-len(stop_str)]
outputs = outputs.strip()
print(outputs)
画像理解の推論
import torch
import os
from ChatUniVi.constants import *
from ChatUniVi.conversation import conv_templates, SeparatorStyle
from ChatUniVi.model.builder import load_pretrained_model
from ChatUniVi.utils import disable_torch_init
from ChatUniVi.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
from PIL import Image
if __name__ == '__main__':
# Model Parameter
model_path = "Chat-UniVi/Chat-UniVi" # or "Chat-UniVi/Chat-UniVi-13B"、"Chat-UniVi/Chat-UniVi-v1.5"
image_path = ${image_path}
# Input Text
qs = "Describe the image."
# Sampling Parameter
conv_mode = "simple"
temperature = 0.2
top_p = None
num_beams = 1
disable_torch_init()
model_path = os.path.expanduser(model_path)
model_name = "ChatUniVi"
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, None, model_name)
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
if mm_use_im_patch_token:
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
if mm_use_im_start_end:
tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
model.resize_token_embeddings(len(tokenizer))
vision_tower = model.get_vision_tower()
if not vision_tower.is_loaded:
vision_tower.load_model()
image_processor = vision_tower.image_processor
# Check if the video exists
if image_path is not None:
cur_prompt = qs
if model.config.mm_use_im_start_end:
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
else:
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
conv = conv_templates[conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
image = Image.open(image_path)
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
keywords = [stop_str]
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
with torch.inference_mode():
output_ids = model.generate(
input_ids,
images=image_tensor.unsqueeze(0).half().cuda(),
do_sample=True,
temperature=temperature,
top_p=top_p,
num_beams=num_beams,
max_new_tokens=1024,
use_cache=True,
stopping_criteria=[stopping_criteria])
input_token_len = input_ids.shape[1]
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
if n_diff_input_output > 0:
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
outputs = outputs.strip()
if outputs.endswith(stop_str):
outputs = outputs[:-len(stop_str)]
outputs = outputs.strip()
print(outputs)
Clip Vit Large Patch14
CLIPはOpenAIによって開発された視覚-言語モデルで、コントラスティブラーニングを通じて画像とテキストを共有の埋め込み空間にマッピングし、ゼロショット画像分類をサポートします
画像生成テキスト
C
openai
44.7M
1,710
Clip Vit Base Patch32
CLIPはOpenAIが開発したマルチモーダルモデルで、画像とテキストの関係を理解し、ゼロショット画像分類タスクをサポートします。
画像生成テキスト
C
openai
14.0M
666
Siglip So400m Patch14 384
Apache-2.0
SigLIPはWebLiデータセットで事前学習された視覚言語モデルで、改良されたシグモイド損失関数を採用し、画像-テキストマッチングタスクを最適化しています。
画像生成テキスト
Transformers

S
google
6.1M
526
Clip Vit Base Patch16
CLIPはOpenAIが開発したマルチモーダルモデルで、コントラスティブラーニングにより画像とテキストを共有の埋め込み空間にマッピングし、ゼロショット画像分類能力を実現します。
画像生成テキスト
C
openai
4.6M
119
Blip Image Captioning Base
Bsd-3-clause
BLIPは先進的な視覚-言語事前学習モデルで、画像キャプション生成タスクに優れており、条件付きおよび無条件のテキスト生成をサポートします。
画像生成テキスト
Transformers

B
Salesforce
2.8M
688
Blip Image Captioning Large
Bsd-3-clause
BLIPは統一された視覚-言語事前学習フレームワークで、画像キャプション生成タスクに優れており、条件付きおよび無条件の画像キャプション生成をサポートします。
画像生成テキスト
Transformers

B
Salesforce
2.5M
1,312
Openvla 7b
MIT
OpenVLA 7BはOpen X-Embodimentデータセットでトレーニングされたオープンソースの視覚-言語-動作モデルで、言語命令とカメラ画像に基づいてロボットの動作を生成できます。
画像生成テキスト
Transformers 英語

O
openvla
1.7M
108
Llava V1.5 7b
LLaVAはオープンソースのマルチモーダルチャットボットで、LLaMA/Vicunaをファインチューニングし、画像とテキストのインタラクションをサポートします。
画像生成テキスト
Transformers

L
liuhaotian
1.4M
448
Vit Gpt2 Image Captioning
Apache-2.0
これはViTとGPT2アーキテクチャに基づく画像記述生成モデルで、入力画像に対して自然言語の記述を生成することができます。
画像生成テキスト
Transformers

V
nlpconnect
939.88k
887
Blip2 Opt 2.7b
MIT
BLIP-2は画像エンコーダーと大規模言語モデルを組み合わせた視覚言語モデルで、画像からテキストを生成するタスクに使用されます。
画像生成テキスト
Transformers 英語

B
Salesforce
867.78k
359
おすすめAIモデル
Llama 3 Typhoon V1.5x 8b Instruct
タイ語専用に設計された80億パラメータの命令モデルで、GPT-3.5-turboに匹敵する性能を持ち、アプリケーションシナリオ、検索拡張生成、制限付き生成、推論タスクを最適化
大規模言語モデル
Transformers 複数言語対応

L
scb10x
3,269
16
Cadet Tiny
Openrail
Cadet-TinyはSODAデータセットでトレーニングされた超小型対話モデルで、エッジデバイス推論向けに設計されており、体積はCosmo-3Bモデルの約2%です。
対話システム
Transformers 英語

C
ToddGoldfarb
2,691
6
Roberta Base Chinese Extractive Qa
RoBERTaアーキテクチャに基づく中国語抽出型QAモデルで、与えられたテキストから回答を抽出するタスクに適しています。
質問応答システム 中国語
R
uer
2,694
98