### Install Training Dependencies Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Clones the VideoLLaMA3 repository and installs all required packages for training, including flash-attn. Ensure you are in the cloned repository directory. ```bash git clone https://github.com/DAMO-NLP-SG/VideoLLaMA3 cd VideoLLaMA3 pip install -r requirements.txt pip install flash-attn --no-build-isolation ``` -------------------------------- ### Start Training Scripts Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Execute the provided bash scripts to start training for VideoLLaMA3 Stage 1 and Stage 2. ```bash # VideoLLaMA3 Stage 1 bash scripts/train/stage1_2b.sh # VideoLLaMA3 Stage 2 bash scripts/train/stage2_2b.sh ``` -------------------------------- ### Data Organization Example Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Organize your image and video data under a root directory and use annotation files (JSONL format) to record conversation data and file paths. ```bash data_root ├── LLaVA-Video-178K │ ├── video_1.mp4 │ └── ... ├── LLaVA-OneVision-Data │ ├── image_1.jpg │ └── ... ├── annotations_video.jsonl ├── annotations_image.jsonl └── ... ``` -------------------------------- ### Launch VideoLLaMA3 Gradio Demo Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Start a local Gradio application for the VideoLLaMA3 model. Specify the model path and optional server/interface ports. ```bash python inference/launch_gradio_demo.py --model-path DAMO-NLP-SG/VideoLLaMA3-7B ``` -------------------------------- ### Install VideoLLaMA 3 Dependencies Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Installs necessary packages for VideoLLaMA 3 inference with CUDA 11.8. For full training, clone the repository and install from requirements.txt. ```bash pip install torch==2.4.0 torchvision==0.19.0 --extra-index-url https://download.pytorch.org/whl/cu118 pip install flash-attn==2.7.3 --no-build-isolation --upgrade pip install transformers==4.46.3 accelerate==1.0.1 pip install decord ffmpeg-python imageio opencv-python # Full training install (clone repo first) git clone https://github.com/DAMO-NLP-SG/VideoLLaMA3 cd VideoLLaMA3 pip install -r requirements.txt pip install flash-attn --no-build-isolation ``` -------------------------------- ### VideoLLaMA 3 Evaluation Script Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Use this bash script to start the evaluation process. Ensure you set the MODEL_PATH, BENCHMARKS, NUM_NODES, and NUM_GPUS variables. You can customize DATA_ROOT and SAVE_DIR within the script. ```bash bash scripts/eval/eval_video.sh ${MODEL_PATH} ${BENCHMARKS} ${NUM_NODES} ${NUM_GPUS} ``` -------------------------------- ### VideoLLaMA Dataset Directory Structure Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md This is an example of the expected directory organization for evaluation datasets. Ensure your downloaded data is structured similarly. ```bash benchmarks └── video │ ├── activitynet_qa │ │ ├── all_test │ │ ├── test_a.json │ │ └── test_q.json │ ├── charades │ │ ├── Charades_v1 │ │ └── charades_annotations_test-random_prompt.json │ ├── egoschema │ │ ├── good_clips_git │ │ └── questions.json │ ├── longvideobench │ │ ├── lvb_val.json │ │ ├── subtitles │ │ └── videos │ ├── lvbench │ │ ├── video │ │ └── video_info.meta.jsonl │ ├── mlvu │ │ ├── json │ │ └── video │ ├── mvbench │ │ ├── json │ │ └── video │ ├── nextqa │ │ ├── map_vid_vidorID.json │ │ ├── NExTVideo │ │ └── test.csv │ ├── perception_test │ │ ├── mc_question_test.json │ │ └── videos │ ├── tempcompass │ │ ├── captioning │ │ ├── caption_matching │ │ ├── multi-choice │ │ ├── videos │ │ └── yes_no │ ├── videomme │ │ ├── subtitles │ │ ├── test-00000-of-00001.parquet │ │ └── videos ``` -------------------------------- ### Install Inference Dependencies Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Installs specific versions of PyTorch, torchvision, flash-attn, transformers, and accelerate for stable inference. Also includes video processing libraries. Ensure CUDA version compatibility. ```bash pip install torch==2.4.0 torchvision==0.19.0 --extra-index-url https://download.pytorch.org/whl/cu118 pip install flash-attn==2.7.3 --no-build-isolation --upgrade pip install transformers==4.46.3 accelerate==1.0.1 pip install decord ffmpeg-python imageio opencv-python ``` -------------------------------- ### Setup Helper Functions for Box Visualization Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/03_visual_referring_and_grounding.ipynb Imports necessary libraries and defines helper functions for image manipulation, bounding box extraction, and visualization. These functions are used to process model outputs and display bounding boxes on images. ```python from PIL import Image, ImageDraw from IPython.display import Markdown, display import matplotlib.pyplot as plt import re def extract_boxes(text): matches = re.findall(r'[[(.*?) ]]', text) result = [] for match in matches: arrays = match.split('],[') inner_list = [] for array in arrays: # Remove any remaining brackets and split by comma to get individual numbers numbers = array.replace('[', '').replace(']', '').split(',') inner_list.append([int(num) for num in numbers]) result.extend(inner_list) return result def normalized2raw(box, h, w): box = [int(box[0]/1000*w), int(box[1]/1000*h), int(box[2]/1000*w), int(box[3]/1000*h)] return box def raw2normalized(box, h, w): box = [int(box[0]/w*1000), int(box[1]/h*1000), int(box[2]/w*1000), int(box[3]/h*1000)] box = [min(b, 1000) for b in box] return box def show_box(raw_box, image, process=True): box_image = image.copy() if process: bbox = normalized2raw(raw_box, box_image.size[1], box_image.size[0]) else: bbox = raw_box draw = ImageDraw.Draw(box_image) draw.rectangle([bbox[0], bbox[1], bbox[2], bbox[3]], outline='red', width=2) plt.imshow(box_image) plt.axis('off') plt.show() ``` -------------------------------- ### Training Script Configuration Example Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Modify training script variables to fit your data and model settings. Key parameters include data folder, data path, model path, and vision encoder. ```bash --data_folder ./datasets \ --data_path ./datasets/annotations_video.jsonl ./datasets/annotations_image.jsonl \ --model_path Qwen/Qwen2.5-1.5B-Instruct \ --vision_encoder DAMO-NLP-SG/SigLIP-NaViT \ ``` -------------------------------- ### VideoLLaMA3 Training Annotation Format Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Example format for training annotations in JSONL. Includes samples for both image and video inputs with corresponding conversations. ```json # Image sample: # {"image": ["images/cat.jpg"], "conversations": [{"from": "human", "value": "\nWhat is this?"}, {"from": "gpt", "value": "A cat."}]} # Video sample: ``` -------------------------------- ### Temporal Grounding within a Video Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/04_video_understanding.ipynb Shows how to ask specific temporal questions about a video, such as when an event occurred. The model can output start and end timestamps for requested events. ```python video_path = 'visuals/cola.mp4' display(Video(video_path, width=480, height=300)) ``` ```python 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." }, ] } ] ``` -------------------------------- ### VideoLLaMA3 Processor for Inference and Training Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Use this processor for both inference and training. For inference, provide a conversation and images/videos. For training, set `return_labels=True` to get target tensors for supervised fine-tuning. ```python from transformers import AutoProcessor from videollama3.mm_utils import load_video, load_images processor = AutoProcessor.from_pretrained( "DAMO-NLP-SG/VideoLLaMA3-7B", trust_remote_code=True ) # --- Inference mode --- frames, timestamps = load_video("assets/cat_and_chicken.mp4", fps=1, max_frames=32) conversation = [ {"role": "system", "content": "You are a helpful assistant."}, { "role": "user", "content": [ {"type": "video", "timestamps": timestamps, "num_frames": len(frames)}, {"type": "text", "text": "Summarize the video."}, ], }, ] inputs = processor( conversation=conversation, images=[("video", frames)], # pre-loaded; skip automatic loading add_system_prompt=True, add_generation_prompt=True, return_tensors="pt", ) print(inputs.keys()) # dict_keys(['input_ids', 'attention_mask', 'pixel_values', 'grid_sizes', 'merge_sizes', 'modals']) # --- Training mode (returns labels) --- training_conv = [ {"role": "user", "content": [{"type": "image", "image": {"image_path": "img.jpg"}}, {"type": "text", "text": "Describe this image."}]}, {"role": "assistant", "content": "The image shows a sunny beach."}, ] train_inputs = processor( conversation=training_conv, return_labels=True, return_tensors="pt", ) print(train_inputs["labels"].shape) # torch.Size([sequence_length]) ``` -------------------------------- ### Perform Visual Grounding for 'logo of the yellow car' Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/03_visual_referring_and_grounding.ipynb Performs visual grounding to find the 'logo of the yellow car' in the image. This example demonstrates how to query for specific details within an image using a text prompt and the expected bounding box output format. ```python conversation = [ { "role": "user", "content": [ { "type": "image", "image": {"image_path": image_path} }, { "type": "text", "text": "Where is the logo of the yellow car? Answer in [[x0,y0,x1,y1]] format." }, ] } ] ``` -------------------------------- ### Launch Gradio Demo for VideoLLaMA3 Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Launch an interactive web-based demo using Gradio. Supports image and video input directly from the browser. Customize model path, server port, interface port, and number of processes. ```bash # Single GPU / default settings python inference/launch_gradio_demo.py --model-path DAMO-NLP-SG/VideoLLaMA3-7B # Multi-GPU with custom ports python inference/launch_gradio_demo.py \ --model-path DAMO-NLP-SG/VideoLLaMA3-7B \ --server-port 16666 \ --interface-port 7860 \ --nproc 4 ``` -------------------------------- ### Understand a Common Video Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/04_video_understanding.ipynb Demonstrates how to process a common video file for detailed description using VideoLLaMA3. It involves setting up the conversation with video input and then generating a response. ```python video_path = 'visuals/basketball.mp4' display(Video(video_path, width=480, height=300)) ``` ```python conversation = [ { "role": "user", "content": [ { "type": "video", "video": {"video_path": video_path, "fps": 1, "max_frames": 180} }, { "type": "text", "text": "Describe the video in detial." }, ] } ] # Single-turn conversation 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)) ``` -------------------------------- ### model_init(model_path, max_visual_tokens=None, **kwargs) Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Loads a VideoLLaMA 3 checkpoint from a local path or HuggingFace Hub, constructs a Videollama3Processor from the image processor and tokenizer, and optionally caps the number of visual tokens processed per image/frame. Returns (model, processor). ```APIDOC ## model_init(model_path, max_visual_tokens=None, **kwargs) ### Description Loads a VideoLLaMA 3 checkpoint from a local path or HuggingFace Hub, constructs a `Videollama3Processor` from the image processor and tokenizer, and optionally caps the number of visual tokens processed per image/frame. Returns `(model, processor)`. ### Parameters - **model_path** (str) - Path to the model checkpoint or HuggingFace Hub identifier. - **max_visual_tokens** (int, optional) - Maximum number of visual tokens to process per image/frame. - **kwargs** - Additional keyword arguments to pass to the underlying model loading functions (e.g., `device_map`). ### Usage ```python from videollama3 import disable_torch_init, model_init disable_torch_init() # Load 7B model onto a single GPU, capping visual tokens at 8192 model, processor = model_init( "DAMO-NLP-SG/VideoLLaMA3-7B", max_visual_tokens=8192, device_map={"ளுக்காக": "cuda:0"}, ) print(type(model)) # print(type(processor)) # ``` ``` -------------------------------- ### Initialize VideoLLaMA 3 Model and Processor Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Loads a VideoLLaMA 3 checkpoint, creates a `Videollama3Processor`, and optionally limits visual tokens. Specify `device_map` for GPU allocation. ```python from videollama3 import disable_torch_init, model_init disable_torch_init() # Load 7B model onto a single GPU, capping visual tokens at 8192 model, processor = model_init( "DAMO-NLP-SG/VideoLLaMA3-7B", max_visual_tokens=8192, device_map={"": "cuda:0"}, ) print(type(model)) # print(type(processor)) # ``` -------------------------------- ### Gradio Demo Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Launches a web-based interactive demo with a Gradio frontend backed by a VideoLLaMA3PlainServer. Supports both image and video input directly from the browser. ```APIDOC ## Gradio Demo ### Description Launches an interactive web-based demo for VideoLLaMA3. ### Usage ```bash # Single GPU / default settings python inference/launch_gradio_demo.py --model-path DAMO-NLP-SG/VideoLLaMA3-7B # Multi-GPU with custom ports python inference/launch_gradio_demo.py \ --model-path DAMO-NLP-SG/VideoLLaMA3-7B \ --server-port 16666 \ --interface-port 7860 \ --nproc 4 ``` ### Parameters - **--model-path** (str) - Path to the model. - **--server-port** (int, optional) - Port for the backend server. - **--interface-port** (int, optional) - Port for the Gradio interface. - **--nproc** (int, optional) - Number of processes (GPU workers). ``` -------------------------------- ### VideoLLaMA3 HuggingFace Transformers API - Video Inference Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Performs video inference using the HuggingFace Transformers API. This allows for model registration via `AutoModelForCausalLM` and `AutoProcessor` without installing the `videollama3` package, making it suitable for deployment. ```APIDOC ## HuggingFace Transformers API — Video Inference ### Description The repository ships a fully self-contained Transformers-compatible implementation under `inference/transformers_api/`. Models registered via `AutoModelForCausalLM` and `AutoProcessor` work without installing the `videollama3` package, making them suitable for deployment environments. ### Usage Example ```python import torch from transformers import AutoModelForCausalLM, AutoProcessor device = "cuda:0" model_path = "DAMO-NLP-SG/VideoLLaMA3-7B" model = AutoModelForCausalLM.from_pretrained( model_path, trust_remote_code=True, device_map={"": device}, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2", ) processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) conversation = [ {"role": "system", "content": "You are a helpful assistant."}, { "role": "user", "content": [ { "type": "video", "video": { "video_path": "assets/cat_and_chicken.mp4", "fps": 1, "max_frames": 180, }, }, {"type": "text", "text": "What is the cat doing?"}, ], }, ] inputs = processor( conversation=conversation, add_system_prompt=True, add_generation_prompt=True, return_tensors="pt", ) inputs = {k: v.to(device) 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=1024) response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip() print(response) # Expected: "The cat is playfully chasing the chicken..." ``` ``` -------------------------------- ### Training Pipeline - 4-Stage Fine-tuning Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Details the four-stage curriculum for fine-tuning VideoLLaMA 3, using torchrun with DeepSpeed ZeRO. ```APIDOC ## Training Pipeline — 4-Stage Fine-tuning ### Description VideoLLaMA 3 uses a four-stage curriculum for fine-tuning: Stage 1 aligns the vision encoder and projector on image-text data; Stage 2 adds video data; Stages 3 and 4 apply full multimodal instruction tuning. Each stage uses `torchrun` with DeepSpeed ZeRO. ### Stages - **Stage 1 — vision-language alignment (2B model, 8 GPUs)** ```bash bash scripts/train/stage1_2b.sh ``` - **Stage 2 — video alignment** ```bash bash scripts/train/stage2_2b.sh ``` - **Stages 3 & 4 — instruction tuning** ```bash bash scripts/train/stage3_2b.sh bash scripts/train/stage4_2b.sh ``` ### Training Annotation Format (`annotations.jsonl`) - **Image sample:** ```json {"image": ["images/cat.jpg"], "conversations": [{"from": "human", "value": "\nWhat is this?"}, {"from": "gpt", "value": "A cat."}]} ``` - **Video sample:** (Format details for video samples are not provided in the source text.) ``` -------------------------------- ### Run VideoLLaMA3 Inference Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Load the model and processor, prepare a conversation with video and text inputs, and generate a response. Ensure the correct device and data types are used for optimal performance. ```python import torch from transformers import AutoModelForCausalLM, AutoProcessor device = "cuda:0" model_path = "DAMO-NLP-SG/VideoLLaMA3-7B" model = AutoModelForCausalLM.from_pretrained( model_path, trust_remote_code=True, device_map={"": device}, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2", ) processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) conversation = [ {"role": "system", "content": "You are a helpful assistant."}, { "role": "user", "content": [ {"type": "video", "video": {"video_path": "./assets/cat_and_chicken.mp4", "fps": 1, "max_frames": 180}}, {"type": "text", "text": "What is the cat doing?"}, ] }, ] inputs = processor( conversation=conversation, add_system_prompt=True, add_generation_prompt=True, return_tensors="pt" ) inputs = {k: v.to(device) 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=1024) response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip() print(response) ``` -------------------------------- ### Load and Display Image Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/03_visual_referring_and_grounding.ipynb Loads an image from a specified path and displays it. Ensure the image path is correct and the image is in RGB format. ```python image_path = "visuals/cars.jpg" image = Image.open(image_path).convert("RGB") plt.imshow(image) plt.axis('on') plt.show() ``` -------------------------------- ### Load and Display Image Source: https://github.com/damo-nlp-sg/videollama3/blob/main/inference/notebooks/01_single_image_understanding.ipynb Loads an image from a specified path and displays it. Ensure the image path is correct. ```python image_path = "visuals/doc.jpg" image = Image.open(image_path).convert("RGB") display(image) ``` -------------------------------- ### Convert HuggingFace Checkpoint to Local Format Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Converts a HuggingFace-format VideoLLaMA 3 checkpoint to the local training format, remapping vision encoder weight keys. Ensure the target directory exists. ```bash python scripts/convert_hf_checkpoint.py \ --model_path DAMO-NLP-SG/VideoLLaMA3-7B \ --save_path weights/videollama3_7b_local ``` -------------------------------- ### VideoLLaMA3 Training Pipeline Scripts Source: https://context7.com/damo-nlp-sg/videollama3/llms.txt Scripts for the four-stage fine-tuning curriculum of VideoLLaMA3. Each stage uses `torchrun` with DeepSpeed ZeRO for distributed training. ```bash # Stage 1 — vision-language alignment (2B model, 8 GPUs) bash scripts/train/stage1_2b.sh # Stage 2 — video alignment bash scripts/train/stage2_2b.sh # Stages 3 & 4 — instruction tuning bash scripts/train/stage3_2b.sh bash scripts/train/stage4_2b.sh ``` -------------------------------- ### Annotation File Format Source: https://github.com/damo-nlp-sg/videollama3/blob/main/README.md Annotation files are lists of dictionaries, each containing 'image' or 'video' paths and a list of 'conversations' with 'from' and 'value' fields. Use .jsonl for efficiency. ```json [ { "image": ["images/xxx.jpg"], "conversations": [ { "from": "human", "value": "\nWhat are the colors of the bus in the image?" }, { "from": "gpt", "value": "The bus in the image is white and red." }, ... ] }, { "video": ["videos/xxx.mp4"], "conversations": [ { "from": "human", "value": "