GithubHelp home page GithubHelp logo

nvlabs / prismer Goto Github PK

View Code? Open in Web Editor NEW
1.3K 15.0 75.0 4.35 MB

The implementation of "Prismer: A Vision-Language Model with Multi-Task Experts".

Home Page: https://shikun.io/projects/prismer

License: Other

Python 92.76% Shell 0.13% C++ 0.71% Cuda 6.40%
image-captioning language-model multi-modal-learning multi-task-learning vision-language-model vision-and-language vqa

prismer's Introduction

Prismer

arXiv Hugginface Space

This repository contains the source code of Prismer and PrismerZ from the paper, Prismer: A Vision-Language Model with Multi-Task Experts. Check out our official demo at HuggingFace Space and a third-party demo at Replicate.

Update Log

  • Apr. 3, 2023: Improve HF Space demo with half precision inference and md5sum image check.
  • Mar. 22, 2023: Fix tensor mismatch problem for the updated transformers package.
  • Mar. 13, 2023: Add official HF Space demo.

Get Started

The implementation is based on PyTorch 1.13, and highly integrated with Huggingface accelerate toolkit for readable and optimised multi-node multi-gpu training.

First, let's install all package dependencies by running

pip install -r requirements.txt

Prepare Accelerator Config

Then we generate the corresponding accelerate config based on your training server configuration. For both single-node multi-gpu and multi-node multi-gpu training, simply run and follow the instructions with,

accelerate config

Datasets

Pre-training

We pre-train Prismer/PrismerZ with a combination of five widely used image-alt/text datasets, with pre-organised data lists provided below.

  • COCO 2014: the Karpathy training split (which will also be used for fine-tuning).
  • Visual Genome: the official Visual Genome captioning dataset.
  • CC3M + SGU: filtered and re-captioned by BLIP-Large.
  • CC12M: filtered and re-captioned by BLIP-Large.

The web datasets (CC3M, SGU, CC12M) is composed with image urls. It is highly recommended to use img2dataset, a highly optimised toolkit for large-scale web scraping to download these images. An example bash script of using img2dataset to download cc12m dataset is provided below.

img2dataset --url_list filtered_cc12m.json --input_format "json" --url_col "url" --caption_col "caption" --output_folder cc12m --processes_count 16 --thread_count 64 --image_size 256

Note: It is expected that the number of downloaded images is less than the number of images in the json file, because some urls might not be valid or require long loading time.

Image Captioning / VQA

We evaluate image captioning performance on two datasets, COCO 2014 and NoCaps; and VQA performance on VQAv2 dataset. In VQA tasks, we additionally augment the training data with Visual Genome QA, following BLIP. Again, we have prepared and organised the training and evaluation data lists provided below.

Generating Expert Labels

Before starting any experiments with Prismer, we need to first pre-generate the modality expert labels, so we may construct a multi-label dataset. In experts folder, we have included all 6 experts we introduced in our paper. We have organised each expert's codebase with a shared and simple API.

Note: Specifically for segmentation experts, please first install deformable convolution operations by cd experts/segmentation/mask2former/modeling/pixel_decoder/ops and run sh make.sh.

To download pre-trained modality experts, run

python download_checkpoints.py --download_experts=True

To generate the expert labels, simply edit the configs/experts.yaml with the corresponding data paths, and run

export PYTHONPATH=.
accelerate launch experts/generate_{EXPERT_NAME}.py

Note: Expert label generation is only required for Prismer models, not for PrismerZ models.

Experiments

We have provided both Prismer and PrismerZ for pre-trained checkpoints (for zero-shot image captioning), as well as fined-tuned checkpoints on VQAv2 and COCO datasets. With these checkpoints, it should be expected to reproduce the exact performance listed below.

Model Pre-trained [Zero-shot] COCO [Fine-tuned] VQAv2 [Fine-tuned]
PrismerZ-BASE COCO CIDEr [109.6] COCO CIDEr [133.7] test-dev [76.58]
Prismer-BASE COCO CIDEr [122.6] COCO CIDEr [135.1] test-dev [76.84]
PrismerZ-LARGE COCO CIDEr [124.8] COCO CIDEr [135.7] test-dev [77.49]
Prismer-LARGE COCO CIDEr [129.7] COCO CIDEr [136.5] test-dev [78.42]

To download pre-trained/fined-tuned checkpoints, run

# to download all model checkpoints (12 models in total)
python download_checkpoints.py --download_models=True

# to download specific checkpoints (Prismer-Base for fine-tuned VQA) in this example
python download_checkpoints.py --download_models="vqa_prismer_base"

Note: Remember to install java via sudo apt-get install default-jre which is required to run the official COCO caption evaluation scripts.

Evaluation

To evaluate the model checkpoints, please run

# zero-shot image captioning (remember to remove caption prefix in the config files)
accelerate launch train_caption.py --exp_name {MODEL_NAME} --evaluate

# fine-tuned image captioning
accelerate launch train_caption.py --exp_name {MODEL_NAME} --from_checkpoint --evaluate

# fine-tuned VQA
accelerate launch train_vqa.py --exp_name {MODEL_NAME} --from_checkpoint --evaluate

Training / Fine-tuning

To pre-train or fine-tune any model with or without checkpoints, please run

# to train/fine-tuning from scratch
accelerate launch train_{TASK}.py --exp_name {MODEL_NAME}

# to train/fine-tuning from the latest checkpoints (saved every epoch)
accelerate launch train_{TASK}.py --exp_name {MODEL_NAME} --from_checkpoint 

We have also included model sharding in the current training script via PyTorch's official FSDP plugin. With the same training commands, additionally add --shard_grad_op for ZeRO-2 Sharding (Gradients + Optimiser States), or --full_shard for ZeRO-3 Sharding (ZeRO-2 + Network Parameters).

Note: You should expect the error range for VQAv2 Acc. to be less than 0.1; for COCO/NoCAPs CIDEr score to be less than 1.0.

A Minimal Example

Finally, we have offered a minimal example to perform image captioning in a single GPU with our fine-tuned Prismer/PrismerZ checkpoint. Simply put your images under helpers/images (support .jpg, .jpeg, and .png images), and run

python demo.py --exp_name {MODEL_NAME}

You then can see all generated modality expert labels in the helpers/labels folder and the generated captions in the helpers/images folder.

Particularly for the Prismer models, we have also offered a simple script to prettify the generated expert labels. To prettify and visualise the expert labels as well as its predicted captions, run

python demo_vis.py

Note: Remember to set up the corresponding config in the configs/caption.yaml demo section. The default demo model config is for Prismer-Base.

Citation

If you found this code/work to be useful in your own research, please considering citing the following:

@article{liu2024prismer,
    title={Prismer: A Vision-Language Model with Multi-Task Experts},
    author={Liu, Shikun and Fan, Linxi and Johns, Edward and Yu, Zhiding and Xiao, Chaowei and Anandkumar, Anima},
    journal={Transactions on Machine Learning Research},
    year={2024}
}

License

Copyright © 2023, NVIDIA Corporation. All rights reserved.

This work is made available under the Nvidia Source Code License-NC.

The model checkpoints are shared under CC-BY-NC-SA-4.0. If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.

For business inquiries, please visit our website and submit the form: NVIDIA Research Licensing.

Acknowledgement

We would like to thank all the researchers who open source their works to make this project possible. @bjoernpl for contributing an automated checkpoint download script.

Contact

If you have any questions, please contact [email protected].

prismer's People

Contributors

bjoernpl avatar lorenmt avatar mike-hearn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prismer's Issues

hardware requirements?

I want to know what is the minimum hardware requirements to run prismer, is it runnable on consumer grade GPUs?

sklearn version

Hi, İ had an issue about cython when i'm trying to install requirements. i think the issue about version of sklearn. It is too old . Here is a part of the error that i'm getting:

  Error compiling Cython file:
  ------------------------------------------------------------
  ...
  
          # Initial capacity
          cdef int init_capacity
  
          if tree.max_depth <= 10:
              init_capacity = (2 ** (tree.max_depth + 1)) - 1
                                                          ^
  ------------------------------------------------------------
  
  sklearn/tree/_tree.pyx:151:56: Cannot assign type 'double' to 'int'
  Traceback (most recent call last):
    File "/tmp/pip-build-env-ku11v_ed/overlay/local/lib/python3.10/dist-packages/Cython/Build/Dependencies.py", line 1345, in cythonize_one_helper
      return cythonize_one(*m)
    File "/tmp/pip-build-env-ku11v_ed/overlay/local/lib/python3.10/dist-packages/Cython/Build/Dependencies.py", line 1321, in cythonize_one
      raise CompileError(None, pyx_file)

I am getting many errors like this one.Is there any suggestion?

ocr_detection: no output and error with demo_vis.py

When running demo_vis.py, I got the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'helpers/labels/ocr_detection/helpers/images/COCO_test2015_000000000014_.png'
I found that ocr_detection never outputs anything, but does not raise any error or warning.
Can you advise, please?

ruamel.yaml import

The imports of ruamel.yaml in the expert files (experts/generate_*.py) are still different and should be adapted like in #4 (a9a09d6). That is with:

try:
    import ruamel_yaml as yaml
except ModuleNotFoundError:
    import ruamel.yaml as yaml

How do we perform pre-training/fine-tuning for visual quesion answering task on custom dataset.

I would greatly value your assistance in offering guidance for initiating pre-training/fine-tuning on the Visual Question Answering (VQA) task, specifically in the following aspects:

  1. The necessary format for the required dataset.
  2. Minimum hardware requirements for its execution.

Please note that while this question might be straightforward and potentially addressed by reviewing the model documentation, I am seeking an expert opinion on this matter.

Thank you sincerely.

I can not understand the generate_config.py

python generate_config.py —-main_ip {MAIN_IP} -—rank {MACHINE_RANK} —-num_machines {TOTAL_MACHINES}

what are the meanings of MAIN_IP MACHINE_RANK TOTAL_MACHINES? And why do we need this step?

python generate_config.py —-main_ip {210.30.97.224} -—rank {0} —-num_machines {1}

I run it as this, but get an erro

CUDA out of memory

Hi,
Thanks for sharing your great work!

Only during segmentation label generation when running demo.py, I encounter CUDA out of memory problem.

I tried to allocate it to multiple gpus but won't work out.

I am embarassed to ask such a simple question but could you help me out with this?

Thank you for your help!

Mismatch tensor while running demo.py

While trying to run demo.py, I see this error
image

hidden_states.shape, and q.shape, k.shape, v.shape as following:

hid torch.Size([3, 4, 768])                                                                                                                                                  
torch.Size([3, 12, 4, 64]) torch.Size([3, 12, 4, 64]) torch.Size([3, 12, 4, 64])                                                                                             
hid torch.Size([3, 4, 768])                                                                                                                                                  
torch.Size([3, 12, 4, 64]) torch.Size([9, 12, 900, 64]) torch.Size([9, 12, 900, 64])

Do you have any idea what is the problem here? It is an error in text_decoder.generate()
I try to run with prismerz_base

How to perform inference using VQA

hello! thank you for your great contribution to the field.

I would like to know how to perform inference for the VQA part. Could you please add guidance to the readme on 'how to' perform this task?

thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.