-
Notifications
You must be signed in to change notification settings - Fork 217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Video-LLaVa now available in the Transformers library! #156
Comments
It's a great feat. Thank you for your generous help! |
@zucchini-nlp I'm seeing the following problem File "/home/rhelck/videotest.py", line 3, in The older example works fine for me, though. I reinstalled transfomers in a new venv for this by the way |
@rhelck hey! Did you install transformers from
|
@zucchini-nlp I want to distribute the model on multiple gpus. raise ValueError( |
@darshana1406 could you open this as issue in Also you are welcome to open a PR, if you think you are willing to, we are always happy for community contributions 🤗 |
@zucchini-nlp That worked perfectly, thanks! |
Can it also be used with images as before or only for videos? |
@IsabelJimenez99 , yes, the model can be used with images / videos / mix of image and video. Check out a colab notebook for inference examples with different input modalities |
Ah, ok. Sorry, I hadn't seen the collab. Thank you very much and excellent work. Congratulations! |
Can we use this library for fine-tuning as well or only for inference? If we can, is there documentation on how to use it properly? |
@BalloutAI Yes, we can. I am preparing a tutorial notebook for fine-tuning and will add it here, when it's done |
Thank you so much! Any expected timeline for that? |
@BalloutAI I made a short notebook for finetuning on a small dataset, you can find it here |
I am testing with the model ‘LanguageBind/Video-LLaVA-7B-hf’ and every time I run it on an image I get a different answer. I would like to know how much confidence the model has in each response, could I know? |
@IsabelJimenez99 You mean the model gives different generation every time, even if you keep the same image and prompt? That shouldn't be the case, can you share a minimal reproducible code? Regarding the model's confidence in each response, have a look at this thread which shows how to get probability of each generated token :) |
Yes, it's the same image, same prompt but different answers. The code I used is the same as the one shown in your collab. This is the code:
On the other hand, I have tested what has happened to me and they propose the following: However, I extrapolate that to their code and I get the following error: AttributeError: 'Tensor' object has no attribute 'sequences' |
@IsabelJimenez99 Ah I see now, the different outputs each time is expected in this case because you have set And for the second issue, you need to set "return_dict_in_generate=True, output_scores=True" in the generate kwargs to get scores in the output. Otherwise we only return the generated text. For more details of which arguments you can pass in kwargs and what they mean, see the docs 🤗 |
Oh! I understand now, thank you very much! And sorry for the inconvenience |
@zucchini-nlp |
@orrzohar yes, the model supports batching. For that you just have to pass the prompts as a list of strings, and also the list of visuals. Also you can do batching with different visual inputs: for ex one prompt has only image and another had only video prompts = ["<video>USER: What do you see in the video? ASSISTANT:", "<image>USER: What do you see in the image? ASSISTANT:", "<video>USER: more video instructions..."],
inputs = processor(text=prompts image=image, video=[clip, clip_2], return_tensors="pt") |
How might one most efficiently batch multiple prompts with 1 single clip/video? e.g. to achieve batched prompts applied to 1 single video Passing in btw in case it helps anyone reading: i had to add padding & truncation args |
@n2nco in that case you have to pass the clip multiple times, as you have two separate prompts each with a special "video" token. Transformers cannot align one video for several clips, as we don't know for sure if that was an intention or a mistake in code, so the safe way is to pass in as many clips as there are special "video" tokens :) |
Just a side note: could you move the fine-tuned notebook to the main page Markdown? It'll be much easier to spot. Much appreciated! |
@WeizhenWang-1210 hey! We don't usually add these notebooks in Transformers docs, but you can find this one and many more in our tutorials repo 🤗 |
Hey, thanks for the awesome work.
def collate_read_video(example, path): def load_videos_from_directory(directory): data = load_videos_from_directory("/mypath") dataset = dataset.map(collate_read_video, batched=False, fn_kwargs={"path": ""}, writer_batch_size= 100) processor = AutoProcessor.from_pretrained(MODEL_ID) class VideoLlavaDataset(Dataset):
def train_collate_fn(examples):
def eval_collate_fn(examples):
train_dataset = VideoLlavaDataset(dataset["train"]) class VideoLlavaModelPLModule(L.LightningModule):
` |
think it'd be straight forward to swap the vicuna-7b for a llama-3-8b base? e.g. https://huggingface.co/lmms-lab/llama3-llava-next-8b |
@BalloutAI , i am not sure where is the "question" that you're referring to in the prompt, and it's weird that the models is getting 100%. Did you try verifying the validation dataloader is correct (shapes and content), and turning on verbose mode to print the prediction/answers? @n2nco yes, swapping the backbone LLM should be easy by tweaking with the model's config, but the new model would require training. AFAIK the llava-Next you're pointing to can do video generation even if it wasn't trained for that. We're working on adding those in transformers 😄 |
Yeah, I have tried printing, and it is getting them correctly ['USER: \nAnswer the following question based on the video by True or False. ASSISTANT: Answer: True']. and it is answering them correctly no matter what the question is for some reason. My guess was that I am feeding the answers to the model directly somehow, but I cant find the problem, because I am getting my answer from the decoded_predictions. |
@BalloutAI Ah, sorry, you're right! Didn't see you had a different way of collate_fn. In the eval_collate when you feed the text to tokenizer, you have to get rid of the answer first. texts = [text.split("Answer: ")[-1] for text in texts] # Extract text w/o answer
batch = processor(text=texts, videos=videos, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt") |
Awesome, thx! I expected that! |
Thanks for your contribution. But I came across a bug: ValueError: Video pixel values should have exactly |
@caichuang0415 hey! Yes, since VIdeoLlava was trained with 8 frames, we currently support only 8-frame videos. You can open a PR if you want to give it a chance, otherwise I'll take a look at it next week :) |
@caichuang0415 now Video-LLaVa can work with any number of frames at input, But note that inference with more than 8 frames degrades quality, as the model wasn't trained in that setting. I recommend to tune with 24 frames first, if you want good performance. To get the updated version, please update transformers with: |
thanks for your updating! I will take your advise and make more experiments |
@s-s-la which notebook you're using? The one I linked above leads to VideoLlava and works in 4.42. The error message mentions another model which I'll merge into transformers on Monday and post about it in LlavaNext repo ;) |
@zucchini-nlp #We sample 8 frames for tuning following the original paper
Traceback (most recent call last): Does it mean that if i really want to change 8 to 30 Also another question is that if i set about more then 50 frame, it'll cause error : OverflowError: There was an overflow with type <class 'list'>. Try to reduce writer_batch_size to have batches smaller than 2GB. How can i solve it if i really want to use? thanks!!! |
@sherlock666 can you update your transformers version and install from main with |
Thanks for reply So do you mean that the latest transformer actually won't cause those two problems? |
It will solve the first problem. The second can be solved by decreasing writer_batch_size as the error msg says. The default is 1000 afaik. The issue is that when you get more frames and if your videos are high-resolution, you'll end up with a memory-consuming batches. I had similar problem with another model (at 8 frames). You can also consider doing collate and "read_video" in one Hope it's clear :) |
I just check , i'm using docker with latest transformer version (4.41.2) Thanks for help update1: |
Sorry if I wasn't clear, I meant updating to the version from |
Sorry for disturbing you @zucchini-nlp. When I try to inference with the script you provided at the top of this issue, the special character '.Ъ' appears for some of the questions in MMBench-Video. lKNB3ZeTYiI_processed.mp4 |
@FangXinyu-0913 yes, I had same problems and the prompt format should be "USER: Also, we are starting to support chat templates for that cases, so we can avoid such errors. @LinB203 can you merge my PR on the hub when you have time? :) |
this prompt format seems not reveal correctly due to some mistakes,can you modify it with code format?(using `` to show the prompt format) |
@FangXinyu-0913 sorry, forgot that GH doesn't like
|
Hello, thanks for your hard work! My code is like this.. from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
model_name = "LanguageBind/Video-LLaVA-7B-hf"
self.processor = VideoLlavaProcessor.from_pretrained(model_name)
self.model = VideoLlavaForConditionalGeneration.from_pretrained(
model_name,
cache_dir=os.path.join(cfg.model_cfg.cache_dir, "LanguageBind/"),
device_map="auto",
attn_implementation=None,
)#.to(device)
# (omitted...)
# videos and text_inputs are list of videos, list of strings, respectively.
inputs = self.processor(videos=videos, text=text_inputs, return_tensors="pt", padding=True).to(self.device)
outputs = self.model.generate(
**inputs,
# do_sample=False,
num_beams=5,
max_new_tokens=10,
min_length=1,
length_penalty=-1,
return_dict_in_generate=True,
output_scores=True,
)
output_text = self.processor.batch_decode(
outputs.sequences, skip_special_tokens=True
)
output_scores = torch.exp(outputs.sequences_scores).tolist() but I got this error: /home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/feature_extraction_utils.py:142: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at /opt/conda/conda-bld/pytorch_1682343962757/work/torch/csrc/utils/tensor_new.cpp:245.)
return torch.tensor(value)
We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)
/opt/conda/conda-bld/pytorch_1682343962757/work/aten/src/ATen/native/cuda/Indexing.cu:1093: indexSelectSmallIndex: block: [92,0,0], thread: [64,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1682343962757/work/aten/src/ATen/native/cuda/Indexing.cu:1093: indexSelectSmallIndex: block: [92,0,0], thread: [65,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
(omitted...)
/opt/conda/conda-bld/pytorch_1682343962757/work/aten/src/ATen/native/cuda/Indexing.cu:1093: indexSelectSmallIndex: block: [92,0,0], thread: [94,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1682343962757/work/aten/src/ATen/native/cuda/Indexing.cu:1093: indexSelectSmallIndex: block: [92,0,0], thread: [95,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
Traceback (most recent call last):
File "main.py", line 166, in <module>
main()
File "main.py", line 102, in main
sub_questions, _ = decomposer(images, text_inputs)
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl
return forward_call(*args, **kwargs)
File "/home/ywjang/LBA_LAVIS_uncertainty_v2/models/model.py", line 301, in forward
outputs = self.model.generate(
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
return func(*args, **kwargs)
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/generation/utils.py", line 1953, in generate
result = self._beam_search(
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/generation/utils.py", line 3011, in _beam_search
model_kwargs["past_key_values"] = self._temporary_reorder_cache(
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/generation/utils.py", line 2756, in _temporary_reorder_cache
past_key_values = self._reorder_cache(past_key_values, beam_idx)
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/models/video_llava/modeling_video_llava.py", line 689, in _reorder_cache
return self.language_model._reorder_cache(*args, **kwargs)
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 1300, in _reorder_cache
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
File "/home/ywjang/miniconda3/envs/LBA_uncertainty_v2/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py", line 1300, in <genexpr>
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
RuntimeError: CUDA error: device-side assert triggered
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. What's the problem? |
@greeksharifa yes, beam search is currently broken on latest versions and I have a fix for it, will be merged soon. But it should be working for older version, I just tried with the below script and got no errors: import av
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
model_name = "LanguageBind/Video-LLaVA-7B-hf"
processor = VideoLlavaProcessor.from_pretrained(model_name)
model = VideoLlavaForConditionalGeneration.from_pretrained(
model_name,
device_map="auto",
attn_implementation=None,
)
def read_video_pyav(container, indices):
frames = []
container.seek(0)
start_index = indices[0]
end_index = indices[-1]
for i, frame in enumerate(container.decode(video=0)):
if i > end_index:
break
if i >= start_index and i in indices:
frames.append(frame)
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
container = av.open(video_path)
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
videos = read_video_pyav(container, indices)
inputs = processor(videos=videos, text="USER: <video>\nWhat do you see here? ASSISTANT:", return_tensors="pt").to(model.device)
outputs = model.generate(
**inputs,
num_beams=5,
max_new_tokens=40,
min_length=1,
length_penalty=-1,
return_dict_in_generate=True,
output_scores=True,
)
output_text = processor.batch_decode(outputs.sequences, skip_special_tokens=True)
print(output_text)
output_scores = torch.exp(outputs.sequences_scores).tolist() I got:
If the above script works for you but fails with your video/text inputs, can you share a fully reproducible code pls. You can upload your video to the hub or send a link to it. |
Thanks for your quick answer. @zucchini-nlp I tried the above code and got no errors but a very strange answer like this: [2024-08-01 08:08:43,282] [INFO] [real_accelerator.py:110:get_accelerator] Setting ds_accelerator to cuda (auto detect)
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function.
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████| 3/3 [00:14<00:00, 4.71s/it]
/opt/conda/lib/python3.10/site-packages/transformers/feature_extraction_utils.py:142: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at ../torch/csrc/utils/tensor_new.cpp:245.)
return torch.tensor(value)
We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)
['USER: \nWhat do you see here? ASSISTANT:Mediaengoymbol abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abb abbcr'] I guess the tokenizer or some special tokens is broken, but it's not certain. I used transformers==4.42, torch==2.0.1 (follows readme ), python==3.10. in addition) GPU: A6000 |
@greeksharifa right, found that video llava had a bug that was related to new cache format. I am opening a PR (huggingface/transformers#32417) to fix this, and you will be able to run beam search when it's merged. Make sure to update transformers with |
Hi, I am trying videlloava to get the types of physical interactions it can see in a video, but it is not able to answer correctly. Is there any way (without finetuning, using the prompt directly) to pass it 2 or 3 videos with its explanation and the type of interaction and a fourth video asking it about the type of interaction? So that the model has the visual context of what the type of interaction looks like. |
@IsabelJimenez99 hey! AFAIK video-llava was not trained in few-shot setting so we can't be sure that it will be pick up from a few examples and continue in the same format, You can try out experimenting and maybe ask authors if they can share any insights on few-shot inference In terms of implementation, transformers supports multi-turn chat formatted input so it should be no problem to run generation :) |
Okey, thanks so much!! |
@zucchini-nlp Hello, and thanks for your hard work! |
Hello, do you know this error occur when running this code? |
Does this code make sense?
|
Hey!
Video-LLaVa is now available in the Transformers library! Feel free to check it out here. Thanks to @LinB203 for helping to ship the model 🤗
To get the model, update transformers by running:
!pip install --upgrade git+https://github.com/huggingface/transformers.git
. Inference with videos can be done as follows:Check out:
The text was updated successfully, but these errors were encountered: