VideoLLaMA 3 Documentation

repository·main·Indexed 22 days ago

https://github.com/damo-nlp-sg/videollama3

A series of multimodal foundation models for frontier-level image and video understanding. VideoLLaMA 3 provides high-performance capabilities for video-based reasoning, visual grounding, and visual referring. The documentation covers installation for inference and training, model zoo variants, data preparation in .jsonl format, and usage with the transformers library including coordinate conversion utilities for bounding boxes.

Tokens
11.9K
Snippets
34
Records
41
Agent score
78%

What's inside VideoLLaMA 3

  1. Start VideoLLaMA3 training

    main

    Training is performed in stages using shell scripts located in scripts/train/. You can modify variables like --data_folder, --data_path, --model_path, and --vision_encoder in the templates provided.

    # VideoLLaMA3 Stage 1
    bash scripts/train/stage1_2b.sh
    
    # VideoLLaMA3 Stage 2
    bash scripts/train/stage2_2b.sh
  2. Evaluate VideoLLaMA3 on benchmarks

    main

    To evaluate the model, first organize benchmark data (e.g., ActivityNet, Charades, EgoSchema, etc.) into the required directory structure. Then run the evaluation script.

    ```bash
    bash scripts/eval/eval_video.sh ${MODEL_PATH} ${BENCHMARKS} ${NUM_NODES} ${NUM_GPUS}

    Note: You can adjust the benchmark and output directories via DATA_ROOT and SAVE_DIR within the evaluation script.

  3. Convert HuggingFace checkpoints to local format

    main

    Before fine-tuning, convert HuggingFace checkpoints to a local format using the provided script.

    python scripts/convert_hf_checkpoint.py --model_path DAMO-NLP-SG/VideoLLaMA3-7B --save_path weights/videollama3_7b_local
  4. Prepare training data for VideoLLaMA3

    main

    Training data should be organized under a data_root directory. Annotations should be provided in .jsonl format (recommended for memory efficiency) containing a list of dictionaries. Each dictionary represents a conversation involving either an image or a video.

    Annotation Format:

    • For images: {"image": ["path/to/image.jpg"], "conversations": [...]}
    • For videos: {"video": ["path/to/video.mp4"], "conversations": [...]}

    Conversation Format: Conversations consist of alternating human and gpt roles. Use <image> or <video> tokens within the human value to indicate the media placement.

    [
        {
            "image": ["images/xxx.jpg"],
            "conversations": [
                {
                    "from": "human",
                    "value": "<image>\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": "<video>\nWhat are the main activities that take place in the video?"
                },
                {
                    "from": "gpt",
                    "value": "The main activities..."
                }
            ]
        }
    ]
  5. Install VideoLLaMA 3 for Training

    main

    To install the environment required for training VideoLLaMA 3, clone the repository and install the dependencies from requirements.txt along with flash-attn using the --no-build-isolation flag.

    git clone https://github.com/DAMO-NLP-SG/VideoLLaMA3
    cd VideoLLaMA3
    pip install -r requirements.txt
    pip install flash-attn --no-build-isolation
  6. Install VideoLLaMA 3 for Inference

    main

    To set up VideoLLaMA 3 for stable inference, ensure you have Python >= 3.10 and CUDA >= 11.8. Follow these installation steps to install specific compatible versions of PyTorch, Flash-attn, Transformers, and video processing dependencies.

    Important Compatibility Note: If you are using CUDA 11.8 with torch==2.4.0 and torchvision==0.19.0, you must use flash-attn==2.7.3. If using different Python or CUDA versions, consult the flash-attn releases for compatible wheels to avoid breaking the setup.

    # PyTorch and torchvision for CUDA 11.8
    pip install torch==2.4.0 torchvision==0.19.0 --extra-index-url https://download.pytorch.org/whl/cu118
    
    # Flash-attn pinned to a compatible version
    pip install flash-attn==2.7.3 --no-build-isolation --upgrade
    
    # Transformers and accelerate
    pip install transformers==4.46.3 accelerate==1.0.1
    
    # Video processing dependencies
    pip install decord ffmpeg-python imageio opencv-python
  7. Enable modality-based length grouping for sampling

    main

    To improve training efficiency by grouping sequences of similar lengths and modalities, enable the group_by_modality_length flag in your training arguments.

    When enabled, the VideoLLaMA3Trainer replaces the default sampler with a LengthGroupedSampler. This sampler uses get_modality_length_grouped_indices to ensure that multi-modal samples and language-only samples are processed in optimized batches, reducing padding and computational waste.

  8. Format conversation structures for different modalities

    main

    The conversation object is a list of dictionaries following a specific schema based on the modality:

    Text-only:

    conversation = [{"role": "user", "content": "Your question here"}]

    Image:

    conversation = [
        {
            "role": "user",
            "content": [
                {"type": "image"},
                {"type": "text", "text": "Your question here"},
            ]
        }
    ]

    Video:

    conversation = [
        {
            "role": "user",
            "content": [
                {"type": "video", "timestamps": timestamps, "num_frames": len(frames)},
                {"type": "text", "text": "Your question here"},
            ]
        }
    ]
  9. Perform Visual Grounding

    main

    Visual Grounding is the task of identifying an object from a text prompt and outputting its bounding box in the format [[x0, y0, x1, y1]].

    Workflow:

    1. Construct a conversation list containing a user role with an image type and a text type prompt (e.g., "Where is the [object]? Answer in [[x0,y0,x1,y1]] format.").
    2. Process the conversation using processor(conversation=conversation, return_tensors="pt").
    3. Move inputs to GPU and ensure pixel_values are in torch.bfloat16.
    4. Generate output using model.generate(**inputs).
    5. Decode the response using processor.batch_decode().
    6. Parse the bounding box from the text response using a helper like extract_boxes().
    conversation = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image", 
                    "image": {"image_path": image_path}
                },
                {
                    "type": "text", 
                    "text": "Where is the white car? Answer in [[x0,y0,x1,y1]] format.",
                },
            ]
        }
    ]
    
    # 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=128)
    response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
    print(response)
  10. Perform Visual Referring

    main

    Visual Referring allows the model to answer questions about a specific region of an image provided via a bounding box.

    Workflow:

    1. Define the target region using a raw bounding box [x0, y0, x1, y1].
    2. Convert the raw box to a normalized format (0-1000 scale) using raw2normalized(box, h, w).
    3. Construct a conversation where the text prompt includes the normalized box coordinates (e.g., f"What is the license plate number of {normalized_box}?").
    4. Process and generate as with standard inference.
    input_box = [150,50,530,300]
    normalized_box = raw2normalized(input_box, image.size[1], image.size[0])
    
    conversation = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image", 
                    "image": {"image_path": image_path}
                },
                {
                    "type": "text", 
                    "text": f"What is the license plate number of {normalized_box}?"
                },
            ]
        }
    ]
    
    # 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=128)
    response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
    print(response)
  11. Save only multi-modal adapters during alignment training

    main

    If you are performing alignment training (indicated by trainer.args.is_alignment == True), the VideoLLaMA3Trainer modifies the saving behavior to save only the multi-modal adapter weights rather than the full model. This saves disk space and focuses on the trainable components.

    When is_alignment is True:

    1. The trainer identifies keys to match (typically ['mm_projector']).
    2. It uses get_mm_adapter_state_maybe_zero_3 to collect these weights, handling DeepSpeed Zero-3 parameter partitioning if necessary.
    3. It saves the weights to a file named mm_projector.bin within the output directory or a mm_projector subfolder if inside a checkpoint directory.
  12. Load VideoLLaMA3 Model and Processor

    main

    To use VideoLLaMA3 for inference, load the model using AutoModelForCausalLM and the AutoProcessor.

    Requirements:

    • Approximately 15,967 MB of VRAM at BFloat16 precision.
    • trust_remote_code=True must be set.
    • For optimal performance, use attn_implementation="flash_attention_2".

    You can restrict the model to a specific GPU by setting the CUDA_VISIBLE_DEVICES environment variable.

    import os
    os.environ["CUDA_VISIBLE_DEVICES"] = "0"
    
    import torch
    from transformers import AutoModelForCausalLM, AutoProcessor
    
    model_path = "DAMO-NLP-SG/VideoLLaMA3-7B-Image"
    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)