VILA: Vision Language Models

repository·main·Indexed 26 days ago

https://github.com/nvlabs/vila

A family of optimized Vision Language Models (VLMs) designed for high-efficiency video understanding and multi-image reasoning. VILA supports various model scales and deployment on NVIDIA GPUs and Jetson Orin. The ecosystem includes LongVILA for extended context lengths (up to 1M), tools for three-stage training (Alignment, Pretraining, and SFT), and CLI utilities such as vila-infer for inference and vila-eval for benchmarking video tasks.

Tokens
13.4K
Snippets
31
Records
67
Agent score
87%

What's inside VILA

  1. Use AutoProcessor for single or batch inference

    main

    VILA supports the AutoProcessor class to prepare data for inference.

    Important: You must call model.eval() before inference; otherwise, the model will remain in training mode and pad to the right.

    Single Call

    Use processor.apply_chat_template to format conversation dictionaries (containing role and content with type: image or type: text) into a prompt string, then pass that string to the processor.

    Batch Call

    Pass a list of conversation dictionaries to apply_chat_template via a list comprehension, then pass the resulting list of texts to the processor to handle multiple inputs at once.

    from transformers import AutoProcessor, AutoModel
    
    model_path = "Efficient-Large-Model/NVILA-Lite-2B-hf-preview"
    processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
    model = AutoModel.from_pretrained(model_path, trust_remote_code=True, device_map="auto")
    model.eval() # Critical: set to eval mode
    
    # Single call example
    gpt_conv = [{
        "role": "user",
        "content": [
            {"type": "image", "path": "https://nvlabs.github.io/VILA/asset/example.jpg"},
            {"type": "text", "text": "Describe this image."}
        ]
    }]
    text = processor.apply_chat_template(gpt_conv, tokenize=False, add_generation_prompt=True)
    inputs = processor([text])
    
    output_ids = model.generate(
        input_ids=inputs.input_ids,
        media=inputs.media,
        media_config=inputs.media_config,
        generation_config=model.generation_config,
        max_new_tokens=256,
    )
    print(processor.tokenizer.batch_decode(output_ids, skip_special_tokens=True))
    
    # Batch call example
    gpt_conv1 = [{"role": "user", "content": [{"type": "image", "path": "..."}, {"type": "text", "text": "..."}]}]
    gpt_conv2 = [{"role": "user", "content": [{"type": "image", "path": "..."}, {"type": "text", "text": "..."}]}]
    
    messages = [gpt_conv1, gpt_conv2]
    texts = [processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages]
    inputs = processor(texts)
    
    output_ids = model.generate(
        input_ids=inputs.input_ids,
        media=inputs.media,
        media_config=inputs.media_config,
        generation_config=model.generation_config,
        max_new_tokens=256,
    )
    output_texts = processor.tokenizer.batch_decode(output_ids, skip_special_tokens=True)
  2. Prepare the VFlan Dataset (TextFLAN and M3IT)

    main

    The VFlan dataset consists of TextFLAN and M3IT.

    TextFLAN: Download the FLAN dataset and run the preprocessing script to sample 1M data points.

    M3IT: Download the M3IT dataset and run the preprocessing script.

    Optional: You can split the combined FLAN+M3IT into multiple chunks to reduce CPU memory pressure during training.

    # TextFLAN
    huggingface-cli download Open-Orca/FLAN --repo-type dataset --local-dir FLAN --local-dir-use-symlinks False
    cd sft
    python preprocess_flan.py
    
    # M3IT
    huggingface-cli download MMInstruction/M3IT --repo-type dataset --local-dir M3IT --local-dir-use-symlinks False
    python preprocess_m3it.py
    
    # Optional: Split combined data
    python split_vflan.py
  3. Train Stage 5: Long Supervised Fine-tuning

    main

    Stage 5 tunes the model to follow instructions for long videos. This stage uses the longvila_sft_dataset.

    For 256 frames: bash longvila/train/5_long_sft_256frames.sh [EXTENDED_64k_PATH] [OUTPUT_NAME]

    For 512 frames: bash longvila/train/5_long_sft_512frames.sh [EXTENDED_256k_PATH] [OUTPUT_NAME]

    Arguments:

    • EXTENDED_64k_PATH / EXTENDED_256k_PATH: Path to the output of the corresponding Stage 4 script.
    • OUTPUT_NAME: Desired folder name under checkpoints for the final checkpoint.
    bash longvila/train/5_long_sft_256frames.sh [EXTENDED_64k_PATH] [OUTPUT_NAME]
    
    bash longvila/train/5_long_sft_512frames.sh [EXTENDED_256k_PATH] [OUTPUT_NAME]
  4. Use NVILA in Hugging Face Compatible Mode

    main
    NVILA supports loading via the Hugging Face transformers library using AutoModel.from_pretrained. To use this mode, you must set trust_remote_code=True. This allows for automatic device mapping (device_map="auto") to shard the model across available hardware. Once loaded, you can perform inference using the generate_content method, which accepts a list containing either text strings or PIL.Image objects.
  5. Use VILA for text and image generation

    main

    You can load VILA models using AutoConfig and AutoModel.from_config, or more directly via AutoModel.from_pretrained. Use trust_remote_code=True when loading.

    To generate content, use the model.generate_content method. This method accepts a list containing either raw text strings or a combination of PIL.Image objects and text strings.

    from transformers import AutoConfig, AutoModel
    from termcolor import colored
    import PIL.Image
    
    model_path = "Efficient-Large-Model/NVILA-Lite-2B-hf-preview"
    
    # Load model directly
    model = AutoModel.from_pretrained(model_path, trust_remote_code=True, device_map="auto")
    
    # Example: Generate with raw text
    res = model.generate_content([
        "how are you today?"
    ])
    print(colored(res, "cyan", attrs=["bold"]))
    
    # Example: Generate with text + image
    response = model.generate_content([
        PIL.Image.open("inference_test/test_data/caption_meat.jpeg"),
        "describe the image?"
    ])
    print(colored(response, "cyan", attrs=["bold"]))
  6. Prepare the MMC4-Core Dataset

    main

    To prepare the MMC4-core dataset for pre-training, follow these steps:

    1. Download annotations from the allenai/mmc4 repository (use the non-fewer-face split).
    2. Modify input/output paths in mmc4_downloader.py.
    3. Scrawl images. You can shard the workload across multiple machines using start and end indices of the jsonl shards (total 23,098 shards, divided into 14 groups).
    4. Filter invalid samples.
    5. Merge images and text into unified pickle files per shard.
  7. Launch VILA fine-tuning training

    main

    Run the training script using bash scripts/NVILA-Lite/sft.sh. You must provide the model path and the dataset name(s). If training on multiple datasets, concatenate their registered names with +.

    To avoid Out-of-Memory (OOM) issues, reduce DEFAULT_GLOBAL_TRAIN_BATCH_SIZE or increase DEFAULT_GRADIENT_ACCUMULATION_STEPS.

    # Single dataset
    DEFAULT_RUN_NAME="NVILA-Lite-8B-finetune-trial" \
    DEFAULT_GLOBAL_TRAIN_BATCH_SIZE=64 \
    DEFAULT_GRADIENT_ACCUMULATION_STEPS=2 \
        bash scripts/NVILA-Lite/sft.sh \
            Efficient-Large-Model/NVILA-Lite-8B \
            SampleQA
    
    # Multiple datasets
    DEFAULT_RUN_NAME="NVILA-Lite-8B-finetune-trial" \
    DEFAULT_GLOBAL_TRAIN_BATCH_SIZE=64 \
    DEFAULT_GRADIENT_ACCUMULATION_STEPS=2 \
        bash scripts/NVILA-Lite/sft.sh \
            Efficient-Large-Model/NVILA-Lite-8B \
            SampleQA+SampleVideo+SampleOCR
  8. Run AWQ-quantized VILA on GPUs

    main
    To run 4-bit quantized VILA on desktop or edge GPUs, use TinyChat. You can follow the TinyChat tutorial for VLM support or use the provided instructions to launch a Gradio server powered by TinyChat and AWQ.