diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..d05e047fdede5dbccc9f4c8101fbe6f7f421b8a2 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+*.mp4 filter=lfs diff=lfs merge=lfs -text
+*.wav filter=lfs diff=lfs merge=lfs -text
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..206b8ecc3646154fe0b39aa5411087a680a889f5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,54 @@
+# Python
+__pycache__
+*.pyc
+*.egg-info
+dist
+
+# Log
+*.log
+*.log.*
+*.json
+*.jsonl
+log_dir*/
+
+# Data
+!**/alpaca-data-conversation.json
+
+# Editor
+.idea
+*.swp
+
+# Other
+.DS_Store
+
+# jupyter
+.ipynb_checkpoints
+*.ipynb
+
+# DevContainer
+!.devcontainer/*
+
+# Demo
+serve_images/
+
+# data folder
+data/
+dataset/
+datasets/
+
+# training folder
+wandb
+ckpts*
+output
+output/
+checkpoints
+checkpoints/
+work_dirs*/
+
+# evaluation folder
+/eval/
+
+# pretrained weights
+pretrained/
+publish_models/
+public_models/
\ No newline at end of file
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bf414d4e90b678ac5e8b9361e68a59a0e6525fc
--- /dev/null
+++ b/app.py
@@ -0,0 +1,370 @@
+import spaces
+
+import os
+import re
+
+import torch
+import gradio as gr
+
+import sys
+sys.path.append('./videollama2')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+
+title_markdown = ("""
+
+
+
+
+
+
VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs
+ If this demo please you, please give us a star â on Github or đ on this space.
+
+
+
+
+
+""")
+
+
+block_css = """
+#buttons button {
+ min-width: min(120px,100%);
+ color: #9C276A
+}
+"""
+
+
+tos_markdown = ("""
+### Terms of use
+By using this service, users are required to agree to the following terms:
+The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
+Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
+For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
+""")
+
+
+learn_more_markdown = ("""
+### License
+This project is released under the Apache 2.0 license as found in the LICENSE file. The service is a research preview intended for non-commercial use ONLY, subject to the model Licenses of LLaMA and Mistral, Terms of Use of the data generated by OpenAI, and Privacy Practices of ShareGPT. Please get in touch with us if you find any potential violations.
+""")
+
+
+plum_color = gr.themes.colors.Color(
+ name='plum',
+ c50='#F8E4EF',
+ c100='#E9D0DE',
+ c200='#DABCCD',
+ c300='#CBA8BC',
+ c400='#BC94AB',
+ c500='#AD809A',
+ c600='#9E6C89',
+ c700='#8F5878',
+ c800='#804467',
+ c900='#713056',
+ c950='#662647',
+)
+
+
+class Chat:
+
+ def __init__(self, model_path, load_8bit=False, load_4bit=False):
+ disable_torch_init()
+
+ self.model, self.processor, self.tokenizer = model_init(model_path, load_8bit=load_8bit, load_4bit=load_4bit)
+
+ @spaces.GPU(duration=120)
+ @torch.inference_mode()
+ def generate(self, data: list, message, temperature, top_p, max_output_tokens):
+ # TODO: support multiple turns of conversation.
+ assert len(data) == 1
+
+ tensor, modal = data[0]
+ response = mm_infer(tensor, message, self.model, self.tokenizer, modal=modal.strip('<>'),
+ do_sample=True if temperature > 0.0 else False,
+ temperature=temperature,
+ top_p=top_p,
+ max_new_tokens=max_output_tokens)
+
+ return response
+
+
+@spaces.GPU(duration=120)
+def generate(image, video, audio, message, chatbot, va_tag, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
+ data = []
+
+ processor = handler.processor
+ try:
+ if image is not None:
+ data.append((processor['image'](image).to(handler.model.device, dtype=dtype), ''))
+ elif video is not None:
+ video_audio = processor['video'](video, va=va_tag=="Audio Vision")
+ if va_tag=="Audio Vision":
+ for k,v in video_audio.items():
+ video_audio[k] = v.to(handler.model.device, dtype=dtype)
+ else:
+ video_audio = video_audio.to(handler.model.device, dtype=dtype)
+ data.append((video_audio, ''))
+ elif audio is not None:
+ data.append((processor['audio'](audio).to(handler.model.device, dtype=dtype), ''))
+ elif image is None and video is None:
+ data.append((None, ''))
+ else:
+ raise NotImplementedError("Not support image and video at the same time")
+ except Exception as e:
+ traceback.print_exc()
+ return gr.update(value=None, interactive=True), gr.update(value=None, interactive=True), message, chatbot
+
+ assert len(message) % 2 == 0, "The message should be a pair of user and system message."
+
+ show_images = ""
+ if image is not None:
+ show_images += f' '
+ if video is not None:
+ show_images += f' '
+ if audio is not None:
+ show_images += f' '
+
+ one_turn_chat = [textbox_in, None]
+
+ # 1. first run case
+ if len(chatbot) == 0:
+ one_turn_chat[0] += "\n" + show_images
+ # 2. not first run case
+ else:
+ previous_image = re.findall(r' 0:
+ previous_image = previous_image[0]
+ # 2.1 new image append or pure text input will start a new conversation
+ if image is not None and os.path.basename(previous_image) != os.path.basename(image):
+ message.clear()
+ one_turn_chat[0] += "\n" + show_images
+ elif len(previous_video) > 0:
+ previous_video = previous_video[0]
+ # 2.2 new video append or pure text input will start a new conversation
+ if video is not None and os.path.basename(previous_video) != os.path.basename(video):
+ message.clear()
+ one_turn_chat[0] += "\n" + show_images
+ elif len(previous_audio) > 0:
+ previous_audio = previous_audio[0]
+ # 2.3 new audio append or pure text input will start a new conversation
+ if audio is not None and os.path.basename(previous_audio) != os.path.basename(video):
+ message.clear()
+ one_turn_chat[0] += "\n" + show_images
+
+ message.append({'role': 'user', 'content': textbox_in})
+
+ if va_tag == "Vision Only":
+ audio_tower = handler.model.model.audio_tower
+ handler.model.model.audio_tower = None
+ elif va_tag == "Audio Only":
+ vision_tower = handler.model.model.vision_tower
+ handler.model.model.vision_tower = None
+
+ text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
+
+ if va_tag == "Vision Only":
+ handler.model.model.audio_tower = audio_tower
+ elif va_tag == "Audio Only":
+ handler.model.model.vision_tower = vision_tower
+
+ message.append({'role': 'assistant', 'content': text_en_out})
+
+ one_turn_chat[1] = text_en_out
+ chatbot.append(one_turn_chat)
+
+ return gr.update(value=image, interactive=True), gr.update(value=video, interactive=True), gr.update(value=audio, interactive=True), message, chatbot
+
+
+def regenerate(message, chatbot):
+ message.pop(-1), message.pop(-1)
+ chatbot.pop(-1)
+ return message, chatbot
+
+
+def clear_history(message, chatbot):
+ message.clear(), chatbot.clear()
+ return (gr.update(value=None, interactive=True),
+ gr.update(value=None, interactive=True),
+ gr.update(value=None, interactive=True),
+ message, chatbot,
+ gr.update(value=None, interactive=True))
+
+
+# BUG of Zero Environment
+# 1. The environment is fixed to torch>=2.0,<=2.2, gradio>=4.x.x
+# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
+# 3. The function can't return tensor or other cuda objects.
+
+model_path = 'DAMO-NLP-SG/VideoLLaMA2.1-7B-AV'
+
+handler = Chat(model_path, load_8bit=False, load_4bit=False)
+
+textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
+
+theme = gr.themes.Default(primary_hue=plum_color)
+# theme.update_color("primary", plum_color.c500)
+theme.set(slider_color="#9C276A")
+theme.set(block_title_text_color="#9C276A")
+theme.set(block_label_text_color="#9C276A")
+theme.set(button_primary_text_color="#9C276A")
+# theme.set(button_secondary_text_color="*neutral_800")
+
+
+with gr.Blocks(title='VideoLLaMA 2 đĨđđĨ', theme=theme, css=block_css) as demo:
+ gr.Markdown(title_markdown)
+ message = gr.State([])
+
+ with gr.Row():
+ with gr.Column(scale=3):
+ image = gr.Image(label="Input Image", type="filepath")
+ video = gr.Video(label="Input Video")
+ audio = gr.Audio(label="Input Audio", type="filepath")
+
+ with gr.Accordion("Parameters", open=True) as parameter_row:
+ # num_beams = gr.Slider(
+ # minimum=1,
+ # maximum=10,
+ # value=1,
+ # step=1,
+ # interactive=True,
+ # label="beam search numbers",
+ # )
+
+ va_tag = gr.Radio(choices=["Audio Vision", "Vision Only", "Audio Only"], value="Audio Vision", label="Select one")
+
+ temperature = gr.Slider(
+ minimum=0.1,
+ maximum=1.0,
+ value=0.2,
+ step=0.1,
+ interactive=True,
+ label="Temperature",
+ )
+
+ top_p = gr.Slider(
+ minimum=0.0,
+ maximum=1.0,
+ value=0.7,
+ step=0.1,
+ interactive=True,
+ label="Top P",
+ )
+
+ max_output_tokens = gr.Slider(
+ minimum=64,
+ maximum=1024,
+ value=512,
+ step=64,
+ interactive=True,
+ label="Max output tokens",
+ )
+
+ with gr.Column(scale=7):
+ chatbot = gr.Chatbot(label="VideoLLaMA 2", bubble_full_width=True, height=750)
+ with gr.Row():
+ with gr.Column(scale=8):
+ textbox.render()
+ with gr.Column(scale=1, min_width=50):
+ submit_btn = gr.Button(value="Send", variant="primary", interactive=True)
+ with gr.Row(elem_id="buttons") as button_row:
+ upvote_btn = gr.Button(value="đ Upvote", interactive=True)
+ downvote_btn = gr.Button(value="đ Downvote", interactive=True)
+ # flag_btn = gr.Button(value="â ī¸ Flag", interactive=True)
+ # stop_btn = gr.Button(value="âšī¸ Stop Generation", interactive=False)
+ regenerate_btn = gr.Button(value="đ Regenerate", interactive=True)
+ clear_btn = gr.Button(value="đī¸ Clear history", interactive=True)
+
+ with gr.Row():
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
+
+ with gr.Column():
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/examples/extreme_ironing.jpg",
+ "What happens in this image?",
+ ],
+ [
+ f"{cur_dir}/examples/waterview.jpg",
+ "What are the things I should be cautious about when I visit here?",
+ ],
+ ],
+ inputs=[image, textbox],
+ )
+
+ with gr.Column():
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/examples/WBS4I.mp4",
+ "Please describe the video:",
+ ],
+ [
+ f"{cur_dir}/examples/sample_demo_1.mp4",
+ "Please describe the video:",
+ ],
+ ],
+ inputs=[video, textbox],
+ )
+ with gr.Column():
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/examples/00000368.mp4",
+ "Please describe the video with audio information:",
+ ],
+ [
+ f"{cur_dir}/examples/00003491.mp4",
+ "Where is the loudest instrument?",
+ ],
+ ],
+ inputs=[video, textbox],
+ )
+ with gr.Column():
+ # audio
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/examples/Y--ZHUMfueO0.flac",
+ "Please describe the audio:",
+ ],
+ [
+ f"{cur_dir}/examples/Traffic and pedestrians.wav",
+ "Please describe the audio:",
+ ],
+ ],
+ inputs=[audio, textbox],
+ )
+
+ gr.Markdown(tos_markdown)
+ gr.Markdown(learn_more_markdown)
+
+ submit_btn.click(
+ generate,
+ [image, video, audio, message, chatbot, va_tag, textbox, temperature, top_p, max_output_tokens],
+ [image, video, audio, message, chatbot])
+
+ regenerate_btn.click(
+ regenerate,
+ [message, chatbot],
+ [message, chatbot]).then(
+ generate,
+ [image, video, audio, message, chatbot, va_tag, textbox, temperature, top_p, max_output_tokens],
+ [image, video, audio, message, chatbot])
+
+ clear_btn.click(
+ clear_history,
+ [message, chatbot],
+ [image, video, audio, message, chatbot, textbox])
+
+demo.launch(share=False)
diff --git a/examples/00000368.mp4 b/examples/00000368.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..8b084c69a73949c4911f7b2d8c3417dcf97c025a
--- /dev/null
+++ b/examples/00000368.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ad8a2238cad4bc690de0e3fe0d1f891e83ebc9f1e0bfd06e17145e34f8031f14
+size 4383040
diff --git a/examples/00003491.mp4 b/examples/00003491.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..67c0cb6cec0cb5d1ca586d06968fd0d3e6379eac
--- /dev/null
+++ b/examples/00003491.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8513fbd368e2ed18b2ae188120ee0efd733105be1633a14e48697257e283b795
+size 3997338
diff --git a/examples/1034346401.mp4 b/examples/1034346401.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..cb132f0838c45014cdb6f7def631c510fe089293
--- /dev/null
+++ b/examples/1034346401.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:08b62a634fe49edc0a19fc53f6ea5cfb345d9b2a6a7047811344c16832dc42b2
+size 1678095
diff --git a/examples/Traffic and pedestrians.wav b/examples/Traffic and pedestrians.wav
new file mode 100644
index 0000000000000000000000000000000000000000..fda8f57a0dc451fbb6ed506259810a21b4b7ed4b
--- /dev/null
+++ b/examples/Traffic and pedestrians.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:39d805c8e0e487427d60c47ded7d7cca9b8fa288c1a53c93118b15f68ecf6792
+size 1656254
diff --git a/examples/WBS4I.mp4 b/examples/WBS4I.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..eb2224e4360c4a577183769eb4881010bc26d0a5
--- /dev/null
+++ b/examples/WBS4I.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7129dddf8da11c9296845eed65f0016dc67a503972c57500fe9f7c3ad2ee1ff3
+size 1052064
diff --git a/examples/Y--ZHUMfueO0.flac b/examples/Y--ZHUMfueO0.flac
new file mode 100644
index 0000000000000000000000000000000000000000..3ade226c110aa4ed26fbe0bcf0925756fca14528
Binary files /dev/null and b/examples/Y--ZHUMfueO0.flac differ
diff --git a/examples/desert.jpg b/examples/desert.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..926c0b192ff0d2074afbeee5552349cdfc176cc0
Binary files /dev/null and b/examples/desert.jpg differ
diff --git a/examples/extreme_ironing.jpg b/examples/extreme_ironing.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..638b078837f175039b2db49a63821288d9681daa
Binary files /dev/null and b/examples/extreme_ironing.jpg differ
diff --git a/examples/sample_demo_1.mp4 b/examples/sample_demo_1.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..a659cf1dc92142e24909bd17655ac47f9ac433db
--- /dev/null
+++ b/examples/sample_demo_1.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fc6562a172eb9cb3c760a3c9992349c1faa2c793c112b7b9e50bd5cb17c2164d
+size 1549315
diff --git a/examples/sample_demo_3.mp4 b/examples/sample_demo_3.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..4eb2c6b90edfd07f9161ac6f49b5ee6e04ebe1a6
--- /dev/null
+++ b/examples/sample_demo_3.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:da6126bce64c64a3d6f7ce889fbe15b5f1c2e3f978846351d8c7a79a950b429e
+size 463547
diff --git a/examples/sample_demo_9.mp4 b/examples/sample_demo_9.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..a0eeac56fbec64a564edf1e7ce62bf8aa22ed003
--- /dev/null
+++ b/examples/sample_demo_9.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f9702694f185e27ae016b85024b367e140cf93a4e3124d072816fd32f2ca0d96
+size 631864
diff --git a/examples/waterview.jpg b/examples/waterview.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..6f44ebaba1aa493b8bab3baa4e827b76752b1869
Binary files /dev/null and b/examples/waterview.jpg differ
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fd931fcec74fad28ceb8feb44c4c3bb79dd93c99
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,41 @@
+# basic dependencies
+torch==2.2.0
+torchaudio==2.2.0
+torchvision==0.17.0
+transformers==4.42.3
+tokenizers==0.19.1
+deepspeed==0.13.1
+accelerate==0.26.1
+peft==0.4.0
+timm==1.0.3
+numpy==1.24.4
+# data processing
+decord==0.6.0
+imageio==2.34.0
+imageio-ffmpeg==0.4.9
+moviepy==1.0.3
+scenedetect==0.6.3
+opencv-python==4.6.0.66
+pysubs2
+librosa
+pytorchvideo
+# misc
+scikit-learn==1.2.2
+huggingface_hub==0.23.4
+sentencepiece==0.1.99
+shortuuid
+einops==0.6.1
+einops-exts==0.0.4
+bitsandbytes==0.43.0
+pydantic>=2.0
+markdown2[all]
+gradio==3.50.0
+gradio_client==0.6.1
+httpx==0.24.1
+openai==1.33.0
+requests
+uvicorn
+fastapi
+tensorboard
+wandb
+tabulate
diff --git a/videollama2/__init__.py b/videollama2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4eced896b2c28b34c6678f32d7080bfb585437de
--- /dev/null
+++ b/videollama2/__init__.py
@@ -0,0 +1,120 @@
+import os
+import copy
+import warnings
+import shutil
+from functools import partial
+
+import torch
+
+from .model import load_pretrained_model
+from .mm_utils import process_image, process_video, tokenizer_multimodal_token, get_model_name_from_path, KeywordsStoppingCriteria, process_audio_file
+from .constants import NUM_FRAMES, DEFAULT_IMAGE_TOKEN, DEFAULT_VIDEO_TOKEN, MODAL_INDEX_MAP, DEFAULT_AUDIO_TOKEN
+
+
+def model_init(model_path=None, **kwargs):
+ model_path = "DAMO-NLP-SG/VideoLLaMA2-7B" if model_path is None else model_path
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, processor, context_len = load_pretrained_model(model_path, None, model_name, **kwargs)
+
+ if tokenizer.pad_token is None and tokenizer.unk_token is not None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ num_frames = model.config.num_frames if hasattr(model.config, "num_frames") else NUM_FRAMES
+ #num_frames = 16
+ processor = {
+ 'image': partial(process_image, processor=processor, aspect_ratio=None),
+ 'video': partial(process_video, processor=processor, aspect_ratio=None, num_frames=num_frames),
+ 'audio': process_audio_file,
+ }
+
+ return model, processor, tokenizer
+
+
+def mm_infer(image_or_video, instruct, model, tokenizer, modal='video', **kwargs):
+ """inference api of VideoLLaMA2 for video understanding.
+
+ Args:
+ model: VideoLLaMA2 model.
+ image_or_video (torch.Tensor): image tensor (1, C, H, W) / video tensor (T, C, H, W).
+ instruct (str): text instruction for understanding video.
+ tokenizer: tokenizer.
+ do_sample (bool): whether to sample.
+ modal (str): inference modality.
+ Returns:
+ str: response of the model.
+ """
+
+ # 1. text preprocess (tag process & generate prompt).
+ if modal == 'image':
+ modal_token = DEFAULT_IMAGE_TOKEN
+ elif modal == 'video':
+ modal_token = DEFAULT_VIDEO_TOKEN
+ elif modal == 'text':
+ modal_token = ''
+ elif modal == 'audio':
+ modal_token = DEFAULT_AUDIO_TOKEN
+ else:
+ raise ValueError(f"Unsupported modal: {modal}")
+
+ # 1. vision preprocess (load & transform image or video).
+ if modal == 'text':
+ tensor = None
+ else:
+ if isinstance(image_or_video, dict):
+ tensor = {k: v.half().cuda() for k, v in image_or_video.items()}
+ else:
+ tensor = image_or_video.half().cuda()
+ tensor = [(tensor, modal)]
+
+ # 2. text preprocess (tag process & generate prompt).
+ if isinstance(instruct, str):
+ message = [{'role': 'user', 'content': modal_token + '\n' + instruct}]
+ elif isinstance(instruct, list):
+ message = copy.deepcopy(instruct)
+ message[0]['content'] = modal_token + '\n' + message[0]['content']
+ else:
+ raise ValueError(f"Unsupported type of instruct: {type(instruct)}")
+
+ if model.config.model_type in ['videollama2', 'videollama2_mistral', 'videollama2_mixtral']:
+ system_message = [
+ {'role': 'system', 'content': (
+ """<>\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature."""
+ """\n"""
+ """If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n< >""")
+ }
+ ]
+ else:
+ system_message = []
+
+ message = system_message + message
+ prompt = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
+
+ input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token, return_tensors='pt').unsqueeze(0).long().cuda()
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
+
+ # 3. generate response according to visual signals and prompts.
+ keywords = [tokenizer.eos_token]
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
+
+ do_sample = kwargs.get('do_sample', False)
+ temperature = kwargs.get('temperature', 0.2 if do_sample else 0.0)
+ top_p = kwargs.get('top_p', 0.9)
+ max_new_tokens = kwargs.get('max_new_tokens', 2048)
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ attention_mask=attention_masks,
+ images=tensor,
+ do_sample=do_sample,
+ temperature=temperature,
+ max_new_tokens=max_new_tokens,
+ top_p=top_p,
+ use_cache=True,
+ stopping_criteria=[stopping_criteria],
+ pad_token_id=tokenizer.eos_token_id,
+ )
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ return outputs
diff --git a/videollama2/constants.py b/videollama2/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba87b61becb0819594962652fd3e193a9c8c3a3f
--- /dev/null
+++ b/videollama2/constants.py
@@ -0,0 +1,32 @@
+CONTROLLER_HEART_BEAT_EXPIRATION = 30
+WORKER_HEART_BEAT_INTERVAL = 15
+
+LOGDIR = "."
+
+# Model Constants
+IGNORE_INDEX = -100
+
+# Image arguments
+IMAGE_TOKEN_INDEX = -200
+DEFAULT_IMAGE_TOKEN = ""
+DEFAULT_IMAGE_PATCH_TOKEN = ""
+DEFAULT_IM_START_TOKEN = ""
+DEFAULT_IM_END_TOKEN = ""
+IMAGE_PLACEHOLDER = ""
+
+# Video arguments
+VIDEO_TOKEN_INDEX = -201
+DEFAULT_VIDEO_TOKEN = ""
+NUM_FRAMES = 8
+MAX_FRAMES = 32
+NUM_FRAMES_PER_SECOND = 1
+
+# Audio arguments
+AUDIO_TOKEN_INDEX = -202
+DEFAULT_AUDIO_TOKEN = ""
+
+MODAL_INDEX_MAP = {
+ "": -200,
+ "": -201,
+ "": -202,
+}
diff --git a/videollama2/conversation.py b/videollama2/conversation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a59b62cd7ba36a54382d8c6db2a701186f9834a4
--- /dev/null
+++ b/videollama2/conversation.py
@@ -0,0 +1,507 @@
+import base64
+import dataclasses
+from io import BytesIO
+from enum import auto, Enum
+from typing import List, Tuple
+
+from PIL import Image
+from .constants import LOGDIR, NUM_FRAMES
+
+
+class SeparatorStyle(Enum):
+ """Different separator style."""
+ SINGLE = auto()
+ TWO = auto()
+ PLAIN = auto()
+ LLAMA2 = auto()
+ QWEN = auto()
+
+@dataclasses.dataclass
+class Conversation:
+ """A class that keeps all conversation history."""
+ system: str
+ roles: List[str]
+ messages: List[List[str]]
+ offset: int
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
+ sep: str = "###"
+ sep2: str = None
+ version: str = "Unknown"
+
+ skip_next: bool = False
+ modality: str = "image"
+
+ def get_prompt(self):
+ messages = self.messages
+ modality_token = f"<{self.modality}>"
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
+ messages = self.messages.copy()
+ init_role, init_msg = messages[0].copy()
+ init_msg = init_msg[0].replace(modality_token, "").strip()
+ if 'mmtag' in self.version:
+ messages[0] = (init_role, init_msg)
+ messages.insert(0, (self.roles[0], " "))
+ messages.insert(1, (self.roles[1], "Received."))
+ else:
+ messages[0] = (init_role, f"{modality_token}\n" + init_msg)
+
+ if self.sep_style == SeparatorStyle.SINGLE:
+ ret = self.system + self.sep
+ for role, message in messages:
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + self.sep
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.TWO:
+ seps = [self.sep, self.sep2]
+ ret = self.system + seps[0]
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + seps[i % 2]
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.LLAMA2:
+ wrap_sys = lambda msg: f"<>\n{msg}\n< >\n\n"
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
+ ret = ""
+
+ for i, (role, message) in enumerate(messages):
+ if i == 0:
+ assert message, "first message should not be none"
+ assert role == self.roles[0], "first message should come from user"
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ if i == 0: message = wrap_sys(self.system) + message
+ if i % 2 == 0:
+ message = wrap_inst(message)
+ ret += self.sep + message
+ else:
+ ret += " " + message + " " + self.sep2
+ else:
+ ret += ""
+ ret = ret.lstrip(self.sep)
+ elif self.sep_style == SeparatorStyle.QWEN:
+ ret = ""
+ # 1. Add system prompt
+ ret += self.system + self.sep + "\n"
+ # 2. Iterate message
+ for i, (role, message) in enumerate(messages):
+ if i == 0:
+ assert message, "first message should not be none"
+ assert role == self.roles[0], "first message should come from user"
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ # 2.1 Add role and message
+ ret += role + message + self.sep + "\n"
+ else:
+ # 2.2 Add generation prompt
+ ret += role
+ elif self.sep_style == SeparatorStyle.PLAIN:
+ seps = [self.sep, self.sep2]
+ ret = self.system
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + message + seps[i % 2]
+ else:
+ ret += role
+ else:
+ raise ValueError(f"Invalid style: {self.sep_style}")
+
+ return ret
+
+ def append_message(self, role, message):
+ self.messages.append([role, message])
+
+ def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=800, min_len=400):
+ if image_process_mode == "Pad":
+ def expand2square(pil_img, background_color=(122, 116, 104)):
+ width, height = pil_img.size
+ if width == height:
+ return pil_img
+ elif width > height:
+ result = Image.new(pil_img.mode, (width, width), background_color)
+ result.paste(pil_img, (0, (width - height) // 2))
+ return result
+ else:
+ result = Image.new(pil_img.mode, (height, height), background_color)
+ result.paste(pil_img, ((height - width) // 2, 0))
+ return result
+ image = expand2square(image)
+ elif image_process_mode in ["Default", "Crop"]:
+ pass
+ elif image_process_mode == "Resize":
+ image = image.resize((336, 336))
+ else:
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
+ if max(image.size) > max_len:
+ max_hw, min_hw = max(image.size), min(image.size)
+ aspect_ratio = max_hw / min_hw
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ longest_edge = int(shortest_edge * aspect_ratio)
+ W, H = image.size
+ if H > W:
+ H, W = longest_edge, shortest_edge
+ else:
+ H, W = shortest_edge, longest_edge
+ image = image.resize((W, H))
+ if return_pil:
+ return image
+ else:
+ buffered = BytesIO()
+ image.save(buffered, format=image_format)
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ return img_b64_str
+
+
+ def get_videos(self, return_pil=False):
+ video_frames = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ from decord import VideoReader, cpu
+ import numpy as np
+ # here video is the file path of input video
+ msg, video, image_process_mode = msg
+ if not return_pil:
+ # return filepath
+ video_frames.append(video)
+ else:
+ # read video using decord.VideoReader
+ decord_vr = VideoReader(uri=video, ctx=cpu(0))
+ duration = len(decord_vr)
+ frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ # convert the extracted image frames into PIL objects
+ all_images = [Image.fromarray(f) for f in decord_vr.get_batch(frame_id_list).asnumpy()]
+ video_frames.extend([self.process_image(image, image_process_mode, return_pil=return_pil) for image in all_images])
+ return video_frames
+
+
+ def get_images(self, return_pil=False):
+ images = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ msg, image, image_process_mode = msg
+ image = self.process_image(image, image_process_mode, return_pil=return_pil)
+ images.append(image)
+
+ # import base64
+ # from io import BytesIO
+ # from PIL import Image
+ # # here image is a PIL object
+ # msg, image, image_process_mode = msg
+ # if image_process_mode == "Pad":
+ # def expand2square(pil_img, background_color=(122, 116, 104)):
+ # width, height = pil_img.size
+ # if width == height:
+ # return pil_img
+ # elif width > height:
+ # result = Image.new(pil_img.mode, (width, width), background_color)
+ # result.paste(pil_img, (0, (width - height) // 2))
+ # return result
+ # else:
+ # result = Image.new(pil_img.mode, (height, height), background_color)
+ # result.paste(pil_img, ((height - width) // 2, 0))
+ # return result
+ # image = expand2square(image)
+ # elif image_process_mode in ["Default", "Crop"]:
+ # pass
+ # elif image_process_mode == "Resize":
+ # image = image.resize((336, 336))
+ # else:
+ # raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
+ # max_hw, min_hw = max(image.size), min(image.size)
+ # aspect_ratio = max_hw / min_hw
+ # max_len, min_len = 800, 400
+ # shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ # longest_edge = int(shortest_edge * aspect_ratio)
+ # W, H = image.size
+ # if longest_edge != max(image.size):
+ # if H > W:
+ # H, W = longest_edge, shortest_edge
+ # else:
+ # H, W = shortest_edge, longest_edge
+ # image = image.resize((W, H))
+ # if return_pil:
+ # images.append(image)
+ # else:
+ # buffered = BytesIO()
+ # image.save(buffered, format="PNG")
+ # img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ # images.append(img_b64_str)
+ return images
+
+ def to_gradio_chatbot(self):
+ ret = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ # import base64
+ # from io import BytesIO
+ # from PIL import Image
+ # msg, image, image_process_mode = msg
+ # max_hw, min_hw = max(image.size), min(image.size)
+ # aspect_ratio = max_hw / min_hw
+ # max_len, min_len = 800, 400
+ # shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ # longest_edge = int(shortest_edge * aspect_ratio)
+ # W, H = image.size
+ # if H > W:
+ # H, W = longest_edge, shortest_edge
+ # else:
+ # H, W = shortest_edge, longest_edge
+ # image = image.resize((W, H))
+ # buffered = BytesIO()
+ # image.save(buffered, format="JPEG")
+ # img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ # img_str = f' '
+ # display image/video in the textbox
+ msg, image_or_video, image_process_mode = msg
+ ##print("imagebox:", image)
+ if isinstance(image_or_video, Image.Image):
+ # image is PIL object
+ img_b64_str = self.process_image(image_or_video, "Default", return_pil=False, image_format='JPEG')
+ img_str = f' '
+ msg = img_str + msg.replace('', '').strip()
+ else:
+ # video is file path
+ vid_str = f' '
+ msg = vid_str + msg.replace('', '').strip()
+ ret.append([msg, None])
+ else:
+ ret.append([msg, None])
+ else:
+ ret[-1][-1] = msg
+ return ret
+
+ def copy(self):
+ return Conversation(
+ system=self.system,
+ roles=self.roles,
+ messages=[[x, y] for x, y in self.messages],
+ offset=self.offset,
+ sep_style=self.sep_style,
+ sep=self.sep,
+ sep2=self.sep2,
+ version=self.version)
+
+ def dict(self):
+ if (self.modality == "image" and len(self.get_images()) > 0) or \
+ (self.modality == "video" and len(self.get_videos()) > 0):
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ "modality": self.modality
+ }
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": self.messages,
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ }
+
+
+conv_vicuna_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
+ ("Assistant",
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
+ "renewable and non-renewable energy sources:\n"
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
+ "energy sources are finite and will eventually run out.\n"
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
+ "and other negative effects.\n"
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
+ "have lower operational costs than non-renewable sources.\n"
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
+ "locations than non-renewable sources.\n"
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
+ ),
+ offset=2,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_llava_plain = Conversation(
+ system="",
+ roles=("", ""),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.PLAIN,
+ sep="",
+ sep2="\n"
+)
+
+conv_llava_v0_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content .",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+ version="v0_mmtag",
+)
+
+conv_llava_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_vicuna_v1 = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llava_v1_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content .",
+ roles=("USER", "ASSISTANT"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+ version="v1_mmtag",
+)
+
+conv_llava_v1 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llava_llama2 = Conversation(
+ system="You are a helpful language and vision assistant. "
+ "You are able to understand the visual content that the user provides, "
+ "and assist the user with a variety of tasks using natural language.",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2=" ",
+)
+
+conv_llama2 = Conversation(
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
+
+If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2=" ",
+)
+
+conv_mistral = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2="",
+)
+
+conv_qwen = Conversation(
+ system="<|im_start|>system\nYou are a helpful assistant.",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.QWEN,
+ sep="<|im_end|>",
+ version="qwen",
+)
+
+conv_qwen_plain = Conversation(
+ system="",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.PLAIN,
+ sep="<|im_end|>",
+ sep2="<|im_end|>",
+ version="qwen_plain",
+)
+
+default_conversation = conv_mistral
+conv_templates = {
+ "default": conv_vicuna_v0,
+ # pretrain template
+ "plain": conv_llava_plain,
+ # llava v0
+ "v0": conv_vicuna_v0,
+ "v0_plain": conv_llava_plain,
+ "v0_mmtag": conv_llava_v0_mmtag,
+ "llava_v0": conv_llava_v0,
+ # llava v1
+ "v1": conv_vicuna_v1,
+ "v1_mmtag": conv_llava_v1_mmtag,
+ "llava_v1": conv_llava_v1,
+ "vicuna_v1": conv_vicuna_v1,
+ # llava v1.5
+ "llava_llama2": conv_llava_llama2,
+ # llama2
+ "llama2": conv_llama2,
+ # mistral
+ "mistral": conv_mistral,
+ # qwen
+ "qwen": conv_qwen,
+ "qwen_plain": conv_qwen_plain,
+}
+
+
+if __name__ == "__main__":
+ print(default_conversation.get_prompt())
diff --git a/videollama2/inference_audio.py b/videollama2/inference_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cc25c3f273fd2ddab0a56f17709e264686740a6
--- /dev/null
+++ b/videollama2/inference_audio.py
@@ -0,0 +1,292 @@
+import os
+import json
+import math
+import argparse
+import warnings
+import traceback
+from tqdm import tqdm
+
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class ClothoAQADataset(Dataset):
+
+ audoi_formats = ['.wav', '.flac']
+
+ def __init__(self, questions, processor):
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ audio_path = sample['audio']
+ question = sample['conversations'][0]["value"]
+ wrapped_question = f"Question: {question}\nAnswer the question using a single word."
+ question_id = sample['id']
+ answer = sample['conversations'][1]["value"]
+
+ audio_tensor = self.processor(audio_path)
+
+ return {
+ 'audio': audio_tensor,
+ 'audio_name': audio_path.split("/")[-1],
+ 'question': wrapped_question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+class ClothoDataset(Dataset):
+
+ audoi_formats = ['.wav', '.flac']
+
+ def __init__(self, questions, processor):
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ audio_path = sample['audio']
+ wrapped_question = f"Describe the audio."
+ question_id = audio_path.split("/")[-1]
+ answer = sample['captions']
+
+ audio_tensor = self.processor(audio_path)
+
+ return {
+ 'audio': audio_tensor,
+ 'audio_name': audio_path.split("/")[-1],
+ 'question': wrapped_question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+class TUT2017Dataset(Dataset):
+
+ audoi_formats = ['.wav', '.flac']
+
+ def __init__(self, questions, processor):
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ audio_path = sample['audio']
+ wrapped_question = f"Question: Identify the sound event in the audio.\nOptions:\n(A) beach\n(B) bus\n(C) cafe or restaurant\n(D) car\n(E) city center\n(F) forest path\n(G) grocery store\n(H) home\n(I) library\n(J) metro station\n(K) office\n(L) park\n(M) residential area\n(N) train\n(O) tram\n.Answer with the option's letter from the given choices directly and only give the best option."
+ question_id = audio_path.split("/")[-1]
+ answer = sample['gt']
+
+ audio_tensor = self.processor(audio_path)
+
+ return {
+ 'audio': audio_tensor,
+ 'audio_name': audio_path.split("/")[-1],
+ 'question': wrapped_question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+class VocalSoundDataset(Dataset):
+
+ audoi_formats = ['.wav', '.flac']
+
+ def __init__(self, questions, processor):
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ audio_path = sample['audio']
+ wrapped_question = f"Identify the human sound in the audio.\nOptions:\n(A) Laughter\n(B) Sigh\n(C) Cough\n(D) Throat clearing\n(E) Sneeze\n(F) Sniff\n.Answer with the option's letter from the given choices directly and only give the best option."
+ question_id = audio_path.split("/")[-1]
+ answer = sample['gt']
+
+ audio_tensor = self.processor(audio_path)
+
+ return {
+ 'audio': audio_tensor,
+ 'audio_name': audio_path.split("/")[-1],
+ 'question': wrapped_question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+class AIRDataset(Dataset):
+
+ audoi_formats = ['.wav', '.flac']
+
+ def __init__(self, questions, processor):
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ audio_path = sample['audio']
+ wrapped_question = sample['query']
+ question_id = sample['id']
+ answer = sample['answer']
+
+ audio_tensor = self.processor(audio_path)
+
+ return {
+ 'audio': audio_tensor,
+ 'audio_name': audio_path.split("/")[-1],
+ 'question': wrapped_question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['audio'] for x in batch]
+ v_id = [x['audio_name'] for x in batch]
+ qus = [x['question'] for x in batch]
+ qid = [x['question_id'] for x in batch]
+ ans = [x['answer'] for x in batch]
+ return vid, v_id, qus, qid, ans
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ # Initialize the model
+ model, processor, tokenizer = model_init(args.model_path)
+ model.model.vision_tower = None
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ if args.dataset == "clothoAQA":
+ gt_questions = json.load(open(args.question_file, "r"))
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ dataset = ClothoAQADataset(gt_questions, processor['audio'])
+ elif args.dataset == "clotho":
+ import csv
+ gt_questions = []
+ with open(args.question_file, mode='r', encoding='utf-8') as file:
+ reader = csv.reader(file)
+ header = next(reader) # remove header
+ for row in reader:
+ gt_questions.append({
+ "audio": os.path.join(args.video_folder, row[0]),
+ "captions": row[1:]
+ })
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ dataset = ClothoDataset(gt_questions, processor['audio'])
+ elif args.dataset == "TUT2017":
+ gt_questions = []
+ with open(args.question_file, "r") as fp:
+ for x in fp.readlines():
+ gt_questions.append(json.loads(x))
+ gt_questions[-1]["audio"] = os.path.join(args.video_folder, gt_questions[-1]["audio"])
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ dataset = TUT2017Dataset(gt_questions, processor['audio'])
+ elif args.dataset == "vocalsound":
+ gt_questions = []
+ with open(args.question_file, "r") as fp:
+ for x in fp.readlines():
+ gt_questions.append(json.loads(x))
+ gt_questions[-1]["audio"] = os.path.join(args.video_folder, gt_questions[-1]["audio"].split("/")[-1])
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ dataset = VocalSoundDataset(gt_questions, processor['audio'])
+ elif args.dataset == "AIR":
+ gt_answer = {x["uniq_id"]: x for x in json.load(open(args.answer_file, "r"))}
+
+ gt_questions = []
+ with open(args.question_file, "r") as fp:
+ for x in fp.readlines():
+ gt_questions.append(json.loads(x))
+ gt_questions[-1]["answer"] = gt_answer[gt_questions[-1]["id"]]["answer_gt"]
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ dataset = AIRDataset(gt_questions, processor['audio'])
+ else:
+ raise NotImplementedError
+
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ answer_file = os.path.join(args.output_file)
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ # Iterate over each sample in the ground truth file
+ for i, (audio_tensors, audio_names, questions, question_ids, answers) in enumerate(tqdm(dataloader)):
+ audio_tensor = audio_tensors[0]
+ audio_name = audio_names[0]
+ question = questions[0]
+ question_id = question_ids[0]
+ answer = answers[0]
+
+ # question = question + '\n' + 'Answer the question using a single word or a short phrase with multiple words.'
+
+ try:
+ output = mm_infer(
+ audio_tensor,
+ question,
+ model=model,
+ tokenizer=tokenizer,
+ modal='audio',
+ do_sample=False,
+ )
+ except:
+ traceback.print_exc()
+ output = "error"
+
+ sample_set = {'id': question_id, 'question': question, 'answer': answer, 'pred': output}
+ ans_file.write(json.dumps(sample_set) + "\n")
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=False)
+ parser.add_argument('--output-file', help='Directory to save the model results JSON.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+ parser.add_argument("--dataset", type=str, required=True)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/mm_utils.py b/videollama2/mm_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..be8823729a271e4625949e70fbb79ade6ca5f45d
--- /dev/null
+++ b/videollama2/mm_utils.py
@@ -0,0 +1,473 @@
+import ast
+import os
+import math
+import base64
+import traceback
+from io import BytesIO
+
+import cv2
+import torch
+import imageio
+import numpy as np
+from PIL import Image
+from decord import VideoReader, cpu
+from moviepy.editor import VideoFileClip
+from transformers import StoppingCriteria
+
+from .constants import NUM_FRAMES, MAX_FRAMES, NUM_FRAMES_PER_SECOND, MODAL_INDEX_MAP, DEFAULT_IMAGE_TOKEN
+from moviepy.editor import VideoFileClip
+import random
+import librosa
+import soundfile as sf
+import torchaudio.compliance.kaldi as ta_kaldi
+from subprocess import CalledProcessError, run, Popen, PIPE
+import math
+from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
+
+def chunk_list(input_list, chunk_size):
+ return [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)]
+
+
+def load_image_from_base64(image):
+ return Image.open(BytesIO(base64.b64decode(image)))
+
+
+def expand2square(pil_img, background_color):
+ width, height = pil_img.size
+ if width == height:
+ return pil_img
+ elif width > height:
+ result = Image.new(pil_img.mode, (width, width), background_color)
+ result.paste(pil_img, (0, (width - height) // 2))
+ return result
+ else:
+ result = Image.new(pil_img.mode, (height, height), background_color)
+ result.paste(pil_img, ((height - width) // 2, 0))
+ return result
+
+
+def create_photo_grid(arr, rows=None, cols=None):
+ """
+ Create a photo grid from a 4D numpy array with shape [t, h, w, c].
+
+ Parameters:
+ arr (numpy.ndarray): Input array with shape [t, h, w, c].
+ rows (int): Optional. Number of rows in the grid. If not set, it will be determined based on `cols` or the square root of `t`.
+ cols (int): Optional. Number of columns in the grid. If not set, it will be determined based on `rows` or the square root of `t`.
+
+ Returns:
+ numpy.ndarray: A 3D numpy array representing the photo grid.
+ """
+
+ if isinstance(arr, list):
+ if isinstance(arr[0], Image.Image):
+ arr = np.stack([np.array(img) for img in arr])
+ elif isinstance(arr[0], np.ndarray):
+ arr = np.stack(arr)
+ else:
+ raise ValueError("Invalid input type. Expected list of Images or numpy arrays.")
+
+ t, h, w, c = arr.shape
+
+ # Calculate the number of rows and columns if not provided
+ if rows is None and cols is None:
+ rows = math.ceil(math.sqrt(t))
+ cols = math.ceil(t / rows)
+ elif rows is None:
+ rows = math.ceil(t / cols)
+ elif cols is None:
+ cols = math.ceil(t / rows)
+
+ # Check if the grid can hold all the images
+ if rows * cols < t:
+ raise ValueError(f"Not enough grid cells ({rows}x{cols}) to hold all images ({t}).")
+
+ # Create the grid array with appropriate height and width
+ grid_height = h * rows
+ grid_width = w * cols
+ grid = np.zeros((grid_height, grid_width, c), dtype=arr.dtype)
+
+ # Fill the grid with images
+ for i in range(t):
+ row_idx = i // cols
+ col_idx = i % cols
+ grid[row_idx*h:(row_idx+1)*h, col_idx*w:(col_idx+1)*w, :] = arr[i]
+
+ return grid
+
+
+def process_image(image_path, processor, aspect_ratio='pad'):
+ image = Image.open(image_path).convert('RGB')
+
+ images = [np.array(image)]
+
+ if aspect_ratio == 'pad':
+ images = [Image.fromarray(f) for f in images]
+ images = [expand2square(image, tuple(int(x*255) for x in processor.image_mean)) for image in images]
+ else:
+ images = [Image.fromarray(f) for f in images]
+
+ images = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ return images
+
+
+def frame_sample(duration, mode='uniform', num_frames=None, fps=None):
+ if mode == 'uniform':
+ assert num_frames is not None, "Number of frames must be provided for uniform sampling."
+ # NOTE: v1 version
+ # Calculate the size of each segment from which a frame will be extracted
+ seg_size = float(duration - 1) / num_frames
+
+ frame_ids = []
+ for i in range(num_frames):
+ # Calculate the start and end indices of each segment
+ start = seg_size * i
+ end = seg_size * (i + 1)
+ # Append the middle index of the segment to the list
+ frame_ids.append((start + end) / 2)
+
+ return np.round(np.array(frame_ids) + 1e-6).astype(int)
+ # NOTE: v0 version
+ # return np.linspace(0, duration-1, num_frames, dtype=int)
+ elif mode == 'fps':
+ assert fps is not None, "FPS must be provided for FPS sampling."
+ segment_len = min(fps // NUM_FRAMES_PER_SECOND, duration)
+ return np.arange(segment_len // 2, duration, segment_len, dtype=int)
+ else:
+ raise ImportError(f'Unsupported frame sampling mode: {mode}')
+
+
+def process_audio_file(wav_path):
+ # read wav
+ #print(wav_path)
+ wav, sr = sf.read(wav_path)
+ if len(wav.shape) == 2:
+ wav = wav[:, 0]
+ if len(wav) > 30 * sr:
+ max_start = len(wav) - 30 * sr
+ start = random.randint(0, max_start)
+ wav = wav[start: start + 30 * sr]
+ if len(wav) < 30 * sr:
+ pad_length = 30 * sr - len(wav)
+ wav = np.pad(wav, (0, pad_length), mode='constant', constant_values=0.0)
+ if sr != 16000:
+ wav = librosa.resample(wav, orig_sr=sr, target_sr=16000, res_type="fft")
+
+ # beats
+ raw_wav = torch.from_numpy(wav).to('cpu')
+ waveform = raw_wav.unsqueeze(0) * 2 ** 15
+ fbank = ta_kaldi.fbank(waveform, num_mel_bins=128, sample_frequency=16000, frame_length=25, frame_shift=10).to(torch.bfloat16)
+ return fbank.unsqueeze(0)
+
+def get_clip_timepoints(clip_sampler, duration):
+ # Read out all clips in this video
+ all_clips_timepoints = []
+ is_last_clip = False
+ end = 0.0
+ while not is_last_clip:
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
+ all_clips_timepoints.append((start, end))
+ return all_clips_timepoints
+
+def load_audio_from_video(file: str, sr: int = 16000):
+ """
+ Open an audio file and read as mono waveform, resampling as necessary
+
+ Parameters
+ ----------
+ file: str
+ The audio file to open
+
+ sr: int
+ The sample rate to resample the audio if necessary
+
+ Returns
+ -------
+ A NumPy array containing the audio waveform, in float32 dtype.
+ """
+
+ # This launches a subprocess to decode audio while down-mixing
+ # and resampling as necessary. Requires the ffmpeg CLI in PATH.
+
+ cmd = ["ffmpeg", "-nostdin", "-i", file, "-vn", # no video
+ "-acodec", "pcm_s16le", # output audio codec (pcm_s16le for .wav)
+ "-ac", "1", # audio channels (1 for mono)
+ "-ar", str(sr), # audio sample rate
+ "-f", "s16le", # output format (s16le for 16-bit PCM)
+ "-" # output to stdout
+ ]
+ # fmt: on
+ try:
+ out = run(cmd, capture_output=True, check=True).stdout
+ except CalledProcessError as e:
+ raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
+ return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0, sr
+
+
+def process_audio_from_video(audio_path, clip_duration, device="cpu", num_mel_bins=128, sample_rate=16000, clips_per_video=8, mean=-4.268, std=9.138):
+ clip_sampler = ConstantClipsPerVideoSampler(
+ clip_duration=2, clips_per_video=clips_per_video
+ )
+ try:
+ waveform, sr = load_audio_from_video(audio_path)
+ #print(audio_path)
+ except Exception as audio_error:
+ print(f"Failed to process audio from video due to error: {audio_error}")
+ waveform = torch.zeros(480000)
+ waveform = waveform.numpy()
+ sr = 16000
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, waveform.shape[0] / sample_rate)
+ all_clips = []
+ #print(waveform.shape[0] / sample_rate)
+ for clip_timepoints in all_clips_timepoints:
+ #print(float(clip_timepoints[0]))
+ #print(float(clip_timepoints[1]))
+ waveform_clip = waveform[
+ int(clip_timepoints[0] * sample_rate) : int(
+ clip_timepoints[1] * sample_rate)]
+ all_clips.append(waveform_clip)
+ all_clips_tensors = [torch.from_numpy(clip) for clip in all_clips]
+ wav = torch.cat(all_clips_tensors, dim=0)
+ if len(wav) > 30 * sr:
+ max_start = len(wav) - 30 * sr
+ start = torch.randint(0, max_start, (1,)).item()
+ wav = wav[start: start + 30 * sr]
+ if len(wav) < 30 * sr:
+ pad_length = 30 * sr - len(wav)
+ wav = torch.nn.functional.pad(wav, (0, pad_length), mode='constant', value=0.0)
+ waveform = wav.unsqueeze(0) * 2 ** 15
+ fbank = ta_kaldi.fbank(waveform, num_mel_bins=128, sample_frequency=16000, frame_length=25, frame_shift=10).to(torch.bfloat16)
+ return fbank.unsqueeze(0)
+
+
+def process_video(video_path, processor, s=None, e=None, aspect_ratio='pad', num_frames=NUM_FRAMES, va=False):
+ if isinstance(video_path, str):
+ if s is not None and e is not None:
+ s = s if s >= 0. else 0.
+ e = e if e >= 0. else 0.
+ if s > e:
+ s, e = e, s
+ elif s == e:
+ e = s + 1
+
+ # 1. Loading Video
+ if os.path.isdir(video_path):
+ frame_files = sorted(os.listdir(video_path))
+
+ fps = 3
+ num_frames_of_video = len(frame_files)
+ elif video_path.endswith('.gif'):
+ gif_reader = imageio.get_reader(video_path)
+
+ fps = 25
+ num_frames_of_video = len(gif_reader)
+ else:
+ vreader = VideoReader(video_path, ctx=cpu(0), num_threads=1)
+
+ fps = vreader.get_avg_fps()
+ num_frames_of_video = len(vreader)
+
+ # 2. Determine frame range & Calculate frame indices
+ f_start = 0 if s is None else max(int(s * fps) - 1, 0)
+ f_end = num_frames_of_video - 1 if e is None else min(int(e * fps) - 1, num_frames_of_video - 1)
+ frame_indices = list(range(f_start, f_end + 1))
+
+ duration = len(frame_indices)
+ # 3. Sampling frame indices
+ if num_frames is None:
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='fps', fps=fps)]
+ else:
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='uniform', num_frames=num_frames)]
+
+ # 4. Acquire frame data
+ if os.path.isdir(video_path):
+ video_data = [Image.open(os.path.join(video_path, frame_files[f_idx])) for f_idx in sampled_frame_indices]
+ elif video_path.endswith('.gif'):
+ video_data = [Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)) for idx, frame in enumerate(gif_reader) if idx in sampled_frame_indices]
+ else:
+ video_data = [Image.fromarray(frame) for frame in vreader.get_batch(sampled_frame_indices).asnumpy()]
+
+ elif isinstance(video_path, np.ndarray):
+ video_data = [Image.fromarray(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], np.ndarray):
+ video_data = [Image.fromarray(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], str):
+ video_data = [Image.open(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], Image.Image):
+ video_data = video_path
+ else:
+ raise ValueError(f"Unsupported video path type: {type(video_path)}")
+
+ while num_frames is not None and len(video_data) < num_frames:
+ video_data.append(Image.fromarray(np.zeros((*video_data[-1].size, 3), dtype=np.uint8)))
+
+ # MAX_FRAMES filter
+ video_data = video_data[:MAX_FRAMES]
+
+ if aspect_ratio == 'pad':
+ images = [expand2square(f, tuple(int(x*255) for x in processor.image_mean)) for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ else:
+ images = [f for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+
+ if va:
+ # Calculate the duration of the video in seconds
+ video_duration_seconds = num_frames_of_video / fps
+ audio = process_audio_from_video(video_path, video_duration_seconds)
+ video = {'video': video, 'audio': audio}
+
+ return video
+
+def process_video_old(video_path, processor, aspect_ratio='pad', num_frames=NUM_FRAMES, image_grid=False, sample_scheme='uniform'):
+ def frame_sample(duration, mode='uniform', local_fps=None):
+ if mode == 'uniform':
+ # Calculate the size of each segment from which a frame will be extracted
+ seg_size = float(duration - 1) / num_frames
+
+ frame_ids = []
+ for i in range(num_frames):
+ # Calculate the start and end indices of each segment
+ start = int(np.round(seg_size * i))
+ end = int(np.round(seg_size * (i + 1)))
+ # Append the middle index of the segment to the list
+ frame_ids.append((start + end) // 2)
+
+ return frame_ids
+ # NOTE: old version
+ # return np.linspace(0, duration-1, num_frames, dtype=int)
+ elif mode == 'fps':
+ assert local_fps is not None
+ segment_len = min(local_fps // NUM_FRAMES_PER_SECOND, duration)
+ return np.arange(segment_len // 2, duration, segment_len, dtype=int)
+ else:
+ raise ImportError(f'Unsupported frame sampling mode: {mode}')
+
+ if isinstance(video_path, str):
+ if video_path.endswith('.gif'):
+ video_gif = imageio.get_reader(video_path)
+ duration, local_fps = len(video_gif), 10
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ video_data = [frame for index, frame in enumerate(video_gif) if index in frame_id_list]
+ # added by lixin4ever, include the support of .webm files from sthsthv2
+ elif video_path.endswith('.webm'):
+ video_webm = VideoFileClip(video_path)
+ video_frames = np.array(list(video_webm.iter_frames()))
+
+ duration, local_fps = len(video_frames), video_webm.fps
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ video_data = video_frames[frame_id_list]
+ else:
+ # NOTE: num_threads=1 is required to avoid deadlock in multiprocessing
+ decord_vr = VideoReader(uri=video_path, ctx=cpu(0), num_threads=1)
+ duration, local_fps = len(decord_vr), float(decord_vr.get_avg_fps())
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ try:
+ video_data = decord_vr.get_batch(frame_id_list).numpy()
+ except:
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+
+ elif isinstance(video_path, np.ndarray):
+ assert len(video_path) == num_frames
+ video_data = video_path
+ elif isinstance(video_path, list):
+ assert len(video_path) == num_frames
+ video_data = np.stack([np.array(x) for x in video_path])
+
+ if image_grid:
+ grid_h = grid_w = math.ceil(math.sqrt(num_frames))
+ pg = create_photo_grid(video_data, grid_h, grid_w)
+ video_data = [pg, *video_data]
+
+ if aspect_ratio == 'pad':
+ images = [Image.fromarray(f.numpy() if isinstance(f, torch.Tensor) else f) for f in video_data]
+ images = [expand2square(image, tuple(int(x*255) for x in processor.image_mean)) for image in images]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ else:
+ images = [Image.fromarray(f.numpy() if isinstance(f, torch.Tensor) else f) for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+
+ return video
+
+
+def tokenizer_multimodal_token(prompt, tokenizer, multimodal_token=DEFAULT_IMAGE_TOKEN, return_tensors=None):
+ """Tokenize text and multimodal tag to input_ids.
+
+ Args:
+ prompt (str): Text prompt (w/ multimodal tag), e.g., '\nDescribe the video.'
+ tokenizer (transformers.PreTrainedTokenizer): Tokenizer object.
+ multimodal_token (int): Token index corresponding to the multimodal tag.
+ """
+ multimodal_token_index = MODAL_INDEX_MAP.get(multimodal_token, None)
+ if multimodal_token_index is None:
+ input_ids = tokenizer(prompt, add_special_tokens=False).input_ids
+ else:
+ prompt_chunks = [tokenizer(chunk, add_special_tokens=False).input_ids for idx, chunk in enumerate(prompt.split(multimodal_token))]
+
+ input_ids = []
+ for i in range(1, 2 * len(prompt_chunks)):
+ if i % 2 == 1:
+ input_ids.extend(prompt_chunks[i // 2])
+ else:
+ input_ids.append(multimodal_token_index)
+
+ if return_tensors is not None:
+ if return_tensors == 'pt':
+ return torch.tensor(input_ids, dtype=torch.long)
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
+ return input_ids
+
+
+def get_model_name_from_path(model_path):
+ model_path = model_path.strip("/")
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ return model_paths[-2] + "_" + model_paths[-1]
+ else:
+ return model_paths[-1]
+
+
+class KeywordsStoppingCriteria(StoppingCriteria):
+ def __init__(self, keywords, tokenizer, input_ids):
+ self.keywords = keywords
+ self.keyword_ids = []
+ self.max_keyword_len = 0
+ for keyword in keywords:
+ cur_keyword_ids = tokenizer(keyword).input_ids
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
+ cur_keyword_ids = cur_keyword_ids[1:]
+ if len(cur_keyword_ids) > self.max_keyword_len:
+ self.max_keyword_len = len(cur_keyword_ids)
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
+ self.tokenizer = tokenizer
+ self.start_len = input_ids.shape[1]
+
+ def call_for_batch(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
+ for keyword_id in self.keyword_ids:
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
+ return True
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
+ for keyword in self.keywords:
+ if keyword in outputs:
+ return True
+ return False
+
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
+ outputs = []
+ for i in range(output_ids.shape[0]):
+ outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores))
+ return all(outputs)
diff --git a/videollama2/model/__init__.py b/videollama2/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e5e0bbb8302a17695dc2ae258b34e8fad51f5d8
--- /dev/null
+++ b/videollama2/model/__init__.py
@@ -0,0 +1,208 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import os
+import warnings
+import shutil
+
+import torch
+from transformers import PretrainedConfig, AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
+
+from .projector import load_mm_projector
+from .videollama2_llama import Videollama2LlamaForCausalLM, Videollama2LlamaConfig
+from .videollama2_mistral import Videollama2MistralForCausalLM, Videollama2MistralConfig
+from .videollama2_mixtral import Videollama2MixtralForCausalLM, Videollama2MixtralConfig
+from .videollama2_qwen2 import Videollama2Qwen2ForCausalLM, Videollama2Qwen2Config
+from .videollama2_gemma2 import Videollama2Gemma2ForCausalLM, Videollama2Gemma2Config
+from .videollama2_phi3 import Videollama2Phi3ForCausalLM, Videollama2Phi3Config
+
+
+VLLMs = {
+ "videollama2": Videollama2MistralForCausalLM,
+ "videollama2_llama": Videollama2LlamaForCausalLM,
+ "videollama2_mistral": Videollama2MistralForCausalLM,
+ "videollama2_mixtral": Videollama2MixtralForCausalLM,
+ "videollama2_qwen2": Videollama2Qwen2ForCausalLM,
+ "videollama2_gemma2": Videollama2Gemma2ForCausalLM,
+ "videollama2_phi3": Videollama2Phi3ForCausalLM,
+}
+
+VLLMConfigs = {
+ "videollama2": Videollama2MistralConfig,
+ "videollama2_llama": Videollama2LlamaConfig,
+ "videollama2_mistral": Videollama2MistralConfig,
+ "videollama2_mixtral": Videollama2MixtralConfig,
+ "videollama2_qwen2": Videollama2Qwen2Config,
+ "videollama2_gemma2": Videollama2Gemma2Config,
+ "videollama2_phi3": Videollama2Phi3Config,
+}
+
+
+def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", use_flash_attn=False, **kwargs):
+ if 'token' in kwargs:
+ token = kwargs['token']
+ else:
+ token = None
+
+ kwargs = {"device_map": device_map, **kwargs}
+
+ if device != "cuda":
+ kwargs['device_map'] = {"": device}
+
+ if load_8bit:
+ kwargs['load_in_8bit'] = True
+ elif load_4bit:
+ # NOTE: High-version Transformers will report: """ValueError: You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing `quantization_config` argument at the same time."""
+ # kwargs['load_in_4bit'] = True
+ kwargs['quantization_config'] = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_compute_dtype=torch.float16,
+ bnb_4bit_use_double_quant=True,
+ bnb_4bit_quant_type='nf4'
+ )
+ else:
+ kwargs['torch_dtype'] = torch.float16
+
+ if use_flash_attn:
+ kwargs['attn_implementation'] = 'flash_attention_2'
+
+ config = AutoConfig.from_pretrained(model_path)
+
+ # judge model type
+ model_type = config.model_type
+
+ # judge pretrain/finetune
+ try:
+ is_pretraining = config.tune_mm_mlp_adapter
+ except:
+ is_pretraining = False
+
+ # NOTE: lora/qlora model loading
+ if 'lora' in model_name.lower() or 'qlora' in model_name.lower():
+ cfg_pretrained = PretrainedConfig.from_pretrained(model_path, token=token)
+ # NOTE: AutoConfig will modify `_name_or_path` property to `model_path` if `model_path` is not None.
+ # cfg_pretrained = AutoConfig.from_pretrained(model_path, token=token)
+ model_base = model_base if model_base is not None else cfg_pretrained._name_or_path
+
+ # NOTE: remove qlora training quantization config
+ if hasattr(lora_cfg_pretrained, 'quantization_config'):
+ del lora_cfg_pretrained.quantization_config
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False, token=token)
+ print('Loading VideoLLaMA from base model...')
+
+ if 'vicuna' in model_base.lower():
+ model = Videollama2LlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif 'mistral' in model_base.lower():
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
+ if model.lm_head.weight.shape[0] != token_num:
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
+
+ print('Loading additional VideoLLaMA weights...')
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
+ else:
+ # this is probably from HF Hub
+ from huggingface_hub import hf_hub_download
+ def load_from_hf(repo_id, filename, subfolder=None):
+ cache_file = hf_hub_download(
+ repo_id=repo_id,
+ filename=filename,
+ subfolder=subfolder)
+ return torch.load(cache_file, map_location='cpu')
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
+ model.load_state_dict(non_lora_trainables, strict=False)
+
+ from peft import PeftModel
+ print('Loading LoRA weights...')
+ model = PeftModel.from_pretrained(model, model_path)
+ print('Merging LoRA weights...')
+ model = model.merge_and_unload()
+ print('Model is loaded...')
+ elif model_base is not None or '-base' in model_name.lower() or is_pretraining:
+ # NOTE: Base/Pretrain model loading
+ print('Loading VideoLLaMA 2 from base model...')
+ cfg_pretrained = PretrainedConfig.from_pretrained(model_path, token=token)
+ # NOTE: AutoConfig will modify `_name_or_path` property to `model_path` if `model_path` is not None.
+ # cfg_pretrained = AutoConfig.from_pretrained(model_path, token=token)
+ model_base = model_base if model_base is not None else cfg_pretrained._name_or_path
+
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False, token=token)
+
+ if model_type in ['videollama2', 'videollama2_mistral']:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_mixtral']:
+ model = Videollama2MixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_qwen2']:
+ model = Videollama2Qwen2ForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_gemma2']:
+ model = Videollama2Gemma2ForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_phi3']:
+ model = Videollama2Phi3ForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+
+ # NOTE; loading vision-language projector
+ # * old codes for loading local mm_projector.bin
+ # mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
+ # mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
+ # model.load_state_dict(mm_projector_weights, strict=False)
+ # * new codes which supports loading mm_projector.bin both offline and online
+ mm_projector_weights = load_mm_projector(model_path, token=token)
+ model.load_state_dict(mm_projector_weights, strict=False)
+ elif 'videollama2' in model_type:
+ # NOTE: SFT model loading
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, token=token)
+
+ if model_type in ['videollama2', 'videollama2_mistral']:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_mixtral']:
+ model = Videollama2MixtralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_qwen2']:
+ model = Videollama2Qwen2ForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_gemma2']:
+ model = Videollama2Gemma2ForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_phi3']:
+ model = Videollama2Phi3ForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, token=token)
+ model = AutoModelForCausalLM.from_pretrained(model_path, config=config, **kwargs)
+
+ processor = None
+
+ if "videollama" in model_type:
+ vision_tower = model.get_vision_tower()
+ if not vision_tower.is_loaded:
+ vision_tower.load_model()
+ vision_tower.to(device=device, dtype=torch.float16)
+ # NOTE: videollama2 adopts the same processor for processing image and video.
+ processor = vision_tower.image_processor
+
+ if hasattr(model.config, "max_sequence_length"):
+ context_len = model.config.max_sequence_length
+ else:
+ context_len = 2048
+
+ return tokenizer, model, processor, context_len
diff --git a/videollama2/model/beats/BEATs.py b/videollama2/model/beats/BEATs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c77c6aa953c04000bdd4df70d7deba0ea3588065
--- /dev/null
+++ b/videollama2/model/beats/BEATs.py
@@ -0,0 +1,185 @@
+# --------------------------------------------------------
+# BEATs: Audio Pre-Training with Acoustic Tokenizers (https://arxiv.org/abs/2212.09058)
+# Github source: https://github.com/microsoft/unilm/tree/master/beats
+# Copyright (c) 2022 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Based on fairseq code bases
+# https://github.com/pytorch/fairseq
+# --------------------------------------------------------
+
+
+import torch
+import torch.nn as nn
+from torch.nn import LayerNorm
+import torchaudio.compliance.kaldi as ta_kaldi
+
+from .backbone import (
+ TransformerEncoder,
+)
+
+import logging
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+class BEATsConfig:
+ def __init__(self, cfg=None):
+ self.input_patch_size: int = 16 # path size of patch embedding
+ self.embed_dim: int = 512 # patch embedding dimension
+ self.conv_bias: bool = False # include bias in conv encoder
+
+ self.encoder_layers: int = 12 # num encoder layers in the transformer
+ self.hidden_size: int = 4096 # 3584 for Qwen2
+ self.encoder_embed_dim: int = 768 # encoder embedding dimension
+ self.encoder_ffn_embed_dim: int = 3072 # encoder embedding dimension for FFN
+ self.encoder_attention_heads: int = 12 # num encoder attention heads
+ self.activation_fn: str = "gelu" # activation function to use
+
+ self.layer_wise_gradient_decay_ratio: float = 0.6 # ratio for layer-wise gradient decay
+ self.layer_norm_first: bool = False # apply layernorm first in the transformer
+ self.deep_norm: bool = True # apply deep_norm first in the transformer
+
+ # dropouts
+ self.dropout: float = 0.0 # dropout probability for the transformer
+ self.attention_dropout: float = 0.0 # dropout probability for attention weights
+ self.activation_dropout: float = 0.0 # dropout probability after activation in FFN
+ self.encoder_layerdrop: float = 0.05 # probability of dropping a tarnsformer layer
+ self.dropout_input: float = 0.0 # dropout to apply to the input (after feat extr)
+
+ # positional embeddings
+ self.conv_pos: int = 128 # number of filters for convolutional positional embeddings
+ self.conv_pos_groups: int = 16 # number of groups for convolutional positional embedding
+
+ # relative position embedding
+ self.relative_position_embedding: bool = True # apply relative position embedding
+ self.num_buckets: int = 320 # number of buckets for relative position embedding
+ self.max_distance: int = 800 # maximum distance for relative position embedding
+ self.gru_rel_pos: bool = True # apply gated relative position embedding
+
+ # label predictor
+ self.finetuned_model: bool = True # whether the model is a fine-tuned model.
+ self.predictor_dropout: float = 0.0 # dropout probability for the predictor
+ self.predictor_class: int = 527 # target class number for the predictor
+
+ if cfg is not None:
+ self.update(cfg)
+
+ def update(self, cfg: dict):
+ self.__dict__.update(cfg)
+
+
+class BEATs(nn.Module):
+ def __init__(
+ self,
+ cfg: BEATsConfig,
+ ) -> None:
+ super().__init__()
+ logger.info(f"BEATs Config: {cfg.__dict__}")
+
+ self.cfg = cfg
+
+ self.embed = cfg.embed_dim
+ self.post_extract_proj = (
+ nn.Linear(self.embed, cfg.encoder_embed_dim)
+ if self.embed != cfg.encoder_embed_dim
+ else None
+ )
+
+ self.input_patch_size = cfg.input_patch_size
+ self.patch_embedding = nn.Conv2d(1, self.embed, kernel_size=self.input_patch_size, stride=self.input_patch_size,
+ bias=cfg.conv_bias)
+
+ self.dropout_input = nn.Dropout(cfg.dropout_input)
+
+ assert not cfg.deep_norm or not cfg.layer_norm_first
+ self.encoder = TransformerEncoder(cfg)
+ self.layer_norm = LayerNorm(self.embed)
+
+ if cfg.finetuned_model:
+ self.predictor_dropout = nn.Dropout(cfg.predictor_dropout)
+ self.predictor = nn.Linear(cfg.encoder_embed_dim, cfg.predictor_class)
+ else:
+ self.predictor = None
+
+ def forward_padding_mask(
+ self,
+ features: torch.Tensor,
+ padding_mask: torch.Tensor,
+ ) -> torch.Tensor:
+ extra = padding_mask.size(1) % features.size(1)
+ if extra > 0:
+ padding_mask = padding_mask[:, :-extra]
+ padding_mask = padding_mask.view(
+ padding_mask.size(0), features.size(1), -1
+ )
+ padding_mask = padding_mask.all(-1)
+ return padding_mask
+
+ def preprocess(
+ self,
+ source: torch.Tensor,
+ fbank_mean: float = 15.41663,
+ fbank_std: float = 6.55582,
+ ) -> torch.Tensor:
+ '''
+ fbanks = []
+ for waveform in source:
+ waveform = waveform.unsqueeze(0) * 2 ** 15
+ fbank = ta_kaldi.fbank(waveform, num_mel_bins=128, sample_frequency=16000, frame_length=25, frame_shift=10)
+ fbanks.append(fbank)
+ fbank = torch.stack(fbanks, dim=0)
+ '''
+ fbank = source
+ fbank = (fbank - fbank_mean) / (2 * fbank_std)
+ return fbank
+
+ def extract_features(
+ self,
+ source: torch.Tensor,
+ padding_mask: Optional[torch.Tensor] = None,
+ fbank_mean: float = 15.41663,
+ fbank_std: float = 6.55582,
+ feature_only=True,
+ ):
+ fbank = self.preprocess(source, fbank_mean=fbank_mean, fbank_std=fbank_std)
+
+ if padding_mask is not None:
+ padding_mask = self.forward_padding_mask(fbank, padding_mask)
+
+ fbank = fbank.unsqueeze(1)
+ features = self.patch_embedding(fbank)
+ T = features.shape[2]
+ F = features.shape[3]
+ features = features.reshape(features.shape[0], features.shape[1], -1)
+ features = features.transpose(1, 2)
+ features = self.layer_norm(features)
+
+ if padding_mask is not None:
+ padding_mask = self.forward_padding_mask(features, padding_mask)
+
+ if self.post_extract_proj is not None:
+ features = self.post_extract_proj(features)
+
+ x = self.dropout_input(features)
+
+ x, layer_results = self.encoder(
+ x,
+ padding_mask=padding_mask,
+ )
+ if not feature_only and self.predictor is not None:
+ x = self.predictor_dropout(x)
+ logits = self.predictor(x)
+
+ if padding_mask is not None and padding_mask.any():
+ logits[padding_mask] = 0
+ logits = logits.sum(dim=1)
+ logits = logits / (~padding_mask).sum(dim=1).unsqueeze(-1).expand_as(logits)
+ else:
+ logits = logits.mean(dim=1)
+
+ lprobs = torch.sigmoid(logits)
+
+ return lprobs, padding_mask
+ else:
+ return x, T, F
\ No newline at end of file
diff --git a/videollama2/model/beats/LICENSE_beats b/videollama2/model/beats/LICENSE_beats
new file mode 100644
index 0000000000000000000000000000000000000000..5ae193c94d0ca44b222ff24d76eaf41709ce2b4f
--- /dev/null
+++ b/videollama2/model/beats/LICENSE_beats
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/videollama2/model/beats/Tokenizers.py b/videollama2/model/beats/Tokenizers.py
new file mode 100644
index 0000000000000000000000000000000000000000..da53a7bb3eb8d028789e3ff50a7ace798030b908
--- /dev/null
+++ b/videollama2/model/beats/Tokenizers.py
@@ -0,0 +1,172 @@
+# --------------------------------------------------------
+# BEATs: Audio Pre-Training with Acoustic Tokenizers (https://arxiv.org/abs/2212.09058)
+# Github source: https://github.com/microsoft/unilm/tree/master/beats
+# Copyright (c) 2022 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Based on fairseq code bases
+# https://github.com/pytorch/fairseq
+# --------------------------------------------------------
+
+
+import torch
+import torch.nn as nn
+from torch.nn import LayerNorm
+import torchaudio.compliance.kaldi as ta_kaldi
+
+from beats.backbone import (
+ TransformerEncoder,
+)
+from beats.quantizer import (
+ NormEMAVectorQuantizer,
+)
+
+import logging
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+class TokenizersConfig:
+ def __init__(self, cfg=None):
+ self.input_patch_size: int = -1 # path size of patch embedding
+ self.embed_dim: int = 512 # patch embedding dimension
+ self.conv_bias: bool = False # include bias in conv encoder
+
+ self.encoder_layers: int = 12 # num encoder layers in the transformer
+ self.encoder_embed_dim: int = 768 # encoder embedding dimension
+ self.encoder_ffn_embed_dim: int = 3072 # encoder embedding dimension for FFN
+ self.encoder_attention_heads: int = 12 # num encoder attention heads
+ self.activation_fn: str = "gelu" # activation function to use
+
+ self.layer_norm_first: bool = False # apply layernorm first in the transformer
+ self.deep_norm: bool = False # apply deep_norm first in the transformer
+
+ # dropouts
+ self.dropout: float = 0.1 # dropout probability for the transformer
+ self.attention_dropout: float = 0.1 # dropout probability for attention weights
+ self.activation_dropout: float = 0.0 # dropout probability after activation in FFN
+ self.encoder_layerdrop: float = 0.0 # probability of dropping a tarnsformer layer
+ self.dropout_input: float = 0.0 # dropout to apply to the input (after feat extr)
+
+ # positional embeddings
+ self.conv_pos: int = 128 # number of filters for convolutional positional embeddings
+ self.conv_pos_groups: int = 16 # number of groups for convolutional positional embedding
+
+ # relative position embedding
+ self.relative_position_embedding: bool = False # apply relative position embedding
+ self.num_buckets: int = 320 # number of buckets for relative position embedding
+ self.max_distance: int = 1280 # maximum distance for relative position embedding
+ self.gru_rel_pos: bool = False # apply gated relative position embedding
+
+ # quantizer
+ self.quant_n: int = 1024 # codebook number in quantizer
+ self.quant_dim: int = 256 # codebook dimension in quantizer
+
+ if cfg is not None:
+ self.update(cfg)
+
+ def update(self, cfg: dict):
+ self.__dict__.update(cfg)
+
+
+class Tokenizers(nn.Module):
+ def __init__(
+ self,
+ cfg: TokenizersConfig,
+ ) -> None:
+ super().__init__()
+ logger.info(f"Tokenizers Config: {cfg.__dict__}")
+
+ self.cfg = cfg
+
+ self.embed = cfg.embed_dim
+ self.post_extract_proj = (
+ nn.Linear(self.embed, cfg.encoder_embed_dim)
+ if self.embed != cfg.encoder_embed_dim
+ else None
+ )
+
+ self.input_patch_size = cfg.input_patch_size
+ self.patch_embedding = nn.Conv2d(1, self.embed, kernel_size=self.input_patch_size, stride=self.input_patch_size,
+ bias=cfg.conv_bias)
+
+ self.dropout_input = nn.Dropout(cfg.dropout_input)
+
+ assert not cfg.deep_norm or not cfg.layer_norm_first
+ self.encoder = TransformerEncoder(cfg)
+ self.layer_norm = LayerNorm(self.embed)
+
+ self.quantize = NormEMAVectorQuantizer(
+ n_embed=cfg.quant_n, embedding_dim=cfg.quant_dim, beta=1.0, kmeans_init=True, decay=0.99,
+ )
+ self.quant_n = cfg.quant_n
+ self.quantize_layer = nn.Sequential(
+ nn.Linear(cfg.encoder_embed_dim, cfg.encoder_embed_dim),
+ nn.Tanh(),
+ nn.Linear(cfg.encoder_embed_dim, cfg.quant_dim) # for quantize
+ )
+
+ def forward_padding_mask(
+ self,
+ features: torch.Tensor,
+ padding_mask: torch.Tensor,
+ ) -> torch.Tensor:
+ extra = padding_mask.size(1) % features.size(1)
+ if extra > 0:
+ padding_mask = padding_mask[:, :-extra]
+ padding_mask = padding_mask.view(
+ padding_mask.size(0), features.size(1), -1
+ )
+ padding_mask = padding_mask.all(-1)
+ return padding_mask
+
+ def preprocess(
+ self,
+ source: torch.Tensor,
+ fbank_mean: float = 15.41663,
+ fbank_std: float = 6.55582,
+ ) -> torch.Tensor:
+ fbanks = []
+ for waveform in source:
+ waveform = waveform.unsqueeze(0) * 2 ** 15
+ fbank = ta_kaldi.fbank(waveform, num_mel_bins=128, sample_frequency=16000, frame_length=25, frame_shift=10)
+ fbanks.append(fbank)
+ fbank = torch.stack(fbanks, dim=0)
+ fbank = (fbank - fbank_mean) / (2 * fbank_std)
+ return fbank
+
+ def extract_labels(
+ self,
+ source: torch.Tensor,
+ padding_mask: Optional[torch.Tensor] = None,
+ fbank_mean: float = 15.41663,
+ fbank_std: float = 6.55582,
+ ):
+ fbank = self.preprocess(source, fbank_mean=fbank_mean, fbank_std=fbank_std)
+
+ if padding_mask is not None:
+ padding_mask = self.forward_padding_mask(fbank, padding_mask)
+
+ fbank = fbank.unsqueeze(1)
+ features = self.patch_embedding(fbank)
+ features = features.reshape(features.shape[0], features.shape[1], -1)
+ features = features.transpose(1, 2)
+ features = self.layer_norm(features)
+
+ if padding_mask is not None:
+ padding_mask = self.forward_padding_mask(features, padding_mask)
+
+ if self.post_extract_proj is not None:
+ features = self.post_extract_proj(features)
+
+ x = self.dropout_input(features)
+
+ x, layer_results = self.encoder(
+ x,
+ padding_mask=padding_mask,
+ )
+
+ quantize_input = self.quantize_layer(x)
+ quantize_feature, embed_loss, embed_ind = self.quantize(quantize_input)
+
+ return embed_ind
diff --git a/videollama2/model/beats/__init__.py b/videollama2/model/beats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/videollama2/model/beats/backbone.py b/videollama2/model/beats/backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..6530ea4fc5d043a96e02319a79e1ba1af9dbff33
--- /dev/null
+++ b/videollama2/model/beats/backbone.py
@@ -0,0 +1,783 @@
+# --------------------------------------------------------
+# BEATs: Audio Pre-Training with Acoustic Tokenizers (https://arxiv.org/abs/2212.09058)
+# Github source: https://github.com/microsoft/unilm/tree/master/beats
+# Copyright (c) 2022 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Based on fairseq code bases
+# https://github.com/pytorch/fairseq
+# --------------------------------------------------------
+
+import math
+import numpy as np
+from typing import Dict, Optional, Tuple
+import torch
+from torch import Tensor, nn
+import torch.nn.functional as F
+from torch.nn import LayerNorm, Parameter
+from .modules import (
+ GradMultiply,
+ SamePad,
+ get_activation_fn,
+ GLU_Linear,
+ quant_noise,
+)
+from .weight_norm_fix import weight_norm
+
+class TransformerEncoder(nn.Module):
+ def __init__(self, args):
+ super().__init__()
+
+ self.dropout = args.dropout
+ self.embedding_dim = args.encoder_embed_dim
+
+ self.pos_conv = nn.Conv1d(
+ self.embedding_dim,
+ self.embedding_dim,
+ kernel_size=args.conv_pos,
+ padding=args.conv_pos // 2,
+ groups=args.conv_pos_groups,
+ )
+ dropout = 0
+ std = math.sqrt((4 * (1.0 - dropout)) / (args.conv_pos * self.embedding_dim))
+ nn.init.normal_(self.pos_conv.weight, mean=0, std=std)
+ nn.init.constant_(self.pos_conv.bias, 0)
+
+ self.pos_conv = weight_norm(self.pos_conv, name="weight", dim=2)
+ self.pos_conv = nn.Sequential(self.pos_conv, SamePad(args.conv_pos), nn.GELU())
+
+ if hasattr(args, "relative_position_embedding"):
+ self.relative_position_embedding = args.relative_position_embedding
+ self.num_buckets = args.num_buckets
+ self.max_distance = args.max_distance
+ else:
+ self.relative_position_embedding = False
+ self.num_buckets = 0
+ self.max_distance = 0
+
+ self.layers = nn.ModuleList(
+ [
+ TransformerSentenceEncoderLayer(
+ embedding_dim=self.embedding_dim,
+ ffn_embedding_dim=args.encoder_ffn_embed_dim,
+ num_attention_heads=args.encoder_attention_heads,
+ dropout=self.dropout,
+ attention_dropout=args.attention_dropout,
+ activation_dropout=args.activation_dropout,
+ activation_fn=args.activation_fn,
+ layer_norm_first=args.layer_norm_first,
+ deep_norm=args.deep_norm,
+ has_relative_attention_bias=self.relative_position_embedding,
+ num_buckets=self.num_buckets,
+ max_distance=self.max_distance,
+ gru_rel_pos=args.gru_rel_pos,
+ encoder_layers=args.encoder_layers,
+ )
+ for i in range(args.encoder_layers)
+ ]
+ )
+ if self.relative_position_embedding:
+ for i in range(1, args.encoder_layers):
+ del self.layers[i].self_attn.relative_attention_bias
+ self.layers[i].self_attn.relative_attention_bias = self.layers[0].self_attn.relative_attention_bias
+
+ self.layer_norm_first = args.layer_norm_first
+ self.layer_norm = LayerNorm(self.embedding_dim)
+ self.layerdrop = args.encoder_layerdrop
+
+ #self.apply(init_bert_params)
+
+ if args.deep_norm:
+ deep_norm_beta = math.pow(8 * args.encoder_layers, -1 / 4)
+ for i in range(args.encoder_layers):
+ nn.init.xavier_normal_(self.layers[i].self_attn.k_proj.weight, gain=1)
+ nn.init.xavier_normal_(self.layers[i].self_attn.v_proj.weight, gain=deep_norm_beta)
+ nn.init.xavier_normal_(self.layers[i].self_attn.q_proj.weight, gain=1)
+ nn.init.xavier_normal_(self.layers[i].self_attn.out_proj.weight, gain=deep_norm_beta)
+ nn.init.xavier_normal_(self.layers[i].fc1.weight, gain=deep_norm_beta)
+ nn.init.xavier_normal_(self.layers[i].fc2.weight, gain=deep_norm_beta)
+
+ self.layer_wise_gradient_decay_ratio = getattr(args, "layer_wise_gradient_decay_ratio", 1)
+
+ def forward(self, x, padding_mask=None, layer=None):
+ x, layer_results = self.extract_features(x, padding_mask, layer)
+
+ if self.layer_norm_first and layer is None:
+ x = self.layer_norm(x)
+
+ return x, layer_results
+
+ def extract_features(self, x, padding_mask=None, tgt_layer=None):
+
+ if padding_mask is not None:
+ x[padding_mask] = 0
+
+ x_conv = self.pos_conv(x.transpose(1, 2))
+ x_conv = x_conv.transpose(1, 2)
+ x = x + x_conv
+
+ if not self.layer_norm_first:
+ x = self.layer_norm(x)
+
+ x = F.dropout(x, p=self.dropout, training=self.training)
+
+ # B x T x C -> T x B x C
+ x = x.transpose(0, 1)
+
+ layer_results = []
+ z = None
+ if tgt_layer is not None:
+ layer_results.append((x, z))
+ r = None
+ pos_bias = None
+ for i, layer in enumerate(self.layers):
+ if self.layer_wise_gradient_decay_ratio != 1.0:
+ x = GradMultiply.apply(x, self.layer_wise_gradient_decay_ratio)
+ dropout_probability = np.random.random()
+ if not self.training or (dropout_probability > self.layerdrop):
+ x, z, pos_bias = layer(x, self_attn_padding_mask=padding_mask, need_weights=False, pos_bias=pos_bias)
+ if tgt_layer is not None:
+ layer_results.append((x, z))
+ if i == tgt_layer:
+ r = x
+ break
+
+ if r is not None:
+ x = r
+
+ # T x B x C -> B x T x C
+ x = x.transpose(0, 1)
+
+ return x, layer_results
+
+
+class TransformerSentenceEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: float = 768,
+ ffn_embedding_dim: float = 3072,
+ num_attention_heads: float = 8,
+ dropout: float = 0.1,
+ attention_dropout: float = 0.1,
+ activation_dropout: float = 0.1,
+ activation_fn: str = "relu",
+ layer_norm_first: bool = False,
+ deep_norm: bool = False,
+ has_relative_attention_bias: bool = False,
+ num_buckets: int = 0,
+ max_distance: int = 0,
+ rescale_init: bool = False,
+ gru_rel_pos: bool = False,
+ encoder_layers: int = 0,
+ ) -> None:
+
+ super().__init__()
+ self.embedding_dim = embedding_dim
+ self.dropout = dropout
+ self.activation_dropout = activation_dropout
+
+ self.activation_name = activation_fn
+ self.activation_fn = get_activation_fn(activation_fn)
+ self.self_attn = MultiheadAttention(
+ self.embedding_dim,
+ num_attention_heads,
+ dropout=attention_dropout,
+ self_attention=True,
+ has_relative_attention_bias=has_relative_attention_bias,
+ num_buckets=num_buckets,
+ max_distance=max_distance,
+ rescale_init=rescale_init,
+ gru_rel_pos=gru_rel_pos,
+ )
+
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(self.activation_dropout)
+ self.dropout3 = nn.Dropout(dropout)
+
+ self.layer_norm_first = layer_norm_first
+
+ self.self_attn_layer_norm = LayerNorm(self.embedding_dim)
+
+ if self.activation_name == "glu":
+ self.fc1 = GLU_Linear(self.embedding_dim, ffn_embedding_dim, "swish")
+ else:
+ self.fc1 = nn.Linear(self.embedding_dim, ffn_embedding_dim)
+ self.fc2 = nn.Linear(ffn_embedding_dim, self.embedding_dim)
+
+ self.final_layer_norm = LayerNorm(self.embedding_dim)
+
+ self.deep_norm = deep_norm
+ if self.deep_norm:
+ self.deep_norm_alpha = math.pow(2 * encoder_layers, 1 / 4)
+ else:
+ self.deep_norm_alpha = 1
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ self_attn_mask: torch.Tensor = None,
+ self_attn_padding_mask: torch.Tensor = None,
+ need_weights: bool = False,
+ pos_bias=None
+ ):
+ residual = x
+
+ if self.layer_norm_first:
+ x = self.self_attn_layer_norm(x)
+ x, attn, pos_bias = self.self_attn(
+ query=x,
+ key=x,
+ value=x,
+ key_padding_mask=self_attn_padding_mask,
+ need_weights=False,
+ attn_mask=self_attn_mask,
+ position_bias=pos_bias
+ )
+ x = self.dropout1(x)
+ x = residual + x
+
+ residual = x
+ x = self.final_layer_norm(x)
+ if self.activation_name == "glu":
+ x = self.fc1(x)
+ else:
+ x = self.activation_fn(self.fc1(x))
+ x = self.dropout2(x)
+ x = self.fc2(x)
+ x = self.dropout3(x)
+ x = residual + x
+ else:
+ x, attn, pos_bias = self.self_attn(
+ query=x,
+ key=x,
+ value=x,
+ key_padding_mask=self_attn_padding_mask,
+ need_weights=need_weights,
+ attn_mask=self_attn_mask,
+ position_bias=pos_bias
+ )
+
+ x = self.dropout1(x)
+ x = residual * self.deep_norm_alpha + x
+
+ x = self.self_attn_layer_norm(x)
+
+ residual = x
+ if self.activation_name == "glu":
+ x = self.fc1(x)
+ else:
+ x = self.activation_fn(self.fc1(x))
+ x = self.dropout2(x)
+ x = self.fc2(x)
+ x = self.dropout3(x)
+ x = residual * self.deep_norm_alpha + x
+ x = self.final_layer_norm(x)
+
+ return x, attn, pos_bias
+
+
+class MultiheadAttention(nn.Module):
+ """Multi-headed attention.
+
+ See "Attention Is All You Need" for more details.
+ """
+
+ def __init__(
+ self,
+ embed_dim,
+ num_heads,
+ kdim=None,
+ vdim=None,
+ dropout=0.0,
+ bias=True,
+ add_bias_kv=False,
+ add_zero_attn=False,
+ self_attention=False,
+ encoder_decoder_attention=False,
+ q_noise=0.0,
+ qn_block_size=8,
+ has_relative_attention_bias=False,
+ num_buckets=32,
+ max_distance=128,
+ gru_rel_pos=False,
+ rescale_init=False,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.kdim = kdim if kdim is not None else embed_dim
+ self.vdim = vdim if vdim is not None else embed_dim
+ self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
+
+ self.num_heads = num_heads
+ self.dropout_module = nn.Dropout(dropout)
+
+ self.has_relative_attention_bias = has_relative_attention_bias
+ self.num_buckets = num_buckets
+ self.max_distance = max_distance
+ if self.has_relative_attention_bias:
+ self.relative_attention_bias = nn.Embedding(num_buckets, num_heads)
+
+ self.head_dim = embed_dim // num_heads
+ self.q_head_dim = self.head_dim
+ self.k_head_dim = self.head_dim
+ assert (
+ self.head_dim * num_heads == self.embed_dim
+ ), "embed_dim must be divisible by num_heads"
+ self.scaling = self.head_dim ** -0.5
+
+ self.self_attention = self_attention
+ self.encoder_decoder_attention = encoder_decoder_attention
+
+ assert not self.self_attention or self.qkv_same_dim, (
+ "Self-attention requires query, key and " "value to be of the same size"
+ )
+
+ k_bias = True
+ if rescale_init:
+ k_bias = False
+
+ k_embed_dim = embed_dim
+ q_embed_dim = embed_dim
+
+ self.k_proj = quant_noise(
+ nn.Linear(self.kdim, k_embed_dim, bias=k_bias), q_noise, qn_block_size
+ )
+ self.v_proj = quant_noise(
+ nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size
+ )
+ self.q_proj = quant_noise(
+ nn.Linear(embed_dim, q_embed_dim, bias=bias), q_noise, qn_block_size
+ )
+
+ self.out_proj = quant_noise(
+ nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size
+ )
+
+ if add_bias_kv:
+ self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
+ self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
+ else:
+ self.bias_k = self.bias_v = None
+
+ self.add_zero_attn = add_zero_attn
+
+ self.gru_rel_pos = gru_rel_pos
+ if self.gru_rel_pos:
+ self.grep_linear = nn.Linear(self.q_head_dim, 8)
+ self.grep_a = nn.Parameter(torch.ones(1, num_heads, 1, 1))
+
+ self.reset_parameters()
+
+ def reset_parameters(self):
+ if self.qkv_same_dim:
+ # Empirically observed the convergence to be much better with
+ # the scaled initialization
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
+ else:
+ nn.init.xavier_uniform_(self.k_proj.weight)
+ nn.init.xavier_uniform_(self.v_proj.weight)
+ nn.init.xavier_uniform_(self.q_proj.weight)
+
+ nn.init.xavier_uniform_(self.out_proj.weight)
+ if self.out_proj.bias is not None:
+ nn.init.constant_(self.out_proj.bias, 0.0)
+ if self.bias_k is not None:
+ nn.init.xavier_normal_(self.bias_k)
+ if self.bias_v is not None:
+ nn.init.xavier_normal_(self.bias_v)
+ if self.has_relative_attention_bias:
+ nn.init.xavier_normal_(self.relative_attention_bias.weight)
+
+ def _relative_positions_bucket(self, relative_positions, bidirectional=True):
+ num_buckets = self.num_buckets
+ max_distance = self.max_distance
+ relative_buckets = 0
+
+ if bidirectional:
+ num_buckets = num_buckets // 2
+ relative_buckets += (relative_positions > 0).to(torch.long) * num_buckets
+ relative_positions = torch.abs(relative_positions)
+ else:
+ relative_positions = -torch.min(relative_positions, torch.zeros_like(relative_positions))
+
+ max_exact = num_buckets // 2
+ is_small = relative_positions < max_exact
+
+ relative_postion_if_large = max_exact + (
+ torch.log(relative_positions.float() / max_exact)
+ / math.log(max_distance / max_exact)
+ * (num_buckets - max_exact)
+ ).to(torch.long)
+ relative_postion_if_large = torch.min(
+ relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)
+ )
+
+ relative_buckets += torch.where(is_small, relative_positions, relative_postion_if_large)
+ return relative_buckets
+
+ def compute_bias(self, query_length, key_length):
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
+ relative_position = memory_position - context_position
+ relative_position_bucket = self._relative_positions_bucket(
+ relative_position,
+ bidirectional=True
+ )
+ relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device)
+ values = self.relative_attention_bias(relative_position_bucket)
+ values = values.permute([2, 0, 1])
+ return values
+
+ def forward(
+ self,
+ query,
+ key: Optional[Tensor],
+ value: Optional[Tensor],
+ key_padding_mask: Optional[Tensor] = None,
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
+ need_weights: bool = True,
+ static_kv: bool = False,
+ attn_mask: Optional[Tensor] = None,
+ before_softmax: bool = False,
+ need_head_weights: bool = False,
+ position_bias: Optional[Tensor] = None
+ ) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
+ """Input shape: Time x Batch x Channel
+
+ Args:
+ key_padding_mask (ByteTensor, optional): mask to exclude
+ keys that are pads, of shape `(batch, src_len)`, where
+ padding elements are indicated by 1s.
+ need_weights (bool, optional): return the attention weights,
+ averaged over heads (default: False).
+ attn_mask (ByteTensor, optional): typically used to
+ implement causal attention, where the mask prevents the
+ attention from looking forward in time (default: None).
+ before_softmax (bool, optional): return the raw attention
+ weights and values before the attention softmax.
+ need_head_weights (bool, optional): return the attention
+ weights for each head. Implies *need_weights*. Default:
+ return the average attention weights over all heads.
+ """
+ if need_head_weights:
+ need_weights = True
+
+ is_tpu = query.device.type == "xla"
+
+ tgt_len, bsz, embed_dim = query.size()
+ src_len = tgt_len
+ assert embed_dim == self.embed_dim
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
+ if key is not None:
+ src_len, key_bsz, _ = key.size()
+ if not torch.jit.is_scripting():
+ assert key_bsz == bsz
+ assert value is not None
+ assert src_len, bsz == value.shape[:2]
+
+ if self.has_relative_attention_bias and position_bias is None:
+ position_bias = self.compute_bias(tgt_len, src_len)
+ position_bias = position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, src_len)
+
+ if incremental_state is not None:
+ saved_state = self._get_input_buffer(incremental_state)
+ if saved_state is not None and "prev_key" in saved_state:
+ # previous time steps are cached - no need to recompute
+ # key and value if they are static
+ if static_kv:
+ assert self.encoder_decoder_attention and not self.self_attention
+ key = value = None
+ else:
+ saved_state = None
+
+ if self.self_attention:
+ q = self.q_proj(query)
+ k = self.k_proj(query)
+ v = self.v_proj(query)
+ elif self.encoder_decoder_attention:
+ # encoder-decoder attention
+ q = self.q_proj(query)
+ if key is None:
+ assert value is None
+ k = v = None
+ else:
+ k = self.k_proj(key)
+ v = self.v_proj(key)
+
+ else:
+ assert key is not None and value is not None
+ q = self.q_proj(query)
+ k = self.k_proj(key)
+ v = self.v_proj(value)
+ q *= self.scaling
+ alpha = 32
+ q *= 1 / alpha
+
+ if self.bias_k is not None:
+ assert self.bias_v is not None
+ k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
+ v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
+ if attn_mask is not None:
+ attn_mask = torch.cat(
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
+ )
+ if key_padding_mask is not None:
+ key_padding_mask = torch.cat(
+ [
+ key_padding_mask,
+ key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
+ ],
+ dim=1,
+ )
+
+ q = (
+ q.contiguous()
+ .view(tgt_len, bsz * self.num_heads, self.q_head_dim)
+ .transpose(0, 1)
+ )
+ if k is not None:
+ k = (
+ k.contiguous()
+ .view(-1, bsz * self.num_heads, self.k_head_dim)
+ .transpose(0, 1)
+ )
+ if v is not None:
+ v = (
+ v.contiguous()
+ .view(-1, bsz * self.num_heads, self.head_dim)
+ .transpose(0, 1)
+ )
+
+ if saved_state is not None:
+ # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
+ if "prev_key" in saved_state:
+ _prev_key = saved_state["prev_key"]
+ assert _prev_key is not None
+ prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
+ if static_kv:
+ k = prev_key
+ else:
+ assert k is not None
+ k = torch.cat([prev_key, k], dim=1)
+ src_len = k.size(1)
+ if "prev_value" in saved_state:
+ _prev_value = saved_state["prev_value"]
+ assert _prev_value is not None
+ prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
+ if static_kv:
+ v = prev_value
+ else:
+ assert v is not None
+ v = torch.cat([prev_value, v], dim=1)
+ prev_key_padding_mask: Optional[Tensor] = None
+ if "prev_key_padding_mask" in saved_state:
+ prev_key_padding_mask = saved_state["prev_key_padding_mask"]
+ assert k is not None and v is not None
+ key_padding_mask = MultiheadAttention._append_prev_key_padding_mask(
+ key_padding_mask=key_padding_mask,
+ prev_key_padding_mask=prev_key_padding_mask,
+ batch_size=bsz,
+ src_len=k.size(1),
+ static_kv=static_kv,
+ )
+
+ saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
+ saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
+ saved_state["prev_key_padding_mask"] = key_padding_mask
+ # In this branch incremental_state is never None
+ assert incremental_state is not None
+ incremental_state = self._set_input_buffer(incremental_state, saved_state)
+ assert k is not None
+ assert k.size(1) == src_len
+
+ # This is part of a workaround to get around fork/join parallelism
+ # not supporting Optional types.
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
+ key_padding_mask = None
+
+ if key_padding_mask is not None:
+ assert key_padding_mask.size(0) == bsz
+ assert key_padding_mask.size(1) == src_len
+
+ if self.add_zero_attn:
+ assert v is not None
+ src_len += 1
+ k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
+ v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
+ if attn_mask is not None:
+ attn_mask = torch.cat(
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
+ )
+ if key_padding_mask is not None:
+ key_padding_mask = torch.cat(
+ [
+ key_padding_mask,
+ torch.zeros(key_padding_mask.size(0), 1).type_as(
+ key_padding_mask
+ ),
+ ],
+ dim=1,
+ )
+
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
+ attn_weights = (attn_weights - attn_weights.max(dim=-1, keepdim=True)[0]) * alpha
+ attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
+
+ assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
+
+ if attn_mask is not None:
+ attn_mask = attn_mask.unsqueeze(0)
+ attn_weights += attn_mask
+
+ if key_padding_mask is not None:
+ # don't attend to padding symbols
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ if not is_tpu:
+ attn_weights = attn_weights.masked_fill(
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),
+ float("-inf"),
+ )
+ else:
+ attn_weights = attn_weights.transpose(0, 2)
+ attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf"))
+ attn_weights = attn_weights.transpose(0, 2)
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if before_softmax:
+ return attn_weights, v, position_bias
+
+ if position_bias is not None:
+ attn_mask_rel_pos = position_bias
+ if self.gru_rel_pos == 1:
+ query_layer = q.view(bsz, self.num_heads, tgt_len, self.q_head_dim) * alpha / self.scaling
+ _B, _H, _L, __ = query_layer.size()
+ gate_a, gate_b = torch.sigmoid(self.grep_linear(query_layer).view(
+ _B, _H, _L, 2, 4).sum(-1, keepdim=False)).chunk(2, dim=-1)
+ gate_a_1 = gate_a * (gate_b * self.grep_a - 1.0) + 2.0
+ attn_mask_rel_pos = gate_a_1.view(bsz * self.num_heads, tgt_len, 1) * position_bias
+
+ attn_mask_rel_pos = attn_mask_rel_pos.view(attn_weights.size())
+
+ attn_weights = attn_weights + attn_mask_rel_pos
+
+ attn_weights_float = F.softmax(
+ attn_weights, dim=-1
+ )
+ attn_weights = attn_weights_float.type_as(attn_weights)
+ attn_probs = self.dropout_module(attn_weights)
+
+ assert v is not None
+ attn = torch.bmm(attn_probs, v)
+ assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
+ attn = self.out_proj(attn)
+ attn_weights: Optional[Tensor] = None
+ if need_weights:
+ attn_weights = attn_weights_float.view(
+ bsz, self.num_heads, tgt_len, src_len
+ ).transpose(1, 0)
+ if not need_head_weights:
+ # average attention weights over heads
+ attn_weights = attn_weights.mean(dim=0)
+
+ return attn, attn_weights, position_bias
+
+ @staticmethod
+ def _append_prev_key_padding_mask(
+ key_padding_mask: Optional[Tensor],
+ prev_key_padding_mask: Optional[Tensor],
+ batch_size: int,
+ src_len: int,
+ static_kv: bool,
+ ) -> Optional[Tensor]:
+ # saved key padding masks have shape (bsz, seq_len)
+ if prev_key_padding_mask is not None and static_kv:
+ new_key_padding_mask = prev_key_padding_mask
+ elif prev_key_padding_mask is not None and key_padding_mask is not None:
+ new_key_padding_mask = torch.cat(
+ [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1
+ )
+ # During incremental decoding, as the padding token enters and
+ # leaves the frame, there will be a time when prev or current
+ # is None
+ elif prev_key_padding_mask is not None:
+ if src_len > prev_key_padding_mask.size(1):
+ filler = torch.zeros(
+ (batch_size, src_len - prev_key_padding_mask.size(1)),
+ device=prev_key_padding_mask.device,
+ )
+ new_key_padding_mask = torch.cat(
+ [prev_key_padding_mask.float(), filler.float()], dim=1
+ )
+ else:
+ new_key_padding_mask = prev_key_padding_mask.float()
+ elif key_padding_mask is not None:
+ if src_len > key_padding_mask.size(1):
+ filler = torch.zeros(
+ (batch_size, src_len - key_padding_mask.size(1)),
+ device=key_padding_mask.device,
+ )
+ new_key_padding_mask = torch.cat(
+ [filler.float(), key_padding_mask.float()], dim=1
+ )
+ else:
+ new_key_padding_mask = key_padding_mask.float()
+ else:
+ new_key_padding_mask = prev_key_padding_mask
+ return new_key_padding_mask
+
+ def _get_input_buffer(
+ self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
+ ) -> Dict[str, Optional[Tensor]]:
+ result = self.get_incremental_state(incremental_state, "attn_state")
+ if result is not None:
+ return result
+ else:
+ empty_result: Dict[str, Optional[Tensor]] = {}
+ return empty_result
+
+ def _set_input_buffer(
+ self,
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
+ buffer: Dict[str, Optional[Tensor]],
+ ):
+ return self.set_incremental_state(incremental_state, "attn_state", buffer)
+
+ def apply_sparse_mask(self, attn_weights, tgt_len: int, src_len: int, bsz: int):
+ return attn_weights
+
+
+def init_bert_params(module):
+ """
+ Initialize the weights specific to the BERT Model.
+ This overrides the default initializations depending on the specified arguments.
+ 1. If normal_init_linear_weights is set then weights of linear
+ layer will be initialized using the normal distribution and
+ bais will be set to the specified value.
+ 2. If normal_init_embed_weights is set then weights of embedding
+ layer will be initialized using the normal distribution.
+ 3. If normal_init_proj_weights is set then weights of
+ in_project_weight for MultiHeadAttention initialized using
+ the normal distribution (to be validated).
+ """
+
+ def normal_(data):
+ # with FSDP, module params will be on CUDA, so we cast them back to CPU
+ # so that the RNG is consistent with and without FSDP
+ data.copy_(
+ data.cpu().normal_(mean=0.0, std=0.02).to(data.device)
+ )
+
+ if isinstance(module, nn.Linear):
+ normal_(module.weight.data)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ if isinstance(module, nn.Embedding):
+ normal_(module.weight.data)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ if isinstance(module, MultiheadAttention):
+ normal_(module.q_proj.weight.data)
+ normal_(module.k_proj.weight.data)
+ normal_(module.v_proj.weight.data)
\ No newline at end of file
diff --git a/videollama2/model/beats/modules.py b/videollama2/model/beats/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..18e2d2066b93139acc9427f0edcdd96b12769f25
--- /dev/null
+++ b/videollama2/model/beats/modules.py
@@ -0,0 +1,218 @@
+# --------------------------------------------------------
+# BEATs: Audio Pre-Training with Acoustic Tokenizers (https://arxiv.org/abs/2212.09058)
+# Github source: https://github.com/microsoft/unilm/tree/master/beats
+# Copyright (c) 2022 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Based on fairseq code bases
+# https://github.com/pytorch/fairseq
+# --------------------------------------------------------
+
+import math
+import warnings
+import torch
+from torch import Tensor, nn
+import torch.nn.functional as F
+
+
+class GradMultiply(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, scale):
+ ctx.scale = scale
+ res = x.new(x)
+ return res
+
+ @staticmethod
+ def backward(ctx, grad):
+ return grad * ctx.scale, None
+
+
+class SamePad(nn.Module):
+ def __init__(self, kernel_size, causal=False):
+ super().__init__()
+ if causal:
+ self.remove = kernel_size - 1
+ else:
+ self.remove = 1 if kernel_size % 2 == 0 else 0
+
+ def forward(self, x):
+ if self.remove > 0:
+ x = x[:, :, : -self.remove]
+ return x
+
+
+class Swish(nn.Module):
+ def __init__(self):
+ super(Swish, self).__init__()
+ self.act = torch.nn.Sigmoid()
+
+ def forward(self, x):
+ return x * self.act(x)
+
+
+class GLU_Linear(nn.Module):
+ def __init__(self, input_dim, output_dim, glu_type="sigmoid", bias_in_glu=True):
+ super(GLU_Linear, self).__init__()
+
+ self.glu_type = glu_type
+ self.output_dim = output_dim
+
+ if glu_type == "sigmoid":
+ self.glu_act = torch.nn.Sigmoid()
+ elif glu_type == "swish":
+ self.glu_act = Swish()
+ elif glu_type == "relu":
+ self.glu_act = torch.nn.ReLU()
+ elif glu_type == "gelu":
+ self.glu_act = torch.nn.GELU()
+
+ if bias_in_glu:
+ self.linear = nn.Linear(input_dim, output_dim * 2, True)
+ else:
+ self.linear = nn.Linear(input_dim, output_dim * 2, False)
+
+ def forward(self, x):
+ # to be consistent with GLU_Linear, we assume the input always has the #channel (#dim) in the last dimension of the tensor, so need to switch the dimension first for 1D-Conv case
+ x = self.linear(x)
+
+ if self.glu_type == "bilinear":
+ x = (x[:, :, 0:self.output_dim] * x[:, :, self.output_dim:self.output_dim * 2])
+ else:
+ x = (x[:, :, 0:self.output_dim] * self.glu_act(x[:, :, self.output_dim:self.output_dim * 2]))
+
+ return x
+
+
+def gelu_accurate(x):
+ if not hasattr(gelu_accurate, "_a"):
+ gelu_accurate._a = math.sqrt(2 / math.pi)
+ return (
+ 0.5 * x * (1 + torch.tanh(gelu_accurate._a * (x + 0.044715 * torch.pow(x, 3))))
+ )
+
+
+def gelu(x: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.gelu(x.float()).type_as(x)
+
+
+def get_activation_fn(activation: str):
+ """Returns the activation function corresponding to `activation`"""
+
+ if activation == "relu":
+ return F.relu
+ elif activation == "gelu":
+ return gelu
+ elif activation == "gelu_fast":
+ warnings.warn(
+ "--activation-fn=gelu_fast has been renamed to gelu_accurate"
+ )
+ return gelu_accurate
+ elif activation == "gelu_accurate":
+ return gelu_accurate
+ elif activation == "tanh":
+ return torch.tanh
+ elif activation == "linear":
+ return lambda x: x
+ elif activation == "glu":
+ return lambda x: x
+ else:
+ raise RuntimeError("--activation-fn {} not supported".format(activation))
+
+
+def quant_noise(module, p, block_size):
+ """
+ Wraps modules and applies quantization noise to the weights for
+ subsequent quantization with Iterative Product Quantization as
+ described in "Training with Quantization Noise for Extreme Model Compression"
+
+ Args:
+ - module: nn.Module
+ - p: amount of Quantization Noise
+ - block_size: size of the blocks for subsequent quantization with iPQ
+
+ Remarks:
+ - Module weights must have the right sizes wrt the block size
+ - Only Linear, Embedding and Conv2d modules are supported for the moment
+ - For more detail on how to quantize by blocks with convolutional weights,
+ see "And the Bit Goes Down: Revisiting the Quantization of Neural Networks"
+ - We implement the simplest form of noise here as stated in the paper
+ which consists in randomly dropping blocks
+ """
+
+ # if no quantization noise, don't register hook
+ if p <= 0:
+ return module
+
+ # supported modules
+ assert isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d))
+
+ # test whether module.weight has the right sizes wrt block_size
+ is_conv = module.weight.ndim == 4
+
+ # 2D matrix
+ if not is_conv:
+ assert (
+ module.weight.size(1) % block_size == 0
+ ), "Input features must be a multiple of block sizes"
+
+ # 4D matrix
+ else:
+ # 1x1 convolutions
+ if module.kernel_size == (1, 1):
+ assert (
+ module.in_channels % block_size == 0
+ ), "Input channels must be a multiple of block sizes"
+ # regular convolutions
+ else:
+ k = module.kernel_size[0] * module.kernel_size[1]
+ assert k % block_size == 0, "Kernel size must be a multiple of block size"
+
+ def _forward_pre_hook(mod, input):
+ # no noise for evaluation
+ if mod.training:
+ if not is_conv:
+ # gather weight and sizes
+ weight = mod.weight
+ in_features = weight.size(1)
+ out_features = weight.size(0)
+
+ # split weight matrix into blocks and randomly drop selected blocks
+ mask = torch.zeros(
+ in_features // block_size * out_features, device=weight.device
+ )
+ mask.bernoulli_(p)
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
+
+ else:
+ # gather weight and sizes
+ weight = mod.weight
+ in_channels = mod.in_channels
+ out_channels = mod.out_channels
+
+ # split weight matrix into blocks and randomly drop selected blocks
+ if mod.kernel_size == (1, 1):
+ mask = torch.zeros(
+ int(in_channels // block_size * out_channels),
+ device=weight.device,
+ )
+ mask.bernoulli_(p)
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
+ else:
+ mask = torch.zeros(
+ weight.size(0), weight.size(1), device=weight.device
+ )
+ mask.bernoulli_(p)
+ mask = (
+ mask.unsqueeze(2)
+ .unsqueeze(3)
+ .repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
+ )
+
+ # scale weights and apply mask
+ mask = mask.to(
+ torch.bool
+ ) # x.bool() is not currently supported in TorchScript
+ s = 1 / (1 - p)
+ mod.weight.data = s * weight.masked_fill(mask, 0)
+
+ module.register_forward_pre_hook(_forward_pre_hook)
+ return module
diff --git a/videollama2/model/beats/quantizer.py b/videollama2/model/beats/quantizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..704be4c357bce7ee425ea2b6737b536333a5a63c
--- /dev/null
+++ b/videollama2/model/beats/quantizer.py
@@ -0,0 +1,215 @@
+# --------------------------------------------------------
+# BEATs: Audio Pre-Training with Acoustic Tokenizers (https://arxiv.org/abs/2212.09058)
+# Github source: https://github.com/microsoft/unilm/tree/master/beats
+# Copyright (c) 2022 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Based on VQGAN code bases
+# https://github.com/CompVis/taming-transformers
+# --------------------------------------------------------'
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.distributed as distributed
+
+try:
+ from einops import rearrange, repeat
+except ImportError:
+ pass
+
+
+def l2norm(t):
+ return F.normalize(t, p=2, dim=-1)
+
+
+def ema_inplace(moving_avg, new, decay):
+ moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
+
+
+def sample_vectors(samples, num):
+ num_samples, device = samples.shape[0], samples.device
+
+ if num_samples >= num:
+ indices = torch.randperm(num_samples, device=device)[:num]
+ else:
+ indices = torch.randint(0, num_samples, (num,), device=device)
+
+ return samples[indices]
+
+
+def kmeans(samples, num_clusters, num_iters=10, use_cosine_sim=False):
+ dim, dtype, device = samples.shape[-1], samples.dtype, samples.device
+
+ means = sample_vectors(samples, num_clusters)
+
+ for _ in range(num_iters):
+ if use_cosine_sim:
+ dists = samples @ means.t()
+ else:
+ diffs = rearrange(samples, 'n d -> n () d') \
+ - rearrange(means, 'c d -> () c d')
+ dists = -(diffs ** 2).sum(dim=-1)
+
+ buckets = dists.max(dim=-1).indices
+ bins = torch.bincount(buckets, minlength=num_clusters)
+ zero_mask = bins == 0
+ bins_min_clamped = bins.masked_fill(zero_mask, 1)
+
+ new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)
+ new_means.scatter_add_(0, repeat(buckets, 'n -> n d', d=dim), samples)
+ new_means = new_means / bins_min_clamped[..., None]
+
+ if use_cosine_sim:
+ new_means = l2norm(new_means)
+
+ means = torch.where(zero_mask[..., None], means, new_means)
+
+ return means, bins
+
+
+class EmbeddingEMA(nn.Module):
+ def __init__(self, num_tokens, codebook_dim, decay=0.99, eps=1e-5, kmeans_init=True, codebook_init_path=''):
+ super().__init__()
+ self.num_tokens = num_tokens
+ self.codebook_dim = codebook_dim
+ self.decay = decay
+ self.eps = eps
+ if codebook_init_path == '':
+ if not kmeans_init:
+ weight = torch.randn(num_tokens, codebook_dim)
+ weight = l2norm(weight)
+ else:
+ weight = torch.zeros(num_tokens, codebook_dim)
+ self.register_buffer('initted', torch.Tensor([not kmeans_init]))
+ else:
+ print(f"load init codebook weight from {codebook_init_path}")
+ codebook_ckpt_weight = torch.load(codebook_init_path, map_location='cpu')
+ weight = codebook_ckpt_weight.clone()
+ self.register_buffer('initted', torch.Tensor([True]))
+
+ self.weight = nn.Parameter(weight, requires_grad=False)
+ self.cluster_size = nn.Parameter(torch.zeros(num_tokens), requires_grad=False)
+ self.embed_avg = nn.Parameter(weight.clone(), requires_grad=False)
+ # self.register_buffer('initted', torch.Tensor([not kmeans_init]))
+ self.update = True
+
+ @torch.jit.ignore
+ def init_embed_(self, data):
+ if self.initted:
+ return
+ print("Performing Kemans init for codebook")
+ embed, cluster_size = kmeans(data, self.num_tokens, 10, use_cosine_sim=True)
+ self.weight.data.copy_(embed)
+ self.cluster_size.data.copy_(cluster_size)
+ self.initted.data.copy_(torch.Tensor([True]))
+
+ def forward(self, embed_id):
+ return F.embedding(embed_id, self.weight)
+
+ def cluster_size_ema_update(self, new_cluster_size):
+ self.cluster_size.data.mul_(self.decay).add_(new_cluster_size, alpha=1 - self.decay)
+
+ def embed_avg_ema_update(self, new_embed_avg):
+ self.embed_avg.data.mul_(self.decay).add_(new_embed_avg, alpha=1 - self.decay)
+
+ def weight_update(self, num_tokens):
+ n = self.cluster_size.sum()
+ smoothed_cluster_size = (
+ (self.cluster_size + self.eps) / (n + num_tokens * self.eps) * n
+ )
+ # normalize embedding average with smoothed cluster size
+ embed_normalized = self.embed_avg / smoothed_cluster_size.unsqueeze(1)
+ # embed_normalized = l2norm(self.embed_avg / smoothed_cluster_size.unsqueeze(1))
+ self.weight.data.copy_(embed_normalized)
+
+
+def norm_ema_inplace(moving_avg, new, decay):
+ moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))
+ moving_avg.data.copy_(l2norm(moving_avg.data))
+
+
+class NormEMAVectorQuantizer(nn.Module):
+ def __init__(self, n_embed, embedding_dim, beta, decay=0.99, eps=1e-5,
+ statistic_code_usage=True, kmeans_init=False, codebook_init_path=''):
+ super().__init__()
+ self.codebook_dim = embedding_dim
+ self.num_tokens = n_embed
+ self.beta = beta
+ self.decay = decay
+
+ # learnable = True if orthogonal_reg_weight > 0 else False
+ self.embedding = EmbeddingEMA(self.num_tokens, self.codebook_dim, decay, eps, kmeans_init, codebook_init_path)
+
+ self.statistic_code_usage = statistic_code_usage
+ if statistic_code_usage:
+ self.register_buffer('cluster_size', torch.zeros(n_embed))
+ if distributed.is_available() and distributed.is_initialized():
+ print("ddp is enable, so use ddp_reduce to sync the statistic_code_usage for each gpu!")
+ self.all_reduce_fn = distributed.all_reduce
+ else:
+ self.all_reduce_fn = nn.Identity()
+
+ def reset_cluster_size(self, device):
+ if self.statistic_code_usage:
+ self.register_buffer('cluster_size', torch.zeros(self.num_tokens))
+ self.cluster_size = self.cluster_size.to(device)
+
+ def forward(self, z):
+ # reshape z -> (batch, height, width, channel) and flatten
+ # z, 'b c h w -> b h w c'
+ # z = rearrange(z, 'b c h w -> b h w c')
+ # z = z.transpose(1, 2)
+ z = l2norm(z)
+ z_flattened = z.reshape(-1, self.codebook_dim)
+
+ self.embedding.init_embed_(z_flattened)
+
+ d = z_flattened.pow(2).sum(dim=1, keepdim=True) + \
+ self.embedding.weight.pow(2).sum(dim=1) - 2 * \
+ torch.einsum('bd,nd->bn', z_flattened, self.embedding.weight) # 'n d -> d n'
+
+ encoding_indices = torch.argmin(d, dim=1)
+
+ z_q = self.embedding(encoding_indices).view(z.shape)
+
+ encodings = F.one_hot(encoding_indices, self.num_tokens).type(z.dtype)
+
+ if not self.training:
+ with torch.no_grad():
+ cluster_size = encodings.sum(0)
+ self.all_reduce_fn(cluster_size)
+ ema_inplace(self.cluster_size, cluster_size, self.decay)
+
+ if self.training and self.embedding.update:
+ # EMA cluster size
+
+ bins = encodings.sum(0)
+ self.all_reduce_fn(bins)
+
+ # self.embedding.cluster_size_ema_update(bins)
+ ema_inplace(self.cluster_size, bins, self.decay)
+
+ zero_mask = (bins == 0)
+ bins = bins.masked_fill(zero_mask, 1.)
+
+ embed_sum = z_flattened.t() @ encodings
+ self.all_reduce_fn(embed_sum)
+
+ embed_normalized = (embed_sum / bins.unsqueeze(0)).t()
+ embed_normalized = l2norm(embed_normalized)
+
+ embed_normalized = torch.where(zero_mask[..., None], self.embedding.weight,
+ embed_normalized)
+ norm_ema_inplace(self.embedding.weight, embed_normalized, self.decay)
+
+ # compute loss for embedding
+ loss = self.beta * F.mse_loss(z_q.detach(), z)
+
+ # preserve gradients
+ z_q = z + (z_q - z).detach()
+
+ # reshape back to match original input shape
+ # z_q, 'b h w c -> b c h w'
+ # z_q = rearrange(z_q, 'b h w c -> b c h w')
+ # z_q = z_q.transpose(1, 2)
+ return z_q, loss, encoding_indices
\ No newline at end of file
diff --git a/videollama2/model/beats/weight_norm_fix.py b/videollama2/model/beats/weight_norm_fix.py
new file mode 100644
index 0000000000000000000000000000000000000000..04016fd431ee82a77ca6bbed07273e03d4d34b51
--- /dev/null
+++ b/videollama2/model/beats/weight_norm_fix.py
@@ -0,0 +1,139 @@
+r"""Weight Normalization from https://arxiv.org/abs/1602.07868."""
+from torch.nn.parameter import Parameter, UninitializedParameter
+from torch import norm_except_dim
+from typing import Any, TypeVar
+import warnings
+from torch.nn.modules import Module
+import torch
+
+class WeightNorm:
+ name: str
+ dim: int
+
+ def __init__(self, name: str, dim: int) -> None:
+ if dim is None:
+ dim = -1
+ self.name = name
+ self.dim = dim
+
+ # TODO Make return type more specific
+ def compute_weight(self, module: Module) -> Any:
+ g = getattr(module, self.name + '_g')
+ v = getattr(module, self.name + '_v')
+
+ input_dtype = v.dtype
+ v = v.to(torch.float32)
+ reduce_dims = list(range(v.dim()))
+ reduce_dims.pop(self.dim)
+ variance = v.pow(2).sum(reduce_dims, keepdim=True)
+ v = v * torch.rsqrt(variance + 1e-6)
+
+ return g * v.to(input_dtype)
+
+ @staticmethod
+ def apply(module, name: str, dim: int) -> 'WeightNorm':
+ warnings.warn("torch.nn.utils.weight_norm is deprecated in favor of torch.nn.utils.parametrizations.weight_norm.")
+
+ for hook in module._forward_pre_hooks.values():
+ if isinstance(hook, WeightNorm) and hook.name == name:
+ raise RuntimeError(f"Cannot register two weight_norm hooks on the same parameter {name}")
+
+ if dim is None:
+ dim = -1
+
+ fn = WeightNorm(name, dim)
+
+ weight = getattr(module, name)
+ if isinstance(weight, UninitializedParameter):
+ raise ValueError(
+ 'The module passed to `WeightNorm` can\'t have uninitialized parameters. '
+ 'Make sure to run the dummy forward before applying weight normalization')
+ # remove w from parameter list
+ del module._parameters[name]
+
+ # add g and v as new parameters and express w as g/||v|| * v
+ module.register_parameter(name + '_g', Parameter(norm_except_dim(weight, 2, dim).data))
+ module.register_parameter(name + '_v', Parameter(weight.data))
+ setattr(module, name, fn.compute_weight(module))
+
+ # recompute weight before every forward()
+ module.register_forward_pre_hook(fn)
+
+ return fn
+
+ def remove(self, module: Module) -> None:
+ weight = self.compute_weight(module)
+ delattr(module, self.name)
+ del module._parameters[self.name + '_g']
+ del module._parameters[self.name + '_v']
+ setattr(module, self.name, Parameter(weight.data))
+
+ def __call__(self, module: Module, inputs: Any) -> None:
+ setattr(module, self.name, self.compute_weight(module))
+
+
+T_module = TypeVar('T_module', bound=Module)
+
+def weight_norm(module: T_module, name: str = 'weight', dim: int = 0) -> T_module:
+ r"""Apply weight normalization to a parameter in the given module.
+
+ .. math::
+ \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|}
+
+ Weight normalization is a reparameterization that decouples the magnitude
+ of a weight tensor from its direction. This replaces the parameter specified
+ by :attr:`name` (e.g. ``'weight'``) with two parameters: one specifying the magnitude
+ (e.g. ``'weight_g'``) and one specifying the direction (e.g. ``'weight_v'``).
+ Weight normalization is implemented via a hook that recomputes the weight
+ tensor from the magnitude and direction before every :meth:`~Module.forward`
+ call.
+
+ By default, with ``dim=0``, the norm is computed independently per output
+ channel/plane. To compute a norm over the entire weight tensor, use
+ ``dim=None``.
+
+ See https://arxiv.org/abs/1602.07868
+
+ .. warning::
+
+ This function is deprecated. Use :func:`torch.nn.utils.parametrizations.weight_norm`
+ which uses the modern parametrization API. The new ``weight_norm`` is compatible
+ with ``state_dict`` generated from old ``weight_norm``.
+
+ Migration guide:
+
+ * The magnitude (``weight_g``) and direction (``weight_v``) are now expressed
+ as ``parametrizations.weight.original0`` and ``parametrizations.weight.original1``
+ respectively. If this is bothering you, please comment on
+ https://github.com/pytorch/pytorch/issues/102999
+
+ * To remove the weight normalization reparametrization, use
+ :func:`torch.nn.utils.parametrize.remove_parametrizations`.
+
+ * The weight is no longer recomputed once at module forward; instead, it will
+ be recomputed on every access. To restore the old behavior, use
+ :func:`torch.nn.utils.parametrize.cached` before invoking the module
+ in question.
+
+ Args:
+ module (Module): containing module
+ name (str, optional): name of weight parameter
+ dim (int, optional): dimension over which to compute the norm
+
+ Returns:
+ The original module with the weight norm hook
+
+ Example::
+
+ >>> m = weight_norm(nn.Linear(20, 40), name='weight')
+ >>> m
+ Linear(in_features=20, out_features=40, bias=True)
+ >>> m.weight_g.size()
+ torch.Size([40, 1])
+ >>> m.weight_v.size()
+ torch.Size([40, 20])
+
+ """
+ WeightNorm.apply(module, name, dim)
+ return module
+
diff --git a/videollama2/model/encoder.py b/videollama2/model/encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..83c400ced7fc6bf835d7897edb1eeff519a10b95
--- /dev/null
+++ b/videollama2/model/encoder.py
@@ -0,0 +1,211 @@
+import os
+
+import torch
+import torch.nn as nn
+
+from transformers import (
+ CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig,
+ SiglipVisionModel, SiglipImageProcessor, SiglipVisionConfig
+)
+from .beats.BEATs import BEATsConfig, BEATs
+
+class CLIPVisionTower(nn.Module):
+
+ def __init__(self, vision_tower, args, delay_load=False):
+ super().__init__()
+
+ self.is_loaded = False
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ if not delay_load:
+ self.load_model()
+ else:
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
+
+ def load_model(self):
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
+
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
+ self.vision_tower.requires_grad_(False)
+
+ self.is_loaded = True
+
+ def feature_select(self, image_forward_outs):
+ image_features = image_forward_outs.hidden_states[self.select_layer]
+ if self.select_feature == 'patch':
+ image_features = image_features[:, 1:]
+ elif self.select_feature == 'cls_patch':
+ image_features = image_features
+ else:
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
+ return image_features
+
+ @torch.no_grad()
+ def forward(self, images):
+ if type(images) is list:
+ image_features = []
+ for image in images:
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
+ image_features.append(image_feature)
+ else:
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dummy_feature(self):
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ if self.is_loaded:
+ return self.vision_tower.config
+ else:
+ return self.cfg_only
+
+ @property
+ def hidden_size(self):
+ return self.config.hidden_size
+
+ @property
+ def num_patches(self):
+ return (self.config.image_size // self.config.patch_size) ** 2
+
+ @property
+ def num_patches_per_side(self):
+ return self.config.image_size // self.config.patch_size
+
+ @property
+ def image_size(self):
+ return self.config.image_size
+
+
+class SiglipVisionTower(nn.Module):
+
+ def __init__(self, vision_tower, args, delay_load=False):
+ super().__init__()
+
+ self.is_loaded = False
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ if not delay_load:
+ self.load_model()
+ else:
+ self.cfg_only = SiglipVisionConfig.from_pretrained(self.vision_tower_name)
+
+ def load_model(self):
+ self.image_processor = SiglipImageProcessor.from_pretrained(self.vision_tower_name)
+
+ self.vision_tower = SiglipVisionModel.from_pretrained(self.vision_tower_name)
+ self.vision_tower.requires_grad_(False)
+
+ self.is_loaded = True
+
+ def feature_select(self, image_forward_outs):
+ image_features = image_forward_outs.hidden_states[self.select_layer]
+ if self.select_feature == 'patch':
+ image_features = image_features
+ else:
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
+ return image_features
+
+ @torch.no_grad()
+ def forward(self, images):
+ if type(images) is list:
+ image_features = []
+ for image in images:
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
+ image_features.append(image_feature)
+ else:
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dummy_feature(self):
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ if self.is_loaded:
+ return self.vision_tower.config
+ else:
+ return self.cfg_only
+
+ @property
+ def hidden_size(self):
+ return self.config.hidden_size
+
+ @property
+ def num_patches(self):
+ return (self.config.image_size // self.config.patch_size) ** 2
+
+ @property
+ def num_patches_per_side(self):
+ return self.config.image_size // self.config.patch_size
+
+ @property
+ def image_size(self):
+ return self.config.image_size
+
+
+def build_vision_tower(vision_tower_cfg, **kwargs):
+ vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
+ if 'clip' in vision_tower:
+ vision_tower = CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
+ elif 'siglip' in vision_tower:
+ vision_tower = SiglipVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
+ else:
+ raise ValueError(f'Unknown vision tower: {vision_tower}')
+ #print(vision_tower)
+ return vision_tower
+
+def build_audio_tower(audio_tower_cfg, delay_load=False, **kwargs):
+ audio_tower = getattr(audio_tower_cfg, 'mm_audio_tower', getattr(audio_tower_cfg, 'audio_tower', None))
+ if not delay_load:
+ beats_checkpoint = torch.load(audio_tower, map_location='cpu')
+ if 'cfg' in beats_checkpoint:
+ beats_cfg = BEATsConfig(beats_checkpoint['cfg'])
+ else:
+ beats_cfg = BEATsConfig()
+ beats = BEATs(beats_cfg)
+ if not audio_tower.endswith('.bin'):
+ print(beats.load_state_dict(beats_checkpoint['model']))
+ else:
+ filtered_checkpoint = {}
+ prefix = 'model.audio_tower.'
+ for key, value in beats_checkpoint.items():
+ if key.startswith(prefix):
+ new_key = key[len(prefix):] # åģé¤åįŧ
+ filtered_checkpoint[new_key] = value
+ print(beats.load_state_dict(filtered_checkpoint, strict=False))
+ else:
+ beats_cfg = BEATsConfig()
+ beats = BEATs(beats_cfg)
+ return beats, beats_cfg
diff --git a/videollama2/model/mel_filters.npz b/videollama2/model/mel_filters.npz
new file mode 100644
index 0000000000000000000000000000000000000000..9793b084efeb26bf24cb2ba1f30d0989b2c94aa1
--- /dev/null
+++ b/videollama2/model/mel_filters.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dd2cc75e70e36fcbdd8ffbc2499062f30094093e6bf2cbafa9859f59972b420b
+size 2048
diff --git a/videollama2/model/projector.py b/videollama2/model/projector.py
new file mode 100644
index 0000000000000000000000000000000000000000..b481a663f312c7c6d7972c57e1d849353825a958
--- /dev/null
+++ b/videollama2/model/projector.py
@@ -0,0 +1,265 @@
+# Copyright 2024 Alibaba DAMO Academy
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+
+import einops
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from timm.models.regnet import RegStage
+from timm.models.layers import LayerNorm, LayerNorm2d
+from transformers import TRANSFORMERS_CACHE
+
+
+def parse_snapshot_folder(repo_id, cache_dir=None, repo_type="model"):
+ revision = "main"
+ # 1. parse the downloaded cache folder
+ if cache_dir is None:
+ cache_dir = TRANSFORMERS_CACHE
+ else:
+ cache_dir = cache_dir
+ object_id = repo_id.replace("/", "--")
+ repo_cache = os.path.join(cache_dir, f"{repo_type}s--{object_id}")
+ # 2. resolve refs (for instance to convert main to the associated commit sha)
+ refs_dir = os.path.join(repo_cache, "refs")
+ if os.path.isdir(refs_dir):
+ revision_file = os.path.join(refs_dir, revision)
+ if os.path.isfile(revision_file):
+ with open(revision_file) as f:
+ revision = f.read()
+ # 3. acquire the snapshot folder
+ folder = os.path.join(repo_cache, "snapshots", revision)
+
+ return folder
+
+
+def load_mm_projector(model_path, cache_dir=None, token=None):
+ if os.path.exists(os.path.join(model_path, 'mm_projector.bin')):
+ is_local = True
+ folder = model_path
+ else:
+ is_local = False
+ folder = parse_snapshot_folder(model_path, cache_dir=cache_dir, repo_type="model")
+ if not os.path.exists(os.path.join(folder, 'mm_projector.bin')):
+ # downloading from remote repo
+ from huggingface_hub import snapshot_download
+ snapshot_download(repo_id=model_path, cache_dir=cache_dir, token=token)
+
+ mm_projector_weights = torch.load(os.path.join(folder, 'mm_projector.bin'), map_location='cpu')
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
+ return mm_projector_weights
+
+
+class IdentityMap(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x, *args, **kwargs):
+ return x
+
+ @property
+ def config(self):
+ return {"mm_projector_type": 'identity'}
+
+
+class SimpleResBlock(nn.Module):
+
+ def __init__(self, channels):
+ super().__init__()
+ self.pre_norm = nn.LayerNorm(channels)
+
+ self.proj = nn.Sequential(
+ nn.Linear(channels, channels),
+ nn.GELU(),
+ nn.Linear(channels, channels)
+ )
+ def forward(self, x):
+ x = self.pre_norm(x)
+ return x + self.proj(x)
+
+
+def build_vision_projector(config, delay_load=False, **kwargs):
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
+ if mlp_gelu_match:
+ mlp_depth = int(mlp_gelu_match.group(1))
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
+ for _ in range(1, mlp_depth):
+ modules.append(nn.GELU())
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
+ return nn.Sequential(*modules)
+
+ if projector_type == "linear":
+ # NOTE: for both linear and mlp2x_gelu projector type, mean pooling is adopted to aggreate video features
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
+ elif projector_type == "stc_connector":
+ return STCConnector(config)
+ elif projector_type == "stp_connector":
+ return STPConnector(config)
+ elif projector_type == "stc_connector_v35":
+ return STCConnectorV35(config)
+ elif projector_type == "spatial_conv":
+ return SpatialConv(config)
+ elif projector_type == "spatial_pool":
+ return SpatialPool(config)
+ if projector_type == 'identity':
+ return IdentityMap()
+
+ raise ValueError(f'Unknown projector type: {projector_type}')
+
+def build_audio_projector(config, delay_load=False, **kwargs):
+ projector_type = getattr(config, 'mm_projector_a_type', 'linear')
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
+ if mlp_gelu_match:
+ mlp_depth = int(mlp_gelu_match.group(1))
+ modules = [nn.Linear(config.mm_hidden_size_a, config.hidden_size_a)]
+ for _ in range(1, mlp_depth):
+ modules.append(nn.GELU())
+ modules.append(nn.Linear(config.hidden_size_a, config.hidden_size_a))
+ return nn.Sequential(*modules)
+ if projector_type == "linear":
+ # note that for both linear and mlp2x_gelu projector type, mean pooling is adopted to aggreate video features
+ return nn.Linear(config.mm_hidden_size_a, config.hidden_size_a)
+ if projector_type == 'identity':
+ return IdentityMap()
+
+def build_mlp(depth, hidden_size, output_hidden_size):
+ modules = [nn.Linear(hidden_size, output_hidden_size)]
+ for _ in range(1, depth):
+ modules.append(nn.GELU())
+ modules.append(nn.Linear(output_hidden_size, output_hidden_size))
+ return nn.Sequential(*modules)
+
+
+class STCConnector(nn.Module):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ """Temporal Convolutional Vision-Language Connector.
+
+ Args:
+ config: config object.
+ downsample: (temporal, height, width) downsample rate.
+ depth: depth of the spatial interaction blocks.
+ mlp_depth: depth of the vision-language projector layers.
+ """
+ super().__init__()
+ self.encoder_hidden_size = encoder_hidden_size = config.mm_hidden_size
+ self.hidden_size = hidden_size = config.hidden_size
+ self.output_hidden_size = output_hidden_size = config.hidden_size
+ # TODO: make these as config arguments
+ self.depth = depth
+ self.mlp_depth = mlp_depth
+ self.downsample = downsample
+ if depth != 0:
+ self.s1 = RegStage(
+ depth=depth,
+ in_chs=encoder_hidden_size,
+ out_chs=hidden_size,
+ stride=1,
+ dilation=1,
+ act_layer=nn.SiLU,
+ norm_layer=LayerNorm2d,
+ )
+ else:
+ self.s1 = nn.Identity()
+ self.sampler = nn.Sequential(
+ nn.Conv3d(
+ in_channels=hidden_size,
+ out_channels=hidden_size,
+ kernel_size=downsample,
+ stride=downsample,
+ padding=1,
+ bias=True
+ ),
+ nn.SiLU()
+ )
+ if depth != 0:
+ self.s2 = RegStage(
+ depth=depth,
+ in_chs=hidden_size,
+ out_chs=hidden_size,
+ stride=1,
+ dilation=1,
+ act_layer=nn.SiLU,
+ norm_layer=LayerNorm2d,
+ )
+ else:
+ self.s2 = nn.Identity()
+ self.readout = build_mlp(mlp_depth, hidden_size, output_hidden_size)
+
+ def forward(self, x):
+ """Aggregate tokens on the temporal and spatial dimensions.
+ Args:
+ x: input tokens [b, t, h, w, d] / [b, t, l, d]
+ Returns:
+ aggregated tokens [b, l, d]
+ """
+ t = x.size(1)
+ if x.ndim == 4:
+ hw = int(x.size(2) ** 0.5)
+ x = einops.rearrange(x, "b t (h w) d -> b d t h w", h=hw, w=hw)
+ elif x.ndim == 5:
+ x = einops.rearrange(x, "b t h w d -> b d t h w")
+
+ x = einops.rearrange(x, "b d t h w -> (b t) d h w")
+ # 1. the first stage of the adapter
+ x = self.s1(x)
+ x = einops.rearrange(x, "(b t) d h w -> b d t h w", t=t)
+ # 2. downsampler
+ x = self.sampler(x)
+ new_t = x.size(2)
+ # 3. the second stage of the adapter
+ x = einops.rearrange(x, "b d t h w -> (b t) d h w")
+ x = self.s2(x)
+ x = einops.rearrange(x, "(b t) d h w -> b (t h w) d", t=new_t)
+ x = self.readout(x)
+ return x
+
+
+class STPConnector(STCConnector):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+ self.sampler = nn.Sequential(nn.AvgPool3d(downsample), nn.SiLU())
+
+
+class STCConnectorV35(STCConnector):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+ self.sampler = nn.Sequential(
+ nn.Conv3d(
+ in_channels=self.hidden_size,
+ out_channels=self.hidden_size,
+ kernel_size=downsample,
+ stride=downsample,
+ padding=0,
+ bias=True
+ ),
+ nn.SiLU())
+
+
+class SpatialConv(STCConnector):
+
+ def __init__(self, config, downsample=(1, 2, 2), depth=0, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+
+
+class SpatialPool(STPConnector):
+
+ def __init__(self, config, downsample=(1, 2, 2), depth=0, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
diff --git a/videollama2/model/videollama2_arch.py b/videollama2/model/videollama2_arch.py
new file mode 100644
index 0000000000000000000000000000000000000000..163b9e3de6528c8942856fc60a4fe65035a826ad
--- /dev/null
+++ b/videollama2/model/videollama2_arch.py
@@ -0,0 +1,377 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+from abc import ABC, abstractmethod
+
+import einops
+import torch
+import torch.nn as nn
+
+from .projector import load_mm_projector, build_vision_projector, build_audio_projector
+from .encoder import build_vision_tower, build_audio_tower
+from ..constants import IGNORE_INDEX, NUM_FRAMES, MODAL_INDEX_MAP
+
+
+class Videollama2MetaModel:
+
+ def __init__(self, config):
+ super(Videollama2MetaModel, self).__init__(config)
+
+ if hasattr(config, "mm_vision_tower"):
+ self.vision_tower = build_vision_tower(config, delay_load=True)
+ self.mm_projector = build_vision_projector(config)
+ if hasattr(config, "mm_audio_tower"):
+ self.audio_tower, audio_tower_cfg = build_audio_tower(config, delay_load=True)
+ self.mm_projector_a = build_audio_projector(config)
+
+ def get_vision_tower(self):
+ vision_tower = getattr(self, 'vision_tower', None)
+ if type(vision_tower) is list:
+ vision_tower = vision_tower[0]
+ return vision_tower
+
+ def get_audio_tower(self):
+ audio_tower = getattr(self, 'audio_tower', None)
+ if type(audio_tower) is list:
+ audio_tower = audio_tower[0]
+ return audio_tower
+
+ def initialize_vision_modules(self, model_args, fsdp=None):
+ vision_tower = model_args.vision_tower
+ mm_vision_select_layer = model_args.mm_vision_select_layer
+ mm_vision_select_feature = model_args.mm_vision_select_feature
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
+
+ self.config.mm_vision_tower = vision_tower
+
+ if self.get_vision_tower() is None:
+ vision_tower = build_vision_tower(model_args)
+
+ if fsdp is not None and len(fsdp) > 0:
+ self.vision_tower = [vision_tower]
+ else:
+ self.vision_tower = vision_tower
+ else:
+ if fsdp is not None and len(fsdp) > 0:
+ vision_tower = self.vision_tower[0]
+ else:
+ vision_tower = self.vision_tower
+ vision_tower.load_model()
+
+ self.config.use_mm_proj = True
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
+ self.config.mm_hidden_size = vision_tower.hidden_size
+ self.config.mm_vision_select_layer = mm_vision_select_layer
+ self.config.mm_vision_select_feature = mm_vision_select_feature
+
+ if getattr(self, 'mm_projector', None) is None:
+ self.mm_projector = build_vision_projector(self.config)
+ else:
+ # In case it is frozen by LoRA
+ for p in self.mm_projector.parameters():
+ p.requires_grad = True
+
+ if pretrain_mm_mlp_adapter is not None:
+ if os.path.exists(pretrain_mm_mlp_adapter):
+ is_local = True
+ if os.path.isdir(pretrain_mm_mlp_adapter):
+ mm_projector_weights = load_mm_projector(pretrain_mm_mlp_adapter)
+ else:
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
+ else:
+ # Support loading projector weights from remote HuggingFace model hub
+ is_local = False
+ pretrain_mm_mlp_adapter = pretrain_mm_mlp_adapter.replace('mm_projector.bin', '')
+ pretrain_mm_mlp_adapter = pretrain_mm_mlp_adapter.strip('/').strip('\\').strip()
+ mm_projector_weights = load_mm_projector(pretrain_mm_mlp_adapter)
+
+ def get_w(weights, keyword):
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
+
+ # self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
+ # set strict=False to avoid missing key error regarding bert.embeddings.position_ids
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'), strict=False)
+
+
+ def initialize_audio_modules(self, model_args, fsdp=None):
+ audio_tower = model_args.audio_tower
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter_a
+ self.config.mm_audio_tower = audio_tower
+ if self.get_audio_tower() is None:
+ audio_tower, audio_tower_cfg = build_audio_tower(model_args)
+ if fsdp is not None and len(fsdp) > 0:
+ self.audio_tower = [audio_tower]
+ else:
+ self.audio_tower = audio_tower
+ else:
+ if fsdp is not None and len(fsdp) > 0:
+ audio_tower = self.audio_tower[0]
+ else:
+ audio_tower = self.audio_tower
+ self.config.use_mm_proj = True
+ self.config.mm_projector_a_type = getattr(model_args, 'mm_projector_a_type', 'linear')
+ if model_args.model_type == 'videollama2_qwen2':
+ audio_tower_cfg.hidden_size = 3584
+ self.config.mm_hidden_size_a = audio_tower_cfg.encoder_embed_dim
+ self.config.hidden_size_a = audio_tower_cfg.hidden_size
+ if getattr(self, 'mm_projector_a', None) is None:
+ self.mm_projector_a = build_audio_projector(self.config)
+ else:
+ # In case it is frozen by LoRA
+ for p in self.mm_projector_a.parameters():
+ p.requires_grad = True
+ if pretrain_mm_mlp_adapter is not None:
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
+ def get_w(weights, keyword):
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
+ self.mm_projector_a.load_state_dict(get_w(mm_projector_weights, 'mm_projector_a'), strict=True)
+
+
+class Videollama2MetaForCausalLM(ABC):
+
+ @abstractmethod
+ def get_model(self):
+ pass
+
+ def num_frames(self):
+ if hasattr(self.config, 'num_frames'):
+ return self.config.num_frames
+ else:
+ return NUM_FRAMES
+
+ def get_vision_tower(self):
+ return self.get_model().get_vision_tower()
+
+ def get_audio_tower(self):
+ return self.get_model().get_audio_tower()
+
+ def encode_images_or_videos(self, images):
+ num_frames = self.config.num_frames if hasattr(self.config, 'num_frames') else NUM_FRAMES
+
+ data_batch = []
+ for i, (data, modal) in enumerate(images):
+ if modal == 'image':
+ data = data.expand(num_frames, -1, -1, -1)
+ else:
+ data = data
+ data_batch.append(data)
+
+ data_batch = torch.stack(data_batch, dim=0)
+
+ assert len(data_batch.size()) == 5
+ batch_size = data_batch.size(0)
+
+ frames = einops.rearrange(data_batch, 'b t c h w -> (b t) c h w')
+ frames_features = self.get_model().get_vision_tower()(frames)
+ frames_features = einops.rearrange(frames_features, '(b t) n h -> b t n h', b = batch_size)
+
+ return self.temporal_aggregator(frames_features)
+
+ def temporal_aggregator(self, frames_features):
+ """Temporal aggregation of frame features.
+ Args:
+ frames_features (torch.Tensor): Frame features with shape (b, t, n, h).
+ Returns:
+ torch.Tensor: Video features with shape (b, n, h).
+ """
+ # TODO: improve the merging method.
+ # *********** mean pooling *************
+ if self.config.mm_projector_type == "mlp2x_gelu" or self.config.mm_projector_type == "linear":
+ video_features = self.get_model().mm_projector(frames_features.mean(1))
+ # *********** spatial convolution *************
+ elif self.config.mm_projector_type == "spatial_conv":
+ video_features = self.get_model().mm_projector(frames_features)
+ # *********** spatial pooling *************
+ elif self.config.mm_projector_type == "spatial_pool":
+ video_features = self.get_model().mm_projector(frames_features)
+ # *********** time ************
+ elif "tc_connector" in self.config.mm_projector_type or "tp_connector" in self.config.mm_projector_type:
+ video_features = self.get_model().mm_projector(frames_features)
+ else:
+ raise Exception(f"Unsupported projector type {self.config.mm_projector_type}!!!")
+
+ return video_features
+
+ def prepare_inputs_labels_for_multimodal(
+ self, input_ids, attention_mask, past_key_values, labels, images
+ ):
+ vision_tower = self.get_vision_tower()
+ audio_tower = self.get_audio_tower()
+ # NOTE: text-only situation
+ if (vision_tower is None and audio_tower is None) or images is None or input_ids.shape[1] == 1:
+ # if past_key_values is not None and vision_tower is not None and Xs is not None and input_ids.shape[1] == 1:
+ # attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
+ return input_ids, attention_mask, past_key_values, None, labels
+ if audio_tower is None:
+ mm_features = self.encode_images_or_videos(images)
+ elif audio_tower is not None and vision_tower is not None and any(modal == 'video' for (_, modal) in images):
+ # [tensor, "image"]
+ # [tensor, "audio"]
+ # [tensor, "video"]
+ # [dict(â, audio), "video"]
+
+ X_video = []
+ X_audio = []
+
+ select_audio_id = []
+ select_videoimage_id = []
+ for idx, data_list in enumerate(images):
+ #print(data_list)
+ if isinstance(data_list[0], dict):
+ assert data_list[1] == "video"
+ X_audio.append(data_list[0]["audio"])
+ select_audio_id.append(True)
+ X_video.append((data_list[0]["video"], "video"))
+ select_videoimage_id.append(True)
+ else:
+ if data_list[1] == "audio":
+ X_audio.append(data_list[0])
+ select_audio_id.append(True)
+ select_videoimage_id.append(False)
+ elif data_list[1] == "video" or data_list[1] == "image":
+ X_video.append(data_list)
+ select_videoimage_id.append(True)
+ select_audio_id.append(False)
+ else:
+ raise NotImplementedError
+
+ if len(X_audio) > 0:
+ Xa_features = torch.cat(X_audio, dim=0)
+ audio_padding_mask = torch.zeros(Xa_features.shape, device=self.device).bool()
+ audio_embedding, T, F = self.get_model().get_audio_tower().extract_features(Xa_features, padding_mask=audio_padding_mask, feature_only=True)
+ Xa_features = self.get_model().mm_projector_a(audio_embedding)
+ Xa_features = Xa_features.view(len(X_audio), -1, Xa_features.shape[-1])
+
+ if len(X_video) > 0:
+ X_features = self.encode_images_or_videos(X_video)
+
+ mm_features = []
+ idx_a, idx_v = 0, 0
+ for audio_idx, videoimage_idx in zip(select_audio_id, select_videoimage_id):
+ if audio_idx and videoimage_idx:
+ mm_features.append(torch.cat([X_features[idx_v], Xa_features[idx_a]], dim=0))
+ idx_a += 1
+ idx_v += 1
+ elif audio_idx:
+ mm_features.append(Xa_features[idx_a])
+ idx_a += 1
+ elif videoimage_idx:
+ mm_features.append(X_features[idx_v])
+ idx_v += 1
+ else:
+ raise NotImplementedError
+ else:
+ data_batch = []
+ for i, (data, modal) in enumerate(images):
+ data_batch.append(data)
+ X_features = torch.cat(data_batch, dim=0)
+ audio_padding_mask = torch.zeros(X_features.shape, device=self.device).bool()
+ audio_embedding, T, F = self.get_model().get_audio_tower().extract_features(X_features,
+ padding_mask=audio_padding_mask, feature_only=True)
+ mm_features = self.get_model().mm_projector_a(audio_embedding)
+ #X_features = X_features.view(len(X_features), -1, X_features.shape[-1])
+
+ new_input_embeds = []
+ new_labels = [] if labels is not None else None
+ cur_mm_idx = 0
+ # replace image/video/audio tokens with pre-computed embeddings
+ for batch_idx, cur_input_ids in enumerate(input_ids):
+ num_multimodals = sum((cur_input_ids == mm_token_idx).sum() for mm_token_idx in MODAL_INDEX_MAP.values())
+ # pure text input
+ if num_multimodals == 0:
+ half_len = cur_input_ids.shape[0] // 2
+ cur_mm_features = mm_features[cur_mm_idx]
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_mm_features[0:0], cur_input_embeds_2], dim=0)
+ new_input_embeds.append(cur_input_embeds)
+ if labels is not None:
+ new_labels.append(labels[batch_idx])
+ cur_mm_idx += 1
+ continue
+
+ cur_new_input_embeds = []
+ if labels is not None:
+ cur_labels = labels[batch_idx]
+ cur_new_labels = []
+ assert cur_labels.shape == cur_input_ids.shape
+
+ mm_token_indices = torch.where(sum([cur_input_ids == mm_token_idx for mm_token_idx in MODAL_INDEX_MAP.values()]))[0]
+ while mm_token_indices.numel() > 0:
+ cur_mm_features = mm_features[cur_mm_idx]
+ mm_token_start = mm_token_indices[0]
+
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:mm_token_start]))
+ cur_new_input_embeds.append(cur_mm_features)
+ if labels is not None:
+ cur_new_labels.append(cur_labels[:mm_token_start])
+ cur_new_labels.append(torch.full((cur_mm_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
+ cur_labels = cur_labels[mm_token_start+1:]
+
+ cur_mm_idx += 1
+ cur_input_ids = cur_input_ids[mm_token_start+1:]
+ mm_token_indices = torch.where(sum([cur_input_ids == mm_token_idx for mm_token_idx in MODAL_INDEX_MAP.values()]))[0]
+
+ if cur_input_ids.numel() > 0:
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
+ if labels is not None:
+ cur_new_labels.append(cur_labels)
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
+ # NOTE: one cur_new_input_embeds per each
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
+ new_input_embeds.append(cur_new_input_embeds)
+ if labels is not None:
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
+ new_labels.append(cur_new_labels)
+
+ # padding
+ if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
+ max_len = max(x.shape[0] for x in new_input_embeds)
+
+ new_input_embeds_align = []
+ for cur_new_embed in new_input_embeds:
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
+ new_input_embeds_align.append(cur_new_embed)
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
+
+ if labels is not None:
+ new_labels_align = []
+ _new_labels = new_labels
+ for cur_new_label in new_labels:
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
+ new_labels_align.append(cur_new_label)
+ new_labels = torch.stack(new_labels_align, dim=0)
+
+ if attention_mask is not None:
+ new_attention_mask = []
+ for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
+ new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
+ new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
+ cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
+ new_attention_mask.append(cur_new_attention_mask)
+ attention_mask = torch.stack(new_attention_mask, dim=0)
+ assert attention_mask.shape == new_labels.shape
+ else:
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
+ if labels is not None:
+ new_labels = torch.stack(new_labels, dim=0)
+
+ if attention_mask is not None:
+ new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
+ assert attention_mask.shape == new_input_embeds.shape[:2]
+
+ return None, attention_mask, past_key_values, new_input_embeds, new_labels
diff --git a/videollama2/model/videollama2_gemma2.py b/videollama2/model/videollama2_gemma2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b57ad3653ce91efbd8f5f5937dea98c2831372a5
--- /dev/null
+++ b/videollama2/model/videollama2_gemma2.py
@@ -0,0 +1,176 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ Gemma2Config, Gemma2Model, Gemma2ForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2Gemma2Config(Gemma2Config):
+ model_type = "videollama2_gemma2"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_gemma2"
+
+
+class Videollama2Gemma2Model(Videollama2MetaModel, Gemma2Model):
+ config_class = Videollama2Gemma2Config
+
+ def __init__(self, config: Gemma2Config):
+ super(Videollama2Gemma2Model, self).__init__(config)
+
+
+class Videollama2Gemma2ForCausalLM(Gemma2ForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2Gemma2Config
+
+ def __init__(self, config, **kwargs):
+ super(Gemma2ForCausalLM, self).__init__(config)
+ self.model = Videollama2Gemma2Model(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[int] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def _prepare_generated_length(self, model_input_name, inputs_tensor, **kwargs):
+ if model_input_name == "inputs_embeds":
+ self.inputs_embeds_length = inputs_tensor.size(1)
+ else:
+ self.inputs_embeds_length = 0
+ return super()._prepare_generated_length(
+ model_input_name=model_input_name,
+ inputs_tensor=inputs_tensor,
+ **kwargs)
+
+ def _get_cache(self, cache_implementation: str, max_batch_size: int, max_cache_len: int, **kwargs):
+ return super()._get_cache(
+ cache_implementation=cache_implementation,
+ max_batch_size=max_batch_size,
+ max_cache_len=max_cache_len + self.inputs_embeds_length,
+ **kwargs)
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_gemma2", Videollama2Gemma2Config)
+AutoModelForCausalLM.register(Videollama2Gemma2Config, Videollama2Gemma2ForCausalLM)
diff --git a/videollama2/model/videollama2_llama.py b/videollama2/model/videollama2_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..7846dbb7cff1213102ed7cba7f2ae163ba806cc4
--- /dev/null
+++ b/videollama2/model/videollama2_llama.py
@@ -0,0 +1,157 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ LlamaConfig, LlamaModel, LlamaForCausalLM
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2LlamaConfig(LlamaConfig):
+ model_type = "videollama2_llama"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_llama"
+
+
+class Videollama2LlamaModel(Videollama2MetaModel, LlamaModel):
+ config_class = Videollama2LlamaConfig
+
+ def __init__(self, config: LlamaConfig):
+ super(Videollama2LlamaModel, self).__init__(config)
+
+
+class Videollama2LlamaForCausalLM(LlamaForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2LlamaConfig
+
+ def __init__(self, config, **kwargs):
+ super(LlamaForCausalLM, self).__init__(config)
+ self.model = Videollama2LlamaModel(config)
+ self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_llama", Videollama2LlamaConfig)
+AutoModelForCausalLM.register(Videollama2LlamaConfig, Videollama2LlamaForCausalLM)
diff --git a/videollama2/model/videollama2_mistral.py b/videollama2/model/videollama2_mistral.py
new file mode 100644
index 0000000000000000000000000000000000000000..d384fe8b941b1a22a577faf5892103ca2edd973e
--- /dev/null
+++ b/videollama2/model/videollama2_mistral.py
@@ -0,0 +1,159 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, PretrainedConfig, \
+ MistralConfig, MistralModel, MistralForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2MistralConfig(MistralConfig):
+ model_type = "videollama2_mistral"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_mistral"
+
+
+class Videollama2MistralModel(Videollama2MetaModel, MistralModel):
+ config_class = Videollama2MistralConfig
+
+ def __init__(self, config: MistralConfig):
+ super(Videollama2MistralModel, self).__init__(config)
+
+
+class Videollama2MistralForCausalLM(MistralForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2MistralConfig
+
+ def __init__(self, config, **kwargs):
+ super(MistralForCausalLM, self).__init__(config)
+ self.model = Videollama2MistralModel(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[int] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_mistral", Videollama2MistralConfig)
+AutoModelForCausalLM.register(Videollama2MistralConfig, Videollama2MistralForCausalLM)
diff --git a/videollama2/model/videollama2_mixtral.py b/videollama2/model/videollama2_mixtral.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc9bea7934c17fad925f1c6ee7775d2cc3024be9
--- /dev/null
+++ b/videollama2/model/videollama2_mixtral.py
@@ -0,0 +1,154 @@
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ MixtralConfig, MixtralModel, MixtralForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2MixtralConfig(MixtralConfig):
+ model_type = "videollama2_mixtral"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_mixtral"
+
+
+class Videollama2MixtralModel(Videollama2MetaModel, MixtralModel):
+ config_class = Videollama2MixtralConfig
+
+ def __init__(self, config: MixtralConfig):
+ super(Videollama2MixtralModel, self).__init__(config)
+
+
+class Videollama2MixtralForCausalLM(MixtralForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2MixtralConfig
+
+ def __init__(self, config, **kwargs):
+ super(MixtralForCausalLM, self).__init__(config)
+ self.model = Videollama2MixtralModel(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[int] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ return super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_mixtral", Videollama2MixtralConfig)
+AutoModelForCausalLM.register(Videollama2MixtralConfig, Videollama2MixtralForCausalLM)
diff --git a/videollama2/model/videollama2_phi3.py b/videollama2/model/videollama2_phi3.py
new file mode 100644
index 0000000000000000000000000000000000000000..f045c09e8fdb2daeab582d91656ab5ad615a40b7
--- /dev/null
+++ b/videollama2/model/videollama2_phi3.py
@@ -0,0 +1,159 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, PretrainedConfig, \
+ Phi3Config, Phi3Model, Phi3ForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2Phi3Config(Phi3Config):
+ model_type = "videollama2_phi3"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_phi3"
+
+
+class Videollama2Phi3Model(Videollama2MetaModel, Phi3Model):
+ config_class = Videollama2Phi3Config
+
+ def __init__(self, config: Phi3Config):
+ super(Videollama2Phi3Model, self).__init__(config)
+
+
+class Videollama2Phi3ForCausalLM(Phi3ForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2Phi3Config
+
+ def __init__(self, config, **kwargs):
+ super(Phi3ForCausalLM, self).__init__(config)
+ self.model = Videollama2Phi3Model(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[int] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_phi3", Videollama2Phi3Config)
+AutoModelForCausalLM.register(Videollama2Phi3Config, Videollama2Phi3ForCausalLM)
diff --git a/videollama2/model/videollama2_qwen2.py b/videollama2/model/videollama2_qwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ccbc1769bd4297d0fc1aa0851aa24976abb0179
--- /dev/null
+++ b/videollama2/model/videollama2_qwen2.py
@@ -0,0 +1,153 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ Qwen2Config, Qwen2Model, Qwen2ForCausalLM
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2Qwen2Config(Qwen2Config):
+ model_type = "videollama2_qwen2"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_qwen2"
+
+
+class Videollama2Qwen2Model(Videollama2MetaModel, Qwen2Model):
+ config_class = Videollama2Qwen2Config
+
+ def __init__(self, config: Videollama2Qwen2Config):
+ super(Videollama2Qwen2Model, self).__init__(config)
+
+
+class Videollama2Qwen2ForCausalLM(Qwen2ForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2Qwen2Config
+
+ def __init__(self, config, **kwargs):
+ super(Qwen2ForCausalLM, self).__init__(config)
+ self.model = Videollama2Qwen2Model(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[int] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ return super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_qwen2", Videollama2Qwen2Config)
+AutoModelForCausalLM.register(Videollama2Qwen2Config, Videollama2Qwen2ForCausalLM)
diff --git a/videollama2/serve/cli.py b/videollama2/serve/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a1fc24a38a9b727392ac74457a896f994891d76
--- /dev/null
+++ b/videollama2/serve/cli.py
@@ -0,0 +1,139 @@
+import argparse
+import torch
+
+from videollama2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, NUM_FRAMES
+from videollama2.conversation import conv_templates, SeparatorStyle
+from videollama2.model.builder import load_pretrained_model
+from videollama2.utils import disable_torch_init
+from videollama2.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, tokenizer_MMODAL_token
+
+from PIL import Image
+from decord import VideoReader, cpu
+
+import requests
+from io import BytesIO
+from transformers import TextStreamer
+
+
+def load_image(image_file):
+ if image_file.startswith('http://') or image_file.startswith('https://'):
+ response = requests.get(image_file)
+ image = Image.open(BytesIO(response.content)).convert('RGB')
+ else:
+ image = Image.open(image_file).convert('RGB')
+ return image
+
+def load_video(video_file):
+ decord_vr = VideoReader(uri=video_file, ctx=cpu(0))
+ duration = len(decord_vr)
+ frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ video = decord_vr.get_batch(frame_id_list)
+ return video
+
+def load_image_or_video(image_or_video_file):
+ if file_path.endswith(('.jpg', '.jpeg', '.png', '.bmp')):
+ return load_image(image_file=image_or_video_file)
+ elif file_path.endswith(('.mp4', '.avi', '.mov')):
+ return load_video(video_file=image_or_video_file)
+ else:
+ raise Exception(f"File type of {image_or_video_file} not supported!!!")
+
+
+def main(args):
+ # Model
+ disable_torch_init()
+
+ model_name = get_model_name_from_path(args.model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
+
+ # if "llama-2" in model_name.lower():
+ # conv_mode = "llava_llama2"
+ # elif "mistral" in model_name.lower():
+ # conv_mode = "mistral"
+ # elif "v1.6-34b" in model_name.lower():
+ # conv_mode = "chatml_direct"
+ # elif "v1" in model_name.lower():
+ # conv_mode = "llava_v1"
+ # else:
+ # conv_mode = "llava_v0"
+ conv_mode = "llava_v1" # fix conversation mode for now
+
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
+ print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
+ else:
+ args.conv_mode = conv_mode
+
+ conv = conv_templates[args.conv_mode].copy()
+ roles = conv.roles
+
+ image = load_image(args.image_file)
+ image_size = image.size
+ # Similar operation in model_worker.py
+ image_tensor = process_images([image], image_processor, model.config)
+ if type(image_tensor) is list:
+ image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
+ else:
+ image_tensor = image_tensor.to(model.device, dtype=torch.float16)
+
+ while True:
+ try:
+ inp = input(f"{roles[0]}: ")
+ except EOFError:
+ inp = ""
+ if not inp:
+ print("exit...")
+ break
+
+ print(f"{roles[1]}: ", end="")
+
+ if image is not None:
+ # first message
+ if model.config.mm_use_im_start_end:
+ inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
+ else:
+ inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
+ conv.append_message(conv.roles[0], inp)
+ image = None
+ else:
+ # later messages
+ conv.append_message(conv.roles[0], inp)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
+ keywords = [stop_str]
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=image_tensor,
+ image_sizes=[image_size],
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ max_new_tokens=args.max_new_tokens,
+ streamer=streamer,
+ use_cache=True)
+
+ outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
+ conv.messages[-1][-1] = outputs
+
+ if args.debug:
+ print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-file", type=str, required=True)
+ parser.add_argument("--device", type=str, default="cuda")
+ parser.add_argument("--conv-mode", type=str, default=None)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--max-new-tokens", type=int, default=512)
+ parser.add_argument("--load-8bit", action="store_true")
+ parser.add_argument("--load-4bit", action="store_true")
+ parser.add_argument("--debug", action="store_true")
+ args = parser.parse_args()
+ main(args)
diff --git a/videollama2/serve/controller.py b/videollama2/serve/controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aeecdf2a4c4da823842d6403cafc3765dbe545a
--- /dev/null
+++ b/videollama2/serve/controller.py
@@ -0,0 +1,298 @@
+"""
+A controller manages distributed workers.
+It sends worker addresses to clients.
+"""
+import argparse
+import asyncio
+import dataclasses
+from enum import Enum, auto
+import json
+import logging
+import time
+from typing import List, Union
+import threading
+
+from fastapi import FastAPI, Request
+from fastapi.responses import StreamingResponse
+import numpy as np
+import requests
+import uvicorn
+
+from videollama2.constants import CONTROLLER_HEART_BEAT_EXPIRATION
+from videollama2.utils import build_logger, server_error_msg
+
+
+logger = build_logger("controller", "controller.log")
+
+
+class DispatchMethod(Enum):
+ LOTTERY = auto()
+ SHORTEST_QUEUE = auto()
+
+ @classmethod
+ def from_str(cls, name):
+ if name == "lottery":
+ return cls.LOTTERY
+ elif name == "shortest_queue":
+ return cls.SHORTEST_QUEUE
+ else:
+ raise ValueError(f"Invalid dispatch method")
+
+
+@dataclasses.dataclass
+class WorkerInfo:
+ model_names: List[str]
+ speed: int
+ queue_length: int
+ check_heart_beat: bool
+ last_heart_beat: str
+
+
+def heart_beat_controller(controller):
+ while True:
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
+ controller.remove_stable_workers_by_expiration()
+
+
+class Controller:
+ def __init__(self, dispatch_method: str):
+ # Dict[str -> WorkerInfo]
+ self.worker_info = {}
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
+
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_controller, args=(self,), daemon=True)
+ self.heart_beat_thread.start()
+
+ logger.info("Init controller")
+
+ def register_worker(self, worker_name: str, check_heart_beat: bool,
+ worker_status: dict):
+ if worker_name not in self.worker_info:
+ logger.info(f"Register a new worker: {worker_name}")
+ else:
+ logger.info(f"Register an existing worker: {worker_name}")
+
+ if not worker_status:
+ worker_status = self.get_worker_status(worker_name)
+ if not worker_status:
+ return False
+
+ self.worker_info[worker_name] = WorkerInfo(
+ worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
+ check_heart_beat, time.time())
+
+ logger.info(f"Register done: {worker_name}, {worker_status}")
+ return True
+
+ def get_worker_status(self, worker_name: str):
+ try:
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
+ except requests.exceptions.RequestException as e:
+ logger.error(f"Get status fails: {worker_name}, {e}")
+ return None
+
+ if r.status_code != 200:
+ logger.error(f"Get status fails: {worker_name}, {r}")
+ return None
+
+ return r.json()
+
+ def remove_worker(self, worker_name: str):
+ del self.worker_info[worker_name]
+
+ def refresh_all_workers(self):
+ old_info = dict(self.worker_info)
+ self.worker_info = {}
+
+ for w_name, w_info in old_info.items():
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
+ logger.info(f"Remove stale worker: {w_name}")
+
+ def list_models(self):
+ model_names = set()
+
+ for w_name, w_info in self.worker_info.items():
+ model_names.update(w_info.model_names)
+
+ return list(model_names)
+
+ def get_worker_address(self, model_name: str):
+ if self.dispatch_method == DispatchMethod.LOTTERY:
+ worker_names = []
+ worker_speeds = []
+ for w_name, w_info in self.worker_info.items():
+ if model_name in w_info.model_names:
+ worker_names.append(w_name)
+ worker_speeds.append(w_info.speed)
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
+ norm = np.sum(worker_speeds)
+ if norm < 1e-4:
+ return ""
+ worker_speeds = worker_speeds / norm
+ if True: # Directly return address
+ pt = np.random.choice(np.arange(len(worker_names)),
+ p=worker_speeds)
+ worker_name = worker_names[pt]
+ return worker_name
+
+ # Check status before returning
+ while True:
+ pt = np.random.choice(np.arange(len(worker_names)),
+ p=worker_speeds)
+ worker_name = worker_names[pt]
+
+ if self.get_worker_status(worker_name):
+ break
+ else:
+ self.remove_worker(worker_name)
+ worker_speeds[pt] = 0
+ norm = np.sum(worker_speeds)
+ if norm < 1e-4:
+ return ""
+ worker_speeds = worker_speeds / norm
+ continue
+ return worker_name
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
+ worker_names = []
+ worker_qlen = []
+ for w_name, w_info in self.worker_info.items():
+ if model_name in w_info.model_names:
+ worker_names.append(w_name)
+ worker_qlen.append(w_info.queue_length / w_info.speed)
+ if len(worker_names) == 0:
+ return ""
+ min_index = np.argmin(worker_qlen)
+ w_name = worker_names[min_index]
+ self.worker_info[w_name].queue_length += 1
+ logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
+ return w_name
+ else:
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
+
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
+ if worker_name not in self.worker_info:
+ logger.info(f"Receive unknown heart beat. {worker_name}")
+ return False
+
+ self.worker_info[worker_name].queue_length = queue_length
+ self.worker_info[worker_name].last_heart_beat = time.time()
+ logger.info(f"Receive heart beat. {worker_name}")
+ return True
+
+ def remove_stable_workers_by_expiration(self):
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
+ to_delete = []
+ for worker_name, w_info in self.worker_info.items():
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
+ to_delete.append(worker_name)
+
+ for worker_name in to_delete:
+ self.remove_worker(worker_name)
+
+ def worker_api_generate_stream(self, params):
+ worker_addr = self.get_worker_address(params["model"])
+ if not worker_addr:
+ logger.info(f"no worker: {params['model']}")
+ ret = {
+ "text": server_error_msg,
+ "error_code": 2,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+ try:
+ response = requests.post(worker_addr + "/worker_generate_stream",
+ json=params, stream=True, timeout=5)
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ yield chunk + b"\0"
+ except requests.exceptions.RequestException as e:
+ logger.info(f"worker timeout: {worker_addr}")
+ ret = {
+ "text": server_error_msg,
+ "error_code": 3,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+ # Let the controller act as a worker to achieve hierarchical
+ # management. This can be used to connect isolated sub networks.
+ def worker_api_get_status(self):
+ model_names = set()
+ speed = 0
+ queue_length = 0
+
+ for w_name in self.worker_info:
+ worker_status = self.get_worker_status(w_name)
+ if worker_status is not None:
+ model_names.update(worker_status["model_names"])
+ speed += worker_status["speed"]
+ queue_length += worker_status["queue_length"]
+
+ return {
+ "model_names": list(model_names),
+ "speed": speed,
+ "queue_length": queue_length,
+ }
+
+
+app = FastAPI()
+
+
+@app.post("/register_worker")
+async def register_worker(request: Request):
+ data = await request.json()
+ controller.register_worker(
+ data["worker_name"], data["check_heart_beat"],
+ data.get("worker_status", None))
+
+
+@app.post("/refresh_all_workers")
+async def refresh_all_workers():
+ models = controller.refresh_all_workers()
+
+
+@app.post("/list_models")
+async def list_models():
+ models = controller.list_models()
+ return {"models": models}
+
+
+@app.post("/get_worker_address")
+async def get_worker_address(request: Request):
+ data = await request.json()
+ addr = controller.get_worker_address(data["model"])
+ return {"address": addr}
+
+
+@app.post("/receive_heart_beat")
+async def receive_heart_beat(request: Request):
+ data = await request.json()
+ exist = controller.receive_heart_beat(
+ data["worker_name"], data["queue_length"])
+ return {"exist": exist}
+
+
+@app.post("/worker_generate_stream")
+async def worker_api_generate_stream(request: Request):
+ params = await request.json()
+ generator = controller.worker_api_generate_stream(params)
+ return StreamingResponse(generator)
+
+
+@app.post("/worker_get_status")
+async def worker_api_get_status(request: Request):
+ return controller.worker_api_get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21001)
+ parser.add_argument("--dispatch-method", type=str, choices=[
+ "lottery", "shortest_queue"], default="shortest_queue")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ controller = Controller(args.dispatch_method)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/gradio_web_server.py b/videollama2/serve/gradio_web_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..2581ccce5240b6be055d963cd6724587fc86d888
--- /dev/null
+++ b/videollama2/serve/gradio_web_server.py
@@ -0,0 +1,499 @@
+import os
+import json
+import time
+import hashlib
+import requests
+import argparse
+import datetime
+
+import numpy as np
+import gradio as gr
+from decord import VideoReader, cpu
+
+from videollama2.constants import LOGDIR, NUM_FRAMES
+from videollama2.conversation import (default_conversation, conv_templates,SeparatorStyle)
+from videollama2.utils import (build_logger, server_error_msg, violates_moderation, moderation_msg)
+
+
+logger = build_logger("gradio_web_server", "gradio_web_server.log")
+
+headers = {"User-Agent": "Videollama2 Client"}
+
+no_change_btn = gr.Button.update()
+enable_btn = gr.Button.update(interactive=True)
+disable_btn = gr.Button.update(interactive=False)
+
+priority = {
+ "vicuna-13b": "aaaaaaa",
+ "koala-13b": "aaaaaab",
+}
+
+
+def get_conv_log_filename():
+ t = datetime.datetime.now()
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
+ return name
+
+
+def get_model_list():
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
+ assert ret.status_code == 200
+ ret = requests.post(args.controller_url + "/list_models")
+ models = ret.json()["models"]
+ models.sort(key=lambda x: priority.get(x, x))
+ logger.info(f"Models: {models}")
+ return models
+
+
+get_window_url_params = """
+function() {
+ const params = new URLSearchParams(window.location.search);
+ url_params = Object.fromEntries(params);
+ console.log(url_params);
+ return url_params;
+ }
+"""
+
+
+def load_demo(url_params, request: gr.Request):
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
+
+ dropdown_update = gr.Dropdown.update(visible=True)
+ if "model" in url_params:
+ model = url_params["model"]
+ if model in models:
+ dropdown_update = gr.Dropdown.update(
+ value=model, visible=True)
+
+ state = default_conversation.copy()
+ return state, dropdown_update
+
+
+def load_demo_refresh_model_list(request: gr.Request):
+ logger.info(f"load_demo. ip: {request.client.host}")
+ models = get_model_list()
+ state = default_conversation.copy()
+ dropdown_update = gr.Dropdown.update(
+ choices=models,
+ value=models[0] if len(models) > 0 else ""
+ )
+ return state, dropdown_update
+
+
+def vote_last_response(state, vote_type, model_selector, request: gr.Request):
+ with open(get_conv_log_filename(), "a") as fout:
+ data = {
+ "tstamp": round(time.time(), 4),
+ "type": vote_type,
+ "model": model_selector,
+ "state": state.dict(),
+ "ip": request.client.host,
+ }
+ fout.write(json.dumps(data) + "\n")
+
+
+def upvote_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"upvote. ip: {request.client.host}")
+ vote_last_response(state, "upvote", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def downvote_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"downvote. ip: {request.client.host}")
+ vote_last_response(state, "downvote", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def flag_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"flag. ip: {request.client.host}")
+ vote_last_response(state, "flag", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def regenerate(state, image_process_mode, request: gr.Request):
+ logger.info(f"regenerate. ip: {request.client.host}")
+ state.messages[-1][-1] = None
+ prev_human_msg = state.messages[-2]
+ if type(prev_human_msg[1]) in (tuple, list):
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
+ state.skip_next = False
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def clear_history(request: gr.Request):
+ logger.info(f"clear_history. ip: {request.client.host}")
+ state = default_conversation.copy()
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def add_text_ori(state, text, image, video, image_process_mode, request: gr.Request):
+ # note: imagebox itself is PIL object while videobox is filepath
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
+ if len(text) <= 0 and image is None:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
+ if args.moderate:
+ flagged = violates_moderation(text)
+ if flagged:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
+ no_change_btn,) * 5
+ assert image is None or video is None, "Please don't feed image and video inputs at the same time!!!"
+ text = text[:1536] # Hard cut-off
+ if image is not None:
+ # here image is the PIL object itself
+ text = text[:1200] # Hard cut-off for images
+ if '' not in text:
+ # text = ' ' + text
+ text = text + '\n'
+ text = (text, image, image_process_mode)
+ if len(state.get_images(return_pil=True)) > 0:
+ state = default_conversation.copy()
+ state.modality = "image"
+ if video is not None:
+ print("Video box:", video)
+ # here video is the file path of video
+ text = text[:1200] # Hard cut-off for images
+ if '' not in text:
+ # text = ' ' + text
+ text = text + '\n'
+ text = (text, video, image_process_mode)
+ if len(state.get_videos(return_pil=True)) > 0:
+ state = default_conversation.copy()
+ state.modality = "video"
+ print("Set modality as video...")
+ state.append_message(state.roles[0], text)
+ state.append_message(state.roles[1], None)
+ state.skip_next = False
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def add_text(state, text, image, video, image_process_mode, request: gr.Request):
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
+
+ # if input is new video or image ,reset the state
+ if image is not None or video is not None:
+ state = default_conversation.copy()
+
+ if len(text) <= 0 and image is None and video is None:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), "", None, None) + (no_change_btn,) * 5
+
+ if args.moderate:
+ flagged = violates_moderation(text)
+ if flagged:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
+
+ # process the input video
+ if video is not None:
+ text = text[:1200] #
+ if '' not in text:
+ text = text + '\n'
+ text = (text, video, image_process_mode)
+ state.modality = "video"
+ # process the input image
+ elif image is not None:
+ text = text[:1200] #
+ if '' not in text:
+ text = text + '\n'
+ text = (text, image, image_process_mode)
+ state.modality = "image"
+ elif state.modality == "image" and len(text)>0:
+ state.modality = "image_text"
+ text = text[:1536] # Hard cut-off
+ elif state.modality == "video" and len(text)>0:
+ state.modality = "video_text"
+ text = text[:1536] # Hard cut-off
+
+ state.append_message(state.roles[0], text)
+ state.append_message(state.roles[1], None)
+ state.skip_next = False
+
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
+ logger.info(f"http_bot. ip: {request.client.host}")
+ start_tstamp = time.time()
+ model_name = model_selector
+
+ if state.skip_next:
+ # This generate call is skipped due to invalid inputs
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
+ return
+
+ if len(state.messages) == state.offset + 2:
+ # First round of conversation
+ if "llava" in model_name.lower():
+ if 'llama-2' in model_name.lower():
+ template_name = "llava_llama2"
+ elif "v1" in model_name.lower():
+ if 'mmtag' in model_name.lower():
+ template_name = "v1_mmtag"
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
+ template_name = "v1_mmtag"
+ else:
+ template_name = "llava_v1"
+ else:
+ if 'mmtag' in model_name.lower():
+ template_name = "v0_mmtag"
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
+ template_name = "v0_mmtag"
+ else:
+ template_name = "llava_v0"
+ elif "llama-2" in model_name:
+ template_name = "llama2"
+ else:
+ template_name = "vicuna_v1"
+ template_name = "llava_v1"
+ new_state = conv_templates[template_name].copy()
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
+ new_state.append_message(new_state.roles[1], None)
+ new_state.modality = state.modality
+ state = new_state
+
+ # Query worker address
+ controller_url = args.controller_url
+ ret = requests.post(controller_url + "/get_worker_address",
+ json={"model": model_name})
+ worker_addr = ret.json()["address"]
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
+
+ # No available worker
+ if worker_addr == "":
+ state.messages[-1][-1] = server_error_msg
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+
+ # Construct prompt
+ prompt = state.get_prompt()
+ if state.modality == "image" or state.modality == "image_text":
+ all_images = state.get_images(return_pil=True) # return PIL.Image object
+ elif state.modality == "video" or state.modality == "video_text":
+ all_images = state.get_videos(return_pil=True) # return video frames where each frame is a PIL.Image object
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
+ for idx, (image, hash) in enumerate(zip(all_images, all_image_hash)):
+ t = datetime.datetime.now()
+ if state.modality == "image" or state.modality == "image_text":
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
+ elif state.modality == "video" or state.modality == "video_text":
+ filename = os.path.join(LOGDIR, "serve_videos", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}_{idx}.jpg")
+ if not os.path.isfile(filename):
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+ image.save(filename)
+
+ # Make requests
+ pload = {
+ "model": model_name,
+ "prompt": prompt,
+ "temperature": float(temperature),
+ "top_p": float(top_p),
+ "max_new_tokens": min(int(max_new_tokens), 1536),
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE] else state.sep2,
+ #"images": f'List of {len(state.get_images())} images: {all_image_hash}',
+ "images": f'List of {len(all_image_hash)} images: {all_image_hash}',
+ }
+ logger.info(f"==== request ====\n{pload}")
+
+ if state.modality == "image" or state.modality == "image_text":
+ pload['images'] = state.get_images()
+ elif state.modality == "video" or state.modality == "video_text":
+ pload['images'] = state.get_videos()
+
+ state.messages[-1][-1] = "â"
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
+
+ try:
+ # Stream output
+ response = requests.post(worker_addr + "/worker_generate_stream",
+ headers=headers, json=pload, stream=True, timeout=10)
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ data = json.loads(chunk.decode())
+ if data["error_code"] == 0:
+ output = data["text"][len(prompt):].strip()
+ state.messages[-1][-1] = output + "â"
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
+ else:
+ output = data["text"] + f" (error_code: {data['error_code']})"
+ state.messages[-1][-1] = output
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+ time.sleep(0.03)
+ except requests.exceptions.RequestException as e:
+ state.messages[-1][-1] = server_error_msg
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
+
+ finish_tstamp = time.time()
+ logger.info(f"{output}")
+
+ with open(get_conv_log_filename(), "a") as fout:
+ data = {
+ "tstamp": round(finish_tstamp, 4),
+ "type": "chat",
+ "model": model_name,
+ "start": round(start_tstamp, 4),
+ "finish": round(start_tstamp, 4),
+ #"state": state.dict(),
+ "images": all_image_hash,
+ "ip": request.client.host,
+ }
+ fout.write(json.dumps(data) + "\n")
+
+title_markdown = ("""
+# The publicl release of VideoLLaMA2
+""")
+
+tos_markdown = ("""
+### Terms of use
+By using this service, users are required to agree to the following terms:
+The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
+Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
+For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
+""")
+
+
+learn_more_markdown = ("""
+### License
+The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
+""")
+
+block_css = """
+
+#buttons button {
+ min-width: min(120px,100%);
+}
+
+"""
+
+def build_demo(embed_mode):
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
+ with gr.Blocks(title="Video-Llama", theme=gr.themes.Default(), css=block_css) as demo:
+ state = gr.State()
+
+ if not embed_mode:
+ gr.Markdown(title_markdown)
+
+ with gr.Row():
+ with gr.Column(scale=3):
+ with gr.Row(elem_id="model_selector_row"):
+ model_selector = gr.Dropdown(
+ choices=models,
+ value=models[0] if len(models) > 0 else "",
+ interactive=True,
+ show_label=False,
+ container=False)
+
+ imagebox = gr.Image(type="pil")
+ videobox = gr.Video()
+ image_process_mode = gr.Radio(
+ ["Crop", "Resize", "Pad", "Default"],
+ value="Default",
+ label="Preprocess for non-square image", visible=False)
+
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
+ gr.Examples(examples=[
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
+ [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
+ [f"{cur_dir}/examples/desert.jpg", "If there are factual errors in the questions, point it out; if not, proceed answering the question. Whatâs happening in the desert?"],
+ ], inputs=[imagebox, textbox], label="Image examples")
+
+ # video example inputs
+ gr.Examples(examples=[
+ [f"{cur_dir}/examples/sample_demo_1.mp4", "Why is this video funny?"],
+ [f"{cur_dir}/examples/sample_demo_3.mp4", "Can you identify any safety hazards in this video?"],
+ [f"{cur_dir}/examples/1034346401.mp4", "What is this young woman doing?"]
+ ], inputs=[videobox, textbox], label="Video examples")
+ #[f"{cur_dir}/examples/sample_demo_9.mp4", "Describe the video in detail and please do not generate repetitive content."]
+
+ with gr.Accordion("Parameters", open=False) as parameter_row:
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
+
+ with gr.Column(scale=8):
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Videollama2 Chatbot", height=550)
+ with gr.Row():
+ with gr.Column(scale=8):
+ textbox.render()
+ with gr.Column(scale=1, min_width=50):
+ submit_btn = gr.Button(value="Send", variant="primary")
+ with gr.Row(elem_id="buttons") as button_row:
+ upvote_btn = gr.Button(value="đ Upvote", interactive=False)
+ downvote_btn = gr.Button(value="đ Downvote", interactive=False)
+ flag_btn = gr.Button(value="â ī¸ Flag", interactive=False)
+ #stop_btn = gr.Button(value="âšī¸ Stop Generation", interactive=False)
+ regenerate_btn = gr.Button(value="đ Regenerate", interactive=False)
+ clear_btn = gr.Button(value="đī¸ Clear", interactive=False)
+
+ if not embed_mode:
+ gr.Markdown(tos_markdown)
+ gr.Markdown(learn_more_markdown)
+ url_params = gr.JSON(visible=False)
+
+ # Register listeners
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
+ upvote_btn.click(upvote_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ downvote_btn.click(downvote_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ flag_btn.click(flag_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ regenerate_btn.click(regenerate, [state, image_process_mode],
+ [state, chatbot, textbox, imagebox, videobox] + btn_list).then(
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+ clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox, videobox] + btn_list)
+
+ textbox.submit(add_text, [state, textbox, imagebox, videobox, image_process_mode], [state, chatbot, textbox, imagebox, videobox] + btn_list
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+ submit_btn.click(add_text, [state, textbox, imagebox, videobox, image_process_mode], [state, chatbot, textbox, imagebox, videobox] + btn_list
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+
+ if args.model_list_mode == "once":
+ demo.load(load_demo, [url_params], [state, model_selector],
+ _js=get_window_url_params)
+ elif args.model_list_mode == "reload":
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector])
+ else:
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
+
+ return demo
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="0.0.0.0")
+ parser.add_argument("--port", type=int)
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
+ parser.add_argument("--concurrency-count", type=int, default=10)
+ parser.add_argument("--model-list-mode", type=str, default="once",
+ choices=["once", "reload"])
+ parser.add_argument("--share", action="store_true")
+ parser.add_argument("--moderate", action="store_true")
+ parser.add_argument("--embed", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ models = get_model_list()
+
+ logger.info(args)
+ demo = build_demo(args.embed)
+ demo.queue(
+ concurrency_count=args.concurrency_count,
+ api_open=False
+ ).launch(
+ server_name=args.host,
+ server_port=args.port,
+ share=args.share
+ )
diff --git a/videollama2/serve/model_worker.py b/videollama2/serve/model_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c58da3cbfd2bf856e1a1d28c46bd17730a54891
--- /dev/null
+++ b/videollama2/serve/model_worker.py
@@ -0,0 +1,397 @@
+"""
+A model worker executes the model.
+"""
+import os
+import json
+import time
+import uuid
+import asyncio
+import requests
+import argparse
+import threading
+from threading import Thread
+from functools import partial
+from typing import Iterator, List, Optional, Tuple
+
+import uvicorn
+from fastapi import FastAPI, Request, BackgroundTasks
+from fastapi.responses import StreamingResponse
+
+import torch
+import decord
+import numpy as np
+from PIL import Image
+from decord import VideoReader, cpu
+from transformers import TextIteratorStreamer
+
+from videollama2.constants import WORKER_HEART_BEAT_INTERVAL
+from videollama2.utils import (build_logger, server_error_msg, pretty_print_semaphore)
+from videollama2.model.builder import load_pretrained_model
+from videollama2.mm_utils import process_images, process_videos, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria, tokenizer_MMODAL_token
+from videollama2.mm_utils import chunk_list, frame_expansion
+from videollama2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_TOKEN, NUM_FRAMES, MMODAL_TOKEN_INDEX
+
+
+GB = 1 << 30
+
+worker_id = str(uuid.uuid4())[:6]
+logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
+global_counter = 0
+
+model_semaphore = None
+
+
+# variable_content = os.getenv('MY_VARIABLE', '')
+# KEYWORDS_LIST = set(variable_content.split('\n'))
+KEYWORDS_LIST = []
+path = 'assets/keywords.txt'
+if os.path.exists(path):
+ with open(path, 'r', encoding='utf-8') as file:
+ for line in file:
+
+ KEYWORDS_LIST.append(line.strip())
+else:
+ KEYWORDS_LIST = []
+
+
+KEYWORD_BLOCK_MESSAGE2 = "The output contains political, erotic and other unsafe content that violates local laws. Please re-enter your question."
+KEYWORD_BLOCK_MESSAGE1 = "Your input question contains political, erotic and other unsafe content that violates local laws. Please re-enter your question."
+STREAM_CHECK_MULTIPLE = 20
+
+
+def heart_beat_worker(controller):
+
+ while True:
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
+ controller.send_heart_beat()
+
+
+def safety_check(text, history=None, ) -> Optional[str]:
+
+ if len(KEYWORDS_LIST) > 0 and any(x in text.lower() for x in KEYWORDS_LIST):
+ print('############')
+ return KEYWORD_BLOCK_MESSAGE2
+
+ return None
+
+
+def input_safety_check(text) -> Optional[str]:
+ if len(KEYWORDS_LIST) > 0 and any(x in text.lower() for x in KEYWORDS_LIST):
+ print('######## Input keyword alarm triggered:', text)
+ return KEYWORD_BLOCK_MESSAGE1
+ return None
+
+
+class ModelWorker:
+
+ def __init__(self, controller_addr, worker_addr,
+ worker_id, no_register,
+ model_path, model_base, model_name,
+ load_8bit, load_4bit, device):
+ self.controller_addr = controller_addr
+ self.worker_addr = worker_addr
+ self.worker_id = worker_id
+ self.model_path = model_path
+ if model_path.endswith("/"):
+ model_path = model_path[:-1]
+ if model_name is None:
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
+ else:
+ self.model_name = model_paths[-1]
+ else:
+ self.model_name = model_name
+
+ self.device = device
+ logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
+ model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device)
+ self.is_multimodal = 'videollama2' in self.model_name.lower() or 'vlb' in self.model_name.lower()
+
+ if not no_register:
+ self.register_to_controller()
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_worker, args=(self,))
+ self.heart_beat_thread.start()
+
+ def register_to_controller(self):
+ logger.info("Register to controller")
+
+ url = self.controller_addr + "/register_worker"
+ data = {
+ "worker_name": self.worker_addr,
+ "check_heart_beat": True,
+ "worker_status": self.get_status()
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
+
+ def send_heart_beat(self):
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
+ f"global_counter: {global_counter}")
+
+ url = self.controller_addr + "/receive_heart_beat"
+
+ while True:
+ try:
+ ret = requests.post(url, json={
+ "worker_name": self.worker_addr,
+ "queue_length": self.get_queue_length()}, timeout=5)
+ exist = ret.json()["exist"]
+ break
+ except requests.exceptions.RequestException as e:
+ logger.error(f"heart beat error: {e}")
+ time.sleep(5)
+
+ if not exist:
+ self.register_to_controller()
+
+ def get_queue_length(self):
+ if model_semaphore is None:
+ return 0
+ else:
+ return args.limit_model_concurrency - model_semaphore._value + (len(
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
+
+ def get_status(self):
+ return {
+ "model_names": [self.model_name],
+ "speed": 1,
+ "queue_length": self.get_queue_length(),
+ }
+
+ @torch.inference_mode()
+ def generate_stream(self, params):
+ tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
+
+ prompt = params["prompt"]
+ ori_prompt = prompt
+ images_or_videos = params.get("images", None)
+ #print("Input images:", images_or_videos)
+ num_image_tokens = 0
+ modal_list = []
+ if images_or_videos is not None and len(images_or_videos) and self.is_multimodal:
+ if len(images_or_videos) > 0:
+ if len(images_or_videos) != prompt.count(DEFAULT_IMAGE_TOKEN) and len(images_or_videos) != (prompt.count(DEFAULT_VIDEO_TOKEN)):
+ raise ValueError("Number of images/videos does not match number of / tokens in prompt")
+
+ try:
+ print("Load image...")
+ images_or_videos = [load_image_from_base64(image) for image in images_or_videos]
+ images_or_videos = process_images(images_or_videos, image_processor, model.config)
+
+ modal_list = ["image"]
+ replace_token = DEFAULT_IMAGE_TOKEN
+ modal_token_index = MMODAL_TOKEN_INDEX["IMAGE"]
+ except:
+ print("Load video instead...")
+ decord_vr = VideoReader(uri=images_or_videos[0], ctx=cpu(0))
+ duration = len(decord_vr)
+ if not "use_taug" in self.model_path:
+ frame_id_list = np.linspace(0, duration-1, 8, dtype=int)
+ video_frames = decord_vr.get_batch(frame_id_list).asnumpy()
+ images_or_videos = process_videos(video_frames, image_processor, model.config)
+ else:
+ print("Temporal augmentation activated!!!")
+ frame_id_list = np.linspace(0, duration-1, 8 * 2 * 2, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list)
+ video_frames = [Image.fromarray(f) for f in video_data.asnumpy()]
+ chunked_video_frames = chunk_list(video_frames, 2*2)
+ expanded_video_frames = [frame_expansion(frame_list, 2) for frame_list in chunked_video_frames]
+ images_or_videos = process_videos(expanded_video_frames, image_processor, model.config)
+
+ # frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ # images_or_videos = decord_vr.get_batch(frame_id_list).asnumpy()
+ # images_or_videos = process_videos(images_or_videos, image_processor, model.config)
+ #print("images_or_videos.shape:", images_or_videos.shape)
+ modal_list = ["video"]
+ replace_token = DEFAULT_VIDEO_TOKEN
+ modal_token_index = MMODAL_TOKEN_INDEX["VIDEO"]
+
+ if type(images_or_videos) is list:
+ images_or_videos = [image.to(self.model.device, dtype=torch.float16) for image in images_or_videos]
+ else:
+ images_or_videos = images_or_videos.to(self.model.device, dtype=torch.float16)
+ if modal_list[0] == "video":
+ print("Video:", images_or_videos.shape)
+ images_or_videos = [images_or_videos]
+ else:
+ print("Image:", images_or_videos.shape)
+
+
+ #image_sizes = [image.size for image in images_or_videos]
+
+
+ # if len(images_or_videos) % NUM_FRAMES == 0:
+ # images_or_videos = process_images(images_or_videos, image_processor, model.config)
+ # #images_or_videos = [image.to(self.model.device, dtype=torch.float16) for image in images_or_videos]
+ # #modal_list = ["image"] * len(images_or_videos)
+ # images_or_videos = images_or_videos.to(self.model.device, dtype=torch.float16)
+ # modal_list = ["video"]
+ # replace_token = DEFAULT_VIDEO_TOKEN
+ # else:
+
+ if getattr(self.model.config, 'mm_use_im_start_end', False):
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
+
+ num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
+ else:
+ images = None
+ modal_list = []
+ image_args = {"images_or_videos": images_or_videos, "modal_list": modal_list}
+ else:
+ images = None
+ image_args = {}
+ print("image_args:", image_args)
+ temperature = float(params.get("temperature", 1.0))
+ top_p = float(params.get("top_p", 1.0))
+ max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
+ stop_str = params.get("stop", None)
+ do_sample = True if temperature > 0.001 else False
+
+ #input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
+ # tokenizer for our video-llama beta
+ input_ids = tokenizer_MMODAL_token(prompt, tokenizer, modal_token_index, return_tensors='pt').unsqueeze(0).to(self.device)
+ #print("Current prompt:", prompt)
+ #print("input_ids.shape:", input_ids.shape)
+ keywords = [stop_str]
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
+
+ max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
+
+ if max_new_tokens < 1:
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
+ return
+
+ thread = Thread(target=model.generate, kwargs=dict(
+ inputs=input_ids,
+ do_sample=do_sample,
+ temperature=temperature,
+ top_p=top_p,
+ max_new_tokens=max_new_tokens,
+ streamer=streamer,
+ stopping_criteria=[stopping_criteria],
+ use_cache=True,
+ **image_args
+ ))
+ thread.start()
+
+ generated_text = ori_prompt
+ token_count = 0
+ for new_text in streamer:
+ generated_text += new_text
+ token_count += len(tokenizer.encode(new_text))
+ if token_count >= STREAM_CHECK_MULTIPLE:
+ safety_message = safety_check(generated_text)
+ if safety_message:
+ print('####### Keyword alarm triggered:', generated_text)
+ yield json.dumps({"text": safety_message , "error_code": 1}).encode() + b"\0"
+ return
+ token_count = 0 #
+
+
+ if generated_text.endswith(stop_str):
+ generated_text = generated_text[:-len(stop_str)]
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
+
+ def generate_stream_gate(self, params):
+ try:
+ input_text = params.get("prompt", "")
+ safety_message = input_safety_check(input_text)
+ if safety_message:
+ yield json.dumps({"text": safety_message, "error_code": 1}).encode() + b"\0"
+ return
+
+ for x in self.generate_stream(params):
+ yield x
+ except ValueError as e:
+ print("Caught ValueError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except torch.cuda.CudaError as e:
+ print("Caught torch.cuda.CudaError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except Exception as e:
+ print("Caught Unknown Error", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+app = FastAPI()
+
+
+def release_model_semaphore(fn=None):
+ model_semaphore.release()
+ if fn is not None:
+ fn()
+
+
+@app.post("/worker_generate_stream")
+async def generate_stream(request: Request):
+ global model_semaphore, global_counter
+ global_counter += 1
+ params = await request.json()
+
+ if model_semaphore is None:
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
+ await model_semaphore.acquire()
+ worker.send_heart_beat()
+ generator = worker.generate_stream_gate(params)
+ background_tasks = BackgroundTasks()
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
+ return StreamingResponse(generator, background=background_tasks)
+
+
+@app.post("/worker_get_status")
+async def get_status(request: Request):
+ return worker.get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21002)
+ parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--model-name", type=str)
+ parser.add_argument("--device", type=str, default="cuda")
+ parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
+ parser.add_argument("--stream-interval", type=int, default=1)
+ parser.add_argument("--no-register", action="store_true")
+ parser.add_argument("--load-8bit", action="store_true")
+ parser.add_argument("--load-4bit", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ if args.multi_modal:
+ logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
+
+ worker = ModelWorker(args.controller_address,
+ args.worker_address,
+ worker_id,
+ args.no_register,
+ args.model_path,
+ args.model_base,
+ args.model_name,
+ args.load_8bit,
+ args.load_4bit,
+ args.device)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/register_worker.py b/videollama2/serve/register_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2c40295e0351f25709ba25554c9329f15bf0d2
--- /dev/null
+++ b/videollama2/serve/register_worker.py
@@ -0,0 +1,26 @@
+"""
+Manually register workers.
+
+Usage:
+python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002
+"""
+
+import argparse
+
+import requests
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--controller-address", type=str)
+ parser.add_argument("--worker-name", type=str)
+ parser.add_argument("--check-heart-beat", action="store_true")
+ args = parser.parse_args()
+
+ url = args.controller_address + "/register_worker"
+ data = {
+ "worker_name": args.worker_name,
+ "check_heart_beat": args.check_heart_beat,
+ "worker_status": None,
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
diff --git a/videollama2/serve/sglang_worker.py b/videollama2/serve/sglang_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3297b7c295abddedfaac7f6fbe882d7b672487d
--- /dev/null
+++ b/videollama2/serve/sglang_worker.py
@@ -0,0 +1,244 @@
+"""
+A model worker executes the model.
+"""
+import argparse
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import json
+import time
+import threading
+import uuid
+
+from fastapi import FastAPI, Request, BackgroundTasks
+from fastapi.responses import StreamingResponse
+import requests
+import re
+import uvicorn
+from functools import partial
+
+from llava.constants import WORKER_HEART_BEAT_INTERVAL
+from llava.utils import (build_logger, server_error_msg,
+ pretty_print_semaphore)
+from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
+from llava.constants import DEFAULT_IMAGE_TOKEN
+
+import sglang as sgl
+from sglang.backend.runtime_endpoint import RuntimeEndpoint
+
+
+GB = 1 << 30
+
+worker_id = str(uuid.uuid4())[:6]
+logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
+global_counter = 0
+
+model_semaphore = None
+
+
+def heart_beat_worker(controller):
+ while True:
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
+ controller.send_heart_beat()
+
+
+@sgl.function
+def pipeline(s, prompt, max_tokens):
+ for p in prompt:
+ if type(p) is str:
+ s += p
+ else:
+ s += sgl.image(p)
+ s += sgl.gen("response", max_tokens=max_tokens)
+
+
+class ModelWorker:
+ def __init__(self, controller_addr, worker_addr, sgl_endpoint,
+ worker_id, no_register, model_name):
+ self.controller_addr = controller_addr
+ self.worker_addr = worker_addr
+ self.worker_id = worker_id
+
+ # Select backend
+ backend = RuntimeEndpoint(sgl_endpoint)
+ sgl.set_default_backend(backend)
+ model_path = backend.model_info["model_path"]
+
+ if model_path.endswith("/"):
+ model_path = model_path[:-1]
+ if model_name is None:
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
+ else:
+ self.model_name = model_paths[-1]
+ else:
+ self.model_name = model_name
+
+ logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
+
+ if not no_register:
+ self.register_to_controller()
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_worker, args=(self,), daemon=True)
+ self.heart_beat_thread.start()
+
+ def register_to_controller(self):
+ logger.info("Register to controller")
+
+ url = self.controller_addr + "/register_worker"
+ data = {
+ "worker_name": self.worker_addr,
+ "check_heart_beat": True,
+ "worker_status": self.get_status()
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
+
+ def send_heart_beat(self):
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
+ f"global_counter: {global_counter}")
+
+ url = self.controller_addr + "/receive_heart_beat"
+
+ while True:
+ try:
+ ret = requests.post(url, json={
+ "worker_name": self.worker_addr,
+ "queue_length": self.get_queue_length()}, timeout=5)
+ exist = ret.json()["exist"]
+ break
+ except requests.exceptions.RequestException as e:
+ logger.error(f"heart beat error: {e}")
+ time.sleep(5)
+
+ if not exist:
+ self.register_to_controller()
+
+ def get_queue_length(self):
+ if model_semaphore is None:
+ return 0
+ else:
+ return args.limit_model_concurrency - model_semaphore._value + (len(
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
+
+ def get_status(self):
+ return {
+ "model_names": [self.model_name],
+ "speed": 1,
+ "queue_length": self.get_queue_length(),
+ }
+
+ async def generate_stream(self, params):
+ ori_prompt = prompt = params["prompt"]
+ images = params.get("images", None)
+ if images is not None and len(images) > 0:
+ if len(images) > 0:
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
+ raise ValueError("Number of images does not match number of tokens in prompt")
+
+ images = [load_image_from_base64(image) for image in images]
+
+ # FIXME: for image-start/end token
+ # replace_token = DEFAULT_IMAGE_TOKEN
+ # if getattr(self.model.config, 'mm_use_im_start_end', False):
+ # replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
+ # prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
+ prompt = prompt.replace(' ' + DEFAULT_IMAGE_TOKEN + '\n', DEFAULT_IMAGE_TOKEN)
+ prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
+ prompt = []
+ for i in range(len(prompt_split)):
+ prompt.append(prompt_split[i])
+ if i < len(images):
+ prompt.append(images[i])
+ else:
+ prompt = [prompt]
+
+ temperature = float(params.get("temperature", 1.0))
+ top_p = float(params.get("top_p", 1.0))
+ # max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
+ stop_str = params.get("stop", None)
+ stop_str = [stop_str] if stop_str is not None else None
+
+ print({'prompt': prompt, 'max_new_tokens': max_new_tokens, 'temperature': temperature, 'top_p': top_p})
+ state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True)
+
+ generated_text = ori_prompt
+ async for text_outputs in state.text_async_iter(var_name="response"):
+ generated_text += text_outputs
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
+
+ async def generate_stream_gate(self, params):
+ try:
+ async for x in self.generate_stream(params):
+ yield x
+ except ValueError as e:
+ print("Caught ValueError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except Exception as e:
+ print("Caught Unknown Error", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+app = FastAPI()
+
+
+def release_model_semaphore(fn=None):
+ model_semaphore.release()
+ if fn is not None:
+ fn()
+
+
+@app.post("/worker_generate_stream")
+async def generate_stream(request: Request):
+ global model_semaphore, global_counter
+ global_counter += 1
+ params = await request.json()
+
+ if model_semaphore is None:
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
+ await model_semaphore.acquire()
+ worker.send_heart_beat()
+ generator = worker.generate_stream_gate(params)
+ background_tasks = BackgroundTasks()
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
+ return StreamingResponse(generator, background=background_tasks)
+
+
+@app.post("/worker_get_status")
+async def get_status(request: Request):
+ return worker.get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21002)
+ parser.add_argument("--worker-address", type=str,
+ default="http://localhost:21002")
+ parser.add_argument("--controller-address", type=str,
+ default="http://localhost:21001")
+ parser.add_argument("--model-name", type=str)
+ parser.add_argument("--sgl-endpoint", type=str)
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
+ parser.add_argument("--stream-interval", type=int, default=1)
+ parser.add_argument("--no-register", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ worker = ModelWorker(args.controller_address,
+ args.worker_address,
+ args.sgl_endpoint,
+ worker_id,
+ args.no_register,
+ args.model_name)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/test_message.py b/videollama2/serve/test_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b090faed0e630b03b2294545050f1f4f5032cad
--- /dev/null
+++ b/videollama2/serve/test_message.py
@@ -0,0 +1,62 @@
+import argparse
+import json
+
+import requests
+
+from llava.conversation import default_conversation
+
+
+def main():
+ if args.worker_address:
+ worker_addr = args.worker_address
+ else:
+ controller_addr = args.controller_address
+ ret = requests.post(controller_addr + "/refresh_all_workers")
+ ret = requests.post(controller_addr + "/list_models")
+ models = ret.json()["models"]
+ models.sort()
+ print(f"Models: {models}")
+
+ ret = requests.post(controller_addr + "/get_worker_address",
+ json={"model": args.model_name})
+ worker_addr = ret.json()["address"]
+ print(f"worker_addr: {worker_addr}")
+
+ if worker_addr == "":
+ return
+
+ conv = default_conversation.copy()
+ conv.append_message(conv.roles[0], args.message)
+ prompt = conv.get_prompt()
+
+ headers = {"User-Agent": "LLaVA Client"}
+ pload = {
+ "model": args.model_name,
+ "prompt": prompt,
+ "max_new_tokens": args.max_new_tokens,
+ "temperature": 0.7,
+ "stop": conv.sep,
+ }
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers,
+ json=pload, stream=True)
+
+ print(prompt.replace(conv.sep, "\n"), end="")
+ for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ data = json.loads(chunk.decode("utf-8"))
+ output = data["text"].split(conv.sep)[-1]
+ print(output, end="\r")
+ print("")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
+ parser.add_argument("--worker-address", type=str)
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
+ parser.add_argument("--max-new-tokens", type=int, default=32)
+ parser.add_argument("--message", type=str, default=
+ "Tell me a story with more than 1000 words.")
+ args = parser.parse_args()
+
+ main()
diff --git a/videollama2/train.py b/videollama2/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..3995296e9a7e65118015d3a4392e2f5e8c035ce5
--- /dev/null
+++ b/videollama2/train.py
@@ -0,0 +1,700 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
+# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
+# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import os
+import copy
+import json
+import random
+import pathlib
+import traceback
+from dataclasses import dataclass, field
+from typing import Dict, Optional, Sequence, List
+
+# torch-related packages
+# NOTE: torch must be imported before transformers. Otherwise, `Segmentation fault (core dumped)` will occur.
+import torch
+from torch.utils.data import Dataset
+
+import transformers
+from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
+
+import sys
+sys.path.append('./')
+from videollama2.model import *
+from videollama2.constants import NUM_FRAMES, IGNORE_INDEX, MODAL_INDEX_MAP
+from videollama2.mm_utils import tokenizer_multimodal_token, process_video, process_image, process_audio_file
+from videollama2.videollama2_trainer import (VideoLLaMA2Trainer,
+ get_peft_state_maybe_zero_3, get_peft_state_non_lora_maybe_zero_3,
+ find_all_linear_names, safe_save_model_for_hf_trainer
+)
+
+# NOTE: fast tokenizer warning issue: https://github.com/huggingface/transformers/issues/5486
+os.environ["TOKENIZERS_PARALLELISM"] = "true"
+
+local_rank = None
+
+
+def rank0_print(*args):
+ if local_rank == 0:
+ print(*args)
+
+
+def set_seed(seed=42):
+ """
+ Set the random seed for reproducible results.
+
+ :param seed: An integer value to be used as the random seed.
+ """
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed) # for multi-GPU setups
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+
+
+@dataclass
+class ModelArguments:
+ # LLM Arguments
+ model_type: Optional[str] = field(default="videollama2", metadata={"help": "Model type selected in the list: " + ", ".join(VLLMs.keys())})
+ model_path: Optional[str] = field(default="lmsys/vicuna-7b-v1.5")
+ version: Optional[str] = field(default="v1", metadata={"help": "Version of the conversation template."})
+ freeze_backbone: bool = field(default=False, metadata={"help": "Whether to freeze the LLM backbone."})
+ tune_adapter_llm: bool = field(default=False)
+ # Connector Arguments
+ mm_projector_type: Optional[str] = field(default='linear')
+ mm_projector_a_type: Optional[str] = field(default='linear')
+ tune_mm_mlp_adapter: bool = field(default=False)
+ tune_mm_mlp_adapter_a: bool = field(default=False)
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
+ pretrain_mm_mlp_adapter_a: Optional[str] = field(default=None)
+ # Vision tower Arguments
+ vision_tower: Optional[str] = field(default=None)
+ mm_vision_select_layer: Optional[int] = field(default=-1)
+ mm_vision_select_feature: Optional[str] = field(default="patch")
+ # Audio tower Arguments
+ audio_tower: Optional[str] = field(default=None)
+ tune_audio_tower: bool = field(default=False)
+
+@dataclass
+class DataArguments:
+ # Path Arguments
+ data_path: str = field(default=None, metadata={"help": "Path to the training data."})
+ data_path_a: Optional[str] = field(default=None, metadata={"help": "Path to the audio data."})
+ # image_folder: Optional[str] = field(default=None)
+ # video_folder: Optional[str] = field(default=None)
+ data_folder: Optional[str] = field(default=None)
+ # Loading Arguments
+ is_multimodal: bool = False
+ va: bool = field(default=False)
+ lazy_preprocess: bool = False
+ num_frames: Optional[int] = field(default=None)
+ # Preprocess Arguments
+ image_aspect_ratio: str = 'square'
+
+
+@dataclass
+class TrainingArguments(transformers.TrainingArguments):
+ optim: str = field(default="adamw_torch")
+ mm_projector_lr: Optional[float] = None
+ freeze_mm_mlp_adapter: bool = field(default=False)
+ remove_unused_columns: bool = field(default=False)
+ cache_dir: Optional[str] = field(default=None)
+ # Training Data Arguments
+ group_by_modality_length: bool = field(default=False)
+ model_max_length: int = field(
+ default=512,
+ metadata={
+ "help":
+ "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
+ },
+ )
+ # Lora or Quant Arguments
+ double_quant: bool = field(
+ default=True,
+ metadata={"help": "Compress the quantization statistics through double quantization."}
+ )
+ quant_type: str = field(
+ default="nf4",
+ metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
+ )
+ bits: int = field(
+ default=16,
+ metadata={"help": "How many bits to use."}
+ )
+ lora_enable: bool = False
+ lora_r: int = 64
+ lora_alpha: int = 16
+ lora_dropout: float = 0.05
+ lora_weight_path: str = ""
+ lora_bias: str = "none"
+
+
+def preprocess_plain(
+ sources: Sequence[str],
+ tokenizer: transformers.PreTrainedTokenizer,
+ modal_token: str = None,
+) -> Dict:
+ roles = {"human": "user", "gpt": "assistant"}
+ conversations = []
+ input_ids = []
+ targets = []
+ #print(sources)
+ for source in sources:
+ # 1. apply chat template for input conversation
+ assert len(source) == 2
+ assert modal_token in source[0]['value']
+ message = [
+ {'role': 'user', 'content': modal_token},
+ {'role': 'assistant', 'content': source[1]['value']}
+ ]
+ conversation = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=False)
+ #print(conversation) // [INST] [/INST] Someone is speaking.
+ # 2. tokenize conversations
+ input_ids.append(tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt'))
+ # 3. make targets
+ targets.append(copy.deepcopy(input_ids[-1]))
+ #print(targets)
+ instruction = tokenizer.apply_chat_template(message[:1], tokenize=False, add_generation_prompt=True)
+ #print(instruction) // [INST] [/INST]
+ instruction_len = len(tokenizer_multimodal_token(instruction, tokenizer, modal_token, return_tensors='pt'))
+ #print(instruction_len) //12
+ targets[-1][:instruction_len] = IGNORE_INDEX
+ # print("instruction: ----------------")
+ # print(instruction)
+ # print("conversation: ----------------")
+ # print(conversation)
+ # print("training targets: ----------------")
+ # print(tokenizer.decode(targets[-1][instruction_len:]))
+ # print(input_ids[-1])
+ # print(targets[-1])
+ return dict(input_ids=input_ids, labels=targets)
+
+
+def preprocess(
+ sources: Sequence[str],
+ tokenizer: transformers.PreTrainedTokenizer,
+ modal_token: str = None,
+) -> Dict:
+ roles = {"human": "user", "gpt": "assistant"}
+
+ # Apply prompt templates
+ conversations = []
+ input_ids = []
+ targets = []
+ for i, source in enumerate(sources):
+ if roles[source[0]["from"]] != "user":
+ # Skip the first one if it is not from human
+ source = source[1:]
+ message = [{'role': roles[sentence['from']], 'content': sentence['value']} for sentence in source]
+ conversation = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=False)
+ #print(conversation)
+ input_ids.append(tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt'))
+ #print(input_ids)
+ targets.append(copy.deepcopy(input_ids[-1]))
+ #print(targets)
+ assert len(source) % 2 == 0, f"Invalid conversation length {len(source)}."
+
+ cur = 0
+ message = []
+ for idx, sentence in enumerate(source):
+ if idx % 2 == 1:
+ tmp_message = [
+ {'role': roles[source[idx-1]['from']], 'content': source[idx-1]['value']},
+ {'role': roles[sentence['from']], 'content': sentence['value']}
+ ]
+
+ instruction = tokenizer.apply_chat_template(message + tmp_message[:1], tokenize=False, add_generation_prompt=True)
+ conversation = tokenizer.apply_chat_template(message + tmp_message, tokenize=False, add_generation_prompt=False)
+
+ instruction_len = len(tokenizer_multimodal_token(instruction, tokenizer, modal_token, return_tensors='pt'))
+ conversation_len = len(tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt'))
+
+ targets[-1][cur:instruction_len] = IGNORE_INDEX
+ #print(targets[-1])
+ cur = conversation_len
+ message += tmp_message
+ return dict(input_ids=input_ids, labels=targets)
+
+
+def preprocess_multimodal(
+ sources: Sequence[str],
+ data_args: DataArguments,
+ modal_token: str = None,
+) -> Dict:
+ is_multimodal = data_args.is_multimodal
+ if not is_multimodal:
+ return sources
+
+ assert modal_token in MODAL_INDEX_MAP, f"Unsupported modal token {modal_token}."
+
+ for source in sources:
+ for sentence in source:
+ if modal_token in sentence['value']:
+ sentence['value'] = sentence['value'].replace(modal_token, '').strip()
+ sentence['value'] = modal_token + '\n' + sentence['value']
+ sentence['value'] = sentence['value'].strip()
+ replace_token = modal_token
+ # TODO: fix this for multimedia, e.g., , , etc.
+ sentence["value"] = sentence["value"].replace(modal_token, replace_token)
+
+ return sources
+
+
+class LazySupervisedDataset(Dataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(self, data_path: str, data_path_a: str,
+ tokenizer: transformers.PreTrainedTokenizer,
+ data_args: DataArguments):
+ super(LazySupervisedDataset, self).__init__()
+ self.mix_sampler_tag = False
+ if data_path is not None and len(data_path.split(",")) == 1:
+ data_path = data_path.split(",")[0]
+ list_data_dict = json.load(open(data_path, "r"))
+ elif data_path is not None and len(data_path.split(",")) > 1:
+ self.mix_sampler_tag = True
+ data_path = data_path.split(",")
+ for path in data_path:
+ if "stage3" in path:
+ self.av_data = json.load(open(path, "r"))
+ random.shuffle(self.av_data)
+ elif "stage2" in path and "audio" in path:
+ self.a_data = json.load(open(path, "r"))
+ random.shuffle(self.a_data)
+ elif "stage2" in path and "video" in path:
+ self.v_data = json.load(open(path, "r"))
+ random.shuffle(self.v_data)
+ else:
+ raise NotImplementedError
+ list_data_dict = self.av_data + self.a_data + self.v_data
+ if data_path_a is not None:
+ list_data_dict = json.load(open(data_path_a, "r"))
+
+ rank0_print("Formatting inputs...Skip in lazy mode")
+ self.tokenizer = tokenizer
+ self.list_data_dict = list_data_dict
+ self.data_args = data_args
+
+ def __len__(self):
+ return len(self.list_data_dict)
+
+ @property
+ def lengths(self):
+ length_list = []
+ for sample in self.list_data_dict:
+ img_tokens = 576 if 'image' in sample else 0
+ length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
+ return length_list
+
+ @property
+ def modality_lengths(self):
+ length_list = []
+ for sample in self.list_data_dict:
+ cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
+ cur_len = cur_len if 'image' in sample else -cur_len
+ length_list.append(cur_len)
+ return length_list
+
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
+ sources = self.list_data_dict[i]
+ if isinstance(i, int):
+ sources = [sources]
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
+ if self.data_args.data_path is not None:
+ image_processor = self.data_args.image_processor
+ video_processor = self.data_args.video_processor
+
+ num_frames = NUM_FRAMES if self.data_args.num_frames is None else self.data_args.num_frames
+
+ if 'image' in sources[0]:
+ image_file = self.list_data_dict[i]['image']
+ image_folder = self.data_args.data_folder
+ image_file = os.path.join(image_folder, image_file)
+
+ try:
+ image = process_image(image_file, image_processor, aspect_ratio=self.data_args.image_aspect_ratio)
+ except:
+ traceback.print_exc()
+ backup_idx = random.randint(0, len(self.list_data_dict) - 1)
+ print(f"Encounted error when reading image {image_file}, use {backup_idx}-th example instead!!!")
+ return self.__getitem__(backup_idx)
+
+ # place tag to question head.
+ modal_token = ""
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, modal_token)
+ elif 'video' in sources[0]:
+ video_file = self.list_data_dict[i]['video']
+ video_folder = self.data_args.data_folder
+ if video_folder:
+ video_file = os.path.join(video_folder, video_file)
+ try:
+ video = process_video(video_file, video_processor, aspect_ratio=self.data_args.image_aspect_ratio, num_frames=num_frames, va = self.data_args.va if not self.mix_sampler_tag else (i < len(self.av_data)))
+ except Exception as e:
+ traceback.print_exc()
+ backup_idx = random.randint(0, len(self.list_data_dict) - 1)
+ print(f"Encounted error when reading video {video_file}, use {backup_idx}-th example instead!!!")
+ return self.__getitem__(backup_idx)
+
+ # place tag to question head.
+ modal_token = ""
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, modal_token)
+
+ elif 'audio' in sources[0]:
+ audio_file = self.list_data_dict[i]['audio']
+ #audio_folder = self.data_args.base_folder
+ #print(audio_file)
+ try:
+ audio = process_audio_file(audio_file)
+ except Exception as e:
+ print(e)
+ backup_idx = random.randint(0, len(self.list_data_dict)-1)
+ print(f"Encounted error when reading audio {audio_file}, use {backup_idx}-th example instead!!!")
+ return self.__getitem__(backup_idx)
+ modal_token = ""
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, modal_token)
+
+ else:
+ modal_token = None
+ sources = copy.deepcopy([e["conversations"] for e in sources])
+
+ if self.data_args.is_pretraining:
+ data_dict = preprocess_plain(sources, self.tokenizer, modal_token=modal_token)
+ else:
+ data_dict = preprocess(sources, self.tokenizer, modal_token=modal_token)
+
+ if isinstance(i, int):
+ data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0])
+
+ # image exist in the data
+ if 'image' in self.list_data_dict[i]:
+ data_dict['image'] = image
+ elif 'video' in self.list_data_dict[i]:
+ data_dict['video'] = video
+ elif 'audio' in self.list_data_dict[i]:
+ data_dict['audio'] = audio
+ elif self.data_args.data_path_a:
+ # image does not exist in the data, but the model is multimodal
+ data_dict['audio'] = torch.zeros(1, 2998, 128)
+ elif self.data_args.is_multimodal:
+ # image does not exist in the data, but the model is multimodal
+ data_dict['image'] = torch.zeros(3, self.data_args.image_size, self.data_args.image_size)
+ return data_dict
+
+
+@dataclass
+class DataCollatorForSupervisedDataset(object):
+ """Collate examples for supervised fine-tuning."""
+
+ tokenizer: transformers.PreTrainedTokenizer
+
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
+ input_ids, labels = tuple([instance[key] for instance in instances]
+ for key in ("input_ids", "labels"))
+ input_ids = torch.nn.utils.rnn.pad_sequence(
+ input_ids,
+ batch_first=True,
+ padding_value=self.tokenizer.pad_token_id)
+ labels = torch.nn.utils.rnn.pad_sequence(labels,
+ batch_first=True,
+ padding_value=IGNORE_INDEX)
+ input_ids = input_ids[:, :self.tokenizer.model_max_length]
+ labels = labels[:, :self.tokenizer.model_max_length]
+ batch = dict(
+ input_ids=input_ids,
+ labels=labels,
+ attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
+ )
+
+ # work for 'images' argument in `prepare_inputs_labels_for_multimodal` of LlavaMetaForCausalLM in llava_arch.py
+ batch['images'] = []
+ for instance in instances:
+ for modal_token in MODAL_INDEX_MAP.keys():
+ modal_token = modal_token.lower()
+ # MODAL_TOKEN shape like: , , ...
+ modal_name = re.findall(f'[<](.*)[>]', modal_token)
+ assert len(modal_name) == 1
+ modal_name = modal_name[0]
+ if modal_name in instance:
+ batch['images'].append((instance[modal_name], modal_name))
+
+ return batch
+
+
+def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
+ data_args) -> Dict:
+ """Make dataset and collator for supervised fine-tuning."""
+ train_dataset = LazySupervisedDataset(
+ tokenizer=tokenizer,
+ data_path=data_args.data_path,
+ data_path_a=data_args.data_path_a,
+ data_args=data_args
+ )
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
+ return dict(train_dataset=train_dataset,
+ eval_dataset=None,
+ data_collator=data_collator)
+
+
+def train(attn_implementation="flash_attention_2"):
+ global local_rank
+ set_seed(42)
+
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+
+ local_rank = training_args.local_rank
+ compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
+
+ bnb_model_from_pretrained_args = {}
+ if training_args.bits in [4, 8]:
+ from transformers import BitsAndBytesConfig
+ bnb_model_from_pretrained_args.update(dict(
+ # device_map={"": training_args.device},
+ # BUG: High version transformers report error:
+ # ValueError: You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing `quantization_config` argument at the same time
+ # load_in_4bit=training_args.bits == 4,
+ # load_in_8bit=training_args.bits == 8,
+ quantization_config=BitsAndBytesConfig(
+ load_in_4bit=training_args.bits == 4,
+ load_in_8bit=training_args.bits == 8,
+ llm_int8_skip_modules=["mm_projector"],
+ llm_int8_threshold=6.0,
+ llm_int8_has_fp16_weight=False,
+ bnb_4bit_compute_dtype=compute_dtype,
+ bnb_4bit_use_double_quant=training_args.double_quant,
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
+ bnb_4bit_quant_storage=compute_dtype,
+ )
+ ))
+
+ config = VLLMConfigs[model_args.model_type].from_pretrained(model_args.model_path, trust_remote_code=True)
+ if 'gemma2' in model_args.model_type:
+ config._attn_implementation = 'eager'
+ else:
+ config._attn_implementation = attn_implementation
+
+ if model_args.vision_tower is not None or model_args.audio_tower is not None:
+ model = VLLMs[model_args.model_type].from_pretrained(
+ model_args.model_path,
+ config=config,
+ cache_dir=training_args.cache_dir,
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
+ do_sample=True,
+ **bnb_model_from_pretrained_args
+ )
+ if 'mixtral' in model_args.model_type:
+ import deepspeed
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
+ else:
+ model = transformers.LlamaForCausalLM.from_pretrained(
+ model_args.model_path,
+ config=config,
+ cache_dir=training_args.cache_dir,
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
+ do_sample=True,
+ **bnb_model_from_pretrained_args
+ )
+ model.config.use_cache = False
+
+
+ if training_args.bits in [4, 8]:
+ from peft import prepare_model_for_kbit_training
+ model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
+
+ if training_args.gradient_checkpointing:
+ if hasattr(model, "enable_input_require_grads"):
+ model.enable_input_require_grads()
+ else:
+ def make_inputs_require_grad(module, input, output):
+ output.requires_grad_(True)
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
+
+ if training_args.lora_enable:
+ from peft import LoraConfig, get_peft_model
+ lora_config = LoraConfig(
+ r=training_args.lora_r,
+ lora_alpha=training_args.lora_alpha,
+ target_modules=find_all_linear_names(model),
+ lora_dropout=training_args.lora_dropout,
+ bias=training_args.lora_bias,
+ task_type="CAUSAL_LM",
+ )
+ if training_args.bits == 16:
+ if training_args.bf16:
+ model.to(torch.bfloat16)
+ if training_args.fp16:
+ model.to(torch.float16)
+ rank0_print("Adding LoRA adapters...")
+ model = get_peft_model(model, lora_config)
+
+
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
+ model_args.model_path,
+ cache_dir=training_args.cache_dir,
+ model_max_length=training_args.model_max_length,
+ padding_side="right",
+ use_fast=True,
+ )
+
+ if tokenizer.pad_token is None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ if model_args.vision_tower is not None:
+ # initialize vision encoder + multi-modal projector
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
+
+ vision_tower = model.get_vision_tower()
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
+
+ data_args.image_size = vision_tower.image_size
+
+ data_args.image_processor = vision_tower.image_processor
+ data_args.video_processor = vision_tower.video_processor if hasattr(vision_tower, "video_processor") else vision_tower.image_processor
+
+ data_args.is_multimodal = True
+
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
+ model.config.tokenizer_padding_side = tokenizer.padding_side
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
+
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
+ if model_args.tune_mm_mlp_adapter:
+ model.requires_grad_(False)
+ for p in model.get_model().mm_projector.parameters():
+ p.requires_grad = True
+
+ if model_args.tune_mm_mlp_adapter:
+ data_args.is_pretraining = True
+ else:
+ data_args.is_pretraining = False
+
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
+ if training_args.freeze_mm_mlp_adapter:
+ for p in model.get_model().mm_projector.parameters():
+ p.requires_grad = False
+
+ if training_args.bits in [4, 8]:
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
+
+ model.config.mm_projector_lr = training_args.mm_projector_lr
+ model.config.num_frames = NUM_FRAMES if data_args.num_frames is None else data_args.num_frames
+
+
+ if model_args.audio_tower is not None:
+ # initialize audio encoder + multi-modal projector
+ model.get_model().initialize_audio_modules(
+ model_args=model_args,
+ fsdp=training_args.fsdp
+ )
+
+ audio_tower = model.get_audio_tower()
+ audio_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
+ data_args.is_multimodal = True
+ model.config.tokenizer_padding_side = tokenizer.padding_side
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
+
+ model.config.tune_mm_mlp_adapter_a = training_args.tune_mm_mlp_adapter_a = model_args.tune_mm_mlp_adapter_a
+ training_args.pretrain_mm_mlp_adapter_a = model_args.pretrain_mm_mlp_adapter_a
+ training_args.tune_audio_tower = model_args.tune_audio_tower
+ # only update mm_mlp's parameters while the remaining ones are kept frozen
+ if model_args.tune_mm_mlp_adapter_a:
+ model.requires_grad_(False)
+ for p in model.get_model().mm_projector_a.parameters():
+ p.requires_grad = True
+
+ if model_args.tune_audio_tower or model_args.tune_adapter_llm:
+ data_args.is_pretraining = False
+ else:
+ data_args.is_pretraining = True
+
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
+ if training_args.freeze_mm_mlp_adapter:
+ for p in model.get_model().mm_projector_a.parameters():
+ p.requires_grad = False
+
+ if model_args.tune_adapter_llm:
+ model.requires_grad_(True)
+ if hasattr(model.get_model(), 'vision_tower'):
+ for p in model.get_model().vision_tower.parameters():
+ p.requires_grad = False
+ for p in model.get_model().audio_tower.parameters():
+ p.requires_grad = False
+
+ if model_args.freeze_backbone:
+ model.requires_grad_(False)
+
+ if model_args.tune_audio_tower:
+ for p in model.get_model().audio_tower.parameters():
+ p.requires_grad = True
+ else:
+ for p in model.get_model().audio_tower.parameters():
+ p.requires_grad = False
+
+ if training_args.bits in [4, 8]:
+ model.get_model().mm_projector_a.to(dtype=compute_dtype, device=training_args.device)
+
+ model.config.mm_projector_lr = training_args.mm_projector_lr
+
+ if training_args.bits in [4, 8]:
+ from peft.tuners.lora import LoraLayer
+ for name, module in model.named_modules():
+ if isinstance(module, LoraLayer):
+ if training_args.bf16:
+ module = module.to(torch.bfloat16)
+ if 'norm' in name:
+ module = module.to(torch.float32)
+ if 'lm_head' in name or 'embed_tokens' in name:
+ if hasattr(module, 'weight'):
+ if training_args.bf16 and module.weight.dtype == torch.float32:
+ module = module.to(torch.bfloat16)
+
+ print("Current model:", model)
+ '''
+ for name, param in model.named_parameters():
+ # Check if the parameter requires gradient
+ if param.requires_grad:
+ print(f'Parameter: {name} is trainable')
+ else:
+ print(f'Parameter: {name} is frozen')
+ '''
+
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
+ # select a Trainer
+ trainer = VideoLLaMA2Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
+ trainer.train(resume_from_checkpoint=True)
+ else:
+ trainer.train()
+ trainer.save_state()
+
+ model.config.use_cache = True
+
+ if training_args.lora_enable:
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
+ model.config.save_pretrained(training_args.output_dir)
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
+ else:
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
+
+
+if __name__ == "__main__":
+ train()
diff --git a/videollama2/train_flash_attn.py b/videollama2/train_flash_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..14941d7197ff1be476b9f7db49f55a5bc87758db
--- /dev/null
+++ b/videollama2/train_flash_attn.py
@@ -0,0 +1,12 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
+# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
+# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn.
+
+import sys
+sys.path.append('./')
+
+from videollama2.train import train
+
+if __name__ == "__main__":
+ train(attn_implementation="flash_attention_2")
diff --git a/videollama2/utils.py b/videollama2/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9f161afab1cf556197a578ef2e90ef973b7574d
--- /dev/null
+++ b/videollama2/utils.py
@@ -0,0 +1,126 @@
+import datetime
+import logging
+import logging.handlers
+import os
+import sys
+
+import requests
+
+from .constants import LOGDIR
+
+server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
+moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
+
+handler = None
+
+
+def build_logger(logger_name, logger_filename):
+ global handler
+
+ formatter = logging.Formatter(
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+
+ # Set the format of root handlers
+ if not logging.getLogger().handlers:
+ logging.basicConfig(level=logging.INFO)
+ logging.getLogger().handlers[0].setFormatter(formatter)
+
+ # Redirect stdout and stderr to loggers
+ stdout_logger = logging.getLogger("stdout")
+ stdout_logger.setLevel(logging.INFO)
+ sl = StreamToLogger(stdout_logger, logging.INFO)
+ sys.stdout = sl
+
+ stderr_logger = logging.getLogger("stderr")
+ stderr_logger.setLevel(logging.ERROR)
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
+ sys.stderr = sl
+
+ # Get logger
+ logger = logging.getLogger(logger_name)
+ logger.setLevel(logging.INFO)
+
+ # Add a file handler for all loggers
+ if handler is None:
+ os.makedirs(LOGDIR, exist_ok=True)
+ filename = os.path.join(LOGDIR, logger_filename)
+ handler = logging.handlers.TimedRotatingFileHandler(
+ filename, when='D', utc=True, encoding='UTF-8')
+ handler.setFormatter(formatter)
+
+ for name, item in logging.root.manager.loggerDict.items():
+ if isinstance(item, logging.Logger):
+ item.addHandler(handler)
+
+ return logger
+
+
+class StreamToLogger(object):
+ """
+ Fake file-like stream object that redirects writes to a logger instance.
+ """
+ def __init__(self, logger, log_level=logging.INFO):
+ self.terminal = sys.stdout
+ self.logger = logger
+ self.log_level = log_level
+ self.linebuf = ''
+
+ def __getattr__(self, attr):
+ return getattr(self.terminal, attr)
+
+ def write(self, buf):
+ temp_linebuf = self.linebuf + buf
+ self.linebuf = ''
+ for line in temp_linebuf.splitlines(True):
+ # From the io.TextIOWrapper docs:
+ # On output, if newline is None, any '\n' characters written
+ # are translated to the system default line separator.
+ # By default sys.stdout.write() expects '\n' newlines and then
+ # translates them so this is still cross platform.
+ if line[-1] == '\n':
+ self.logger.log(self.log_level, line.rstrip())
+ else:
+ self.linebuf += line
+
+ def flush(self):
+ if self.linebuf != '':
+ self.logger.log(self.log_level, self.linebuf.rstrip())
+ self.linebuf = ''
+
+
+def disable_torch_init():
+ """
+ Disable the redundant torch default initialization to accelerate model creation.
+ """
+ import torch
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
+
+
+def violates_moderation(text):
+ """
+ Check whether the text violates OpenAI moderation API.
+ """
+ url = "https://api.openai.com/v1/moderations"
+ headers = {"Content-Type": "application/json",
+ "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
+ text = text.replace("\n", "")
+ data = "{" + '"input": ' + f'"{text}"' + "}"
+ data = data.encode("utf-8")
+ try:
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
+ flagged = ret.json()["results"][0]["flagged"]
+ except requests.exceptions.RequestException as e:
+ flagged = False
+ except KeyError as e:
+ flagged = False
+
+ return flagged
+
+
+def pretty_print_semaphore(semaphore):
+ if semaphore is None:
+ return "None"
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
diff --git a/videollama2/videollama2_trainer.py b/videollama2/videollama2_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff9274536ff78c00e21aa49947d4d0150d678313
--- /dev/null
+++ b/videollama2/videollama2_trainer.py
@@ -0,0 +1,447 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA/blob/main/llava/train/llava_trainer.py
+import os
+import logging
+from typing import List, Optional
+
+import torch
+import torch.nn as nn
+from torch.utils.data import Sampler
+
+from transformers import Trainer
+from transformers.trainer import (
+ is_sagemaker_mp_enabled,
+ get_parameter_names,
+ has_length,
+ ALL_LAYERNORM_LAYERS,
+ logger,
+ TRAINER_STATE_NAME,
+)
+
+
+def maybe_zero_3(param, ignore_status=False, name=None):
+ from deepspeed import zero
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
+ if hasattr(param, "ds_id"):
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
+ if not ignore_status:
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
+ with zero.GatheredParameters([param]):
+ param = param.data.detach().cpu().clone()
+ else:
+ param = param.detach().cpu().clone()
+ return param
+
+
+def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
+ to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
+ return to_return
+
+
+# Borrowed from peft.utils.get_peft_model_state_dict
+def get_peft_state_maybe_zero_3(named_params, bias):
+ if bias == "none":
+ to_return = {k: t for k, t in named_params if "lora_" in k}
+ elif bias == "all":
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
+ elif bias == "lora_only":
+ to_return = {}
+ maybe_lora_bias = {}
+ lora_bias_names = set()
+ for k, t in named_params:
+ if "lora_" in k:
+ to_return[k] = t
+ bias_name = k.split("lora_")[0] + "bias"
+ lora_bias_names.add(bias_name)
+ elif "bias" in k:
+ maybe_lora_bias[k] = t
+ for k, t in maybe_lora_bias:
+ if bias_name in lora_bias_names:
+ to_return[bias_name] = t
+ else:
+ raise NotImplementedError
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
+ return to_return
+
+
+def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
+ if require_grad_only:
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
+ return to_return
+
+
+def find_all_linear_names(model):
+ cls = torch.nn.Linear
+ lora_module_names = set()
+ multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
+ for name, module in model.named_modules():
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
+ continue
+ if isinstance(module, cls):
+ names = name.split('.')
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
+
+ if 'lm_head' in lora_module_names: # needed for 16-bit
+ lora_module_names.remove('lm_head')
+ return list(lora_module_names)
+
+
+def safe_save_model_for_hf_trainer(trainer: Trainer,
+ output_dir: str):
+ """Collects the state dict and dump to disk."""
+
+ if getattr(trainer.args, "tune_mm_mlp_adapter", False):
+ # Only save Adapter
+ keys_to_match = ['mm_projector']
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
+ trainer.model.config.save_pretrained(output_dir)
+
+ current_folder = output_dir.split('/')[-1]
+ parent_folder = os.path.dirname(output_dir)
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
+ if current_folder.startswith('checkpoint-'):
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
+ os.makedirs(mm_projector_folder, exist_ok=True)
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
+ else:
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
+ return
+
+ elif getattr(trainer.args, "tune_mm_mlp_adapter_a", False):
+ # Only save Adapter
+ keys_to_match = ['mm_projector_a']
+ if getattr(trainer.args, "use_im_start_end", False):
+ keys_to_match.extend(['embed_tokens', 'embed_in'])
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
+ trainer.model.config.save_pretrained(output_dir)
+
+ current_folder = output_dir.split('/')[-1]
+ parent_folder = os.path.dirname(output_dir)
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
+ if current_folder.startswith('checkpoint-'):
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector_a")
+ os.makedirs(mm_projector_folder, exist_ok=True)
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
+ else:
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector_a.bin'))
+
+ elif getattr(trainer.args, "pretrain_mm_mlp_adapter_a", False):
+ # Only save Adapter
+ keys_to_match = ['mm_projector_a']
+ if getattr(trainer.args, "use_im_start_end", False):
+ keys_to_match.extend(['embed_tokens', 'embed_in'])
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
+ trainer.model.config.save_pretrained(output_dir)
+
+ current_folder = output_dir.split('/')[-1]
+ parent_folder = os.path.dirname(output_dir)
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
+ if current_folder.startswith('checkpoint-'):
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector_a")
+ os.makedirs(mm_projector_folder, exist_ok=True)
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
+ else:
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector_a.bin'))
+
+ if getattr(trainer.args, "tune_audio_tower", False):
+ # Only save Adapter
+ keys_to_match = ['audio_tower']
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
+ trainer.model.config.save_pretrained(output_dir)
+
+ current_folder = output_dir.split('/')[-1]
+ parent_folder = os.path.dirname(output_dir)
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
+ if current_folder.startswith('checkpoint-'):
+ mm_projector_folder = os.path.join(parent_folder, "audio_tower")
+ os.makedirs(mm_projector_folder, exist_ok=True)
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
+ else:
+ torch.save(weight_to_save, os.path.join(output_dir, f'audio_tower.bin'))
+
+ if trainer.deepspeed:
+ torch.cuda.synchronize()
+ trainer.save_model(output_dir)
+ return
+
+ state_dict = trainer.model.state_dict()
+ if trainer.args.should_save:
+ cpu_state_dict = {
+ key: value.cpu()
+ for key, value in state_dict.items()
+ }
+ del state_dict
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
+
+
+def split_to_even_chunks(indices, lengths, num_chunks):
+ """
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
+ """
+ if len(indices) % num_chunks != 0:
+ return [indices[i::num_chunks] for i in range(num_chunks)]
+ num_indices_per_chunk = len(indices) // num_chunks
+ chunks = [[] for _ in range(num_chunks)]
+ chunks_lengths = [0 for _ in range(num_chunks)]
+ for index in indices:
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
+ chunks[shortest_chunk].append(index)
+ chunks_lengths[shortest_chunk] += lengths[index]
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
+ chunks_lengths[shortest_chunk] = float("inf")
+ return chunks
+
+
+def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
+ assert all(l != 0 for l in lengths), "Should not have zero length."
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
+ # all samples are in the same modality
+ return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator)
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
+
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
+ megabatch_size = world_size * batch_size
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
+
+ last_mm = mm_megabatches[-1]
+ last_lang = lang_megabatches[-1]
+ additional_batch = last_mm + last_lang
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
+ megabatches = [megabatches[i] for i in megabatch_indices]
+
+ if len(additional_batch) > 0:
+ megabatches.append(sorted(additional_batch))
+
+ return [i for megabatch in megabatches for i in megabatch]
+
+
+def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
+ indices = torch.randperm(len(lengths), generator=generator)
+ megabatch_size = world_size * batch_size
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
+
+
+class LengthGroupedSampler(Sampler):
+ r"""
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
+ keeping a bit of randomness.
+ """
+
+ def __init__(
+ self,
+ batch_size: int,
+ world_size: int,
+ lengths: Optional[List[int]] = None,
+ generator=None,
+ group_by_modality: bool = False,
+ ):
+ if lengths is None:
+ raise ValueError("Lengths must be provided.")
+
+ self.batch_size = batch_size
+ self.world_size = world_size
+ self.lengths = lengths
+ self.generator = generator
+ self.group_by_modality = group_by_modality
+
+ def __len__(self):
+ return len(self.lengths)
+
+ def __iter__(self):
+ if self.group_by_modality:
+ indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
+ else:
+ indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
+ return iter(indices)
+
+
+class MixSampler(Sampler):
+ def __init__(self, dataset, batch_size=4):
+ self.dataset = dataset
+ self.av_count = len(dataset.av_data)
+ self.a_count = len(dataset.a_data)
+ self.v_count = len(dataset.v_data)
+ self.batch_size = batch_size
+
+ def __iter__(self):
+ for i in range(0, self.av_count, 2):
+ if i + 1 == self.av_count:
+ break
+ batch_ids = [i, i+1]
+
+ audio_index = i % self.a_count
+ batch_ids.append(self.av_count + audio_index)
+ video_index = i % self.v_count
+ batch_ids.append(self.av_count + self.a_count + video_index)
+
+ for x in batch_ids:
+ yield x
+
+ def __len__(self):
+ return self.av_count * 2
+
+
+class VideoLLaMA2Trainer(Trainer):
+
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
+ if self.train_dataset is None or not has_length(self.train_dataset):
+ return None
+ if self.train_dataset.mix_sampler_tag:
+ assert self.args.train_batch_size % 4 == 0
+ return MixSampler(self.train_dataset, self.args.train_batch_size * self.args.gradient_accumulation_steps)
+
+ if self.args.group_by_modality_length:
+ lengths = self.train_dataset.modality_lengths
+ return LengthGroupedSampler(
+ self.args.train_batch_size,
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps,
+ lengths=lengths,
+ group_by_modality=True,
+ )
+ else:
+ return super()._get_train_sampler()
+
+ def create_optimizer(self):
+ """
+ Setup the optimizer.
+
+ We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
+ Trainer's init through `optimizers`, or subclass and override this method in a subclass.
+ """
+ if is_sagemaker_mp_enabled():
+ return super().create_optimizer()
+
+ opt_model = self.model
+
+ if self.optimizer is None:
+ decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
+ if self.args.mm_projector_lr is not None:
+ projector_parameters = [name for name, _ in opt_model.named_parameters() if "mm_projector" in name]
+ optimizer_grouped_parameters = [
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ "lr": self.args.mm_projector_lr,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ "lr": self.args.mm_projector_lr,
+ },
+ ]
+ else:
+ optimizer_grouped_parameters = [
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ },
+ ]
+
+ optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args)
+
+ self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
+ if optimizer_cls.__name__ == "Adam8bit":
+ import bitsandbytes
+
+ manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
+
+ skipped = 0
+ for module in opt_model.modules():
+ if isinstance(module, nn.Embedding):
+ skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values())
+ logger.info(f"skipped {module}: {skipped/2**20}M params")
+ manager.register_module_override(module, "weight", {"optim_bits": 32})
+ logger.debug(f"bitsandbytes: will optimize {module} in fp32")
+ logger.info(f"skipped: {skipped/2**20}M params")
+
+ return self.optimizer
+
+ def _save_checkpoint(self, model, trial, metrics=None):
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
+
+ run_dir = self._get_output_dir(trial=trial)
+ output_dir = os.path.join(run_dir, checkpoint_folder)
+
+ # Only save Adapter
+ keys_to_match = ['mm_projector', 'vision_resampler']
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
+
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
+ self.model.config.save_pretrained(output_dir)
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
+ # Save optimizer and scheduler
+ self._save_optimizer_and_scheduler(output_dir)
+ # Save RNG state
+ self._save_rng_state(output_dir)
+ self.state.save_to_json(os.path.join(output_dir, TRAINER_STATE_NAME))
+ self.args.distributed_state.wait_for_everyone()
+ else:
+ # NOTE: Supporting save complete lora checkpoint during training.
+ if self.args.lora_enable:
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
+
+ run_dir = self._get_output_dir(trial=trial)
+ output_dir = os.path.join(run_dir, checkpoint_folder)
+
+ state_dict = get_peft_state_maybe_zero_3(self.model.named_parameters(), self.args.lora_bias)
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(self.model.named_parameters())
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
+ # save for acquring `config.json`
+ self.model.config.save_pretrained(output_dir)
+ # save for acquring `adapter_config.json`, `adapter_model.bin`
+ # self.model.save_pretrained(output_dir, state_dict=state_dict)
+ torch.save(non_lora_state_dict, os.path.join(output_dir, 'non_lora_trainables.bin'))
+
+ # save for acquring lora adapter parameters & trainer states: `adapter_config.json`, `adapter_model.safetensors`
+ super(VideoLLaMA2Trainer, self)._save_checkpoint(model, trial, metrics)
+ else:
+ super(VideoLLaMA2Trainer, self)._save_checkpoint(model, trial, metrics)
+
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
+ pass
+ else:
+ super(VideoLLaMA2Trainer, self)._save(output_dir, state_dict)