[WIP] Added Llama-vid
Author: nileshkokane01
Pull request: yes
Labels: name: New model

# What does this PR do?

Adds Llama-VID 


<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes #27980

For video: 
```python
from PIL import Image
import requests
from transformers import LLaMAVIDLlavaForConditionalGeneration, LLaMAVIDLlavaProcessor,LLaMAVIDLlavaConfig
from huggingface_hub import hf_hub_download
import torch
import numpy as np
from decord import VideoReader, cpu



def load_video(video_path, fps=1):
    vr = VideoReader(video_path, ctx=cpu(0))
    fps = round(vr.get_avg_fps()/fps)
    frame_idx = [i for i in range(0, len(vr), fps)]
    spare_frames = vr.get_batch(frame_idx).asnumpy()
    return spare_frames

model = LLaMAVIDLlavaForConditionalGeneration.from_pretrained("Nilesh360/llama-vid-7b-full-224-video-fps-1")
processor = LLaMAVIDLlavaProcessor.from_pretrained("Nilesh360/llama-vid-7b-full-224-video-fps-1")

prompt = "<image>\nUSER: What's the content of the video?\nASSISTANT:"
video= hf_hub_download(repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset")
images= load_video(video)

inputs = processor(text=[prompt], images=[images], return_tensors="pt")
# Generate
generate_ids = model.generate(**inputs, max_length=512)
reply = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(reply)

```
For image : 
```python
from PIL import Image
import requests
from transformers import LLaMAVIDLlavaForConditionalGeneration, LLaMAVIDLlavaProcessor,LLaMAVIDLlavaConfig
import torch
import numpy as np

processor = LLaMAVIDLlavaProcessor.from_pretrained("Nilesh360/llama-vid-7b-full-336")
model = LLaMAVIDLlavaForConditionalGeneration.from_pretrained("Nilesh360/llama-vid-7b-full-336")

prompt = "<image>\nUSER: What's the content of the image?\nASSISTANT:"
url= 'https://huggingface.co/datasets/huggingface/cats-image'
image=  Image.open(requests.get(url, stream=True).convert('RGB'))


inputs = processor(text=[prompt], images=[image], return_tensors="pt")
# Generate
generate_ids = model.generate(**inputs, max_length=512)
reply = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(reply)
```

Colab: https://colab.research.google.com/drive/1fvaagb4nSjtEvx2YDrcqY0E2jWIsdCtv#scrollTo=v4Ry7RyyiruU



## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [x] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?
@amyeroberts

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Awesome work @nileshkokane01 Thanks for opening a PR! Let us know when it's ready for review or you have any questions about the port into transformers 

@amyeroberts 

I'm looking through llama pr as a base, that is what I see a closest + some combination of other pr that has vision models, as ref to port llama-vid. ( ... and of course the official new model contribution doc on hf website).

Let me know if this approach is correct.

Since this is the first model that I'm contributing to hf,  it will take a bit of time, and might need a  bit of help. I'm sorry for the inconvenience. 

@nileshkokane01 Yep, that's the right approach. Ideally we can leverage existing architectures as much as possible using `# Copied from` comments. I'd suggest looking at llava as well as llama. 



@amyeroberts ,

Based on the [comment](https://github.com/dvlab-research/LLaMA-VID/issues/13#issuecomment-1855744892) from the author, what I understand is [VisionTransformer](https://github.com/dvlab-research/LLaMA-VID/blob/main/llamavid/model/multimodal_encoder/builder.py#L16) should be replaced by [BLIP2](https://github.com/huggingface/transformers/blob/main/src/transformers/models/blip_2/modeling_blip_2.py) and the [qformer](https://github.com/dvlab-research/LLaMA-VID/blob/main/llamavid/model/llamavid_arch.py#L104) with [instructBLIP](https://github.com/huggingface/transformers/blob/main/src/transformers/models/instructblip/modeling_instructblip.py). 

Can you please confirm ? 

comparing, BLIP2 and instructBLIP visionModels, they turned out to be same, so I use the instructBLIP for VIT and Qformer.

That also means I have to copy the qformer and the associated  embedding class etc from the instructBLIP with `#copied from` comments ?

> That also means I have to copy the qformer and the associated embedding class etc from the instructBLIP with #copied from comments ?

Yep! 

@amyeroberts,

Most of the implementation has been integrated from my side and I did whatever is possible without the GPU  and will need your help/guidance/inputs for the following 2 points. 

1. All of the components are giving accurate results  with 1e-3 or more , but vit. As I had to modify the tensors to CPU/float32 for cpu implementation and I see cascading impact, due to the modification, that affect the results  to comply to 1e-3 expectations as tensors flows from vit- >  qformer -> token_generator -> LLM .
 
But if I insert the output of vit from the original implementation as an input to Qformer of transformer. All the  subsequent  intermediate results match the original implementation with 1e-3 accuracy.  Besides, inspecting the implementation and the config values is all the same between the original and the transformer for vit and the rest, and has been verified.

2.  Converted check points loaded locally has no problem , however via [hub](https://colab.research.google.com/drive/1fvaagb4nSjtEvx2YDrcqY0E2jWIsdCtv#scrollTo=v4Ry7RyyiruU), I get error for qformer. I did ref InstructBLIP qformer and @NielsRogge  implementation for convertor script, but I do know whats missing and why it ask for config for qformer if loaded from hub, but not with the local hf model saved using ( save_pretrained).

Any assistance would be appretiated for the above 2 points. Prehaps, request you to have a first review and let me know if I'm deviating too much from the expectations.

I will continue with the test cases once the above 2 points are resolved, but again the expected values are needed for the test cases - as the models consumes just above the freely available  VRAM from colab.
 
 



cc @zucchini-nlp as she is currently working on adding Video-LLaVa

@amyeroberts @NielsRogge ,

Any hints, I am really interested getting this merged. Please let me know.