Requirements and Installation
- requirements
- Python >= 3.10
- Pytorch >= 2.4.0
- CUDA Version >= 11.8
- transformers >= 4.46.3
- [inference-only]
pip install torch==2.4.0 torchvision==0.17.0 --extra-index-url https://download.pytorch.org/whl/cu118
pip install flash-attn --no-build-isolation
pip install transformers==4.46.3 accelerate==1.0.1
pip install decord ffmpeg-python imageio opencv-python
git clone https://github.com/DAMO-NLP-SG/VideoLLaMA3
cd VideoLLaMA3
pip install -r requirements.txt
pip install flash-attn --no-build-isolation
Model Zoo
- LLM base model 으로는 Qwen2.5 을 사용함
- pre-trained Vision Encoder만 별도로 다운로드 받을 수 있음
- 예: VideoLLaMA3-7B Vision Encoder
CookBook
VideoLLaMA3/inference/notebooks/
폴더에는 아래의 application에 대한 예시 코드가 있음
- Image Understanding
- Multi-image Understanding
- Fine-grained Image Recognition & Understanding
- Video Understanding
- Video Understanding
Video Understanding
- VideoLLaMA3/inference/notebooks/04_video_understanding.ipynb
[General] Load Model and Processor
- 내 PC GPU: 6141MiB
- 하지만 "DAMO-NLP-SG/VideoLLaMA3-7B"는 15,967 MB of VRAM 을 필요로 함 (BFloat16 precision 에서)
- 16GB 이상의 VRAM을 지닌 GPU 리스트
대안
- VideoLLaMA3-2B 모델은 VRAM을 덜 필요로 하지 않을까..? 하는 기대
VideoLLaMA3-7B Vision Encoder
만 쓰면, 덜 필요로 하지 않을까..? 하는 기대
코드
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from PIL import Image
from IPython.display import Markdown, clear_output, display, Video
import matplotlib.pyplot as plt
import torch
from transformers import AutoModelForCausalLM, AutoProcessor, AutoModel, AutoImageProcessor
model_path = "DAMO-NLP-SG/VideoLLaMA3-7B"
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
device_map="auto",
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
)
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
Set-Up
- Necessary imports helper functions for video frames visualization.
import cv2
import matplotlib.pyplot as plt
import numpy as np
from typing import List, Tuple
def sample_frames_from_video(video_path: str, num_frames: int = 64) -> List[np.ndarray]:
"""
동영상에서 균등한 간격으로 프레임을 추출하여 RGB 형식의 프레임 리스트를 반환합니다.
Args:
video_path (str): 동영상 파일의 경로.
num_frames (int, optional): 추출할 프레임의 수. 기본값은 64입니다.
Returns:
List[np.ndarray]: RGB 형식으로 변환된 추출된 프레임들의 리스트.
각 프레임은 (H, W, 3) 형태의 numpy.ndarray로, H는 높이, W는 너비, 3은 RGB 채널을 의미합니다.
"""
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
step = total_frames // num_frames
frames: List[np.ndarray] = []
for i in range(num_frames):
cap.set(cv2.CAP_PROP_POS_FRAMES, i * step)
ret, frame = cap.read()
if not ret:
break
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame_rgb)
cap.release()
return frames
def display_frames_grid(frames: List[np.ndarray], grid_size: Tuple[int, int] = (8, 8)) -> None:
"""
추출된 프레임들을 지정된 행×열 그리드 형태로 시각화합니다.
Args:
frames (List[np.ndarray]): 시각화할 이미지 프레임들의 리스트.
각 프레임은 (H, W, 3) 형태의 numpy.ndarray여야 합니다.
grid_size (Tuple[int, int], optional): 그리드의 행과 열의 수를 나타내며, 기본값은 (8, 8)입니다.
Returns:
None
"""
fig, axes = plt.subplots(grid_size[0], grid_size[1], figsize=(16, 10))
for i, ax in enumerate(axes.flat):
if i < len(frames):
ax.imshow(frames[i])
ax.axis('off')
else:
ax.axis('off')
plt.tight_layout()
plt.show()
Understand a Common Video
- 비디오를 효과적으로 분석하고, 의미있는 insights를 도출하는 방법
video_path = 'visuals/basketball.mp4'
display(Video(video_path, width=480, height=300))
conversation = [
{
"role": "user",
"content": [
{
"type": "video",
"video": {"video_path": video_path, "fps": 1, "max_frames": 180}
},
{
"type": "text",
"text": "Describe the video in detial."
},
]
}
]
inputs = processor(conversation=conversation, return_tensors="pt")
inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
if "pixel_values" in inputs:
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
output_ids = model.generate(**inputs, max_new_tokens=256)
response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
display(Markdown(response))
Temporal Grounding within a video
- 특정 비디오 이벤트에 대한 절대 timestamps를 정확하게 찾아내는 방법
video_path = 'visuals/cola.mp4'
display(Video(video_path, width=480, height=300))
conversation = [
{
"role": "user",
"content": [
{
"type": "video",
"video": {"video_path": video_path, "fps": 1, "max_frames": 180}
},
{
"type": "text",
"text": "When did the man pour the cola into the cup? Please output the start and end timestamps."
},
]
}
]
inputs = processor(conversation=conversation, return_tensors="pt")
inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
if "pixel_values" in inputs:
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
output_ids = model.generate(**inputs, max_new_tokens=256)
response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
display(Markdown(response))
- The man poured the cola into the cup from 25.6 seconds to 34.6 seconds.
Long video Understanding
- 긴 비디오를, 디테일을 포함하여 요약하는 방법
"""
Due to the slow loading of long videos, we uniformly sample 64 frames and visualize them as images.
"""
video_path = 'visuals/long.mp4'
frames = sample_frames_from_video(video_path, num_frames=64)
display_frames_grid(frames, grid_size=(8, 8))
conversation = [
{
"role": "user",
"content": [
{
"type": "video",
"video": {"video_path": video_path, "fps": 1, "max_frames": 180}
},
{
"type": "text",
"text": "Please describe the video in detail."
},
]
}
]
inputs = processor(conversation=conversation, return_tensors="pt")
inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
if "pixel_values" in inputs:
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
output_ids = model.generate(**inputs, max_new_tokens=256)
response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
display(Markdown(response))
Demo
- gradio app을 로컬에서 실행할 수 있음
python inference/launch_gradio_demo.py --model-path DAMO-NLP-SG/VideoLLaMA3-7B
options:
--model-path MODEL_PATH, --model_path MODEL_PATH
--server-port SERVER_PORT, --server_port SERVER_PORT
Optional. Port of the model server.
--interface-port INTERFACE_PORT, --interface_port INTERFACE_PORT
Optional. Port of the gradio interface.
--nproc NPROC
Optional. Number of model processes
Evaluation
Step 1: Prepare evaluation data
Step 2: Start evaluation
bash scripts/eval/eval_video.sh ${MODEL_PATH} ${BENCHMARKS} ${NUM_NODES} ${NUM_GPUS}