diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..5febc5f8c6599b10f1132897925c305eee622d5e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,7 @@ 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
+data/IT_data/T-T+X_data/audio_t2x.json filter=lfs diff=lfs merge=lfs -text
+data/IT_data/T-T+X_data/image_t2x.json filter=lfs diff=lfs merge=lfs -text
+data/IT_data/T-T+X_data/video_t2x.json filter=lfs diff=lfs merge=lfs -text
+figures/demo.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..a03164857dacfceb0de215a15e40fa2612cd9fcd
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+__pycache__/
+.idea
\ No newline at end of file
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..7059d4adb9115845347d574009a98ecc914cb7ee
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,13 @@
+BSD 3-Clause License
+
+Copyright 2023 Shengqiong Wu All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/README.md b/README.md
index e7d90ddb789e264c5ea4a99dccd0b911883df4c5..69259f3750de7bd025535229075aba1c20992db5 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,417 @@
----
-license: unknown
----
+# NExT-GPT: Any-to-Any Multimodal LLM
+[Shengqiong Wu](https://chocowu.github.io/), [Hao Fei](http://haofei.vip/)*, [Leigang Qu](#), [Wei Ji](https://jiwei0523.github.io/), and [Tat-Seng Chua](https://www.chuatatseng.com/).
+(*Correspondence )
+
+**[NExT++](https://www.nextcenter.org/), School of Computing, National University of Singapore**
+
+-----
+
+
+
+
+
+[](https://www.youtube.com/watch?v=aqw2SCWeWD0)
+
+
+This repository hosts the code, data and model weight of **NExT-GPT**, the first end-to-end MM-LLM that perceives input and generates output in arbitrary combinations (any-to-any) of text, image, video, and audio and beyond.
+
+
+
+-----------
+
+## 🎉 News
+
+- [x] [2023.09.15] 🚀🚀 Release the code of NExT-GPT in version `7b_tiva_v0`.
+- [x] [2023.09.27] 🔨🧩 Added modality-blended batch sampler .
+- [x] [2023.10.01] 📢📢 Release the T2M instruction dataset.
+- [x] [2023.10.04] 👏👏 Release the checkpoint of NExT-GPT in version [7b_tiva_v0](https://huggingface.co/ChocoWu/nextgpt_7b_tiva_v0) .
+- [x] [2023.10.15] 🔨🚀 Update of NExT-GPT in version [7b_tiva_v0](https://huggingface.co/ChocoWu/nextgpt_7b_tiva_v0) .
+
+
+## 👉 TODO
+- [ ] Release MosIT data.
+- [ ] Updating NExT-GPT in more types&sizes of LLMs.
+- [ ] Empowering NExT-GPT with more modalities of inputs&outputs.
+- [ ] ...
+
+
+
+-----------
+
+## Example Demos
+Here we showcase examples generated from NExT-GPT.
+For more examples, kindly visit the [webpage](https://next-gpt.github.io/), or the online live [demo](https://acc414b22d6839d28f.gradio.live).
+
+
+https://github.com/NExT-GPT/NExT-GPT/assets/18722770/0c2b3d88-a533-4899-ab44-65580fe54538
+
+
+https://github.com/NExT-GPT/NExT-GPT/assets/18722770/eb1319a6-38aa-4546-a96e-163207e7de93
+
+
+https://github.com/NExT-GPT/NExT-GPT/assets/18722770/36bec0ad-9bad-4bcf-bc37-92b028f1bc6a
+
+
+
+
+
+## Brief Introduction
+
+
+NExt-GPT is built on top of existing pre-trained LLM, multimodal encoder and SoTA diffusion models, with sufficient end-to-end instruction tuning.
+
+
+
+
+
+- **Multimodal Encoding Stage.** Leveraging established encoders to encode inputs in various modalities, where these representations are projected into language-like representations comprehensible to the LLM through a projection layer.
+- **LLM Understanding and Reasoning Stage.** Harnessing an existing open-sourced LLM as the core to process input information for semantic understanding and reasoning. The LLM not only directly generates text tokens but also produces unique “modality signal” tokens that serve as instructions to dictate the decoding layers whether & what modal content to output correspondingly.
+- **Multimodal Generation Stage.** Receiving the multimodal signals with specific instructions from LLM (if any), the Transformer-based output projection layers map the signal token representations into the ones that are understandable to following multimodal decoders.
+
+
+For more technical details, kindly refer to the [paper](https://arxiv.org/pdf/2309.05519.pdf).
+
+
+-----------
+
+
+
+
+## Getting Started
+
+
+
+
+
+### Table of Contents:
+* 1. Code Structure
+* 2. Environment Preparation
+* 3. Training/Adapting NExt-GPT on Your Own
+ * 3.1. Preparing Pre-trained Checkpoint
+ * 3.2. Preparing Dataset
+ * 3.3. Precomputing Embeddings
+ * 3.4. Training NExT-GPT
+* 4. Running NExT-GPT System
+ * 4.1. Preparing checkpoints
+ * 4.2. Deploying Demo System
+
+****
+
+
+
+
+
+
+
+### 1. Code Structure
+
+```
+├── figures
+├── data
+│ ├── T-X_pair_data
+│ │ ├── audiocap # text-autio pairs data
+│ │ │ ├── audios # audio files
+│ │ │ └── audiocap.json # the audio captions
+│ │ ├── cc3m # text-image paris data
+│ │ │ ├── images # image files
+│ │ │ └── cc3m.json # the image captions
+│ │ └── webvid # text-video pairs data
+│ │ │ ├── videos # video files
+│ │ │ └── webvid.json # the video captions
+│ ├── IT_data # instruction data
+│ │ ├── T+X-T_data # text+[image/audio/video] to text instruction data
+│ │ │ ├── alpaca # textual instruction data
+│ │ │ ├── llava # visual instruction data
+│ │ ├── T-T+X # synthesized text to text+[image/audio/video] instruction data
+│ │ └── MosIT # Modality-switching Instruction Tuning instruction data
+├── code
+│ ├── config
+│ │ ├── base.yaml # the model configuration
+│ │ ├── stage_1.yaml # enc-side alignment training configuration
+│ │ ├── stage_2.yaml # dec-side alignment training configuration
+│ │ └── stage_3.yaml # instruction-tuning configuration
+│ ├── dsconfig
+│ │ ├── stage_1.json # deepspeed configuration for enc-side alignment training
+│ │ ├── stage_2.json # deepspeed configuration for dec-side alignment training
+│ │ └── stage_3.json # deepspeed configuration for instruction-tuning training
+│ ├── datast
+│ │ ├── base_dataset.py
+│ │ ├── catalog.py # the catalog information of the dataset
+│ │ ├── cc3m_datast.py # process and load text-image pair dataset
+│ │ ├── audiocap_datast.py # process and load text-audio pair dataset
+│ │ ├── webvid_dataset.py # process and load text-video pair dataset
+│ │ ├── T+X-T_instruction_dataset.py # process and load text+x-to-text instruction dataset
+│ │ ├── T-T+X_instruction_dataset.py # process and load text-to-text+x instruction dataset
+│ │ └── concat_dataset.py # process and load multiple dataset
+│ ├── model
+│ │ ├── ImageBind # the code from ImageBind Model
+│ │ ├── common
+│ │ ├── anyToImageVideoAudio.py # the main model file
+│ │ ├── agent.py
+│ │ ├── modeling_llama.py
+│ │ ├── custom_ad.py # the audio diffusion
+│ │ ├── custom_sd.py # the image diffusion
+│ │ ├── custom_vd.py # the video diffusion
+│ │ ├── layers.py # the output projection layers
+│ │ └── ...
+│ ├── scripts
+│ │ ├── train.sh # training NExT-GPT script
+│ │ └── app.sh # deploying demo script
+│ ├── header.py
+│ ├── process_embeddings.py # precompute the captions embeddings
+│ ├── train.py # training
+│ ├── inference.py # inference
+│ ├── demo_app.py # deploy Gradio demonstration
+│ └── ...
+├── ckpt
+│ ├── delta_ckpt # tunable NExT-GPT params
+│ │ ├── nextgpt
+│ │ │ ├── 7b_tiva_v0 # the directory to save the log file
+│ │ │ │ ├── log # the logs
+│ └── ...
+│ ├── pretrained_ckpt # frozen params of pretrained modules
+│ │ ├── imagebind_ckpt
+│ │ │ ├──huge # version
+│ │ │ │ └──imagebind_huge.pth
+│ │ ├── vicuna_ckpt
+│ │ │ ├── 7b_v0 # version
+│ │ │ │ ├── config.json
+│ │ │ │ ├── pytorch_model-00001-of-00002.bin
+│ │ │ │ ├── tokenizer.model
+│ │ │ │ └── ...
+├── LICENCE.md
+├── README.md
+└── requirements.txt
+```
+
+
+
+
+
+### 2. Environment Preparation [Back to Top]
+Please first clone the repo and install the required environment, which can be done by running the following commands:
+```
+conda env create -n nextgpt python=3.8
+
+conda activate nextgpt
+
+# CUDA 11.6
+conda install pytorch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 pytorch-cuda=11.6 -c pytorch -c nvidia
+
+git clone https://github.com/NExT-GPT/NExT-GPT.git
+cd NExT-GPT
+
+pip install -r requirements.txt
+```
+
+
+
+### 3. Training/Adapting NExt-GPT on Your Own
+
+####
+
+
+
+
+
+#### 3.1. Preparing Pre-trained Checkpoint [Back to Top]
+NExT-GPT is trained based on following excellent existing models.
+Please follow the instructions to prepare the checkpoints.
+
+- `ImageBind`
+is the unified image/video/audio encoder. The pre-trained checkpoint can be downloaded from [here](https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth) with version `huge`. Afterward, put the `imagebind_huge.pth` file at [[./ckpt/pretrained_ckpt/imagebind_ckpt/huge]](ckpt/pretrained_ckpt/imagebind_ckpt/).
+- `Vicuna`:
+first prepare the LLaMA by following the instructions [[here]](ckpt/pretrained_ckpt/prepare_vicuna.md). Then put the pre-trained model at [[./ckpt/pretrained_ckpt/vicuna_ckpt/]](ckpt/pretrained_ckpt/vicuna_ckpt/).
+- `Image Diffusion`
+is used to generate images. NExT-GPT uses [Stable Diffusion](https://huggingface.co/runwayml/stable-diffusion-v1-5) with version `
+v1-5`. (_will be automatically downloaded_)
+- `Audio Diffusion`
+for producing audio content. NExT-GPT employs [AudioLDM](https://github.com/haoheliu/AudioLDM) with version `l-full`. (_will be automatically downloaded_)
+- `Video Diffusion`
+for the video generation. We employ [ZeroScope](https://huggingface.co/cerspense/zeroscope_v2_576w) with version `v2_576w`. (_will be automatically downloaded_)
+
+
+
+
+
+#### 3.2. Preparing Dataset [Back to Top]
+Please download the following datasets used for model training:
+
+A) T-X pairs data
+ - `CC3M` of ***text-image*** pairs, please follow this instruction [[here]](./data/T-X_pair_data/cc3m/prepare.md). Then put the data at [[./data/T-X_pair_data/cc3m]](./data/T-X_pair_data/cc3m).
+ - `WebVid` of ***text-video*** pairs, see the [[instruction]](./data/T-X_pair_data/webvid/prepare.md). The file should be saved at [[./data/T-X_pair_data/webvid]](./data/T-X_pair_data/webvid).
+ - `AudioCap` of ***text-audio*** pairs, see the [[instruction]](./data/T-X_pair_data/audiocap/prepare.md). Save the data in [[./data/T-X_pair_data/audiocap]](./data/T-X_pair_data/audiocap).
+
+B) Instruction data
+ - T+X-T
+ - `LLaVA` of the ***visual instruction data***, download it from [here](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md), and then put it at [[./data/IT_data/T+X-T_data/llava]](./data/IT_data/T+X-T_data/llava/).
+ - `Alpaca` of the ***textual instruction data***, download it from [here](https://github.com/tatsu-lab/stanford_alpaca), and then put it at [[./data/IT_data/T+X-T_data/alpaca/]](data/IT_data/T+X-T_data/alpaca/).
+ - `VideoChat`, download the ***video instruction data*** [here](https://github.com/OpenGVLab/InternVideo/tree/main/Data/instruction_data), and then put it at [[./data/IT_data/T+X-T_data/videochat/]](data/IT_data/T+X-T_data/videochat/).
+
+ Side note:After downloading dataset, please run `preprocess_dataset.py` to preprocess the dataset into a unified format.
+ - T-X+T (T2M)
+ - The `T-X+T` instruction datasets (T2M) are saved at [[./data/IT_data/T-T+X_data]](./data/IT_data/T-T+X_data).
+
+ - MosIT
+ - Download the file from [here](), put them in [[./data/IT_data/MosIT_data/]](./data/IT_data/MosIT_data/). (_We are in the process of finalizing the data and handling the copyright issue. Will release later._)
+
+
+
+
+#### 3.3. Precomputing Embeddings [Back to Top]
+In decoding-side alignment training, we minimize the distance between the representation of signal tokens and captions.
+To save costs of time and memory, we precompute the text embeddings for image, audio and video captions using the text encoder within the respective diffusion models.
+
+Please run this command before the following training of NExT-GPT, where the produced `embedding` file will be saved at [[./data/embed]](./data/embed).
+```angular2html
+cd ./code/
+python process_embeddings.py ../data/T-X_pair_data/cc3m/cc3m.json image ../data/embed/ runwayml/stable-diffusion-v1-5
+```
+
+Note of arguments:
+- args[1]: path of caption file;
+- args[2]: modality, which can be `image`, `video`, and `audio`;
+- args[3]: saving path of embedding file;
+- args[4]: corresponding pre-trained diffusion model name.
+
+
+
+
+
+#### 3.4. Training NExT-GPT [Back to Top]
+
+First of all, please refer to the base configuration file [[./code/config/base.yaml]](./code/config/base.yaml) for the basic system setting of overall modules.
+
+Then, the training of NExT-GPT starts with this script:
+```angular2html
+cd ./code
+bash scripts/train.sh
+```
+Specifying the command:
+```angular2html
+deepspeed --include localhost:0 --master_addr 127.0.0.1 --master_port 28459 train.py \
+ --model nextgpt \
+ --stage 1\
+ --save_path ../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/\
+ --log_path ../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/log/
+```
+where the key arguments are:
+- `--include`: `localhost:0` indicating the GPT cuda number `0` of deepspeed.
+- `--stage`: training stage.
+- `--save_path`: the directory which saves the trained delta weights. This directory will be automatically created.
+- `--log_path`: the directory which saves the log file.
+
+
+
+
+
+
+The whole NExT-GPT training involves 3 steps:
+
+- **Step-1**: Encoding-side LLM-centric Multimodal Alignment. This stage trains the ***input projection layer*** while freezing the ImageBind, LLM, output projection layer.
+
+ Just run the above `train.sh` script by setting: `--stage 1`
+
+ Also refer to the running config file [[./code/config/stage_1.yaml]](./code/config/stage_1.yaml) and deepspeed config file [[./code/dsconfig/stage_1.yaml]](./code/dsconfig/stage_1.yaml) for more step-wise configurations.
+
+ Note that the dataset used for training in this step is included `dataset_name_list` and the dataset name must precisely match the definition in [[./code/dataset/catalog.py]](./code/dataset/catalog.py)
+
+
+
+- **Step-2**: Decoding-side Instruction-following Alignment. This stage trains the ***output projection layers*** while freezing the ImageBind, LLM, input projection layers.
+
+ Just run the above `train.sh` script by setting: `--stage 2`
+
+ Also refer to the running config file [[./code/config/stage_2.yaml]](./code/config/stage_2.yaml) and deepspeed config file [[./code/dsconfig/stage_2.yaml]](./code/dsconfig/stage_2.yaml) for more step-wise configurations.
+
+
+
+
+
+- **Step-3**: Instruction Tuning. This stage instruction-tune 1) the ***LLM*** via LoRA, 2) ***input projection layer*** and 3) ***output projection layer*** on the instruction dataset.
+
+ Just run the above `train.sh` script by setting: `--stage 3`
+
+ Also refer to the running config file [[./code/config/stage_3.yaml]](./code/config/stage_3.yaml) and deepspeed config file [[./code/dsconfig/stage_3.yaml]](./code/dsconfig/stage_3.yaml) for more step-wise configurations.
+
+
+
+
+
+
+## 4. Running NExT-GPT System [Back to Top]
+
+
+
+
+
+#### 4.1. Preparing Checkpoints
+
+First, loading the pre-trained NExT-GPT system.
+- **Step-1**: load `Frozen parameters`. Please refer to 3.1 Preparing Pre-trained Checkpoint .
+
+- **Step-2**: load `Tunable parameters`. Please put the NExT-GPT system at [[./ckpt/delta_ckpt/nextgpt/7b_tiva_v0]](./ckpt/delta_ckpt/nextgpt/7b_tiva_v0). You may either 1) use the params trained yourselves, or 2) download our checkpoints from [Huggingface](https://huggingface.co/ChocoWu/nextgpt_7b_tiva_v0).
+
+
+
+
+
+#### 4.2. Deploying Gradio Demo
+Upon completion of the checkpoint loading, you can run the demo locally via:
+```angular2html
+cd ./code
+bash scripts/app.sh
+```
+Specifying the key arguments as:
+- `--nextgpt_ckpt_path`: the path of pre-trained NExT-GPT params.
+
+---------
+
+
+## Contact
+
+For any questions or feedback, feel free to contact [Shengqiong Wu](mailto:swu@u.nus.edu) and [Hao Fei](mailto:haofei37@nus.edu.sg).
+
+
+## Citation
+
+If you find NextGPT useful in your research or applications, please kindly cite:
+```
+@articles{wu2023nextgpt,
+ title={NExT-GPT: Any-to-Any Multimodal LLM},
+ author={Shengqiong Wu and Hao Fei and Leigang Qu and Wei Ji and Tat-Seng Chua},
+ journal = {CoRR},
+ volume = {abs/2309.05519},
+ year={2023}
+}
+```
+
+
+
+
+
+## Acknowledgements
+You may refer to related work that serves as foundations for our framework and code repository,
+[Vicuna](https://github.com/lm-sys/FastChat),
+[ImageBind](https://github.com/facebookresearch/ImageBind),
+[Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img),
+[AudioLDM](https://github.com/haoheliu/AudioLDM), and
+[Zeroscope](https://huggingface.co/cerspense/zeroscope_v2_576w).
+We also partially draw inspirations from
+[PandaGPT](https://github.com/yxuansu/PandaGPT),
+[VPGTrans](https://vpgtrans.github.io/),
+[GILL](https://github.com/kohjingyu/gill/),
+[CoDi](https://codi-gen.github.io/),
+[Video-LLaMA](https://github.com/DAMO-NLP-SG/Video-LLaMA),
+and [MiniGPT-4](https://github.com/Vision-CAIR/MiniGPT-4).
+Thanks for their wonderful works.
+
+
+
+
+## License Notices
+This repository is under [BSD 3-Clause License](LICENSE.txt).
+NExT-GPT is a research project intended for non-commercial use only.
+One must NOT use the code of NExT-GPT for any illegal, harmful, violent, racist, or sexual purposes.
+One is strictly prohibited from engaging in any activity that will potentially violate these guidelines.
+Any potential commercial use of this code should be approved by the authors.
diff --git a/ckpt/__init__.py b/ckpt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/ckpt/delta_ckpt/nextgpt/7b_tiva_v0/__init__.py b/ckpt/delta_ckpt/nextgpt/7b_tiva_v0/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/ckpt/pretrained_ckpt/__init__.py b/ckpt/pretrained_ckpt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/ckpt/pretrained_ckpt/imagebind_ckpt/__init__.py b/ckpt/pretrained_ckpt/imagebind_ckpt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/ckpt/pretrained_ckpt/imagebind_ckpt/huge/__init__.py b/ckpt/pretrained_ckpt/imagebind_ckpt/huge/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/ckpt/pretrained_ckpt/prepare_vicuna.md b/ckpt/pretrained_ckpt/prepare_vicuna.md
new file mode 100644
index 0000000000000000000000000000000000000000..9b005136f0a47ea5f52f765a49518e17513202dc
--- /dev/null
+++ b/ckpt/pretrained_ckpt/prepare_vicuna.md
@@ -0,0 +1,80 @@
+# 1. Prepare Vicuna Checkpoint
+
+The language decoder of NExT-GPT relies on Vicuna version 0 which is an open-source LLaMA-based LLM.
+However, due to the distribution license of LLaMA, manual restoration of Vicuna's weights is required.
+Below are the instructions for restoring these weights.
+(These original instruction comes from the [PandaGPT](https://github.com/yxuansu/PandaGPT)).
+
+
+## 1.1. Prepare LLaMA Weights
+* Request the original weights of LLaMA from Meta by filling [this form](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform).
+* After obtaining the weights of a specific LLaMA (e.g. 7B, 13B), following [instructions](https://huggingface.co/docs/transformers/main/model_doc/llama) provided by Huggingface to convert it into Huggingface format.
+
+> **** After conversion, the directory should look like:
+
+ .
+ └── ./{path_to_llama_weights}/
+ │ ├── config.json
+ │ ├── generation_config.json
+ │ ├── pytorch_model-00001-of-00002.bin
+ │ ├── pytorch_model-00002-of-00002.bin
+ │ ├── pytorch_model.bin.index.json
+ │ ├── special_tokens_map.json
+ │ ├── tokenizer.model
+ │ └── tokenizer_config.json
+
+`{path_to_llama_weights}` is where you store the checkpoints.
+
+
+## 1.2. Prepare the Delta Weights of Vicuna
+
+Then, you should download the delta weights of Vicuna provided by the original authors. You can find the corresponding links to 7B/13B Vicuna models in the table below.
+
+|**Model Size**|**Delta Weights Address**|**Version**|
+|:-------------:|:-------------:|:-------------:|
+|7B|[[Link]](https://huggingface.co/lmsys/vicuna-7b-delta-v0)|0|
+|13B|[[Link]](https://huggingface.co/lmsys/vicuna-13b-delta-v0)|0|
+
+
+
+> **** After conversion, the directory should look like:
+
+ .
+ └── ./{path_to_delta_vicuna_weights}/
+ ├── config.json
+ ├── generation_config.json
+ ├── pytorch_model-00001-of-00002.bin
+ ├── pytorch_model-00002-of-00002.bin
+ ├── pytorch_model.bin.index.json
+ ├── special_tokens_map.json
+ ├── tokenizer.model
+ └── tokenizer_config.json
+
+`{path_to_delta_vicuna_weights}` is where you store the delta weights of Vicuna.
+
+## 1.3. Combine the Weights:
+
+When the two sets of weights are ready, you can combine them using tools from the Vicuna team.
+
+First, install the required library.
+```yaml
+pip install git+https://github.com/lm-sys/FastChat.git@v0.1.10
+```
+
+Then, run the following command.
+```yaml
+python -m fastchat.model.apply_delta --base {path_to_llama_weights} --target ./vicuna_ckpt/7b_v0/ --delta {path_to_delta_vicuna_weights}
+```
+
+> **** Now, the final weights are ready as:
+
+ .
+ └── ./vicuna_ckpt/7b_v0/
+ ├── config.json
+ ├── generation_config.json
+ ├── pytorch_model-00001-of-00002.bin
+ ├── pytorch_model-00002-of-00002.bin
+ ├── pytorch_model.bin.index.json
+ ├── special_tokens_map.json
+ ├── tokenizer.model
+ └── tokenizer_config.json
\ No newline at end of file
diff --git a/ckpt/pretrained_ckpt/vicuna_ckpt/__init__.py b/ckpt/pretrained_ckpt/vicuna_ckpt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/__init__.py b/code/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/bot.png b/code/bot.png
new file mode 100644
index 0000000000000000000000000000000000000000..0047bf66e24ff259b7ea02081316c3d881854856
Binary files /dev/null and b/code/bot.png differ
diff --git a/code/config/__init__.py b/code/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cfacbf97b6ec4c64fb5086589887c9e2cd1e966
--- /dev/null
+++ b/code/config/__init__.py
@@ -0,0 +1,41 @@
+import yaml
+
+
+def load_model_config(stage, mode):
+ # load special config for each model
+ config_path = f'config/stage_{stage}.yaml'
+ print(f'[!] load configuration from {config_path}')
+ with open(config_path) as f:
+ configuration = yaml.load(f, Loader=yaml.FullLoader)
+ new_config = {}
+ for key, value in configuration.items():
+ if key in ['train', 'test', 'validation']:
+ if mode == key:
+ new_config.update(value)
+ else:
+ new_config[key] = value
+ configuration = new_config
+ return configuration
+
+
+def load_config(args):
+ '''the configuration of each model can rewrite the base configuration'''
+ # base config
+ base_configuration = load_base_config()
+
+ # load stage config
+ # if args.get('mode'):
+ stage_configuration = load_model_config(args['stage'], args['mode'])
+
+ # update and append the stage config for base config
+ base_configuration.update(stage_configuration)
+ configuration = base_configuration
+ return configuration
+
+
+def load_base_config():
+ config_path = f'config/base.yaml'
+ with open(config_path) as f:
+ configuration = yaml.load(f, Loader=yaml.FullLoader)
+ print(f'[!] load base configuration: {config_path}')
+ return configuration
diff --git a/code/config/base.yaml b/code/config/base.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..eb4c3b4c4c110877cb11670c24feab14726b82a4
--- /dev/null
+++ b/code/config/base.yaml
@@ -0,0 +1,45 @@
+# ========= system global ========== #
+models:
+ nextgpt:
+ model_name: NextGPTModel
+ agent_name: DeepSpeedAgent
+
+seed: 13
+max_length: 512 # max length of the user input prompt
+logging_step: 5
+num_clip_tokens: 77
+gen_emb_dim: 768
+pretrained_ckpt_path: ../ckpt/pretrained_ckpt/
+
+# ========= LLM ========== #
+vicuna_version: 7b_v0 # [7b_v0, ]
+
+# ========= multimodal encoder ========== #
+imagebind_version: huge
+
+# ========= text-to-image alignment tuning ========== #
+n_img_tokens: 4
+text_emb_to_img_layers: [-1]
+num_gen_img_tokens: 4
+text_fc_to_img_mode: transformer # [qformer, transformer]
+
+# ========= text-to-video alignment tuning ========== #
+n_video_tokens: 24
+text_emb_to_video_layers: [-1]
+num_gen_video_tokens: 24
+text_fc_to_video_mode: transformer # [qformer, transformer]
+
+# ========= text-to-audio alignment tuning ========== #
+n_audio_tokens: 8
+text_emb_to_audio_layers: [-1]
+num_gen_audio_tokens: 8
+text_fc_to_audio_mode: transformer # [qformer, transformer]
+
+# ========= image diffusion model ========== #
+image_diffusion: runwayml/stable-diffusion-v1-5 # [runwayml/stable-diffusion-v1-5, stabilityai/stable-diffusion-2]
+
+# ========= video diffusion model ========== #
+video_diffusion: cerspense/zeroscope_v2_576w
+
+# ========= audio diffusion model ========== #
+audio_diffusion: cvssp/audioldm-l-full # [cvssp/audioldm-l-full, cvssp/audioldm-s-full-v2]
diff --git a/code/config/stage_1.yaml b/code/config/stage_1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d47328bd44d8d25fe440ef35d06a4cab6778252a
--- /dev/null
+++ b/code/config/stage_1.yaml
@@ -0,0 +1,10 @@
+freeze_lm: true
+freeze_input_proj: false
+freeze_output_proj: true
+prompt: 'generate a caption' # the prompting information for the enc-side alignment.
+train:
+ warmup_rate: 0.1
+ epochs: 1
+ max_length: 512
+ max_shard_size: 10GB
+ dataset_name_list: ['cc3m_enc', 'webvid_enc', 'audiocap_enc']
diff --git a/code/config/stage_2.yaml b/code/config/stage_2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c360fba38ad11c16785f68d4bbac7986fb33a7dc
--- /dev/null
+++ b/code/config/stage_2.yaml
@@ -0,0 +1,10 @@
+freeze_lm: true
+freeze_input_proj: true
+freeze_output_proj: false
+prompt: '' # the prompting information for the enc-side alignment.
+train:
+ warmup_rate: 0.1
+ epochs: 1
+ max_length: 512
+ max_shard_size: 10GB
+ dataset_name_list: ['cc3m_dec', 'webvid_dec', 'audiocap_dec']
\ No newline at end of file
diff --git a/code/config/stage_3.yaml b/code/config/stage_3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..242bb7ae0b8a770eac79db3d242659001524f34c
--- /dev/null
+++ b/code/config/stage_3.yaml
@@ -0,0 +1,18 @@
+# ========= lora hyper-params ========== #
+lora_r: 32
+lora_alpha: 32
+lora_dropout: 0.1
+
+freeze_lm: false
+freeze_input_proj: false
+freeze_output_proj: false
+prompt: '' # the prompting information for the enc-side alignment.
+
+train:
+ warmup_rate: 0.1
+ epochs: 1
+ max_length: 512
+ max_shard_size: 10GB
+ dataset_name_list: ['audio_instruction', 'video_instruction', 'image_instruction', 'llava_instruction', 'alpaca_instruction']
+
+
diff --git a/code/dataset/T+X-T_instruction_dataset.py b/code/dataset/T+X-T_instruction_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..496ab7c7cf4f996c45d4878b73eef1f3dfd4f66b
--- /dev/null
+++ b/code/dataset/T+X-T_instruction_dataset.py
@@ -0,0 +1,63 @@
+import json
+import os.path
+
+from torch.utils.data import Dataset
+from tqdm import tqdm
+import pandas as pd
+import re
+import random
+import numpy as np
+import torch
+
+
+# from .base_dataset import BaseDataset
+
+
+class TX2TInstructionDataset(Dataset):
+ """
+ T + X - T instruction Dataset
+ """
+ def __init__(self, data_path: str, mm_root_path: str = None, dataset_type: str='ImageToText'):
+ super(TX2TInstructionDataset, self).__init__()
+
+ self.mm_root_path = mm_root_path
+ self.instruction_list = []
+ self.mm_path_list = []
+ self.dataset_category = 't2t' if mm_root_path is None else 'tx2t'
+ with open(data_path, 'r', encoding='utf-8') as f:
+ res = json.load(f)
+ for instance in tqdm(res, total=len(res)):
+ self.instruction_list.append(instance['conversation'])
+ if self.dataset_category == 'tx2t':
+ # Text + X -> Text dataset
+ self.mm_path_list.append(os.path.join(mm_root_path, instance['image_name']))
+ self.dataset_type_list = [dataset_type for _ in range(len(self.instruction_list))]
+
+ def __len__(self): # number of instances
+ return len(self.instruction_list)
+
+ def __getitem__(self, i):
+ if self.dataset_category == 'tx2t':
+ # Text + X -> Text dataset
+ return dict(mm_paths=self.mm_path_list[i], output_texts=self.instruction_list[i],
+ dataset_types=self.dataset_type_list[i])
+ else:
+ # Text -> Text dataset
+ return dict(output_texts=self.instruction_list[i], dataset_types=self.dataset_type_list[i])
+
+ def collate(self, instances):
+ if self.dataset_category == 'tx2t':
+ mm_paths, output_texts, dataset_types = tuple(
+ [instance[key] for instance in instances] for key in ("mm_paths", "output_texts", "dataset_types"))
+ return dict(
+ mm_paths=mm_paths,
+ output_texts=output_texts,
+ dataset_types=dataset_types
+ )
+ else:
+ output_texts, dataset_types = tuple(
+ [instance[key] for instance in instances] for key in ("output_texts", "dataset_types"))
+ return dict(
+ output_texts=output_texts,
+ dataset_types=dataset_types
+ )
diff --git a/code/dataset/T-T+X_instruction_dataset.py b/code/dataset/T-T+X_instruction_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..40d34ddb42e6e7cd310f3e4106eaa63068552ea3
--- /dev/null
+++ b/code/dataset/T-T+X_instruction_dataset.py
@@ -0,0 +1,49 @@
+import json
+import os.path
+
+from torch.utils.data import Dataset
+from tqdm import tqdm
+import pandas as pd
+import re
+import random
+import numpy as np
+import torch
+
+
+# from .base_dataset import BaseDataset
+
+
+class T2XTInstructionDataset(Dataset):
+ """
+ T - T + X instruction Dataset
+ """
+ def __init__(self, data_path: str, embed_path: str, dataset_type: str = "TextToImage"):
+ super(T2XTInstructionDataset, self).__init__()
+
+ self.embed_path = embed_path
+ self.instruction_list = []
+ self.mm_path_list = []
+ with open(data_path, 'r', encoding='utf-8') as f:
+ res = json.load(f)
+ for instance in tqdm(res, total=len(res)):
+ self.instruction_list.append(instance['conversation'])
+ self.mm_path_list.append(instance['mm_name'])
+ self.dataset_type_list = [dataset_type for _ in range(len(self.instruction_list))]
+
+ def __len__(self): # number of instances
+ return len(self.instruction_list)
+
+ def __getitem__(self, i):
+ with open(os.path.join(self.embed_path, str(os.path.basename(self.mm_path_list[i])) + '.npy'), 'rb') as f:
+ caption_embs = torch.from_numpy(np.load(f, allow_pickle=True)) # (num_clip_tokens, 768)
+
+ return dict(output_texts=self.instruction_list[i], caption_embs=caption_embs, dataset_types=self.dataset_type_list[i])
+
+ def collate(self, instances):
+ output_texts, caption_embs, dataset_types = tuple(
+ [instance[key] for instance in instances] for key in ("output_texts", "caption_embs", "dataset_types"))
+ return dict(
+ output_texts=output_texts,
+ caption_embs=caption_embs,
+ dataset_types=dataset_types
+ )
diff --git a/code/dataset/__init__.py b/code/dataset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b9faa69c0562038a5dd39b3cbcb96ee628e1a4
--- /dev/null
+++ b/code/dataset/__init__.py
@@ -0,0 +1,37 @@
+from header import *
+from .samplers import DistributedBatchSampler, DistributedMultiDatasetBatchSampler
+from .catalog import DatasetCatalog
+from .utils import instantiate_from_config
+import torch
+from torch.utils.data import ConcatDataset
+from .concat_dataset import MyConcatDataset
+
+
+def load_dataset(args, dataset_name_list):
+ """
+ Args:
+ args:
+ dataset_name_list: List[str]
+ repeats: List[int], the training epochs for each dataset
+
+ """
+ # concat_data = get_concat_dataset(dataset_name_list)
+ concat_data = MyConcatDataset(dataset_name_list)
+ world_size = torch.distributed.get_world_size()
+ rank = torch.distributed.get_rank()
+ batch_size = args['world_size'] * args['dschf'].config['train_micro_batch_size_per_gpu']
+ sampler = torch.utils.data.RandomSampler(concat_data)
+ batch_sampler = DistributedMultiDatasetBatchSampler(dataset=concat_data,
+ sampler=sampler,
+ batch_size=batch_size,
+ drop_last=True,
+ rank=rank,
+ world_size=world_size)
+ iter_ = DataLoader(
+ concat_data,
+ batch_sampler=batch_sampler,
+ num_workers=1,
+ collate_fn=concat_data.collate,
+ pin_memory=True
+ )
+ return concat_data, iter_, sampler
diff --git a/code/dataset/audiocap_dataset.py b/code/dataset/audiocap_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5e3cc0b2ce3ba8063f97d01e46918333665d37c
--- /dev/null
+++ b/code/dataset/audiocap_dataset.py
@@ -0,0 +1,55 @@
+# 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 copy
+import os
+import json
+from tqdm import tqdm
+import ipdb
+import random
+from torch.nn.utils.rnn import pad_sequence
+from dataclasses import dataclass, field
+from typing import Callable, Dict, Sequence
+
+import torch
+import torch.distributed as dist
+import transformers
+import numpy as np
+from torch.utils.data import Dataset
+from .base_dataset import BaseDataset
+from tqdm import tqdm
+import pandas as pd
+from .utils import process_caption
+
+
+class AudioCapDataset(BaseDataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(self, data_path: str, mm_root_path: str, embed_path: str, dataset_type: str):
+ super(AudioCapDataset, self).__init__(data_path, mm_root_path, embed_path, dataset_type)
+ self.embed_path = embed_path
+
+ print('Load Audiocap dataset ...')
+ self.mm_path_list, self.caption_list = [], []
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ for row in tqdm(data, total=len(data)):
+ audio_id, one_caption = row["audio_name"], row["caption"]
+ self.mm_path_list.append(os.path.join(mm_root_path, audio_id))
+ self.caption_list.append(process_caption(one_caption))
+
+ print(f'[!] collect {len(self.mm_path_list)} samples for training')
+ self.dataset_type_list = [dataset_type for _ in range(len(self.caption_list))]
+
+
diff --git a/code/dataset/base_dataset.py b/code/dataset/base_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..7461e822c5bafafe81d951cc0710b73c2ec7fc38
--- /dev/null
+++ b/code/dataset/base_dataset.py
@@ -0,0 +1,55 @@
+# 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 copy
+import os
+import torch
+import numpy as np
+import json
+from torch.utils.data import Dataset
+from tqdm import tqdm
+import pandas as pd
+from .utils import process_caption
+
+
+class BaseDataset(Dataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(self, data_path: str, mm_root_path: str, embed_path: str, dataset_type: str):
+ super(BaseDataset, self).__init__()
+ self.embed_path = embed_path
+ self.mm_path_list, self.caption_list = [], []
+ self.dataset_type_list = []
+
+ def __len__(self): # number of instances
+ return len(self.mm_path_list)
+
+ def __getitem__(self, i):
+ with open(os.path.join(self.embed_path, str(os.path.basename(self.mm_path_list[i])) + '.npy'), 'rb') as f:
+ caption_embs = torch.from_numpy(np.load(f, allow_pickle=True)) # (num_clip_tokens, 768)
+
+ return dict(mm_paths=self.mm_path_list[i], output_texts=self.caption_list[i], caption_embs=caption_embs,
+ dataset_types=self.dataset_type_list[i])
+
+ def collate(self, instances):
+ mm_paths, output_texts, caption_embs, dataset_types = tuple(
+ [instance[key] for instance in instances] for key in
+ ("mm_paths", "output_texts", "caption_embs", "dataset_types"))
+ return dict(
+ mm_paths=mm_paths,
+ output_texts=output_texts,
+ caption_embs=caption_embs,
+ dataset_types=dataset_types
+ )
+
diff --git a/code/dataset/catalog.py b/code/dataset/catalog.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a8564ae0d07683fa716e5e15a5c4b9ea01abef7
--- /dev/null
+++ b/code/dataset/catalog.py
@@ -0,0 +1,125 @@
+import os
+
+
+class DatasetCatalog:
+ def __init__(self):
+ # the following dataset utilized for encoding-side alignment learning
+ self.audiocap_enc = {
+ "target": "dataset.audiocap_dataset.AudioCapDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/audiocap/audiocap.json",
+ mm_root_path="../data/T-X_pair_data/audiocap/audios",
+ embed_path="../data/embed/",
+ dataset_type="AudioToText",
+ ),
+ }
+
+ self.webvid_enc = {
+ "target": "dataset.webvid_dataset.WebvidDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/webvid/webvid.json",
+ mm_root_path="../data/T-X_pair_data/webvid/videos",
+ embed_path="../data/embed/",
+ dataset_type="VideoToText",
+ ),
+ }
+
+ self.cc3m_enc = {
+ "target": "dataset.cc3m_dataset.CC3MDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/cc3m/cc3m.json",
+ mm_root_path="../data/T-X_pair_data/cc3m/images",
+ embed_path="../data/embed/",
+ dataset_type="ImageToText",
+ ),
+ }
+
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
+
+ # the following dataset utilized for decoding-side alignment learning.
+
+ self.audiocap_dec = {
+ "target": "dataset.audiocap_dataset.AudioCapDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/audiocap/audiocap.json",
+ mm_root_path="../data/T-X_pair_data/audiocap/audios",
+ embed_path="../data/embed/",
+ dataset_type="TextToAudio",
+ ),
+ }
+
+ self.webvid_dec = {
+ "target": "dataset.webvid_dataset.WebvidDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/webvid/webvid.json",
+ mm_root_path="../data/T-X_pair_data/webvid/videos",
+ embed_path="../data/embed/",
+ dataset_type="TextToVideo",
+ ),
+ }
+
+ self.cc3m_dec = {
+ "target": "dataset.cc3m_dataset.CC3MDataset",
+ "params": dict(
+ data_path="../data/T-X_pair_data/cc3m/cc3m.json",
+ mm_root_path="../data/T-X_pair_data/cc3m/images",
+ embed_path="../data/embed/",
+ dataset_type="TextToImage",
+ ),
+ }
+
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
+
+ # the following dataset utilized for instruction tuning, so they are instruction dataset.
+ self.audio_instruction = {
+ "target": "dataset.T-T+X_instruction_dataset.T2XTInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T-T+X_data/audio_t2x.json",
+ embed_path="./embed/",
+ dataset_type="TextToAudio",
+ ),
+ }
+
+ self.video_instruction = {
+ "target": "dataset.T-T+X_instruction_dataset.T2XTInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T-T+X_data/video_t2x.json",
+ embed_path="./embed/",
+ dataset_type="TextToVideo",
+ ),
+ }
+
+ self.image_instruction = {
+ "target": "dataset.T-T+X_instruction_dataset.T2XTInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T-T+X_data/image_t2x.json",
+ embed_path="./embed/",
+ dataset_type="TextToImage",
+
+ ),
+ }
+
+ self.llava_instruction = {
+ "target": "dataset.T+X-T_instruction_dataset.TX2TInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T+X-T_data/llava/llava.json",
+ mm_root_path="../data/IT_data/T+X-T_data/llava/images",
+ dataset_type="ImageToText",
+ ),
+ }
+
+ self.alpaca_instruction = {
+ "target": "dataset.T+X-T_instruction_dataset.TX2TInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T+X-T_data/alpaca/alpaca.json",
+ dataset_type="TextToText",
+ ),
+ }
+
+ self.videochat_instruction = {
+ "target": "dataset.T+X-T_instruction_dataset.TX2TInstructionDataset",
+ "params": dict(
+ data_path="../data/IT_data/T+X-T_data/videochat/videochat.json",
+ dataset_type="VideoToText",
+ ),
+ }
diff --git a/code/dataset/cc3m_dataset.py b/code/dataset/cc3m_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..03f54e83229061abe6524a27a7179d443f78b1fb
--- /dev/null
+++ b/code/dataset/cc3m_dataset.py
@@ -0,0 +1,45 @@
+# 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 copy
+import os
+import torch
+import numpy as np
+import json
+from .base_dataset import BaseDataset
+from torch.utils.data import Dataset
+from tqdm import tqdm
+import pandas as pd
+from .utils import process_caption
+
+
+class CC3MDataset(BaseDataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(self, data_path: str, mm_root_path: str, embed_path: str, dataset_type: str):
+ super(CC3MDataset, self).__init__(data_path, mm_root_path, embed_path, dataset_type)
+ self.embed_path = embed_path
+
+ print('Load CC3M dataset ...')
+ self.mm_path_list, self.caption_list = [], []
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ for row in tqdm(data, total=len(data)):
+ image_id, one_caption = row["image_name"], row["caption"]
+ self.mm_path_list.append(os.path.join(mm_root_path, image_id))
+ self.caption_list.append(process_caption(one_caption))
+
+ print(f'[!] collect {len(self.mm_path_list)} samples for training')
+ self.dataset_type_list = [dataset_type for _ in range(len(self.caption_list))]
+
diff --git a/code/dataset/concat_dataset.py b/code/dataset/concat_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaeaa189d10a2c8e8f1b94bb830597a4727c6065
--- /dev/null
+++ b/code/dataset/concat_dataset.py
@@ -0,0 +1,38 @@
+from torch.utils.data import ConcatDataset, Dataset
+from .catalog import DatasetCatalog
+from .utils import instantiate_from_config
+
+
+class MyConcatDataset(Dataset):
+ def __init__(self, dataset_name_list):
+ super(MyConcatDataset, self).__init__()
+
+ _datasets = []
+
+ catalog = DatasetCatalog()
+ for dataset_idx, dataset_name in enumerate(dataset_name_list):
+ dataset_dict = getattr(catalog, dataset_name)
+
+ target = dataset_dict['target']
+ params = dataset_dict['params']
+ print(target)
+ print(params)
+ dataset = instantiate_from_config(dict(target=target, params=params))
+
+ _datasets.append(dataset)
+ self.datasets = ConcatDataset(_datasets)
+
+ def __len__(self):
+ return self.datasets.__len__()
+
+ def __getitem__(self, item):
+ return self.datasets.__getitem__(item)
+
+ def collate(self, instances):
+ data = {key: [] for key in instances[0].keys()} if instances else {}
+
+ for instance in instances:
+ for key, value in instance.items():
+ data[key].append(value)
+
+ return data
diff --git a/code/dataset/preprocess_dataset.py b/code/dataset/preprocess_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..6caec9c899b02847e4ca4a3ef4265bdf94f8ec3f
--- /dev/null
+++ b/code/dataset/preprocess_dataset.py
@@ -0,0 +1,144 @@
+import json
+import os.path
+
+from torch.utils.data import Dataset
+from tqdm import tqdm
+import pandas as pd
+import re
+import random
+import numpy as np
+import torch
+
+
+def load_alpaca(data_path, sample_data=False, sample_numer=1000, save_dir=''):
+ """
+ sample and process the alpaca dataset in to the following format:
+ [
+ {
+ "image_name": "00000000000",
+ "output_modality": "text",
+ "conversation": [
+ {
+ "from": "human",
+ "value": "Give three tips for staying healthy.",
+ "input_modality": "text"
+ },
+ {
+ "from": "gpt",
+ "value": "1. Eat a balanced and nutritious diet: ...",
+ "caption": "",
+ "output_modality": "text"
+ }
+ ]
+ },
+ ...
+ ]
+ """
+ with open(data_path, 'r') as f:
+ data = json.load(f)
+ print('the total instance is {}'.format(len(data)))
+ if sample_data and sample_numer > 0:
+ data = random.sample(data, sample_numer)
+ res = []
+ for d in data:
+ _temp = dict()
+ _temp['image_name'] = '00000000000'
+ _temp['output_modality'] = 'text'
+ conversation = []
+
+ conversation.append(
+ {'from': 'human',
+ 'value': d['instruction'] + d['input'],
+ 'input_modality': 'text'}
+ )
+ conversation.append(
+ {'from': 'gpt',
+ 'value': d['output'],
+ 'caption': '',
+ 'output_modality': 'text'}
+ )
+ _temp['conversation'] = conversation
+ res.append(_temp)
+ if not os.path.exists(save_dir):
+ os.makedirs(save_dir)
+ save_path = os.path.join(save_dir, os.path.basename(data_path))
+ with open(save_path, 'w', encoding='utf-8') as f:
+ json.dump(res, f, indent=4)
+ return res
+
+
+def load_llava(data_path, sample_data=False, sample_numer=1000, save_dir=''):
+ """
+ sample and process the llava instruction dataset into the following format:
+ [
+ {
+ "image_name": "00000000000.jpg",
+ "output_modality": "text",
+ "conversation": [
+ {
+ "from": "human",
+ "value": "Give three tips for staying healthy.",
+ "input_modality": "image"
+ },
+ {
+ "from": "gpt",
+ "value": "1. Eat a balanced and nutritious diet: ...",
+ "caption": "",
+ "output_modality": "text"
+ }
+ ]
+ },
+ ...
+ ]
+ """
+ with open(data_path, 'r') as f:
+ data = json.load(f)
+ print('the total instance is {}'.format(len(data)))
+ if sample_data and sample_numer > 0:
+ res = random.sample(data, sample_numer)
+ else:
+ res = data
+ # res = data
+ save_path = os.path.join(save_dir, os.path.basename(data_path))
+ for x in res:
+ i = 0
+ x['output_modality'] = 'text'
+ for j in x['conversation']:
+ if j['from'] == 'gpt':
+ j['caption'] = ''
+ j['output_modality'] = 'text'
+ elif j['from'] == 'human':
+ if i == 0:
+ j['input_modality'] = 'image'
+ i += 1
+ else:
+ j['input_modality'] = 'text'
+ with open(save_path, 'w', encoding='utf-8') as f:
+ json.dump(res, f, indent=4)
+ return res
+
+
+def load_t2x(data_path):
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ return data
+
+
+if __name__ == '__main__':
+ save_dir = '../../data/IT_data/T+X-T_data'
+ res = []
+
+ # audios = load_t2x(os.path.join(save_dir, 'audio_t2x.json'))
+ # videos = load_t2x(os.path.join(save_dir, 'video_t2x.json'))
+ # images = load_t2x(os.path.join(save_dir, 'image_t2x.json'))
+ # sample_number = max(len(audios), len(videos), len(images))
+ #
+ # print(sample_number)
+ sample_number = 1000
+
+ print('Load aplaca dataset ...')
+ text = load_alpaca('../../data/IT_data/T+X-T_data/alpaca/alpaca.json', False, sample_number, save_dir)
+ res.extend(text)
+
+ print('Load llava dataset ...')
+ data = load_llava('../../data/IT_data/T+X-T_data/llava/llava.json', False, sample_number, save_dir)
diff --git a/code/dataset/samplers.py b/code/dataset/samplers.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc1bb1aa72a65df314a2763468788c5090e5131a
--- /dev/null
+++ b/code/dataset/samplers.py
@@ -0,0 +1,221 @@
+# coding=utf-8
+# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
+#
+# 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.
+"""batch samplers that work with either random or sequential data samplers"""
+import math
+import os
+import sys
+
+import torch
+from torch.utils import data
+import numpy as np
+
+
+class RandomSampler(data.sampler.Sampler):
+ r"""
+ Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler,
+ but this class lets the user set an epoch like DistributedSampler
+ Samples elements randomly. If without replacement, then sample from a shuffled dataset.
+ If with replacement, then user can specify ``num_samples`` to draw.
+ Arguments:
+ data_source (Dataset): dataset to sample from
+ num_samples (int): number of samples to draw, default=len(dataset)
+ replacement (bool): samples are drawn with replacement if ``True``, default=False
+ """
+
+ def __init__(self, data_source, replacement=False, num_samples=None):
+ super(RandomSampler, self).__init__(data_source)
+ self.data_source = data_source
+ self.replacement = replacement
+ self._num_samples = num_samples
+ self.epoch = -1
+
+ if self._num_samples is not None and replacement is False:
+ raise ValueError("With replacement=False, num_samples should not be specified, "
+ "since a random permute will be performed.")
+
+ if not isinstance(self.num_samples, int) or self.num_samples <= 0:
+ raise ValueError("num_samples should be a positive integer "
+ "value, but got num_samples={}".format(self.num_samples))
+ if not isinstance(self.replacement, bool):
+ raise ValueError("replacement should be a boolean value, but got "
+ "replacement={}".format(self.replacement))
+
+ @property
+ def num_samples(self):
+ # dataset size might change at runtime
+ if self._num_samples is None:
+ return len(self.data_source)
+ return self._num_samples
+
+ def __iter__(self):
+ n = len(self.data_source)
+ g = torch.Generator()
+ if self.epoch >= 0:
+ g.manual_seed(self.epoch)
+ if self.replacement:
+ for _ in range(self.num_samples // 32):
+ yield from torch.randint(high=n, size=(32,), dtype=torch.int64, generator=g).tolist()
+ yield from torch.randint(high=n, size=(self.num_samples % 32,), dtype=torch.int64,
+ generator=g).tolist()
+ else:
+ yield from torch.randperm(n, generator=self.generator).tolist()
+
+ def __len__(self):
+ return self.num_samples
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
+
+
+class DistributedSequentialSampler(data.sampler.Sampler):
+ def __init__(self, num_samples, train_iters, batch_size, rank=-1, world_size=2):
+ super().__init__(num_samples)
+ if rank == -1:
+ rank = 0
+ world_size = 1
+ self.num_samples = num_samples
+ self.rank = rank
+ self.world_size = world_size
+ self.start_iter = 0
+ self.train_iters = train_iters
+ self.batch_size = batch_size
+ self.batch_bias = [i * (num_samples // batch_size) for i in range(batch_size)]
+
+ def __iter__(self):
+ for idx in range(self.start_iter, self.train_iters * 10):
+ batch = [(idx + bias) % self.num_samples for bias in self.batch_bias]
+ tbatch = self._batch(batch)
+ yield tbatch
+
+ def __len__(self):
+ return self.train_iters
+
+ def _batch(self, batch):
+ """extracts samples only pertaining to this worker's batch"""
+ start = self.rank*self.batch_size//self.world_size
+ end = (self.rank+1)*self.batch_size//self.world_size
+ return batch[start:end]
+
+
+class DistributedBatchSampler(data.sampler.BatchSampler):
+ """
+ similar to normal implementation of distributed sampler, except implementation is at the
+ batch sampler level, instead of just the sampler level. This allows wrapping of arbitrary
+ data samplers (sequential, random, WeightedRandomSampler, etc.) with this batch sampler.
+ """
+ def __init__(self, sampler, batch_size, drop_last, rank=-1, world_size=2, wrap_last=False, gradient_accumulation_steps=None):
+ super(DistributedBatchSampler, self).__init__(sampler, batch_size, drop_last)
+ if rank == -1:
+ assert False, 'should not be here'
+ self.rank = rank
+ self.world_size = world_size
+ self.sampler.wrap_around = 0
+ self.wrap_around = 0
+ self.wrap_last = wrap_last
+ self.start_iter = 0
+ self.effective_batch_size = batch_size if gradient_accumulation_steps is None else batch_size * gradient_accumulation_steps
+
+ def __iter__(self):
+ batch = []
+ i = 0
+ for idx in self.data_iterator(self.sampler, wrap_around=False):
+ batch.append(idx)
+ if len(batch) == self.batch_size:
+ tbatch = self._batch(batch)
+ if i >= self.start_iter * self.effective_batch_size:
+ yield tbatch
+ self.start_iter = 0
+ i += len(batch)
+ batch = []
+ batch_len = len(batch)
+ if batch_len > 0 and not self.drop_last:
+ if self.wrap_last:
+ self.sampler.wrap_around -= (self.batch_size)
+ self.wrap_around += (len(batch))
+ self.wrap_around %= self.batch_size
+ yield self._batch(batch)
+ if self.wrap_last:
+ self.sampler.wrap_around += self.batch_size
+
+ def data_iterator(self, _iter, wrap_around=False):
+ """iterates through data and handles wrap around"""
+ for i, idx in enumerate(_iter):
+ if i < self.wrap_around%self.batch_size:
+ continue
+ if wrap_around:
+ self.wrap_around += 1
+ self.wrap_around %= self.batch_size
+ yield idx
+
+ def _batch(self, batch):
+ """extracts samples only pertaining to this worker's batch"""
+ start = self.rank*self.batch_size//self.world_size
+ end = (self.rank+1)*self.batch_size//self.world_size
+ return batch[start:end]
+
+
+class DistributedMultiDatasetBatchSampler(data.sampler.BatchSampler):
+ """
+ This is a modality-blended batch sampler which allows to sample a batch data from different dataset alternatively.
+ """
+ def __init__(self, sampler, batch_size, dataset, drop_last, rank=-1, world_size=2, wrap_last=False, gradient_accumulation_steps=None):
+ super(DistributedMultiDatasetBatchSampler, self).__init__(sampler, batch_size, drop_last)
+ if rank == -1:
+ assert False, 'should not be here'
+ self.rank = rank
+ self.world_size = world_size
+ self.wrap_last = wrap_last
+ self.drop_last = drop_last
+ self.gradient_accumulation_steps = gradient_accumulation_steps
+ self.dataset = dataset
+ self.batch_size = batch_size
+ self.number_of_datasets = len(dataset.datasets.datasets)
+ self.largest_dataset_size = max([_cur_dataset.__len__() for _cur_dataset in dataset.datasets.datasets])
+
+ def __iter__(self):
+ samplers_list = []
+ sampler_iterators = []
+ for dataset_idx in range(self.number_of_datasets):
+ cur_dataset = self.dataset.datasets.datasets[dataset_idx]
+ sampler = torch.utils.data.RandomSampler(cur_dataset)
+ batch_sampler = DistributedBatchSampler(sampler, self.batch_size, self.drop_last, self.rank,
+ self.world_size, self.wrap_last, self.gradient_accumulation_steps)
+ samplers_list.append(batch_sampler)
+ cur_sampler_iterator = batch_sampler.__iter__()
+ sampler_iterators.append(cur_sampler_iterator)
+
+ push_index_val = [0] + self.dataset.datasets.cumulative_sizes[:-1]
+ step = self.batch_size * self.number_of_datasets
+ samples_to_grab = self.batch_size
+ # for this case we want to get all samples in dataset, this force us to resample from the smaller datasets
+ epoch_samples = self.largest_dataset_size * self.number_of_datasets
+
+ for _ in range(0, epoch_samples, step):
+ for i in range(self.number_of_datasets):
+ # for j in range(self.world_size):
+ cur_batch_sampler = sampler_iterators[i]
+ try:
+ cur_sample_org = cur_batch_sampler.__next__()
+ cur_samples = [x + push_index_val[i] for x in cur_sample_org]
+ yield cur_samples
+ except StopIteration:
+ # got to the end of iterator - restart the iterator and continue to get samples
+ # until reaching "epoch_samples"
+ sampler_iterators[i] = samplers_list[i].__iter__()
+ cur_batch_sampler = sampler_iterators[i]
+ cur_sample_org = cur_batch_sampler.__next__()
+ cur_samples = [x + push_index_val[i] for x in cur_sample_org]
+ yield cur_samples
+
diff --git a/code/dataset/utils.py b/code/dataset/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ce1ac14375dec2eb1f34d378deff0fd958c84a9
--- /dev/null
+++ b/code/dataset/utils.py
@@ -0,0 +1,37 @@
+from header import *
+import importlib
+
+
+def process_caption(caption):
+ caption = re.sub(
+ r"([\"()*#:;~])",
+ " ",
+ caption.lower(),
+ )
+ caption = re.sub(
+ r"\s{2,}",
+ " ",
+ caption,
+ )
+ caption = caption.rstrip("\n")
+ caption = caption.strip(" ")
+
+ return caption
+
+
+def instantiate_from_config(config):
+ if not "target" in config:
+ if config == '__is_first_stage__':
+ return None
+ elif config == "__is_unconditional__":
+ return None
+ raise KeyError("Expected key `target` to instantiate.")
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
+
+
+def get_obj_from_str(string, reload=False):
+ module, cls = string.rsplit(".", 1)
+ if reload:
+ module_imp = importlib.import_module(module)
+ importlib.reload(module_imp)
+ return getattr(importlib.import_module(module, package=None), cls)
diff --git a/code/dataset/webvid_dataset.py b/code/dataset/webvid_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d50d8c62993df3e1a0ad365063c203b431d0c7a
--- /dev/null
+++ b/code/dataset/webvid_dataset.py
@@ -0,0 +1,44 @@
+# 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 copy
+import os
+import json
+import numpy as np
+from torch.utils.data import Dataset
+from .base_dataset import BaseDataset
+from tqdm import tqdm
+import pandas as pd
+from .utils import process_caption
+import torch
+
+
+class WebvidDataset(BaseDataset):
+ """webvid Dataset with video-text pairs."""
+
+ def __init__(self, data_path: str, mm_root_path: str, embed_path: str, dataset_type: str):
+ super(WebvidDataset, self).__init__(data_path, mm_root_path, embed_path, dataset_type)
+ self.embed_path = embed_path
+
+ print('Load WebVid dataset ...')
+ self.mm_path_list, self.caption_list = [], []
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ for row in tqdm(data, total=len(data)):
+ video_id, one_caption = row["video_name"], row["caption"]
+ self.mm_path_list.append(os.path.join(mm_root_path, video_id))
+ self.caption_list.append(process_caption(one_caption))
+
+ print(f'[!] collect {len(self.mm_path_list)} samples for training')
+ self.dataset_type_list = [dataset_type for _ in range(len(self.caption_list))]
diff --git a/code/demo_app.py b/code/demo_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d3e9ce7121df09ddc6f87b7ea04a5dcdef80f72
--- /dev/null
+++ b/code/demo_app.py
@@ -0,0 +1,516 @@
+from transformers import AutoModel, AutoTokenizer
+from copy import deepcopy
+import os
+import ipdb
+import gradio as gr
+import mdtex2html
+from model.anyToImageVideoAudio import NextGPTModel
+import torch
+import json
+import tempfile
+from PIL import Image
+import scipy
+from config import *
+import imageio
+import argparse
+import re
+
+# init the model
+
+parser = argparse.ArgumentParser(description='train parameters')
+parser.add_argument('--model', type=str, default='nextgpt')
+parser.add_argument('--nextgpt_ckpt_path', type=str) # the delta parameters trained in each stages
+parser.add_argument('--stage', type=int, default=3)
+args = parser.parse_args()
+args = vars(args)
+args.update(load_config(args))
+model = NextGPTModel(**args)
+delta_ckpt = torch.load(os.path.join(args['nextgpt_ckpt_path'], f'pytorch_model.pt'), map_location=torch.device('cpu'))
+model.load_state_dict(delta_ckpt, strict=False)
+model = model.eval().half().cuda()
+print(f'[!] init the 7b model over ...')
+
+g_cuda = torch.Generator(device='cuda').manual_seed(13)
+
+filter_value = -float('Inf')
+min_word_tokens = 10
+gen_scale_factor = 4.0
+stops_id = [[835]]
+ENCOUNTERS = 1
+load_sd = True
+generator = g_cuda
+
+max_num_imgs = 1
+max_num_vids = 1
+height = 320
+width = 576
+
+max_num_auds = 1
+max_length = 246
+
+"""Override Chatbot.postprocess"""
+
+
+def postprocess(self, y):
+ if y is None:
+ return []
+ for i, (message, response) in enumerate(y):
+ y[i] = (
+ None if message is None else mdtex2html.convert((message)),
+ None if response is None else mdtex2html.convert(response),
+ )
+ return y
+
+
+gr.Chatbot.postprocess = postprocess
+
+
+def parse_text(text, image_path, video_path, audio_path):
+ """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
+ outputs = text
+ lines = text.split("\n")
+ lines = [line for line in lines if line != ""]
+ count = 0
+ for i, line in enumerate(lines):
+ if "```" in line:
+ count += 1
+ items = line.split('`')
+ if count % 2 == 1:
+ lines[i] = f''
+ else:
+ lines[i] = f'
'
+ else:
+ if i > 0:
+ if count % 2 == 1:
+ line = line.replace("`", "\`")
+ line = line.replace("<", "<")
+ line = line.replace(">", ">")
+ line = line.replace(" ", " ")
+ line = line.replace("*", "*")
+ line = line.replace("_", "_")
+ line = line.replace("-", "-")
+ line = line.replace(".", ".")
+ line = line.replace("!", "!")
+ line = line.replace("(", "(")
+ line = line.replace(")", ")")
+ line = line.replace("$", "$")
+ lines[i] = " " + line
+ text = "".join(lines) + " "
+ res_text = ''
+ split_text = re.split(r' <|> ', text)
+ image_path_list, video_path_list, audio_path_list = [], [], []
+ for st in split_text:
+ if st.startswith(''):
+ pattern = r'Image>(.*?)<\/Image'
+ matches = re.findall(pattern, text)
+ for m in matches:
+ image_path_list.append(m)
+ elif st.startswith(''):
+ pattern = r'Audio>(.*?)<\/Audio'
+ matches = re.findall(pattern, text)
+ for m in matches:
+ audio_path_list.append(m)
+ elif st.startswith(''):
+ pattern = r'Video>(.*?)<\/Video'
+ matches = re.findall(pattern, text)
+ for m in matches:
+ video_path_list.append(m)
+ else:
+ res_text += st
+ text = res_text
+ if image_path is not None:
+ text += f' '
+ outputs = f'{image_path} ' + outputs
+ if len(image_path_list) > 0:
+ for i in image_path_list:
+ text += f' '
+ outputs = f'{i} ' + outputs
+ if video_path is not None:
+ text += f' '
+ outputs = f'{video_path} ' + outputs
+ if len(video_path_list) > 0:
+ for i in video_path_list:
+ text += f' '
+ outputs = f'{i} ' + outputs
+ if audio_path is not None:
+ text += f' '
+ outputs = f'{audio_path} ' + outputs
+ if len(audio_path_list) > 0:
+ for i in audio_path_list:
+ text += f' '
+ outputs = f'{i} ' + outputs
+ # text = text[::-1].replace(">rb<", "", 1)[::-1]
+ text = text[:-len(" ")].rstrip() if text.endswith(" ") else text
+ return text, outputs
+
+
+def save_image_to_local(image: Image.Image):
+ # TODO: Update so the url path is used, to prevent repeat saving.
+ if not os.path.exists('temp'):
+ os.mkdir('temp')
+ filename = os.path.join('temp', next(tempfile._get_candidate_names()) + '.jpg')
+ image.save(filename)
+ return filename
+
+
+def save_video_to_local(video):
+ if not os.path.exists('temp'):
+ os.mkdir('temp')
+ filename = os.path.join('temp', next(tempfile._get_candidate_names()) + '.mp4')
+ writer = imageio.get_writer(filename, format='FFMPEG', fps=8)
+ for frame in video:
+ writer.append_data(frame)
+ writer.close()
+ return filename
+
+
+def save_audio_to_local(audio):
+ if not os.path.exists('temp'):
+ os.mkdir('temp')
+ filename = os.path.join('temp', next(tempfile._get_candidate_names()) + '.wav')
+ scipy.io.wavfile.write(filename, rate=16000, data=audio)
+ return filename
+
+
+def parse_reponse(model_outputs):
+ response = ''
+ text_outputs = []
+ for output_i, p in enumerate(model_outputs):
+ if isinstance(p, str):
+ response += p
+ response += ' '
+ text_outputs.append(p)
+ elif 'img' in p.keys():
+ _temp_output = ''
+ for m in p['img']:
+ if isinstance(m, str):
+ response += m.replace(' '.join([f'[IMG{i}]' for i in range(args['num_gen_img_tokens'])]), '')
+ response += ' '
+ _temp_output += m.replace(' '.join([f'[IMG{i}]' for i in range(args['num_gen_img_tokens'])]), '')
+ else:
+ filename = save_image_to_local(m[0])
+ print(filename)
+ _temp_output = f'{filename} ' + _temp_output
+ response += f' '
+ text_outputs.append(_temp_output)
+ elif 'vid' in p.keys():
+ _temp_output = ''
+ for idx, m in enumerate(p['vid']):
+ if isinstance(m, str):
+ response += m.replace(' '.join([f'[VID{i}]' for i in range(args['num_gen_video_tokens'])]), '')
+ response += ' '
+ _temp_output += m.replace(' '.join([f'[VID{i}]' for i in range(args['num_gen_video_tokens'])]), '')
+ else:
+ filename = save_video_to_local(m)
+ print(filename)
+ _temp_output = f'{filename} ' + _temp_output
+ response += f' '
+ text_outputs.append(_temp_output)
+ elif 'aud' in p.keys():
+ _temp_output = ''
+ for idx, m in enumerate(p['aud']):
+ if isinstance(m, str):
+ response += m.replace(' '.join([f'[AUD{i}]' for i in range(args['num_gen_audio_tokens'])]), '')
+ response += ' '
+ _temp_output += m.replace(' '.join([f'[AUD{i}]' for i in range(args['num_gen_audio_tokens'])]), '')
+ else:
+ filename = save_audio_to_local(m)
+ print(filename)
+ _temp_output = f'{filename} ' + _temp_output
+ response += f' '
+ text_outputs.append(_temp_output)
+ else:
+ pass
+ response = response[:-len(" ")].rstrip() if response.endswith(" ") else response
+ return response, text_outputs
+
+
+def re_predict(
+ prompt_input,
+ image_path,
+ audio_path,
+ video_path,
+ # thermal_path,
+ chatbot,
+ # max_length,
+ top_p,
+ temperature,
+ history,
+ modality_cache,
+ guidance_scale_for_img,
+ num_inference_steps_for_img,
+ guidance_scale_for_vid,
+ num_inference_steps_for_vid,
+ num_frames,
+ guidance_scale_for_aud,
+ num_inference_steps_for_aud,
+ audio_length_in_s
+):
+ # drop the latest query and answers and generate again
+
+ q, a = history.pop()
+ chatbot.pop()
+ return predict(q, image_path, audio_path, video_path, chatbot, top_p,
+ temperature, history, modality_cache, guidance_scale_for_img, num_inference_steps_for_img,
+ guidance_scale_for_vid, num_inference_steps_for_vid, num_frames,
+ guidance_scale_for_aud, num_inference_steps_for_aud, audio_length_in_s)
+
+
+def predict(
+ prompt_input,
+ image_path,
+ audio_path,
+ video_path,
+ chatbot,
+ top_p,
+ temperature,
+ history,
+ modality_cache,
+ guidance_scale_for_img,
+ num_inference_steps_for_img,
+ guidance_scale_for_vid,
+ num_inference_steps_for_vid,
+ num_frames,
+ guidance_scale_for_aud,
+ num_inference_steps_for_aud,
+ audio_length_in_s
+):
+ # prepare the prompt
+ prompt_text = ''
+
+ if len(history) == 0:
+ prompt_text += '### Human: '
+ if image_path is not None:
+ prompt_text += f'{image_path} '
+ if audio_path is not None:
+ prompt_text += f'{audio_path} '
+ if video_path is not None:
+ prompt_text += f'{video_path} '
+ prompt_text += f' {prompt_input}'
+ else:
+ for idx, (q, a) in enumerate(history):
+ if idx == 0:
+ prompt_text += f'### Human: {q}\n### Assistant: {a}\n###'
+ else:
+ prompt_text += f' Human: {q}\n### Assistant: {a}\n###'
+ prompt_text += ' Human: '
+ if image_path is not None:
+ prompt_text += f'{image_path} '
+ if audio_path is not None:
+ prompt_text += f'{audio_path} '
+ if video_path is not None:
+ prompt_text += f'{video_path} '
+ prompt_text += f' {prompt_input}'
+ print('prompt_text: ', prompt_text)
+ print('image_path: ', image_path)
+ print('audio_path: ', audio_path)
+ print('video_path: ', video_path)
+ response = model.generate({
+ 'prompt': prompt_text,
+ 'image_paths': [image_path] if image_path else [],
+ 'audio_paths': [audio_path] if audio_path else [],
+ 'video_paths': [video_path] if video_path else [],
+ # 'thermal_paths': [thermal_path] if thermal_path else [],
+ 'top_p': top_p,
+ 'temperature': temperature,
+ 'max_tgt_len': max_length,
+ 'modality_embeds': modality_cache,
+ 'filter_value': filter_value, 'min_word_tokens': min_word_tokens,
+ 'gen_scale_factor': gen_scale_factor, 'max_num_imgs': max_num_imgs,
+ 'stops_id': stops_id,
+ 'load_sd': load_sd,
+ 'generator': generator,
+ 'guidance_scale_for_img': guidance_scale_for_img,
+ 'num_inference_steps_for_img': num_inference_steps_for_img,
+
+ 'guidance_scale_for_vid': guidance_scale_for_vid,
+ 'num_inference_steps_for_vid': num_inference_steps_for_vid,
+ 'max_num_vids': max_num_vids,
+ 'height': height,
+ 'width': width,
+ 'num_frames': num_frames,
+
+ 'guidance_scale_for_aud': guidance_scale_for_aud,
+ 'num_inference_steps_for_aud': num_inference_steps_for_aud,
+ 'max_num_auds': max_num_auds,
+ 'audio_length_in_s': audio_length_in_s,
+ 'ENCOUNTERS': ENCOUNTERS,
+ })
+ response_chat, response_outputs = parse_reponse(response)
+ print('text_outputs: ', response_outputs)
+ user_chat, user_outputs = parse_text(prompt_input, image_path, video_path, audio_path)
+ chatbot.append((user_chat, response_chat))
+ history.append((user_outputs, ''.join(response_outputs).replace('\n###', '')))
+ return chatbot, history, modality_cache, None, None, None,
+
+
+def reset_user_input():
+ return gr.update(value='')
+
+
+def reset_dialog():
+ return [], []
+
+
+def reset_state():
+ return None, None, None, None, [], [], []
+
+
+def upload_image(conversation, chat_history, image_input):
+ input_image = Image.open(image_input.name).resize(
+ (224, 224)).convert('RGB')
+ input_image.save(image_input.name) # Overwrite with smaller image.
+ conversation += [(f' ', "")]
+ return conversation, chat_history + [input_image, ""]
+
+
+def upload_image_video_audio(gr_image, gr_video, gr_audio, chatbot, history):
+ if gr_image is not None:
+ print(gr_image)
+ chatbot.append(((gr_image.name,), None))
+ history = history + [((gr_image,), None)]
+ if gr_video is not None:
+ print(gr_video)
+ chatbot.append(((gr_video.name,), None))
+ history = history + [((gr_video,), None)]
+ if gr_audio is not None:
+ print(gr_audio)
+ chatbot.append(((gr_audio.name,), None))
+ history = history + [((gr_audio,), None)]
+ return gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), chatbot, history
+
+
+with gr.Blocks() as demo:
+
+ gr.HTML("""
+ NExT-GPT
+ This is the demo page of NExT-GPT, an any-to-any multimodal LLM that allows for seamless conversion and generation among text, image, video and audio!
+ The current initial version of NExT-GPT, limited by the quantity of fine-tuning data and the quality of the base models, may generate some low-quality or hallucinated content. Please interpret the results with caution. We will continue to update the model to enhance its performance. Thank you for trying the demo! If you have any questions or feedback, feel free to contact us.
+      
     
+ """)
+
+ with gr.Row():
+ with gr.Column(scale=0.7, min_width=500):
+ with gr.Row():
+ chatbot = gr.Chatbot(label='NExT-GPT Chatbot', avatar_images=((os.path.join(os.path.dirname(__file__), 'user.png')), (os.path.join(os.path.dirname(__file__), "bot.png")))).style(height=440)
+
+ with gr.Tab("User Input"):
+ with gr.Row(scale=3):
+ user_input = gr.Textbox(label="Text", placeholder="Key in something here...", lines=3)
+ with gr.Row(scale=3):
+ with gr.Column(scale=1):
+ # image_btn = gr.UploadButton("🖼️ Upload Image", file_types=["image"])
+ image_path = gr.Image(type="filepath", label="Image") # .style(height=200) #
+ with gr.Column(scale=1):
+ audio_path = gr.Audio(type='filepath') #.style(height=200)
+ with gr.Column(scale=1):
+ video_path = gr.Video() #.style(height=200) # , value=None, interactive=True
+ with gr.Column(scale=0.3, min_width=300):
+ with gr.Group():
+ with gr.Accordion('Text Advanced Options', open=True):
+ top_p = gr.Slider(0, 1, value=0.01, step=0.01, label="Top P", interactive=True)
+ temperature = gr.Slider(0, 1, value=1.0, step=0.01, label="Temperature", interactive=True)
+ with gr.Accordion('Image Advanced Options', open=True):
+ guidance_scale_for_img = gr.Slider(1, 10, value=7.5, step=0.5, label="Guidance scale",
+ interactive=True)
+ num_inference_steps_for_img = gr.Slider(10, 50, value=50, step=1, label="Number of inference steps",
+ interactive=True)
+ with gr.Accordion('Video Advanced Options', open=False):
+ guidance_scale_for_vid = gr.Slider(1, 10, value=7.5, step=0.5, label="Guidance scale",
+ interactive=True)
+ num_inference_steps_for_vid = gr.Slider(10, 50, value=50, step=1, label="Number of inference steps",
+ interactive=True)
+ num_frames = gr.Slider(label='Number of frames', minimum=16, maximum=32, step=8, value=24,
+ interactive=True,
+ info='Note that the content of the video also changes when you change the number of frames.')
+ with gr.Accordion('Audio Advanced Options', open=False):
+ guidance_scale_for_aud = gr.Slider(1, 10, value=7.5, step=0.5, label="Guidance scale",
+ interactive=True)
+ num_inference_steps_for_aud = gr.Slider(10, 50, value=50, step=1, label="Number of inference steps",
+ interactive=True)
+ audio_length_in_s = gr.Slider(1, 9, value=9, step=1, label="The audio length in seconds",
+ interactive=True)
+ with gr.Tab("Operation"):
+ with gr.Row(scale=1):
+ submitBtn = gr.Button(value="Submit & Run", variant="primary")
+ with gr.Row(scale=1):
+ resubmitBtn = gr.Button("Rerun")
+ with gr.Row(scale=1):
+ emptyBtn = gr.Button("Clear History")
+
+ history = gr.State([])
+ modality_cache = gr.State([])
+
+ submitBtn.click(
+ predict, [
+ user_input,
+ image_path,
+ audio_path,
+ video_path,
+ chatbot,
+ # max_length,
+ top_p,
+ temperature,
+ history,
+ modality_cache,
+ guidance_scale_for_img,
+ num_inference_steps_for_img,
+ guidance_scale_for_vid,
+ num_inference_steps_for_vid,
+ num_frames,
+ guidance_scale_for_aud,
+ num_inference_steps_for_aud,
+ audio_length_in_s
+ ], [
+ chatbot,
+ history,
+ modality_cache,
+ image_path,
+ audio_path,
+ video_path
+ ],
+ show_progress=True
+ )
+
+ resubmitBtn.click(
+ re_predict, [
+ user_input,
+ image_path,
+ audio_path,
+ video_path,
+ chatbot,
+ # max_length,
+ top_p,
+ temperature,
+ history,
+ modality_cache,
+ guidance_scale_for_img,
+ num_inference_steps_for_img,
+ guidance_scale_for_vid,
+ num_inference_steps_for_vid,
+ num_frames,
+ guidance_scale_for_aud,
+ num_inference_steps_for_aud,
+ audio_length_in_s
+ ], [
+ chatbot,
+ history,
+ modality_cache,
+ image_path,
+ audio_path,
+ video_path
+ ],
+ show_progress=True
+ )
+
+ submitBtn.click(reset_user_input, [], [user_input])
+ emptyBtn.click(reset_state, outputs=[
+ image_path,
+ audio_path,
+ video_path,
+ chatbot,
+ history,
+ modality_cache
+ ], show_progress=True)
+
+demo.queue().launch(share=True, inbrowser=True, server_name='0.0.0.0', server_port=24004)
diff --git a/code/dsconfig/stage_1.json b/code/dsconfig/stage_1.json
new file mode 100644
index 0000000000000000000000000000000000000000..b1afb1e05ec26172bd0a03c845d32e33d599a4b8
--- /dev/null
+++ b/code/dsconfig/stage_1.json
@@ -0,0 +1,58 @@
+{
+ "train_batch_size": 2,
+ "train_micro_batch_size_per_gpu": 1,
+ "gradient_accumulation_steps": 1,
+ "steps_per_print": 1,
+ "gradient_clipping": 1.0,
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu"
+ },
+ "contiguous_gradients": true,
+ "allgather_bucket_size": 500000000,
+ "allgather_partitions": true
+ },
+ "fp16": {
+ "enabled": true,
+ "opt_level": "O2",
+ "loss_scale": 64,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enable": true
+ },
+ "optimizer": {
+ "type": "Adam",
+ "params": {
+ "lr": 0.0004,
+ "betas": [
+ 0.9,
+ 0.95
+ ],
+ "eps": 1e-8,
+ "weight_decay": 0.001
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": 0,
+ "warmup_max_lr": 0.0005,
+ "warmup_num_steps": 10,
+ "total_num_steps": 10000
+ }
+ },
+ "activation_checkpointing": {
+ "partition_activations": true,
+ "cpu_checkpointing": true,
+ "contiguous_memory_optimization": false,
+ "number_checkpoints": null,
+ "synchronize_checkpoint_boundary": false,
+ "profile": false
+ }
+
+}
diff --git a/code/dsconfig/stage_2.json b/code/dsconfig/stage_2.json
new file mode 100644
index 0000000000000000000000000000000000000000..b1afb1e05ec26172bd0a03c845d32e33d599a4b8
--- /dev/null
+++ b/code/dsconfig/stage_2.json
@@ -0,0 +1,58 @@
+{
+ "train_batch_size": 2,
+ "train_micro_batch_size_per_gpu": 1,
+ "gradient_accumulation_steps": 1,
+ "steps_per_print": 1,
+ "gradient_clipping": 1.0,
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu"
+ },
+ "contiguous_gradients": true,
+ "allgather_bucket_size": 500000000,
+ "allgather_partitions": true
+ },
+ "fp16": {
+ "enabled": true,
+ "opt_level": "O2",
+ "loss_scale": 64,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enable": true
+ },
+ "optimizer": {
+ "type": "Adam",
+ "params": {
+ "lr": 0.0004,
+ "betas": [
+ 0.9,
+ 0.95
+ ],
+ "eps": 1e-8,
+ "weight_decay": 0.001
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": 0,
+ "warmup_max_lr": 0.0005,
+ "warmup_num_steps": 10,
+ "total_num_steps": 10000
+ }
+ },
+ "activation_checkpointing": {
+ "partition_activations": true,
+ "cpu_checkpointing": true,
+ "contiguous_memory_optimization": false,
+ "number_checkpoints": null,
+ "synchronize_checkpoint_boundary": false,
+ "profile": false
+ }
+
+}
diff --git a/code/dsconfig/stage_3.json b/code/dsconfig/stage_3.json
new file mode 100644
index 0000000000000000000000000000000000000000..036ccb8f8e041782ac95d28e2d746531539ba24a
--- /dev/null
+++ b/code/dsconfig/stage_3.json
@@ -0,0 +1,58 @@
+{
+ "train_batch_size": 2,
+ "train_micro_batch_size_per_gpu": 1,
+ "gradient_accumulation_steps": 1,
+ "steps_per_print": 1,
+ "gradient_clipping": 1.0,
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu"
+ },
+ "contiguous_gradients": true,
+ "allgather_bucket_size": 500000000,
+ "allgather_partitions": true
+ },
+ "fp16": {
+ "enabled": true,
+ "opt_level": "O2",
+ "loss_scale": 64,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enable": true
+ },
+ "optimizer": {
+ "type": "Adam",
+ "params": {
+ "lr": 0.0005,
+ "betas": [
+ 0.9,
+ 0.95
+ ],
+ "eps": 1e-8,
+ "weight_decay": 0.001
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": 0,
+ "warmup_max_lr": 0.0005,
+ "warmup_num_steps": 10,
+ "total_num_steps": 10000
+ }
+ },
+ "activation_checkpointing": {
+ "partition_activations": true,
+ "cpu_checkpointing": true,
+ "contiguous_memory_optimization": false,
+ "number_checkpoints": null,
+ "synchronize_checkpoint_boundary": false,
+ "profile": false
+ }
+
+}
diff --git a/code/header.py b/code/header.py
new file mode 100644
index 0000000000000000000000000000000000000000..01df0b9a5b7a25152c683068af9647e0c4738b02
--- /dev/null
+++ b/code/header.py
@@ -0,0 +1,39 @@
+import torch
+import datetime
+import types
+import deepspeed
+from transformers.deepspeed import HfDeepSpeedConfig
+import transformers
+import numpy as np
+from collections import OrderedDict
+from torch.utils.data import Dataset, DataLoader
+from torch.nn.utils import clip_grad_norm_
+from torch.cuda.amp import autocast, GradScaler
+from torch.nn import DataParallel
+from torch.optim import lr_scheduler
+import torch.optim as optim
+import torch.nn as nn
+import torch.nn.functional as F
+from tqdm import tqdm
+import os
+import re
+import math
+import random
+import json
+import time
+import logging
+from omegaconf import OmegaConf
+from copy import deepcopy
+import ipdb
+import argparse
+import data
+from transformers import LlamaTokenizer, LlamaForCausalLM, LlamaConfig
+from torch.nn.utils.rnn import pad_sequence
+from peft import LoraConfig, TaskType, get_peft_model
+from diffusers.utils import export_to_video
+import scipy
+from torch.utils.tensorboard import SummaryWriter
+
+logging.getLogger("transformers").setLevel(logging.WARNING)
+logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)
+os.environ['TOKENIZERS_PARALLELISM'] = 'false'
diff --git a/code/inference.py b/code/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..211866480186edeee7e5bd6523b84ea5b14af20f
--- /dev/null
+++ b/code/inference.py
@@ -0,0 +1,175 @@
+import os
+from model.anyToImageVideoAudio import NextGPTModel
+import torch
+import json
+from config import *
+import matplotlib.pyplot as plt
+from diffusers.utils import export_to_video
+import scipy
+
+
+def predict(
+ input,
+ image_path=None,
+ audio_path=None,
+ video_path=None,
+ thermal_path=None,
+ max_tgt_len=200,
+ top_p=10.0,
+ temperature=0.1,
+ history=None,
+ modality_cache=None,
+ filter_value=-float('Inf'), min_word_tokens=0,
+ gen_scale_factor=10.0, max_num_imgs=1,
+ stops_id=None,
+ load_sd=True,
+ generator=None,
+ guidance_scale_for_img=7.5,
+ num_inference_steps_for_img=50,
+ guidance_scale_for_vid=7.5,
+ num_inference_steps_for_vid=50,
+ max_num_vids=1,
+ height=320,
+ width=576,
+ num_frames=24,
+ guidance_scale_for_aud=7.5,
+ num_inference_steps_for_aud=50,
+ max_num_auds=1,
+ audio_length_in_s=9,
+ ENCOUNTERS=1,
+):
+ if image_path is None and audio_path is None and video_path is None and thermal_path is None:
+ # return [(input, "There is no input data provided! Please upload your data and start the conversation.")]
+ print('no image, audio, video, and thermal are input')
+ else:
+ print(
+ f'[!] image path: {image_path}\n[!] audio path: {audio_path}\n[!] video path: {video_path}\n[!] thermal path: {thermal_path}')
+
+ # prepare the prompt
+ prompt_text = ''
+ if history != None:
+ for idx, (q, a) in enumerate(history):
+ if idx == 0:
+ prompt_text += f'{q}\n### Assistant: {a}\n###'
+ else:
+ prompt_text += f' Human: {q}\n### Assistant: {a}\n###'
+ prompt_text += f'### Human: {input}'
+ else:
+ prompt_text += f'### Human: {input}'
+
+ print('prompt_text: ', prompt_text)
+
+ response = model.generate({
+ 'prompt': prompt_text,
+ 'image_paths': [image_path] if image_path else [],
+ 'audio_paths': [audio_path] if audio_path else [],
+ 'video_paths': [video_path] if video_path else [],
+ 'thermal_paths': [thermal_path] if thermal_path else [],
+ 'top_p': top_p,
+ 'temperature': temperature,
+ 'max_tgt_len': max_tgt_len,
+ 'modality_embeds': modality_cache,
+ 'filter_value': filter_value, 'min_word_tokens': min_word_tokens,
+ 'gen_scale_factor': gen_scale_factor, 'max_num_imgs': max_num_imgs,
+ 'stops_id': stops_id,
+ 'load_sd': load_sd,
+ 'generator': generator,
+ 'guidance_scale_for_img': guidance_scale_for_img,
+ 'num_inference_steps_for_img': num_inference_steps_for_img,
+
+ 'guidance_scale_for_vid': guidance_scale_for_vid,
+ 'num_inference_steps_for_vid': num_inference_steps_for_vid,
+ 'max_num_vids': max_num_vids,
+ 'height': height,
+ 'width': width,
+ 'num_frames': num_frames,
+
+ 'guidance_scale_for_aud': guidance_scale_for_aud,
+ 'num_inference_steps_for_aud': num_inference_steps_for_aud,
+ 'max_num_auds': max_num_auds,
+ 'audio_length_in_s': audio_length_in_s,
+ 'ENCOUNTERS': ENCOUNTERS,
+
+ })
+ return response
+
+
+if __name__ == '__main__':
+ # init the model
+
+ g_cuda = torch.Generator(device='cuda').manual_seed(1337)
+ args = {'model': 'nextgpt',
+ 'nextgpt_ckpt_path': '../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/',
+ 'max_length': 128,
+ 'stage': 3,
+ 'root_dir': '../',
+ 'mode': 'validate',
+ }
+ args.update(load_config(args))
+
+ model = NextGPTModel(**args)
+ delta_ckpt = torch.load(os.path.join(args['nextgpt_ckpt_path'], 'pytorch_model.pt'), map_location=torch.device('cuda'))
+ # print(delta_ckpt)
+ model.load_state_dict(delta_ckpt, strict=False)
+ model = model.eval().half().cuda()
+ # model = model.eval().cuda()
+ print(f'[!] init the 7b model over ...')
+
+ """Override Chatbot.postprocess"""
+ max_tgt_length = 150
+ top_p = 1.0
+ temperature = 0.4
+ modality_cache = None
+
+ prompt = 'show me a video. a woman walk a dop in the park.'
+
+ history = []
+
+ output = predict(input=prompt, history=history,
+ max_tgt_len=max_tgt_length, top_p=top_p,
+ temperature=temperature, modality_cache=modality_cache,
+ filter_value=-float('Inf'), min_word_tokens=10,
+ gen_scale_factor=4.0, max_num_imgs=1,
+ stops_id=[[835]],
+ load_sd=True,
+ generator=g_cuda,
+ guidance_scale_for_img=7.5,
+ num_inference_steps_for_img=50,
+ guidance_scale_for_vid=7.5,
+ num_inference_steps_for_vid=50,
+ max_num_vids=1,
+ height=320,
+ width=576,
+ num_frames=24,
+ ENCOUNTERS=1
+ )
+
+ # print("output: ", output)
+
+ for i in output:
+ if isinstance(i, str):
+ print(i)
+ elif 'img' in i.keys():
+ for m in i['img']:
+ if isinstance(m, str):
+ print(m)
+ else:
+ m[0].save(f'./assets/images/{prompt}.jpg')
+
+ elif 'vid' in i.keys():
+ for idx, m in enumerate(i['vid']):
+ if isinstance(m, str):
+ print(m)
+ else:
+ video_path = export_to_video(video_frames=m, output_video_path=f'./assets/videos/{prompt}.mp4')
+ print("video_path: ", video_path)
+ elif 'aud' in i.keys():
+ for idx, m in enumerate(i['aud']):
+ if isinstance(m, str):
+ print(m)
+ else:
+ audio_path = f'./assets/audios/{prompt}.wav'
+ scipy.io.wavfile.write(audio_path, rate=16000, data=m)
+ print("video_path: ", audio_path)
+ else:
+ pass
diff --git a/code/model/ImageBind/CODE_OF_CONDUCT.md b/code/model/ImageBind/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..f913b6a55a6c5ab6e1224e11fc039c3d4c3b6283
--- /dev/null
+++ b/code/model/ImageBind/CODE_OF_CONDUCT.md
@@ -0,0 +1,80 @@
+# Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to make participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies within all project spaces, and it also applies when
+an individual is representing the project or its community in public spaces.
+Examples of representing a project or community include using an official
+project e-mail address, posting via an official social media account, or acting
+as an appointed representative at an online or offline event. Representation of
+a project may be further defined and clarified by project maintainers.
+
+This Code of Conduct also applies outside the project spaces when there is a
+reasonable belief that an individual's behavior may have a negative impact on
+the project or its community.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at . All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
\ No newline at end of file
diff --git a/code/model/ImageBind/CONTRIBUTING.md b/code/model/ImageBind/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..63d0b751e8a00b606ddff92e2524faa3c90a63b0
--- /dev/null
+++ b/code/model/ImageBind/CONTRIBUTING.md
@@ -0,0 +1,31 @@
+# Contributing to ImageBind
+We want to make contributing to this project as easy and transparent as
+possible.
+
+## Pull Requests
+We actively welcome your pull requests.
+
+1. Fork the repo and create your branch from `main`.
+2. If you've added code that should be tested, add tests.
+3. If you've changed APIs, update the documentation.
+4. Ensure the test suite passes.
+5. Make sure your code lints.
+6. If you haven't already, complete the Contributor License Agreement ("CLA").
+
+## Contributor License Agreement ("CLA")
+In order to accept your pull request, we need you to submit a CLA. You only need
+to do this once to work on any of Meta's open source projects.
+
+Complete your CLA here:
+
+## Issues
+We use GitHub issues to track public bugs. Please ensure your description is
+clear and has sufficient instructions to be able to reproduce the issue.
+
+Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
+disclosure of security bugs. In those cases, please go through the process
+outlined on that page and do not file a public issue.
+
+## License
+By contributing to Omnivore, you agree that your contributions will be licensed
+under the [LICENSE](LICENSE) file in the root directory of this source tree.
diff --git a/code/model/ImageBind/LICENSE b/code/model/ImageBind/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..bfef380bf7d9cb74ec9ba533b37c3fbeef3bdc09
--- /dev/null
+++ b/code/model/ImageBind/LICENSE
@@ -0,0 +1,437 @@
+Attribution-NonCommercial-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
+Public License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-NonCommercial-ShareAlike 4.0 International Public License
+("Public License"). To the extent this Public License may be
+interpreted as a contract, You are granted the Licensed Rights in
+consideration of Your acceptance of these terms and conditions, and the
+Licensor grants You such rights in consideration of benefits the
+Licensor receives from making the Licensed Material available under
+these terms and conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-NC-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution, NonCommercial, and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. NonCommercial means not primarily intended for or directed towards
+ commercial advantage or monetary compensation. For purposes of
+ this Public License, the exchange of the Licensed Material for
+ other material subject to Copyright and Similar Rights by digital
+ file-sharing or similar means is NonCommercial provided there is
+ no payment of monetary compensation in connection with the
+ exchange.
+
+ l. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ m. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ n. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part, for NonCommercial purposes only; and
+
+ b. produce, reproduce, and Share Adapted Material for
+ NonCommercial purposes only.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties, including when
+ the Licensed Material is used other than for NonCommercial
+ purposes.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-NC-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database for NonCommercial purposes
+ only;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+ including for purposes of Section 3(b); and
+
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+=======================================================================
+
+Creative Commons is not a party to its public
+licenses. Notwithstanding, Creative Commons may elect to apply one of
+its public licenses to material it publishes and in those instances
+will be considered the “Licensor.” The text of the Creative Commons
+public licenses is dedicated to the public domain under the CC0 Public
+Domain Dedication. Except for the limited purpose of indicating that
+material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the
+public licenses.
+
+Creative Commons may be contacted at creativecommons.org.
\ No newline at end of file
diff --git a/code/model/ImageBind/README.md b/code/model/ImageBind/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..028fa988bb6cd9843aec9454636e1541b53680e7
--- /dev/null
+++ b/code/model/ImageBind/README.md
@@ -0,0 +1,155 @@
+# ImageBind: One Embedding Space To Bind Them All
+
+**[FAIR, Meta AI](https://ai.facebook.com/research/)**
+
+Rohit Girdhar*,
+Alaaeldin El-Nouby*,
+Zhuang Liu,
+Mannat Singh,
+Kalyan Vasudev Alwala,
+Armand Joulin,
+Ishan Misra*
+
+To appear at CVPR 2023 (*Highlighted paper*)
+
+[[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)]
+
+PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
+
+ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
+
+
+
+
+
+## ImageBind model
+
+Emergent zero-shot classification performance.
+
+
+
+ Model
+ IN1k
+ K400
+ NYU-D
+ ESC
+ LLVIP
+ Ego4D
+ download
+
+
+ imagebind_huge
+ 77.7
+ 50.0
+ 54.0
+ 66.9
+ 63.4
+ 25.0
+ checkpoint
+
+
+
+
+## Usage
+
+Install pytorch 1.13+ and other 3rd party dependencies.
+
+```shell
+conda create --name imagebind python=3.8 -y
+conda activate imagebind
+
+pip install -r requirements.txt
+```
+
+For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
+
+```
+pip install soundfile
+```
+
+
+Extract and compare features across modalities (e.g. Image, Text and Audio).
+
+```python
+import data
+import torch
+from models import imagebind_model
+from models.imagebind_model import ModalityType
+
+text_list=["A dog.", "A car", "A bird"]
+image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
+audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
+
+device = "cuda:0" if torch.cuda.is_available() else "cpu"
+
+# Instantiate model
+model = imagebind_model.imagebind_huge(pretrained=True)
+model.eval()
+model.to(device)
+
+# Load data
+inputs = {
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
+ ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
+}
+
+with torch.no_grad():
+ embeddings = model(inputs)
+
+print(
+ "Vision x Text: ",
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
+)
+print(
+ "Audio x Text: ",
+ torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
+)
+print(
+ "Vision x Audio: ",
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
+)
+
+# Expected output:
+#
+# Vision x Text:
+# tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
+# [3.3836e-05, 9.9994e-01, 2.4118e-05],
+# [4.7997e-05, 1.3496e-02, 9.8646e-01]])
+#
+# Audio x Text:
+# tensor([[1., 0., 0.],
+# [0., 1., 0.],
+# [0., 0., 1.]])
+#
+# Vision x Audio:
+# tensor([[0.8070, 0.1088, 0.0842],
+# [0.1036, 0.7884, 0.1079],
+# [0.0018, 0.0022, 0.9960]])
+
+```
+
+## Model card
+Please see the [model card](model_card.md) for details.
+
+## License
+
+ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
+
+## Contributing
+
+See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
+
+## Citing ImageBind
+
+If you find this repository useful, please consider giving a star :star: and citation
+
+```
+@inproceedings{girdhar2023imagebind,
+ title={ImageBind: One Embedding Space To Bind Them All},
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
+and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
+ booktitle={CVPR},
+ year={2023}
+}
+```
diff --git a/code/model/ImageBind/__init__.py b/code/model/ImageBind/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d872d0725710d6dde3af3b6e05382922f074338b
--- /dev/null
+++ b/code/model/ImageBind/__init__.py
@@ -0,0 +1,2 @@
+from .models import imagebind_model
+from .models.imagebind_model import ModalityType
diff --git a/code/model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz b/code/model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz
new file mode 100644
index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113
--- /dev/null
+++ b/code/model/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
+size 1356917
diff --git a/code/model/ImageBind/data.py b/code/model/ImageBind/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bc32bf17bc95a280051817d0d7bd379f1416509
--- /dev/null
+++ b/code/model/ImageBind/data.py
@@ -0,0 +1,375 @@
+#!/usr/bin/env python3
+# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import math
+
+import torch
+import torch.nn as nn
+import torchaudio
+import logging
+
+from .models.multimodal_preprocessors import SimpleTokenizer
+from PIL import Image
+from pytorchvideo import transforms as pv_transforms
+from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
+from pytorchvideo.data.encoded_video import EncodedVideo
+
+from torchvision import transforms
+from torchvision.transforms._transforms_video import NormalizeVideo
+
+DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
+
+BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz"
+
+
+def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
+ waveform -= waveform.mean()
+ fbank = torchaudio.compliance.kaldi.fbank(
+ waveform,
+ htk_compat=True,
+ sample_frequency=sample_rate,
+ use_energy=False,
+ window_type="hanning",
+ num_mel_bins=num_mel_bins,
+ dither=0.0,
+ frame_length=25,
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
+ )
+ # Convert to [mel_bins, num_frames] shape
+ fbank = fbank.transpose(0, 1)
+ # Pad to target_length
+ n_frames = fbank.size(1)
+ p = target_length - n_frames
+ # if p is too large (say >20%), flash a warning
+ if abs(p) / n_frames > 0.2:
+ logging.warning(
+ "Large gap between audio n_frames(%d) and "
+ "target_length (%d). Is the audio_target_length "
+ "setting correct?",
+ n_frames,
+ target_length,
+ )
+ # cut and pad
+ if p > 0:
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
+ elif p < 0:
+ fbank = fbank[:, 0:target_length]
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
+ # channel image
+ fbank = fbank.unsqueeze(0)
+ return fbank
+
+
+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_and_transform_vision_data(image_paths, device):
+ if image_paths is None:
+ return None
+
+ image_ouputs = []
+ for image_path in image_paths:
+ data_transform = transforms.Compose(
+ [
+ transforms.Resize(
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
+ ),
+ transforms.CenterCrop(224),
+ transforms.ToTensor(),
+ transforms.Normalize(
+ mean=(0.48145466, 0.4578275, 0.40821073),
+ std=(0.26862954, 0.26130258, 0.27577711),
+ ),
+ ]
+ )
+ if isinstance(image_path, Image.Image):
+ image = image_path
+ else:
+ with open(image_path, "rb") as fopen:
+ image = Image.open(fopen).convert("RGB")
+
+ image = data_transform(image).to(device)
+ image_ouputs.append(image)
+ return torch.stack(image_ouputs, dim=0)
+
+
+def load_and_transform_thermal_data(thermal_paths, device):
+ if thermal_paths is None:
+ return None
+
+ thermal_ouputs = []
+ for thermal_path in thermal_paths:
+ data_transform = transforms.Compose(
+ [
+ transforms.Resize(
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
+ ),
+ transforms.CenterCrop(224),
+ transforms.ToTensor(),
+ ]
+ )
+ with open(thermal_path, "rb") as fopen:
+ thermal = Image.open(fopen).convert("L")
+ thermal = data_transform(thermal).to(device)
+ thermal_ouputs.append(thermal)
+ return torch.stack(thermal_ouputs, dim=0)
+
+
+def load_and_transform_text(text, device):
+ if text is None:
+ return None
+ tokenizer = SimpleTokenizer(bpe_path=BPE_PATH)
+ tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
+ tokens = torch.cat(tokens, dim=0)
+ return tokens
+
+
+def load_and_transform_audio_data(
+ audio_paths,
+ device,
+ num_mel_bins=128,
+ target_length=204,
+ sample_rate=16000,
+ clip_duration=2,
+ clips_per_video=3,
+ mean=-4.268,
+ std=9.138,
+):
+ if audio_paths is None:
+ return None
+
+ audio_outputs = []
+ clip_sampler = ConstantClipsPerVideoSampler(
+ clip_duration=clip_duration, clips_per_video=clips_per_video
+ )
+
+ for audio_path in audio_paths:
+ waveform, sr = torchaudio.load(audio_path)
+ if sample_rate != sr:
+ waveform = torchaudio.functional.resample(
+ waveform, orig_freq=sr, new_freq=sample_rate
+ )
+ all_clips_timepoints = get_clip_timepoints(
+ clip_sampler, waveform.size(1) / sample_rate
+ )
+ all_clips = []
+ for clip_timepoints in all_clips_timepoints:
+ waveform_clip = waveform[
+ :,
+ int(clip_timepoints[0] * sample_rate): int(
+ clip_timepoints[1] * sample_rate
+ ),
+ ]
+ waveform_melspec = waveform2melspec(
+ waveform_clip, sample_rate, num_mel_bins, target_length
+ )
+ all_clips.append(waveform_melspec)
+
+ normalize = transforms.Normalize(mean=mean, std=std)
+ all_clips = [normalize(ac).to(device) for ac in all_clips]
+
+ all_clips = torch.stack(all_clips, dim=0)
+ audio_outputs.append(all_clips)
+
+ return torch.stack(audio_outputs, dim=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 crop_boxes(boxes, x_offset, y_offset):
+ """
+ Perform crop on the bounding boxes given the offsets.
+ Args:
+ boxes (ndarray or None): bounding boxes to perform crop. The dimension
+ is `num boxes` x 4.
+ x_offset (int): cropping offset in the x axis.
+ y_offset (int): cropping offset in the y axis.
+ Returns:
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
+ `num boxes` x 4.
+ """
+ cropped_boxes = boxes.copy()
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
+
+ return cropped_boxes
+
+
+def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
+ """
+ Perform uniform spatial sampling on the images and corresponding boxes.
+ Args:
+ images (tensor): images to perform uniform crop. The dimension is
+ `num frames` x `channel` x `height` x `width`.
+ size (int): size of height and weight to crop the images.
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
+ crop if height is larger than width.
+ boxes (ndarray or None): optional. Corresponding boxes to images.
+ Dimension is `num boxes` x 4.
+ scale_size (int): optinal. If not None, resize the images to scale_size before
+ performing any crop.
+ Returns:
+ cropped (tensor): images with dimension of
+ `num frames` x `channel` x `size` x `size`.
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
+ `num boxes` x 4.
+ """
+ assert spatial_idx in [0, 1, 2]
+ ndim = len(images.shape)
+ if ndim == 3:
+ images = images.unsqueeze(0)
+ height = images.shape[2]
+ width = images.shape[3]
+
+ if scale_size is not None:
+ if width <= height:
+ width, height = scale_size, int(height / width * scale_size)
+ else:
+ width, height = int(width / height * scale_size), scale_size
+ images = torch.nn.functional.interpolate(
+ images,
+ size=(height, width),
+ mode="bilinear",
+ align_corners=False,
+ )
+
+ y_offset = int(math.ceil((height - size) / 2))
+ x_offset = int(math.ceil((width - size) / 2))
+
+ if height > width:
+ if spatial_idx == 0:
+ y_offset = 0
+ elif spatial_idx == 2:
+ y_offset = height - size
+ else:
+ if spatial_idx == 0:
+ x_offset = 0
+ elif spatial_idx == 2:
+ x_offset = width - size
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
+ if ndim == 3:
+ cropped = cropped.squeeze(0)
+ return cropped, cropped_boxes
+
+
+class SpatialCrop(nn.Module):
+ """
+ Convert the video into 3 smaller clips spatially. Must be used after the
+ temporal crops to get spatial crops, and should be used with
+ -2 in the spatial crop at the slowfast augmentation stage (so full
+ frames are passed in here). Will return a larger list with the
+ 3x spatial crops as well.
+ """
+
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
+ super().__init__()
+ self.crop_size = crop_size
+ if num_crops == 3:
+ self.crops_to_ext = [0, 1, 2]
+ self.flipped_crops_to_ext = []
+ elif num_crops == 1:
+ self.crops_to_ext = [1]
+ self.flipped_crops_to_ext = []
+ else:
+ raise NotImplementedError("Nothing else supported yet")
+
+ def forward(self, videos):
+ """
+ Args:
+ videos: A list of C, T_I_V_A.txt, H, W videos.
+ Returns:
+ videos: A list with 3x the number of elements. Each video converted
+ to C, T_I_V_A.txt, H', W' by spatial cropping.
+ """
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T_I_V_A.txt,H,W)"
+ res = []
+ for video in videos:
+ for spatial_idx in self.crops_to_ext:
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
+ if not self.flipped_crops_to_ext:
+ continue
+ flipped_video = transforms.functional.hflip(video)
+ for spatial_idx in self.flipped_crops_to_ext:
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
+ return res
+
+
+def load_and_transform_video_data(
+ video_paths,
+ device,
+ clip_duration=2,
+ clips_per_video=5,
+ sample_rate=16000,
+):
+ if video_paths is None:
+ return None
+
+ video_outputs = []
+ video_transform = transforms.Compose(
+ [
+ pv_transforms.ShortSideScale(224),
+ NormalizeVideo(
+ mean=(0.48145466, 0.4578275, 0.40821073),
+ std=(0.26862954, 0.26130258, 0.27577711),
+ ),
+ ]
+ )
+
+ clip_sampler = ConstantClipsPerVideoSampler(
+ clip_duration=clip_duration, clips_per_video=clips_per_video
+ )
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
+
+ for video_path in video_paths:
+ video = EncodedVideo.from_path(
+ video_path,
+ decoder="decord",
+ decode_audio=False,
+ # **{"sample_rate": sample_rate},
+ )
+
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
+
+ all_video = []
+ for clip_timepoints in all_clips_timepoints:
+ # Read the clip, get frames
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
+ if clip is None:
+ raise ValueError("No clip found")
+ video_clip = frame_sampler(clip["video"])
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
+
+ all_video.append(video_clip)
+
+ all_video = [video_transform(clip) for clip in all_video]
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
+
+ all_video = torch.stack(all_video, dim=0)
+ video_outputs.append(all_video)
+
+ return torch.stack(video_outputs, dim=0).to(device)
diff --git a/code/model/ImageBind/model_card.md b/code/model/ImageBind/model_card.md
new file mode 100644
index 0000000000000000000000000000000000000000..c7bb26500b6590b64ffa6350f37be80dc88612d8
--- /dev/null
+++ b/code/model/ImageBind/model_card.md
@@ -0,0 +1,94 @@
+# Model Card for ImageBind
+
+Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.
+Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.
+
+# Model Details
+
+## Model Description
+
+
+Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images
+
+- **Developed by:** Meta AI
+- **Model type:** Multimodal model
+- **Language(s) (NLP):** en
+- **License:** CC BY-NC-SA 4.0
+- **Resources for more information:**
+ - [GitHub Repo](https://github.com/facebookresearch/ImageBind)
+
+
+# Uses
+
+
+This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images.
+We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities.
+
+## Out-of-Scope Use
+
+
+
+
+This model is *NOT* intended to be used in any real world application -- commercial or otherwise.
+It may produce harmful associations with different inputs.
+The model needs to be investigated and likely re-trained on specific data for any such application.
+The model is expected to work better on web-based visual data since it was trained on such data.
+The text encoder is likely to work only on English language text because of the underlying training datasets.
+
+# Bias, Risks, and Limitations
+
+
+Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness).
+Since our model uses such models as initialization, it will exhibit such biases too.
+Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes.
+
+
+
+# Training Details
+
+## Training Data
+
+
+
+ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.
+In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.
+We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset.
+We provide the exact training data details in the paper.
+
+
+## Training Procedure
+
+
+Please refer to the research paper and github repo for exact details on this.
+
+# Evaluation
+
+## Testing Data, Factors & Metrics
+
+We evaluate the model on a variety of different classification benchmarks for each modality.
+The evaluation details are presented in the paper.
+The models performance is measured using standard classification metrics such as accuracy and mAP.
+
+# Citation
+
+
+
+**BibTeX:**
+```
+@inproceedings{girdhar2023imagebind,
+ title={ImageBind: One Embedding Space To Bind Them All},
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
+and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
+ booktitle={CVPR},
+ year={2023}
+}
+```
+
+
+# Model Card Contact
+
+Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com
+
+# How to Get Started with the Model
+
+Our github repo provides a simple example to extract embeddings from images, audio etc.
diff --git a/code/model/ImageBind/models/__init__.py b/code/model/ImageBind/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/model/ImageBind/models/helpers.py b/code/model/ImageBind/models/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..049e1f1b0580832e8574350991bf347b6da81482
--- /dev/null
+++ b/code/model/ImageBind/models/helpers.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import math
+
+import einops
+import numpy as np
+import torch
+
+import torch.nn as nn
+
+
+class Normalize(nn.Module):
+ def __init__(self, dim: int) -> None:
+ super().__init__()
+ self.dim = dim
+
+ def forward(self, x):
+ return torch.nn.functional.normalize(x, dim=self.dim, p=2)
+
+
+class LearnableLogitScaling(nn.Module):
+ def __init__(
+ self,
+ logit_scale_init: float = 1 / 0.07,
+ learnable: bool = True,
+ max_logit_scale: float = 100,
+ ) -> None:
+ super().__init__()
+ self.max_logit_scale = max_logit_scale
+ self.logit_scale_init = logit_scale_init
+ self.learnable = learnable
+ log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
+ if learnable:
+ self.log_logit_scale = nn.Parameter(log_logit_scale)
+ else:
+ self.register_buffer("log_logit_scale", log_logit_scale)
+
+ def forward(self, x):
+ return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
+
+ def extra_repr(self):
+ st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}, max_logit_scale={self.max_logit_scale}"
+ return st
+
+
+class EinOpsRearrange(nn.Module):
+ def __init__(self, rearrange_expr: str, **kwargs) -> None:
+ super().__init__()
+ self.rearrange_expr = rearrange_expr
+ self.kwargs = kwargs
+
+ def forward(self, x):
+ assert isinstance(x, torch.Tensor)
+ return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
+
+
+class VerboseNNModule(nn.Module):
+ """
+ Wrapper around nn.Module that prints registered buffers and parameter names.
+ """
+
+ @staticmethod
+ def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
+ st = (
+ "("
+ + name
+ + "): "
+ + "tensor("
+ + str(tuple(tensor[1].shape))
+ + ", requires_grad="
+ + str(tensor[1].requires_grad)
+ + ")\n"
+ )
+ return st
+
+ def extra_repr(self) -> str:
+ named_modules = set()
+ for p in self.named_modules():
+ named_modules.update([p[0]])
+ named_modules = list(named_modules)
+
+ string_repr = ""
+ for p in self.named_parameters():
+ name = p[0].split(".")[0]
+ if name not in named_modules:
+ string_repr += self.get_readable_tensor_repr(name, p)
+
+ for p in self.named_buffers():
+ name = p[0].split(".")[0]
+ string_repr += self.get_readable_tensor_repr(name, p)
+
+ return string_repr
+
+
+def cast_if_src_dtype(
+ tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
+):
+ updated = False
+ if tensor.dtype == src_dtype:
+ tensor = tensor.to(dtype=tgt_dtype)
+ updated = True
+ return tensor, updated
+
+
+class QuickGELU(nn.Module):
+ # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
+ def forward(self, x: torch.Tensor):
+ return x * torch.sigmoid(1.702 * x)
+
+
+class SelectElement(nn.Module):
+ def __init__(self, index) -> None:
+ super().__init__()
+ self.index = index
+
+ def forward(self, x):
+ assert x.ndim >= 3
+ return x[:, self.index, ...]
+
+
+class SelectEOSAndProject(nn.Module):
+ """
+ Text Pooling used in OpenCLIP
+ """
+
+ def __init__(self, proj: nn.Module) -> None:
+ super().__init__()
+ self.proj = proj
+
+ def forward(self, x, seq_len):
+ assert x.ndim == 3
+ # x is of shape B x L x D
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ x = x[torch.arange(x.shape[0]), seq_len]
+ x = self.proj(x)
+ return x
diff --git a/code/model/ImageBind/models/imagebind_model.py b/code/model/ImageBind/models/imagebind_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba1981e8790b98131e2a89388142a79c6de94628
--- /dev/null
+++ b/code/model/ImageBind/models/imagebind_model.py
@@ -0,0 +1,521 @@
+#!/usr/bin/env python3
+# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+import os
+import urllib
+from functools import partial
+from types import SimpleNamespace
+
+import torch
+import torch.nn as nn
+
+from .helpers import (
+ EinOpsRearrange,
+ LearnableLogitScaling,
+ Normalize,
+ SelectElement,
+ SelectEOSAndProject,
+)
+from .multimodal_preprocessors import (
+ AudioPreprocessor,
+ IMUPreprocessor,
+ PadIm2Video,
+ PatchEmbedGeneric,
+ RGBDTPreprocessor,
+ SpatioTemporalPosEmbeddingHelper,
+ TextPreprocessor,
+ ThermalPreprocessor,
+)
+
+from .transformer import MultiheadAttention, SimpleTransformer
+
+
+ModalityType = SimpleNamespace(
+ VISION="vision",
+ TEXT="text",
+ AUDIO="audio",
+ THERMAL="thermal",
+ DEPTH="depth",
+ IMU="imu",
+)
+
+
+class ImageBindModel(nn.Module):
+ def __init__(
+ self,
+ video_frames=2,
+ kernel_size=(2, 14, 14),
+ audio_kernel_size=16,
+ audio_stride=10,
+ out_embed_dim=768,
+ vision_embed_dim=1024,
+ vision_num_blocks=24,
+ vision_num_heads=16,
+ audio_embed_dim=768,
+ audio_num_blocks=12,
+ audio_num_heads=12,
+ audio_num_mel_bins=128,
+ audio_target_len=204,
+ audio_drop_path=0.1,
+ text_embed_dim=768,
+ text_num_blocks=12,
+ text_num_heads=12,
+ depth_embed_dim=384,
+ depth_kernel_size=16,
+ depth_num_blocks=12,
+ depth_num_heads=8,
+ depth_drop_path=0.0,
+ thermal_embed_dim=768,
+ thermal_kernel_size=16,
+ thermal_num_blocks=12,
+ thermal_num_heads=12,
+ thermal_drop_path=0.0,
+ imu_embed_dim=512,
+ imu_kernel_size=8,
+ imu_num_blocks=6,
+ imu_num_heads=8,
+ imu_drop_path=0.7,
+ ):
+ super().__init__()
+
+ self.modality_preprocessors = self._create_modality_preprocessors(
+ video_frames,
+ vision_embed_dim,
+ kernel_size,
+ text_embed_dim,
+ audio_embed_dim,
+ audio_kernel_size,
+ audio_stride,
+ audio_num_mel_bins,
+ audio_target_len,
+ depth_embed_dim,
+ depth_kernel_size,
+ thermal_embed_dim,
+ thermal_kernel_size,
+ imu_embed_dim,
+ )
+
+ self.modality_trunks = self._create_modality_trunks(
+ vision_embed_dim,
+ vision_num_blocks,
+ vision_num_heads,
+ text_embed_dim,
+ text_num_blocks,
+ text_num_heads,
+ audio_embed_dim,
+ audio_num_blocks,
+ audio_num_heads,
+ audio_drop_path,
+ depth_embed_dim,
+ depth_num_blocks,
+ depth_num_heads,
+ depth_drop_path,
+ thermal_embed_dim,
+ thermal_num_blocks,
+ thermal_num_heads,
+ thermal_drop_path,
+ imu_embed_dim,
+ imu_num_blocks,
+ imu_num_heads,
+ imu_drop_path,
+ )
+
+ self.modality_heads = self._create_modality_heads(
+ out_embed_dim,
+ vision_embed_dim,
+ text_embed_dim,
+ audio_embed_dim,
+ depth_embed_dim,
+ thermal_embed_dim,
+ imu_embed_dim,
+ )
+
+ self.modality_postprocessors = self._create_modality_postprocessors(
+ out_embed_dim
+ )
+
+ def _create_modality_preprocessors(
+ self,
+ video_frames=2,
+ vision_embed_dim=1024,
+ kernel_size=(2, 14, 14),
+ text_embed_dim=768,
+ audio_embed_dim=768,
+ audio_kernel_size=16,
+ audio_stride=10,
+ audio_num_mel_bins=128,
+ audio_target_len=204,
+ depth_embed_dim=768,
+ depth_kernel_size=16,
+ thermal_embed_dim=768,
+ thermal_kernel_size=16,
+ imu_embed_dim=512,
+ ):
+ rgbt_stem = PatchEmbedGeneric(
+ proj_stem=[
+ PadIm2Video(pad_type="repeat", ntimes=2),
+ nn.Conv3d(
+ in_channels=3,
+ kernel_size=kernel_size,
+ out_channels=vision_embed_dim,
+ stride=kernel_size,
+ bias=False,
+ ),
+ ]
+ )
+ rgbt_preprocessor = RGBDTPreprocessor(
+ img_size=[3, video_frames, 224, 224],
+ num_cls_tokens=1,
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
+ rgbt_stem=rgbt_stem,
+ depth_stem=None,
+ )
+
+ text_preprocessor = TextPreprocessor(
+ context_length=77,
+ vocab_size=49408,
+ embed_dim=text_embed_dim,
+ causal_masking=True,
+ )
+
+ audio_stem = PatchEmbedGeneric(
+ proj_stem=[
+ nn.Conv2d(
+ in_channels=1,
+ kernel_size=audio_kernel_size,
+ stride=audio_stride,
+ out_channels=audio_embed_dim,
+ bias=False,
+ ),
+ ],
+ norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
+ )
+ audio_preprocessor = AudioPreprocessor(
+ img_size=[1, audio_num_mel_bins, audio_target_len],
+ num_cls_tokens=1,
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
+ audio_stem=audio_stem,
+ )
+
+ depth_stem = PatchEmbedGeneric(
+ [
+ nn.Conv2d(
+ kernel_size=depth_kernel_size,
+ in_channels=1,
+ out_channels=depth_embed_dim,
+ stride=depth_kernel_size,
+ bias=False,
+ ),
+ ],
+ norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
+ )
+
+ depth_preprocessor = RGBDTPreprocessor(
+ img_size=[1, 224, 224],
+ num_cls_tokens=1,
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
+ rgbt_stem=None,
+ depth_stem=depth_stem,
+ )
+
+ thermal_stem = PatchEmbedGeneric(
+ [
+ nn.Conv2d(
+ kernel_size=thermal_kernel_size,
+ in_channels=1,
+ out_channels=thermal_embed_dim,
+ stride=thermal_kernel_size,
+ bias=False,
+ ),
+ ],
+ norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
+ )
+ thermal_preprocessor = ThermalPreprocessor(
+ img_size=[1, 224, 224],
+ num_cls_tokens=1,
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
+ thermal_stem=thermal_stem,
+ )
+
+ imu_stem = PatchEmbedGeneric(
+ [
+ nn.Linear(
+ in_features=48,
+ out_features=imu_embed_dim,
+ bias=False,
+ ),
+ ],
+ norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
+ )
+
+ imu_preprocessor = IMUPreprocessor(
+ img_size=[6, 2000],
+ num_cls_tokens=1,
+ kernel_size=8,
+ embed_dim=imu_embed_dim,
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
+ imu_stem=imu_stem,
+ )
+
+ modality_preprocessors = {
+ ModalityType.VISION: rgbt_preprocessor,
+ ModalityType.TEXT: text_preprocessor,
+ ModalityType.AUDIO: audio_preprocessor,
+ ModalityType.DEPTH: depth_preprocessor,
+ ModalityType.THERMAL: thermal_preprocessor,
+ ModalityType.IMU: imu_preprocessor,
+ }
+
+ return nn.ModuleDict(modality_preprocessors)
+
+ def _create_modality_trunks(
+ self,
+ vision_embed_dim=1024,
+ vision_num_blocks=24,
+ vision_num_heads=16,
+ text_embed_dim=768,
+ text_num_blocks=12,
+ text_num_heads=12,
+ audio_embed_dim=768,
+ audio_num_blocks=12,
+ audio_num_heads=12,
+ audio_drop_path=0.0,
+ depth_embed_dim=768,
+ depth_num_blocks=12,
+ depth_num_heads=12,
+ depth_drop_path=0.0,
+ thermal_embed_dim=768,
+ thermal_num_blocks=12,
+ thermal_num_heads=12,
+ thermal_drop_path=0.0,
+ imu_embed_dim=512,
+ imu_num_blocks=6,
+ imu_num_heads=8,
+ imu_drop_path=0.7,
+ ):
+ def instantiate_trunk(
+ embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
+ ):
+ return SimpleTransformer(
+ embed_dim=embed_dim,
+ num_blocks=num_blocks,
+ ffn_dropout_rate=0.0,
+ drop_path_rate=drop_path,
+ attn_target=partial(
+ MultiheadAttention,
+ embed_dim=embed_dim,
+ num_heads=num_heads,
+ bias=True,
+ add_bias_kv=add_bias_kv,
+ ),
+ pre_transformer_layer=nn.Sequential(
+ nn.LayerNorm(embed_dim, eps=1e-6)
+ if pre_transformer_ln
+ else nn.Identity(),
+ EinOpsRearrange("b l d -> l b d"),
+ ),
+ post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
+ )
+
+ modality_trunks = {}
+ modality_trunks[ModalityType.VISION] = instantiate_trunk(
+ vision_embed_dim,
+ vision_num_blocks,
+ vision_num_heads,
+ pre_transformer_ln=True,
+ add_bias_kv=False,
+ drop_path=0.0,
+ )
+ modality_trunks[ModalityType.TEXT] = instantiate_trunk(
+ text_embed_dim,
+ text_num_blocks,
+ text_num_heads,
+ pre_transformer_ln=False,
+ add_bias_kv=False,
+ drop_path=0.0,
+ )
+ modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
+ audio_embed_dim,
+ audio_num_blocks,
+ audio_num_heads,
+ pre_transformer_ln=False,
+ add_bias_kv=True,
+ drop_path=audio_drop_path,
+ )
+ modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
+ depth_embed_dim,
+ depth_num_blocks,
+ depth_num_heads,
+ pre_transformer_ln=False,
+ add_bias_kv=True,
+ drop_path=depth_drop_path,
+ )
+ modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
+ thermal_embed_dim,
+ thermal_num_blocks,
+ thermal_num_heads,
+ pre_transformer_ln=False,
+ add_bias_kv=True,
+ drop_path=thermal_drop_path,
+ )
+ modality_trunks[ModalityType.IMU] = instantiate_trunk(
+ imu_embed_dim,
+ imu_num_blocks,
+ imu_num_heads,
+ pre_transformer_ln=False,
+ add_bias_kv=True,
+ drop_path=imu_drop_path,
+ )
+
+ return nn.ModuleDict(modality_trunks)
+
+ def _create_modality_heads(
+ self,
+ out_embed_dim,
+ vision_embed_dim,
+ text_embed_dim,
+ audio_embed_dim,
+ depth_embed_dim,
+ thermal_embed_dim,
+ imu_embed_dim,
+ ):
+ modality_heads = {}
+
+ modality_heads[ModalityType.VISION] = nn.Sequential(
+ nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
+ SelectElement(index=0),
+ nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
+ )
+
+ modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
+ proj=nn.Sequential(
+ nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
+ nn.Linear(text_embed_dim, out_embed_dim, bias=False),
+ )
+ )
+
+ modality_heads[ModalityType.AUDIO] = nn.Sequential(
+ nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
+ SelectElement(index=0),
+ nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
+ )
+
+ modality_heads[ModalityType.DEPTH] = nn.Sequential(
+ nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
+ SelectElement(index=0),
+ nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
+ )
+
+ modality_heads[ModalityType.THERMAL] = nn.Sequential(
+ nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
+ SelectElement(index=0),
+ nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
+ )
+
+ modality_heads[ModalityType.IMU] = nn.Sequential(
+ nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
+ SelectElement(index=0),
+ nn.Dropout(p=0.5),
+ nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
+ )
+
+ return nn.ModuleDict(modality_heads)
+
+ def _create_modality_postprocessors(self, out_embed_dim):
+ modality_postprocessors = {}
+
+ modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
+ modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
+ Normalize(dim=-1), LearnableLogitScaling(learnable=True)
+ )
+ modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
+ Normalize(dim=-1),
+ LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
+ )
+ modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
+ Normalize(dim=-1),
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
+ )
+ modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
+ Normalize(dim=-1),
+ LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
+ )
+ modality_postprocessors[ModalityType.IMU] = nn.Sequential(
+ Normalize(dim=-1),
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
+ )
+ return nn.ModuleDict(modality_postprocessors)
+
+ def forward(self, inputs):
+ outputs = {}
+ for modality_key, modality_value in inputs.items():
+ reduce_list = (
+ modality_value.ndim >= 5
+ ) # Audio and Video inputs consist of multiple clips
+ if reduce_list:
+ B, S = modality_value.shape[:2]
+ modality_value = modality_value.reshape(
+ B * S, *modality_value.shape[2:]
+ )
+
+ if modality_value is not None:
+ modality_value = self.modality_preprocessors[modality_key](
+ **{modality_key: modality_value}
+ )
+ trunk_inputs = modality_value["trunk"]
+ head_inputs = modality_value["head"]
+ modality_value = self.modality_trunks[modality_key](**trunk_inputs)
+ modality_value = self.modality_heads[modality_key](
+ modality_value, **head_inputs
+ )
+ if modality_key in [ModalityType.AUDIO]:
+ modality_value = self.modality_postprocessors[modality_key][0](
+ modality_value
+ )
+ else:
+ modality_value = self.modality_postprocessors[modality_key](
+ modality_value
+ )
+
+ if reduce_list:
+ modality_value = modality_value.reshape(B, S, -1)
+ modality_value = modality_value.mean(dim=1)
+
+ outputs[modality_key] = modality_value
+
+ return outputs
+
+
+def imagebind_huge(pretrained=False, store_path=r'.checkpoints'):
+ model = ImageBindModel(
+ vision_embed_dim=1280,
+ vision_num_blocks=32,
+ vision_num_heads=16,
+ text_embed_dim=1024,
+ text_num_blocks=24,
+ text_num_heads=16,
+ out_embed_dim=1024,
+ audio_drop_path=0.1,
+ imu_drop_path=0.7,
+ )
+
+ if pretrained:
+ if not os.path.exists("{}/imagebind_huge.pth".format(store_path)):
+ print(
+ "Downloading imagebind weights to {}/imagebind_huge.pth ...".format(store_path)
+ )
+ os.makedirs(store_path, exist_ok=True)
+ torch.hub.download_url_to_file(
+ "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth",
+ "{}/imagebind_huge.pth".format(store_path),
+ progress=True,
+ )
+
+ model.load_state_dict(torch.load("{}/imagebind_huge.pth".format(store_path)))
+
+ return model, 1024
diff --git a/code/model/ImageBind/models/multimodal_preprocessors.py b/code/model/ImageBind/models/multimodal_preprocessors.py
new file mode 100644
index 0000000000000000000000000000000000000000..d16fa8bca2a3edba6d24dd5e16b8965cc004b577
--- /dev/null
+++ b/code/model/ImageBind/models/multimodal_preprocessors.py
@@ -0,0 +1,687 @@
+#!/usr/bin/env python3
+# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import gzip
+import html
+import io
+import math
+from functools import lru_cache
+from typing import Callable, List, Optional
+
+import ftfy
+
+import numpy as np
+import regex as re
+import torch
+import torch.nn as nn
+from iopath.common.file_io import g_pathmgr
+from timm.models.layers import trunc_normal_
+
+from .helpers import cast_if_src_dtype, VerboseNNModule
+
+
+def get_sinusoid_encoding_table(n_position, d_hid):
+ """Sinusoid position encoding table"""
+
+ # TODO: make it with torch instead of numpy
+ def get_position_angle_vec(position):
+ return [
+ position / np.power(10000, 2 * (hid_j // 2) / d_hid)
+ for hid_j in range(d_hid)
+ ]
+
+ sinusoid_table = np.array(
+ [get_position_angle_vec(pos_i) for pos_i in range(n_position)]
+ )
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
+
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
+
+
+def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
+ N = pos_embed.shape[1]
+ if N == target_spatial_size:
+ return pos_embed
+ dim = pos_embed.shape[-1]
+ # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
+ pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
+ pos_embed = nn.functional.interpolate(
+ pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
+ 0, 3, 1, 2
+ ),
+ scale_factor=math.sqrt(target_spatial_size / N),
+ mode="bicubic",
+ )
+ if updated:
+ pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
+ pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+ return pos_embed
+
+
+def interpolate_pos_encoding(
+ npatch_per_img,
+ pos_embed,
+ patches_layout,
+ input_shape=None,
+ first_patch_idx=1,
+):
+ assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
+ N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
+ if npatch_per_img == N:
+ return pos_embed
+
+ assert (
+ patches_layout[-1] == patches_layout[-2]
+ ), "Interpolation of pos embed not supported for non-square layouts"
+
+ class_emb = pos_embed[:, :first_patch_idx]
+ pos_embed = pos_embed[:, first_patch_idx:]
+
+ if input_shape is None or patches_layout[0] == 1:
+ # simple 2D pos embedding, no temporal component
+ pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
+ elif patches_layout[0] > 1:
+ # pos embed has a temporal component
+ assert len(input_shape) == 4, "temporal interpolation not supported"
+ # we only support 2D interpolation in this case
+ num_frames = patches_layout[0]
+ num_spatial_tokens = patches_layout[1] * patches_layout[2]
+ pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
+ # interpolate embedding for zeroth frame
+ pos_embed = interpolate_pos_encoding_2d(
+ npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
+ )
+ else:
+ raise ValueError("This type of interpolation isn't implemented")
+
+ return torch.cat((class_emb, pos_embed), dim=1)
+
+
+def _get_pos_embedding(
+ npatch_per_img,
+ pos_embed,
+ patches_layout,
+ input_shape,
+ first_patch_idx=1,
+):
+ pos_embed = interpolate_pos_encoding(
+ npatch_per_img,
+ pos_embed,
+ patches_layout,
+ input_shape=input_shape,
+ first_patch_idx=first_patch_idx,
+ )
+ return pos_embed
+
+
+class PatchEmbedGeneric(nn.Module):
+ """
+ PatchEmbed from Hydra
+ """
+
+ def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
+ super().__init__()
+
+ if len(proj_stem) > 1:
+ self.proj = nn.Sequential(*proj_stem)
+ else:
+ # Special case to be able to load pre-trained models that were
+ # trained with a standard stem
+ self.proj = proj_stem[0]
+ self.norm_layer = norm_layer
+
+ def get_patch_layout(self, img_size):
+ with torch.no_grad():
+ dummy_img = torch.zeros(
+ [
+ 1,
+ ]
+ + img_size
+ )
+ dummy_out = self.proj(dummy_img)
+ embed_dim = dummy_out.shape[1]
+ patches_layout = tuple(dummy_out.shape[2:])
+ num_patches = np.prod(patches_layout)
+ return patches_layout, num_patches, embed_dim
+
+ def forward(self, x):
+ x = self.proj(x)
+ # B C (T_I_V_A.txt) H W -> B (T_I_V_A.txt)HW C
+ x = x.flatten(2).transpose(1, 2)
+ if self.norm_layer is not None:
+ x = self.norm_layer(x)
+ return x
+
+
+class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
+ def __init__(
+ self,
+ patches_layout: List,
+ num_patches: int,
+ num_cls_tokens: int,
+ embed_dim: int,
+ learnable: bool,
+ ) -> None:
+ super().__init__()
+ self.num_cls_tokens = num_cls_tokens
+ self.patches_layout = patches_layout
+ self.num_patches = num_patches
+ self.num_tokens = num_cls_tokens + num_patches
+ self.learnable = learnable
+ if self.learnable:
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
+ trunc_normal_(self.pos_embed, std=0.02)
+ else:
+ self.register_buffer(
+ "pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
+ )
+
+ def get_pos_embedding(self, vision_input, all_vision_tokens):
+ input_shape = vision_input.shape
+ pos_embed = _get_pos_embedding(
+ all_vision_tokens.size(1) - self.num_cls_tokens,
+ pos_embed=self.pos_embed,
+ patches_layout=self.patches_layout,
+ input_shape=input_shape,
+ first_patch_idx=self.num_cls_tokens,
+ )
+ return pos_embed
+
+
+class RGBDTPreprocessor(VerboseNNModule):
+ def __init__(
+ self,
+ rgbt_stem: PatchEmbedGeneric,
+ depth_stem: PatchEmbedGeneric,
+ img_size: List = (3, 224, 224),
+ num_cls_tokens: int = 1,
+ pos_embed_fn: Callable = None,
+ use_type_embed: bool = False,
+ init_param_style: str = "openclip",
+ ) -> None:
+ super().__init__()
+ stem = rgbt_stem if rgbt_stem is not None else depth_stem
+ (
+ self.patches_layout,
+ self.num_patches,
+ self.embed_dim,
+ ) = stem.get_patch_layout(img_size)
+ self.rgbt_stem = rgbt_stem
+ self.depth_stem = depth_stem
+ self.use_pos_embed = pos_embed_fn is not None
+ self.use_type_embed = use_type_embed
+ self.num_cls_tokens = num_cls_tokens
+
+ if self.use_pos_embed:
+ self.pos_embedding_helper = pos_embed_fn(
+ patches_layout=self.patches_layout,
+ num_cls_tokens=num_cls_tokens,
+ num_patches=self.num_patches,
+ embed_dim=self.embed_dim,
+ )
+ if self.num_cls_tokens > 0:
+ self.cls_token = nn.Parameter(
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
+ )
+ if self.use_type_embed:
+ self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
+
+ self.init_parameters(init_param_style)
+
+ @torch.no_grad()
+ def init_parameters(self, init_param_style):
+ if init_param_style == "openclip":
+ # OpenCLIP style initialization
+ scale = self.embed_dim**-0.5
+ if self.use_pos_embed:
+ nn.init.normal_(self.pos_embedding_helper.pos_embed)
+ self.pos_embedding_helper.pos_embed *= scale
+
+ if self.num_cls_tokens > 0:
+ nn.init.normal_(self.cls_token)
+ self.cls_token *= scale
+ elif init_param_style == "vit":
+ self.cls_token.data.fill_(0)
+ else:
+ raise ValueError(f"Unknown init {init_param_style}")
+
+ if self.use_type_embed:
+ nn.init.normal_(self.type_embed)
+
+ def tokenize_input_and_cls_pos(self, input, stem, mask):
+ # tokens is of shape B x L x D
+ tokens = stem(input)
+ assert tokens.ndim == 3
+ assert tokens.shape[2] == self.embed_dim
+ B = tokens.shape[0]
+ if self.num_cls_tokens > 0:
+ class_tokens = self.cls_token.expand(
+ B, -1, -1
+ ) # stole class_tokens impl from Phil Wang, thanks
+ tokens = torch.cat((class_tokens, tokens), dim=1)
+ if self.use_pos_embed:
+ pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
+ tokens = tokens + pos_embed
+ if self.use_type_embed:
+ tokens = tokens + self.type_embed.expand(B, -1, -1)
+ return tokens
+
+ def forward(self, vision=None, depth=None, patch_mask=None):
+ if patch_mask is not None:
+ raise NotImplementedError()
+
+ if vision is not None:
+ vision_tokens = self.tokenize_input_and_cls_pos(
+ vision, self.rgbt_stem, patch_mask
+ )
+
+ if depth is not None:
+ depth_tokens = self.tokenize_input_and_cls_pos(
+ depth, self.depth_stem, patch_mask
+ )
+
+ # aggregate tokens
+ if vision is not None and depth is not None:
+ final_tokens = vision_tokens + depth_tokens
+ else:
+ final_tokens = vision_tokens if vision is not None else depth_tokens
+ return_dict = {
+ "trunk": {
+ "tokens": final_tokens,
+ },
+ "head": {},
+ }
+ return return_dict
+
+
+class AudioPreprocessor(RGBDTPreprocessor):
+ def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
+ super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
+
+ def forward(self, audio=None):
+ return super().forward(vision=audio)
+
+
+class ThermalPreprocessor(RGBDTPreprocessor):
+ def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
+ super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
+
+ def forward(self, thermal=None):
+ return super().forward(vision=thermal)
+
+
+def build_causal_attention_mask(context_length):
+ # lazily create causal attention mask, with full attention between the vision tokens
+ # pytorch uses additive attention mask; fill with -inf
+ mask = torch.empty(context_length, context_length, requires_grad=False)
+ mask.fill_(float("-inf"))
+ mask.triu_(1) # zero out the lower diagonal
+ return mask
+
+
+class TextPreprocessor(VerboseNNModule):
+ def __init__(
+ self,
+ vocab_size: int,
+ context_length: int,
+ embed_dim: int,
+ causal_masking: bool,
+ supply_seq_len_to_head: bool = True,
+ num_cls_tokens: int = 0,
+ init_param_style: str = "openclip",
+ ) -> None:
+ super().__init__()
+ self.vocab_size = vocab_size
+ self.context_length = context_length
+ self.token_embedding = nn.Embedding(vocab_size, embed_dim)
+ self.pos_embed = nn.Parameter(
+ torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
+ )
+ self.causal_masking = causal_masking
+ if self.causal_masking:
+ mask = build_causal_attention_mask(self.context_length)
+ # register the mask as a buffer so it can be moved to the right device
+ self.register_buffer("mask", mask)
+
+ self.supply_seq_len_to_head = supply_seq_len_to_head
+ self.num_cls_tokens = num_cls_tokens
+ self.embed_dim = embed_dim
+ if num_cls_tokens > 0:
+ assert self.causal_masking is False, "Masking + CLS token isn't implemented"
+ self.cls_token = nn.Parameter(
+ torch.zeros(1, self.num_cls_tokens, embed_dim)
+ )
+
+ self.init_parameters(init_param_style)
+
+ @torch.no_grad()
+ def init_parameters(self, init_param_style="openclip"):
+ # OpenCLIP style initialization
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
+ nn.init.normal_(self.pos_embed, std=0.01)
+
+ if init_param_style == "openclip":
+ # OpenCLIP style initialization
+ scale = self.embed_dim**-0.5
+ if self.num_cls_tokens > 0:
+ nn.init.normal_(self.cls_token)
+ self.cls_token *= scale
+ elif init_param_style == "vit":
+ self.cls_token.data.fill_(0)
+ else:
+ raise ValueError(f"Unknown init {init_param_style}")
+
+ def forward(self, text):
+ # text tokens are of shape B x L x D
+ text_tokens = self.token_embedding(text)
+ # concat CLS tokens if any
+ if self.num_cls_tokens > 0:
+ B = text_tokens.shape[0]
+ class_tokens = self.cls_token.expand(
+ B, -1, -1
+ ) # stole class_tokens impl from Phil Wang, thanks
+ text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
+ text_tokens = text_tokens + self.pos_embed
+ return_dict = {
+ "trunk": {
+ "tokens": text_tokens,
+ },
+ "head": {},
+ }
+ # Compute sequence length after adding CLS tokens
+ if self.supply_seq_len_to_head:
+ text_lengths = text.argmax(dim=-1)
+ return_dict["head"] = {
+ "seq_len": text_lengths,
+ }
+ if self.causal_masking:
+ return_dict["trunk"].update({"attn_mask": self.mask})
+ return return_dict
+
+
+class Im2Video(nn.Module):
+ """Convert an image into a trivial video."""
+
+ def __init__(self, time_dim=2):
+ super().__init__()
+ self.time_dim = time_dim
+
+ def forward(self, x):
+ if x.ndim == 4:
+ # B, C, H, W -> B, C, T_I_V_A.txt, H, W
+ return x.unsqueeze(self.time_dim)
+ elif x.ndim == 5:
+ return x
+ else:
+ raise ValueError(f"Dimension incorrect {x.shape}")
+
+
+class PadIm2Video(Im2Video):
+ def __init__(self, ntimes, pad_type, time_dim=2):
+ super().__init__(time_dim=time_dim)
+ assert ntimes > 0
+ assert pad_type in ["zero", "repeat"]
+ self.ntimes = ntimes
+ self.pad_type = pad_type
+
+ def forward(self, x):
+ x = super().forward(x)
+ if x.shape[self.time_dim] == 1:
+ if self.pad_type == "repeat":
+ new_shape = [1] * len(x.shape)
+ new_shape[self.time_dim] = self.ntimes
+ x = x.repeat(new_shape)
+ elif self.pad_type == "zero":
+ padarg = [0, 0] * len(x.shape)
+ padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
+ x = nn.functional.pad(x, padarg)
+ return x
+
+
+# Modified from github.com/openai/CLIP
+@lru_cache()
+def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
+ """
+ bs = (
+ list(range(ord("!"), ord("~") + 1))
+ + list(range(ord("¡"), ord("¬") + 1))
+ + list(range(ord("®"), ord("ÿ") + 1))
+ )
+ cs = bs[:]
+ n = 0
+ for b in range(2**8):
+ if b not in bs:
+ bs.append(b)
+ cs.append(2**8 + n)
+ n += 1
+ cs = [chr(n) for n in cs]
+ return dict(zip(bs, cs))
+
+
+def get_pairs(word):
+ """Return set of symbol pairs in a word.
+ Word is represented as tuple of symbols (symbols being variable-length strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+def basic_clean(text):
+ text = ftfy.fix_text(text)
+ text = html.unescape(html.unescape(text))
+ return text.strip()
+
+
+def whitespace_clean(text):
+ text = re.sub(r"\s+", " ", text)
+ text = text.strip()
+ return text
+
+
+class SimpleTokenizer(object):
+ def __init__(self, bpe_path: str, context_length=77):
+ self.byte_encoder = bytes_to_unicode()
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
+
+ with g_pathmgr.open(bpe_path, "rb") as fh:
+ bpe_bytes = io.BytesIO(fh.read())
+ merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
+ merges = merges[1 : 49152 - 256 - 2 + 1]
+ merges = [tuple(merge.split()) for merge in merges]
+ vocab = list(bytes_to_unicode().values())
+ vocab = vocab + [v + "" for v in vocab]
+ for merge in merges:
+ vocab.append("".join(merge))
+ vocab.extend(["<|startoftext|>", "<|endoftext|>"])
+ self.encoder = dict(zip(vocab, range(len(vocab))))
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {
+ "<|startoftext|>": "<|startoftext|>",
+ "<|endoftext|>": "<|endoftext|>",
+ }
+ self.pat = re.compile(
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
+ re.IGNORECASE,
+ )
+ self.context_length = context_length
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token[:-1]) + (token[-1] + "",)
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token + ""
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ new_word.extend(word[i:j])
+ i = j
+ except:
+ new_word.extend(word[i:])
+ break
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ self.cache[token] = word
+ return word
+
+ def encode(self, text):
+ bpe_tokens = []
+ text = whitespace_clean(basic_clean(text)).lower()
+ for token in re.findall(self.pat, text):
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
+ bpe_tokens.extend(
+ self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
+ )
+ return bpe_tokens
+
+ def decode(self, tokens):
+ text = "".join([self.decoder[token] for token in tokens])
+ text = (
+ bytearray([self.byte_decoder[c] for c in text])
+ .decode("utf-8", errors="replace")
+ .replace("", " ")
+ )
+ return text
+
+ def __call__(self, texts, context_length=None):
+ if not context_length:
+ context_length = self.context_length
+
+ if isinstance(texts, str):
+ texts = [texts]
+
+ sot_token = self.encoder["<|startoftext|>"]
+ eot_token = self.encoder["<|endoftext|>"]
+ all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
+
+ for i, tokens in enumerate(all_tokens):
+ tokens = tokens[:context_length]
+ result[i, : len(tokens)] = torch.tensor(tokens)
+
+ if len(result) == 1:
+ return result[0]
+ return result
+
+
+class IMUPreprocessor(VerboseNNModule):
+ def __init__(
+ self,
+ kernel_size: int,
+ imu_stem: PatchEmbedGeneric,
+ embed_dim: int,
+ img_size: List = (6, 2000),
+ num_cls_tokens: int = 1,
+ pos_embed_fn: Callable = None,
+ init_param_style: str = "openclip",
+ ) -> None:
+ super().__init__()
+ stem = imu_stem
+ self.imu_stem = imu_stem
+ self.embed_dim = embed_dim
+ self.use_pos_embed = pos_embed_fn is not None
+ self.num_cls_tokens = num_cls_tokens
+ self.kernel_size = kernel_size
+ self.pos_embed = nn.Parameter(
+ torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
+ )
+
+ if self.num_cls_tokens > 0:
+ self.cls_token = nn.Parameter(
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
+ )
+
+ self.init_parameters(init_param_style)
+
+ @torch.no_grad()
+ def init_parameters(self, init_param_style):
+ nn.init.normal_(self.pos_embed, std=0.01)
+
+ if init_param_style == "openclip":
+ # OpenCLIP style initialization
+ scale = self.embed_dim**-0.5
+
+ if self.num_cls_tokens > 0:
+ nn.init.normal_(self.cls_token)
+ self.cls_token *= scale
+ elif init_param_style == "vit":
+ self.cls_token.data.fill_(0)
+ else:
+ raise ValueError(f"Unknown init {init_param_style}")
+
+ def tokenize_input_and_cls_pos(self, input, stem):
+ # tokens is of shape B x L x D
+ tokens = stem.norm_layer(stem.proj(input))
+ assert tokens.ndim == 3
+ assert tokens.shape[2] == self.embed_dim
+ B = tokens.shape[0]
+ if self.num_cls_tokens > 0:
+ class_tokens = self.cls_token.expand(
+ B, -1, -1
+ ) # stole class_tokens impl from Phil Wang, thanks
+ tokens = torch.cat((class_tokens, tokens), dim=1)
+ if self.use_pos_embed:
+ tokens = tokens + self.pos_embed
+ return tokens
+
+ def forward(self, imu):
+ # Patchify
+ imu = imu.unfold(
+ -1,
+ self.kernel_size,
+ self.kernel_size,
+ ).permute(0, 2, 1, 3)
+ imu = imu.reshape(imu.size(0), imu.size(1), -1)
+
+ imu_tokens = self.tokenize_input_and_cls_pos(
+ imu,
+ self.imu_stem,
+ )
+
+ return_dict = {
+ "trunk": {
+ "tokens": imu_tokens,
+ },
+ "head": {},
+ }
+ return return_dict
diff --git a/code/model/ImageBind/models/transformer.py b/code/model/ImageBind/models/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..98902ac8f08868c486a7c74781e952bee444c2e6
--- /dev/null
+++ b/code/model/ImageBind/models/transformer.py
@@ -0,0 +1,284 @@
+#!/usr/bin/env python3
+# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+# Code modified from
+# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
+# https://github.com/facebookresearch/deit/blob/main/models.py
+# and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
+
+
+import copy
+import fnmatch
+import logging
+from functools import partial
+from typing import Callable, List
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint as checkpoint
+
+from timm.models.layers import DropPath, trunc_normal_
+
+
+class Attention(nn.Module):
+ def __init__(
+ self,
+ dim,
+ num_heads=8,
+ qkv_bias=False,
+ qk_scale=None,
+ attn_drop=0.0,
+ proj_drop=0.0,
+ ):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ # NOTE scale factor was wrong in my original version,
+ # can set manually to be compat with prev weights
+ self.scale = qk_scale or head_dim**-0.5
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ def forward(self, x):
+ B, N, C = x.shape
+ qkv = (
+ self.qkv(x)
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
+ .permute(2, 0, 3, 1, 4)
+ )
+ q, k, v = (
+ qkv[0],
+ qkv[1],
+ qkv[2],
+ ) # make torchscript happy (cannot use tensor as tuple)
+
+ attn = (q @ k.transpose(-2, -1)) * self.scale
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+class Mlp(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class MultiheadAttention(nn.MultiheadAttention):
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
+ return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
+
+
+class ViTAttention(Attention):
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
+ assert attn_mask is None
+ return super().forward(x)
+
+
+class BlockWithMasking(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ attn_target: Callable,
+ mlp_ratio: int = 4,
+ act_layer: Callable = nn.GELU,
+ norm_layer: Callable = nn.LayerNorm,
+ ffn_dropout_rate: float = 0.0,
+ drop_path: float = 0.0,
+ layer_scale_type: str = None,
+ layer_scale_init_value: float = 1e-4,
+ ):
+ super().__init__()
+
+ assert not isinstance(
+ attn_target, nn.Module
+ ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
+ self.attn = attn_target()
+ if drop_path > 0.0:
+ self.drop_path = DropPath(drop_path)
+ else:
+ self.drop_path = nn.Identity()
+ self.norm_1 = norm_layer(dim)
+ mlp_hidden_dim = int(mlp_ratio * dim)
+ self.mlp = Mlp(
+ in_features=dim,
+ hidden_features=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=ffn_dropout_rate,
+ )
+ self.norm_2 = norm_layer(dim)
+ self.layer_scale_type = layer_scale_type
+ if self.layer_scale_type is not None:
+ assert self.layer_scale_type in [
+ "per_channel",
+ "scalar",
+ ], f"Found Layer scale type {self.layer_scale_type}"
+ if self.layer_scale_type == "per_channel":
+ # one gamma value per channel
+ gamma_shape = [1, 1, dim]
+ elif self.layer_scale_type == "scalar":
+ # single gamma value for all channels
+ gamma_shape = [1, 1, 1]
+ # two gammas: for each part of the fwd in the encoder
+ self.layer_scale_gamma1 = nn.Parameter(
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
+ requires_grad=True,
+ )
+ self.layer_scale_gamma2 = nn.Parameter(
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
+ requires_grad=True,
+ )
+
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
+ if self.layer_scale_type is None:
+ x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
+ x = x + self.drop_path(self.mlp(self.norm_2(x)))
+ else:
+ x = (
+ x
+ + self.drop_path(self.attn(self.norm_1(x), attn_mask))
+ * self.layer_scale_gamma1
+ )
+ x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
+ return x
+
+
+_LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
+
+
+class SimpleTransformer(nn.Module):
+ def __init__(
+ self,
+ attn_target: Callable,
+ embed_dim: int,
+ num_blocks: int,
+ block: Callable = BlockWithMasking,
+ pre_transformer_layer: Callable = None,
+ post_transformer_layer: Callable = None,
+ drop_path_rate: float = 0.0,
+ drop_path_type: str = "progressive",
+ norm_layer: Callable = _LAYER_NORM,
+ mlp_ratio: int = 4,
+ ffn_dropout_rate: float = 0.0,
+ layer_scale_type: str = None, # from cait; possible values are None, "per_channel", "scalar"
+ layer_scale_init_value: float = 1e-4, # from cait; float
+ weight_init_style: str = "jax", # possible values jax or pytorch
+ ):
+ """
+ Simple Transformer with the following features
+ 1. Supports masked attention
+ 2. Supports DropPath
+ 3. Supports LayerScale
+ 4. Supports Dropout in Attention and FFN
+ 5. Makes few assumptions about the input except that it is a Tensor
+ """
+ super().__init__()
+ self.pre_transformer_layer = pre_transformer_layer
+ if drop_path_type == "progressive":
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
+ elif drop_path_type == "uniform":
+ dpr = [drop_path_rate for i in range(num_blocks)]
+ else:
+ raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
+
+ self.blocks = nn.Sequential(
+ *[
+ block(
+ dim=embed_dim,
+ attn_target=attn_target,
+ mlp_ratio=mlp_ratio,
+ ffn_dropout_rate=ffn_dropout_rate,
+ drop_path=dpr[i],
+ norm_layer=norm_layer,
+ layer_scale_type=layer_scale_type,
+ layer_scale_init_value=layer_scale_init_value,
+ )
+ for i in range(num_blocks)
+ ]
+ )
+ self.post_transformer_layer = post_transformer_layer
+ self.weight_init_style = weight_init_style
+ self.apply(self._init_weights)
+
+ def _init_weights(self, m):
+ if isinstance(m, nn.Linear):
+ if self.weight_init_style == "jax":
+ # Based on MAE and official Jax ViT implementation
+ torch.nn.init.xavier_uniform_(m.weight)
+ elif self.weight_init_style == "pytorch":
+ # PyTorch ViT uses trunc_normal_
+ trunc_normal_(m.weight, std=0.02)
+
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, (nn.LayerNorm)):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+
+ def forward(
+ self,
+ tokens: torch.Tensor,
+ attn_mask: torch.Tensor = None,
+ use_checkpoint: bool = False,
+ checkpoint_every_n: int = 1,
+ checkpoint_blk_ids: List[int] = None,
+ ):
+ """
+ Inputs
+ - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
+ - attn: mask of shape L x L
+
+ Output
+ - x: data of shape N x L x D (or L x N x D depending on the attention implementation)
+ """
+ if self.pre_transformer_layer:
+ tokens = self.pre_transformer_layer(tokens)
+ if use_checkpoint and checkpoint_blk_ids is None:
+ checkpoint_blk_ids = [
+ blk_id
+ for blk_id in range(len(self.blocks))
+ if blk_id % checkpoint_every_n == 0
+ ]
+ if checkpoint_blk_ids:
+ checkpoint_blk_ids = set(checkpoint_blk_ids)
+ for blk_id, blk in enumerate(self.blocks):
+ if use_checkpoint and blk_id in checkpoint_blk_ids:
+ tokens = checkpoint.checkpoint(
+ blk, tokens, attn_mask, use_reentrant=False
+ )
+ else:
+ tokens = blk(tokens, attn_mask=attn_mask)
+ if self.post_transformer_layer:
+ tokens = self.post_transformer_layer(tokens)
+ return tokens
diff --git a/code/model/ImageBind/requirements.txt b/code/model/ImageBind/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..572ae079a6cc3592552d93b8ca08c3ec7fd4efc9
--- /dev/null
+++ b/code/model/ImageBind/requirements.txt
@@ -0,0 +1,10 @@
+--extra-index-url https://download.pytorch.org/whl/cu113
+torchvision==0.14.0
+torchaudio==0.13.0
+pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d
+timm==0.6.7
+ftfy
+regex
+einops
+fvcore
+decord==0.6.0
diff --git a/code/model/__init__.py b/code/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..469bdf5b9c3f3e52f7ee61e990f5a27a2052ec15
--- /dev/null
+++ b/code/model/__init__.py
@@ -0,0 +1,15 @@
+import os.path
+from collections import OrderedDict
+
+from .agent import DeepSpeedAgent
+from .anyToImageVideoAudio import NextGPTModel
+import torch
+
+
+def load_model(args):
+ agent_name = args['models'][args['model']]['agent_name']
+ model_name = args['models'][args['model']]['model_name']
+ model = globals()[model_name](**args)
+
+ agent = globals()[agent_name](model, args)
+ return agent
diff --git a/code/model/agent.py b/code/model/agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc2af973a4ad7beb185737612205a088a06e55ba
--- /dev/null
+++ b/code/model/agent.py
@@ -0,0 +1,161 @@
+import os.path
+
+import torch
+from header import *
+
+
+class DeepSpeedAgent:
+
+ def __init__(self, model, args):
+ super(DeepSpeedAgent, self).__init__()
+ self.args = args
+ self.model = model
+
+ self.print_model_parameters()
+ self.writer = SummaryWriter(args['log_path'])
+
+ self.load_parameters(self.args['save_path'], self.args['stage'])
+
+ # load config parameters of deepspeed
+ ds_params = json.load(open(self.args['ds_config_path']))
+ ds_params['scheduler']['params']['total_num_steps'] = self.args['total_steps']
+ ds_params['scheduler']['params']['warmup_num_steps'] = max(10, int(
+ self.args['total_steps'] * self.args['warmup_rate']))
+ self.ds_engine, self.optimizer, _, _ = deepspeed.initialize(
+ model=self.model,
+ model_parameters=self.model.parameters(),
+ config_params=ds_params,
+ dist_init_required=True,
+ args=types.SimpleNamespace(**args)
+ )
+
+ @torch.no_grad()
+ def predict(self):
+ self.ds_engine.module.eval()
+ output = self.ds_engine.generate(self.args)
+ return output
+
+ def train_model(self, batch, current_step=0, pbar=None):
+ self.ds_engine.module.train()
+
+ loss, mle_acc, mse_loss = self.ds_engine(batch)
+
+ self.writer.add_scalar('loss', loss, current_step)
+ self.writer.add_scalar('mle_acc', mle_acc, current_step)
+ # if isinstance(mse_loss, list):
+ # self.writer.add_scalar('img_mse_loss', mse_loss[0], current_step)
+ # self.writer.add_scalar('vid_mse_loss', mse_loss[1], current_step)
+ # self.writer.add_scalar('aud_mse_loss', mse_loss[2], current_step)
+ if isinstance(mse_loss, torch.Tensor):
+ self.writer.add_scalar('mse_loss', mse_loss, current_step)
+ else:
+ pass
+ # self.writer.add_scalar('mse_loss', mse_loss, current_step)
+
+ self.ds_engine.backward(loss)
+ self.ds_engine.step()
+ # pbar.set_description(f'[!] loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc * 100, 2)}; mse_loss: {round(mse_loss[0].item(), 4)} ')
+ pbar.set_description(f'[!] loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc * 100, 2)}')
+ pbar.update(1)
+ if self.args['local_rank'] == 0 and self.args['log_path'] and current_step % self.args['logging_step'] == 0:
+ elapsed = pbar.format_dict['elapsed']
+ rate = pbar.format_dict['rate']
+ remaining = (pbar.total - pbar.n) / rate if rate and pbar.total else 0
+ remaining = str(datetime.timedelta(seconds=remaining))
+ logging.info(
+ f'[!] progress: {round(pbar.n / pbar.total, 5)}; remaining time: {remaining}; loss: {round(loss.item(), 4)}; token_acc: {round(mle_acc * 100, 2)}')
+ # ; mse_loss: {round(mse_loss[0].item(), 4)}
+ mle_acc *= 100
+ return mle_acc
+
+ def save_model(self, path, current_step):
+ """
+ this function also save the trainable parameters and specific name parameters
+ """
+ param_grad_dic = {
+ k: v.requires_grad for (k, v) in self.ds_engine.module.named_parameters()
+ }
+ state_dict = self.ds_engine.module.state_dict()
+ checkpoint = OrderedDict()
+ for k, v in self.ds_engine.module.named_parameters():
+ if v.requires_grad:
+ checkpoint[k] = v
+ if 'gen_text_hidden_fcs' in k:
+ checkpoint[k] = v
+ if 'gen_text_hidden_fcs_video' in k:
+ checkpoint[k] = v
+ if 'gen_text_hidden_fcs_audio' in k:
+ checkpoint[k] = v
+ if 'llama_proj' in k:
+ checkpoint[k] = v
+ torch.save(checkpoint, f'{path}/pytorch_model.pt')
+ # save tokenizer
+ self.model.llama_tokenizer.save_pretrained(path)
+ # save configuration
+ self.model.llama_model.config.save_pretrained(path)
+ print(f'[!] save model into {path}')
+
+ def print_model_parameters(self, use_4bit=False):
+ """
+ Prints the number of trainable parameters in the model.
+ """
+ trainable_params = 0
+ all_param = 0
+ lora = 0
+ image = 0
+ video = 0
+ audio = 0
+ linear = 0
+ llama = 0
+ imagebind = 0
+ for name, param in self.model.named_parameters():
+ num_params = param.numel()
+ # if using DS Zero 3 and the weights are initialized empty
+ if num_params == 0 and hasattr(param, "ds_numel"):
+ num_params = param.ds_numel
+
+ if 'lora' in name:
+ lora += num_params
+ elif 'gen_text_hidden_fcs_video' in name:
+ video += num_params
+ elif 'gen_text_hidden_fcs_audio' in name:
+ audio += num_params
+ elif 'gen_text_hidden_fcs' in name:
+ image += num_params
+ elif 'llama_proj' in name:
+ linear += num_params
+ elif 'llama_model' in name:
+ llama += num_params
+ elif 'visual_encoder' in name:
+ imagebind += num_params
+ else:
+ pass
+
+ all_param += num_params
+ if param.requires_grad:
+ trainable_params += num_params
+ if use_4bit:
+ trainable_params /= 2
+ print(
+ f"all params: {all_param:,d} || trainable params: {trainable_params:,d} || trainable%: {100 * trainable_params / all_param}"
+ )
+ print(f'lora params: {lora:,d} || video params: {video:,d} || audio params: {audio:,d} || image params: {image:,d}')
+ print(f'linear params: {linear:,d} || imagebind params: {imagebind:,d} || llama params: {llama:,d}')
+
+ def load_parameters(self, path, stage=3):
+ if os.path.exists(os.path.join(path, 'pytorch_model.pt')):
+ print('loading parameters from {}'.format(self.args['save_path']))
+ delta_ckpt = torch.load(f'{path}/pytorch_model.pt', map_location=torch.device('cuda'))
+ checkpoint = OrderedDict()
+ if stage == 3:
+ for k, v in delta_ckpt.items():
+ if 'llama_model.model.embed_tokens.weight' in k:
+ checkpoint['llama_model.base_model.model.model.embed_tokens.weight'] = v
+ elif 'llama_model.lm_head.weight' in k:
+ checkpoint['llama_model.base_model.model.lm_head.weight'] = v
+ else:
+ checkpoint[k] = v
+ else:
+ checkpoint = delta_ckpt
+ self.model.load_state_dict(checkpoint, strict=False)
+
diff --git a/code/model/anyToImageVideoAudio.py b/code/model/anyToImageVideoAudio.py
new file mode 100644
index 0000000000000000000000000000000000000000..95c556a2a7364061b5c10e8a14e7035a279ef315
--- /dev/null
+++ b/code/model/anyToImageVideoAudio.py
@@ -0,0 +1,993 @@
+import logging
+import os.path
+from typing import List
+
+import torch
+from header import *
+import torch.nn.functional as F
+from .ImageBind import *
+from .ImageBind import data
+from .modeling_llama import LlamaForCausalLM
+from transformers import StoppingCriteria, StoppingCriteriaList
+# from diffusers import StableDiffusionPipeline
+from .custom_sd import StableDiffusionPipeline
+from .custom_vd import TextToVideoSDPipeline
+from .custom_ad import AudioLDMPipeline
+from .layers import *
+from .common.utils import *
+
+
+class StoppingCriteriaSub(StoppingCriteria):
+
+ def __init__(self, stops: List = None, encounters: int = 1):
+ super().__init__()
+ self.stops = stops
+ self.ENCOUNTERS = encounters
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
+ stop_count = 0
+ for stop in self.stops:
+ _stop = torch.tensor(stop).to(input_ids[0].device)
+ indices = torch.where(_stop[0] == input_ids)
+ for i in indices:
+ if len(i) > 0:
+ if torch.all(input_ids[0][i:i + len(_stop)] == _stop):
+ stop_count += 1
+ if stop_count >= self.ENCOUNTERS:
+ return True
+ return False
+
+
+class NextGPTModel(nn.Module):
+ """LoRA for LLaMa model"""
+
+ def __init__(self, **args):
+ super(NextGPTModel, self).__init__()
+ self.args = args
+
+ self.max_length = args['max_length']
+ self.device = torch.cuda.current_device()
+ self.stage = args['stage']
+ print('args max_length', args['max_length'])
+
+ imagebind_ckpt_path = os.path.join(self.args['pretrained_ckpt_path'], 'imagebind_ckpt',
+ self.args['imagebind_version'])
+ print(f'Initializing visual encoder from {imagebind_ckpt_path} ...')
+ self.visual_encoder, self.visual_hidden_size = \
+ imagebind_model.imagebind_huge(pretrained=True, store_path=imagebind_ckpt_path)
+ # free vision encoder
+ for name, param in self.visual_encoder.named_parameters():
+ param.requires_grad = False
+ self.visual_encoder.eval()
+ print('Visual encoder initialized.')
+
+ self.vicuna_ckpt_path = os.path.join(self.args['pretrained_ckpt_path'], 'vicuna_ckpt',
+ self.args['vicuna_version'])
+ print(f'Initializing language decoder from {self.vicuna_ckpt_path} ...')
+
+ self.llama_model = LlamaForCausalLM.from_pretrained(self.vicuna_ckpt_path)
+ if self.args.get('freeze_lm'):
+ print("Freezing the LLaMa ...")
+ for param in self.llama_model.parameters():
+ param.requires_grad = False
+ self.llama_model.eval()
+ else:
+ print("Instruct tuning the LLaMa ...")
+ # add the lora module
+ peft_config = LoraConfig(
+ task_type=TaskType.CAUSAL_LM,
+ inference_mode=False,
+ r=self.args['lora_r'],
+ lora_alpha=self.args['lora_alpha'],
+ lora_dropout=self.args['lora_dropout'],
+ target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj']
+ )
+
+ self.llama_model = get_peft_model(self.llama_model, peft_config)
+ self.llama_model.print_trainable_parameters()
+ print('Language decoder initialized.')
+
+ # use the new trained tokenizer
+ tokenizer_path = self.vicuna_ckpt_path
+ print(f'Initializing tokenizer from {tokenizer_path} ...')
+ self.llama_tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path, use_fast=False)
+ self.llama_tokenizer.pad_token = self.llama_tokenizer.eos_token
+ self.llama_tokenizer.padding_side = "right"
+ # self.llama_tokenizer.add_special_tokens({"mask_token": "[MASK]"})
+ self._add_image_token()
+ self._add_video_token()
+ self._add_audio_token()
+ self.llama_model.resize_token_embeddings(len(self.llama_tokenizer))
+ print('Tokenizer initialized.')
+
+ self.llama_proj = nn.Linear(
+ self.visual_hidden_size, self.llama_model.config.hidden_size
+ )
+ if self.args.get('freeze_input_proj'):
+ for param in self.llama_proj.parameters():
+ param.requires_grad = False
+
+ self.input_embeddings = self.llama_model.get_input_embeddings()
+
+ # the alignment module for LLM-TO-IMAGE
+ self.sd_ckpt_path = self.args['image_diffusion']
+ self.gen_text_hidden_fcs = nn.ModuleList([])
+ for layer_idx in self.args['text_emb_to_img_layers']:
+ if layer_idx == -1 or layer_idx == self.llama_model.config.num_hidden_layers:
+ in_dim = self.llama_model.config.hidden_size
+
+ self.gen_text_hidden_fcs.append(
+ TextFcLayer(in_dim, 768, num_input_tokens=self.args['num_gen_img_tokens'],
+ num_output_tokens=self.args['num_clip_tokens'],
+ mode=self.args['text_fc_to_img_mode']))
+ # self.sd_pipe.text_encoder.config.hidden_size
+ elif layer_idx < self.llama_model.config.num_hidden_layers:
+ self.gen_text_hidden_fcs.append(
+ TextFcLayer(self.llama_model.config.hidden_size, 768,
+ num_input_tokens=self.args['num_gen_img_tokens'],
+ num_output_tokens=self.args['num_clip_tokens'],
+ mode=self.args['text_fc_to_img_mode']))
+ else:
+ raise ValueError(
+ f'Embedding of layer {layer_idx} was requested but model only has {self.llama_model.config.num_hidden_layers} layers.')
+
+ # the alignment module for LLM-TO-VIDEO
+ self.vd_ckpt_path = self.args['video_diffusion']
+ self.gen_text_hidden_fcs_video = nn.ModuleList([])
+ for layer_idx in self.args['text_emb_to_video_layers']:
+ if layer_idx == -1 or layer_idx == self.llama_model.config.num_hidden_layers:
+ in_dim = self.llama_model.config.hidden_size # 4096
+
+ self.gen_text_hidden_fcs_video.append(
+ TextFcLayer(in_dim, 1024, num_input_tokens=self.args['num_gen_video_tokens'],
+ num_output_tokens=self.args['num_clip_tokens'],
+ mode=self.args['text_fc_to_video_mode']))
+ # self.vd_pipe.text_encoder.config.hidden_size
+ elif layer_idx < self.llama_model.config.num_hidden_layers:
+ self.gen_text_hidden_fcs_video.append(
+ TextFcLayer(self.llama_model.config.hidden_size, 1024,
+ num_input_tokens=self.args['num_gen_video_tokens'],
+ num_output_tokens=self.args['num_clip_tokens'],
+ mode=self.args['text_fc_to_video_mode']))
+ else:
+ raise ValueError(
+ f'Embedding of layer {layer_idx} was requested but model only has {self.llama_model.config.num_hidden_layers} layers.')
+
+ # the alignment module for LLM-TO-AUDIO
+ self.ad_ckpt_path = self.args['audio_diffusion']
+ self.gen_text_hidden_fcs_audio = nn.ModuleList([])
+ for layer_idx in self.args['text_emb_to_audio_layers']:
+ if layer_idx == -1 or layer_idx == self.llama_model.config.num_hidden_layers:
+ in_dim = self.llama_model.config.hidden_size
+
+ self.gen_text_hidden_fcs_audio.append(
+ TextFcLayer(in_dim, 512,
+ num_input_tokens=self.args['num_gen_audio_tokens'],
+ num_output_tokens=1,
+ mode=self.args['text_fc_to_audio_mode']))
+ # self.ad_pipe.text_encoder.config.projection_dim
+ elif layer_idx < self.llama_model.config.num_hidden_layers:
+ self.gen_text_hidden_fcs_audio.append(
+ TextFcLayer(self.llama_model.config.hidden_size, 512,
+ num_input_tokens=self.args['num_gen_audio_tokens'],
+ num_output_tokens=1,
+ mode=self.args['text_fc_to_audio_mode']))
+ else:
+ raise ValueError(
+ f'Embedding of layer {layer_idx} was requested but model only has {self.llama_model.config.num_hidden_layers} layers.')
+
+ if self.args.get('freeze_output_proj'):
+ for name, param in self.gen_text_hidden_fcs.named_parameters():
+ param.requires_grad = False
+ for name, param in self.gen_text_hidden_fcs_video.named_parameters():
+ param.requires_grad = False
+ for name, param in self.gen_text_hidden_fcs_audio.named_parameters():
+ param.requires_grad = False
+
+ def _add_image_token(self):
+ # Add an image token for loss masking (and visualization) purposes.
+ self.llama_tokenizer.add_tokens([" "]) # add special image token to tokenizer
+ self.llama_tokenizer.add_tokens([""]) # add special image token to tokenizer
+
+ # Add [IMG] tokens to the vocabulary.
+ self.args['gen_img_token_idx'] = []
+ for i in range(self.args['num_gen_img_tokens']):
+ print(f'Adding [IMG{i}] token to vocabulary.')
+ print(f'Before adding new token, tokenizer("[IMG{i}]") =',
+ self.llama_tokenizer(f'[IMG{i}]', add_special_tokens=False))
+ num_added_tokens = self.llama_tokenizer.add_tokens(f'[IMG{i}]')
+ print(f'After adding {num_added_tokens} new tokens, tokenizer("[IMG{i}]") =',
+ self.llama_tokenizer(f'[IMG{i}]', add_special_tokens=False))
+ gen_token_idx = self.llama_tokenizer(f'[IMG{i}]', add_special_tokens=False).input_ids
+ assert len(gen_token_idx) == 1, gen_token_idx
+ self.args['gen_img_token_idx'].append(gen_token_idx[0])
+
+ def _add_video_token(self):
+ # self.llama_tokenizer.add_tokens({""}) # add special video token to tokenizer
+ # self.llama_tokenizer.add_tokens({" "}) # add special video token to tokenizer
+
+ # Add [VID] tokens to the vocabulary.
+ self.args['gen_video_token_idx'] = []
+ for i in range(self.args['num_gen_video_tokens']):
+ print(f'Adding [VID{i}] token to vocabulary.')
+ print(f'Before adding new token, tokenizer("[VID{i}]") =',
+ self.llama_tokenizer(f'[VID{i}]', add_special_tokens=False))
+ num_added_tokens = self.llama_tokenizer.add_tokens(f'[VID{i}]')
+ print(f'After adding {num_added_tokens} new tokens, tokenizer("[VID{i}]") =',
+ self.llama_tokenizer(f'[VID{i}]', add_special_tokens=False))
+ gen_token_idx = self.llama_tokenizer(f'[VID{i}]', add_special_tokens=False).input_ids
+ assert len(gen_token_idx) == 1, gen_token_idx
+ self.args['gen_video_token_idx'].append(gen_token_idx[0])
+
+ def _add_audio_token(self):
+ # self.llama_tokenizer.add_tokens({""}) # add special audio token to tokenizer
+ # self.llama_tokenizer.add_tokens({" "}) # add special audio token to tokenizer
+
+ # Add [AUD] tokens to the vocabulary.
+ self.args['gen_audio_token_idx'] = []
+ for i in range(self.args['num_gen_audio_tokens']):
+ print(f'Adding [AUD{i}] token to vocabulary.')
+ print(f'Before adding new token, tokenizer("[AUD{i}]") =',
+ self.llama_tokenizer(f'[AUD{i}]', add_special_tokens=False))
+ num_added_tokens = self.llama_tokenizer.add_tokens(f'[AUD{i}]')
+ print(f'After adding {num_added_tokens} new tokens, tokenizer("[AUD{i}]") =',
+ self.llama_tokenizer(f'[AUD{i}]', add_special_tokens=False))
+ gen_token_idx = self.llama_tokenizer(f'[AUD{i}]', add_special_tokens=False).input_ids
+ assert len(gen_token_idx) == 1, gen_token_idx
+ self.args['gen_audio_token_idx'].append(gen_token_idx[0])
+
+ def encode_video(self, video_paths):
+ inputs = {ModalityType.VISION: data.load_and_transform_video_data(video_paths, self.device)}
+ # convert into visual dtype
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
+ with torch.no_grad():
+ embeddings = self.visual_encoder(inputs)
+ video_embeds = embeddings[ModalityType.VISION] # bsz x 1024
+ inputs_llama = self.llama_proj(video_embeds).unsqueeze(1) # bsz x 1 x llama_size
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
+ return inputs_llama, atts_llama
+
+ def encode_audio(self, audio_paths):
+ inputs = {ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, self.device)}
+ # convert into visual dtype
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
+ with torch.no_grad():
+ embeddings = self.visual_encoder(inputs)
+ audio_embeds = embeddings[ModalityType.AUDIO] # bsz x 1024
+ inputs_llama = self.llama_proj(audio_embeds).unsqueeze(1) # bsz x 1 x llama_size
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
+ return inputs_llama, atts_llama
+
+ def encode_image(self, image_paths):
+ inputs = {ModalityType.VISION: data.load_and_transform_vision_data(image_paths, self.device)}
+ # convert into visual dtype
+ inputs = {key: inputs[key].to(self.llama_model.dtype) for key in inputs}
+ with torch.no_grad():
+ embeddings = self.visual_encoder(inputs)
+ image_embeds = embeddings['vision'] # bsz x 1024
+ inputs_llama = self.llama_proj(image_embeds).unsqueeze(1) # bsz x 1 x llama_size
+ atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(self.device) # bsz x 1
+ return inputs_llama, atts_llama
+
+ def prompt_wrap(self, img_embeds, input_ids, target_ids, attention_mask):
+ '''
+ input_ids, target_ids, attention_mask: bsz x s2
+ '''
+ input_ids = input_ids.to(self.device) # bsz x s2
+ target_ids = target_ids.to(self.device) # bsz x s2
+ attention_mask = attention_mask.to(self.device) # bsz x s2
+
+ batch_size = input_ids.shape[0]
+
+ bos = torch.ones([batch_size, 1], dtype=input_ids.dtype,
+ device=input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
+ if self.args['freeze_lm']:
+ p_after_embeds = self.llama_model.model.embed_tokens(input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ bos_embeds = self.llama_model.model.embed_tokens(bos) # bsz x 1 x embed_dim
+ else:
+ p_after_embeds = self.llama_model.model.model.embed_tokens(input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
+ if img_embeds is not None:
+ p_before = '### Human: '
+ p_before_tokens = self.llama_tokenizer(p_before, return_tensors="pt", add_special_tokens=False).to(
+ self.device)
+ # peft model need deeper call
+ if self.args['freeze_lm']:
+ p_before_embeds = self.llama_model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ else:
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(
+ batch_size, -1, -1) # bsz x s1 x embed_dim
+ inputs_embeds = torch.cat([bos_embeds, p_before_embeds, img_embeds, p_after_embeds], dim=1).to(
+ self.device) # bsz x (1+s1+1+s2) x embed_dim
+
+ # create targets
+ empty_targets = (
+ torch.ones([batch_size, 1 + p_before_embeds.size()[1] + 1], # 1 (bos) + s1 + 1
+ dtype=torch.long).to(self.device).fill_(-100)
+ ) # bsz x (1 + s1)
+ targets = torch.cat([empty_targets, target_ids], dim=1).to(self.device) # bsz x (1 + s1 + 1 + s2)
+ assert inputs_embeds.size()[1] == targets.size()[1]
+
+ atts_prefix = torch.ones([batch_size, 1 + p_before_embeds.size()[1] + 1], dtype=torch.long).to(
+ self.device) # bsz x (1 + s1 + 1)
+ attention_mask = torch.cat([atts_prefix, attention_mask], dim=1).to(self.device)
+ assert attention_mask.size() == targets.size() # bsz x (1 + s1 + 1 + s2)
+ else:
+ p_before = '### Human: '
+ p_before_tokens = self.llama_tokenizer(p_before, return_tensors="pt", add_special_tokens=False).to(
+ self.device)
+ # peft model need deeper call
+ if self.args['freeze_lm']:
+ p_before_embeds = self.llama_model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ else:
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_tokens.input_ids).expand(
+ batch_size, -1, -1) # bsz x s1 x embed_dim
+ inputs_embeds = torch.cat([bos_embeds, p_before_embeds, p_after_embeds], dim=1).to(
+ self.device) # bsz x (1+s1+s2) x embed_dim
+
+ # create targets
+ empty_targets = (
+ torch.ones([batch_size, 1 + p_before_embeds.size()[1]], # 1 (bos) + s1
+ dtype=torch.long).to(self.device).fill_(-100)
+ ) # bsz x (1 + s1)
+ targets = torch.cat([empty_targets, target_ids], dim=1).to(self.device) # bsz x (1 + s1 + s2)
+ assert inputs_embeds.size()[1] == targets.size()[1]
+
+ atts_prefix = torch.ones([batch_size, 1 + p_before_embeds.size()[1]], dtype=torch.long).to(
+ self.device) # bsz x (1 + s1)
+ attention_mask = torch.cat([atts_prefix, attention_mask], dim=1).to(self.device)
+ assert attention_mask.size() == targets.size() # bsz x (1 + s1 + s2)
+ return inputs_embeds, targets, attention_mask
+
+ def _train_with_mode(self, texts, img_embeds=None, modality='text', num_gen_tokens='8',
+ text_hidden_fcs=None, gen_token_idx=None, text_emb_layers=None, text_prompt_embeddins=None,
+ loss_scale=1.0, stage=2):
+ """
+ :param num_gen_tokens: the number of generation tokens
+ :param modality: mode can be 'image' / 'video' / 'audio' / 'text'
+ :param text_hidden_fcs: alignment module
+ :param gen_token_idx: List
+ :param text_emb_layers: the layer index of LLM hidden states
+ :param text_prompt_embeddins: the textual caption/prompt embeddings
+ :param loss_scale: the scale on the mse loss for alignment
+ :param stage: the training stage
+ :param
+ """
+ if stage == 2:
+ input_ids, target_ids, attention_mask = process_batch_stage_2(self.llama_tokenizer, texts,
+ self.max_length,
+ num_gen_tokens,
+ modality
+ )
+ elif stage == 3:
+ input_ids, target_ids, attention_mask = process_batch_stage_3(self.llama_tokenizer, texts, self.max_length,
+ self.args['num_gen_img_tokens'],
+ self.args['num_gen_video_tokens'],
+ self.args['num_gen_audio_tokens']
+ )
+ else:
+ raise NotImplementedError
+ inputs_embeds, targets, attention_mask = self.prompt_wrap(img_embeds, input_ids, target_ids, attention_mask)
+
+ outputs = self.llama_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ return_dict=True,
+ output_hidden_states=True,
+ labels=targets,
+ )
+
+ loss = outputs.loss
+ # calculate the token accuracy
+ chosen_tokens = torch.max(outputs.logits, dim=-1)[1][:, 1:-1] # [B, S-1]
+ labels = targets[:, 2:]
+ gen_acc = (chosen_tokens.reshape(-1) == labels.reshape(-1)).to(torch.long) # [B*S]
+ valid_mask = (labels != -100).reshape(-1)
+ valid_tokens = gen_acc & valid_mask # [B*S]
+ gen_acc = valid_tokens.sum().item() / (valid_mask.sum().item() + 1.0)
+
+ if modality == 'text':
+ return loss, gen_acc, torch.zeros_like(loss)
+ else:
+ hidden_states = []
+ # text_hidden_fcs = self.gen_text_hidden_fcs
+
+ # based on the targets to obtain the hidden state, targets includes the [BOS] token
+ start_pos = (targets == gen_token_idx[0]).nonzero(as_tuple=False)[:, 1].tolist()
+ end_pos = (targets == gen_token_idx[-1]).nonzero(as_tuple=False)[:, 1].tolist()
+ # logging.info(f'targets : {targets}')
+ # logging.info(f'start_pos : {start_pos}')
+ # logging.info(f'end_pos : {end_pos}')
+ assert 0 < len(start_pos) == len(end_pos) == input_ids.size(0) and len(end_pos) > 0, (start_pos, end_pos)
+ for idx, fc_layer in zip(text_emb_layers, text_hidden_fcs):
+ hidden_embedding = []
+ input_embedding = []
+ for b, (s, e) in enumerate(zip(start_pos, end_pos)):
+ assert e - s + 1 == num_gen_tokens, (s, e)
+ hidden_embedding.append(outputs.hidden_states[idx][b, s:e + 1, :])
+ input_embedding.append(self.input_embeddings(targets[b, s:e + 1]))
+ hidden_embedding = torch.stack(hidden_embedding, dim=0)
+ input_embedding = torch.stack(input_embedding, dim=0)
+ hidden_states.append(fc_layer(hidden_embedding, input_embedding)) # (N, seq_len, 2048)
+ embeddings = torch.stack(hidden_states, dim=-1).sum(dim=-1) # (N, 77, 768)
+ # embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (N, T_I_V_A.txt, 256)
+
+ # Obtain the embeddings produced by the text encoder of a frozen text-to-image generation model
+ input_text = [conversation for conversation in texts]
+
+ if modality == 'image':
+ mse_loss = l2_loss(embeddings, torch.stack(text_prompt_embeddins, dim=0).to(self.device))
+ elif modality == 'video':
+ mse_loss = l2_loss(embeddings, torch.stack(text_prompt_embeddins, dim=0).to(self.device))
+ else:
+ text_prompt_embeddins = torch.stack(text_prompt_embeddins, dim=0).to(self.device)
+ assert len(text_prompt_embeddins.shape) == 2, text_prompt_embeddins.shape
+ text_prompt_embeddins = text_prompt_embeddins.view(text_prompt_embeddins.size(0), 1,
+ text_prompt_embeddins.size(1))
+ mse_loss = l2_loss(embeddings, text_prompt_embeddins)
+ mse_loss = mse_loss.mean()
+ loss += loss_scale * mse_loss
+
+ return loss, gen_acc, mse_loss
+
+ def _enc_align_training_stage_1(self, inputs):
+ """
+ In the stage 1: training the encoding-side alignment via image/video/audio caption tasks
+ modality: the input modality for each caption task, it could be 'image', 'video' or 'audio'.
+ """
+ dataset_type = inputs['dataset_types'][0]
+ if dataset_type == 'ImageToText':
+ image_paths = inputs['mm_paths']
+ mm_embeds, _ = self.encode_image(image_paths)
+ elif dataset_type == 'VideoToText':
+ video_paths = inputs['mm_paths']
+ mm_embeds, _ = self.encode_video(video_paths)
+ elif dataset_type == 'AudioToText':
+ audio_paths = inputs['mm_paths']
+ mm_embeds, _ = self.encode_audio(audio_paths)
+ else:
+ raise NotImplementedError
+ input_ids, target_ids, attention_mask = process_batch_stage_1(self.llama_tokenizer,
+ inputs['output_texts'],
+ self.max_length,
+ self.args['prompt'])
+ # print(input_ids)
+ inputs_embeds, targets, attention_mask = self.prompt_wrap(mm_embeds, input_ids, target_ids, attention_mask)
+ outputs = self.llama_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ return_dict=True,
+ output_hidden_states=True,
+ labels=targets,
+ )
+
+ loss = outputs.loss
+ # calculate the token accuracy
+ chosen_tokens = torch.max(outputs.logits, dim=-1)[1][:, 1:-1] # [B, S-1]
+ labels = targets[:, 2:]
+ gen_acc = (chosen_tokens.reshape(-1) == labels.reshape(-1)).to(torch.long) # [B*S]
+ valid_mask = (labels != -100).reshape(-1)
+ valid_tokens = gen_acc & valid_mask # [B*S]
+ gen_acc = valid_tokens.sum().item() / (valid_mask.sum().item() + 1.0)
+ return loss, gen_acc
+
+ def _dec_align_training_stage_2(self, inputs):
+ """
+ In the stage 2: training the decoding-side alignment via minimize the distance between the
+ representation of signal tokens and caption from text encoder within the respective diffusion models.
+ modality: the output modality for each caption.
+ """
+ dataset_type = inputs['dataset_types'][0]
+ if dataset_type == 'TextToImage':
+ loss, gen_acc, mse_loss = self._train_with_mode(texts=inputs['output_texts'],
+ modality='image',
+ num_gen_tokens=self.args['num_gen_img_tokens'],
+ text_hidden_fcs=self.gen_text_hidden_fcs,
+ gen_token_idx=self.args['gen_img_token_idx'],
+ text_emb_layers=self.args['text_emb_to_img_layers'],
+ text_prompt_embeddins=inputs['caption_embs'],
+ stage=self.stage)
+ elif dataset_type == 'TextToVideo':
+ loss, gen_acc, mse_loss = self._train_with_mode(texts=inputs['output_texts'],
+ modality='video',
+ num_gen_tokens=self.args['num_gen_video_tokens'],
+ text_hidden_fcs=self.gen_text_hidden_fcs_video,
+ gen_token_idx=self.args['gen_video_token_idx'],
+ text_emb_layers=self.args['text_emb_to_video_layers'],
+ text_prompt_embeddins=inputs['caption_embs'],
+ stage=self.stage)
+ elif dataset_type == 'TextToAudio':
+ loss, gen_acc, mse_loss = self._train_with_mode(texts=inputs['output_texts'],
+ modality='audio',
+ num_gen_tokens=self.args['num_gen_audio_tokens'],
+ text_hidden_fcs=self.gen_text_hidden_fcs_audio,
+ gen_token_idx=self.args['gen_audio_token_idx'],
+ text_emb_layers=self.args['text_emb_to_audio_layers'],
+ text_prompt_embeddins=inputs['caption_embs'],
+ stage=self.stage)
+ else:
+ raise NotImplementedError
+
+ return loss, gen_acc, mse_loss
+
+ def _instruction_tuning_stage_3(self, inputs):
+ """
+ In the stage 3: instruction-following training via the instruction dataset.
+ """
+ loss = 0
+ gen_acc = 0
+ mse_loss = []
+
+ dataset_type = inputs['dataset_types'][0]
+ if dataset_type == 'TextToImage':
+ loss, gen_acc, mse_loss = self._train_with_mode(inputs['output_texts'], None, 'image',
+ self.args['num_gen_img_tokens'],
+ self.gen_text_hidden_fcs,
+ self.args['gen_img_token_idx'],
+ self.args['text_emb_to_img_layers'],
+ inputs['caption_embs'], stage=self.stage)
+ elif dataset_type == 'TextToVideo':
+ loss, gen_acc, mse_loss = self._train_with_mode(inputs['output_texts'], None, 'video',
+ self.args['num_gen_video_tokens'],
+ self.gen_text_hidden_fcs_video,
+ self.args['gen_video_token_idx'],
+ self.args['text_emb_to_video_layers'],
+ inputs['caption_embs'], loss_scale=2,
+ stage=self.stage)
+ elif dataset_type == 'TextToAudio':
+ loss, gen_acc, mse_loss = self._train_with_mode(inputs['output_texts'], None, 'audio',
+ self.args['num_gen_audio_tokens'],
+ self.gen_text_hidden_fcs_audio,
+ self.args['gen_audio_token_idx'],
+ self.args['text_emb_to_audio_layers'],
+ inputs['caption_embs'], stage=self.stage)
+ elif dataset_type == 'ImageToText':
+ image_paths = inputs['mm_paths']
+ img_embeds, _ = self.encode_image(image_paths)
+ loss, gen_acc, _ = self._train_with_mode(inputs['output_texts'], img_embeds, modality='text',
+ stage=self.stage)
+ elif dataset_type == 'TextToText':
+ loss, gen_acc, _ = self._train_with_mode(inputs['output_texts'], None, modality='text',
+ stage=self.stage)
+ else:
+ raise NotImplementedError
+ return loss, gen_acc, mse_loss
+
+ def _stage_4_training(self, inputs):
+ """
+ In the stage 4, we employ the modality-switch dataset to instruction-tune the overall framework
+ """
+ pass
+
+ def forward(self, inputs):
+ loss = 0
+ gen_acc = 0
+ mse_loss = None
+
+ if self.stage == 1:
+ loss, gen_acc = self._enc_align_training_stage_1(inputs)
+ elif self.stage == 2:
+ loss, gen_acc, mse_loss = self._dec_align_training_stage_2(inputs)
+ elif self.stage == 3:
+ loss, gen_acc, mse_loss = self._instruction_tuning_stage_3(inputs)
+ else:
+ raise NotImplementedError(f"stage {self.stage} is not implemented, now it only support [1, 2, 3]")
+
+ return loss, gen_acc, mse_loss
+
+ def extract_multimodal_feature(self, inputs):
+ features = []
+ if inputs['image_paths']:
+ image_embeds, _ = self.encode_image(inputs['image_paths'])
+ features.append(image_embeds)
+ if inputs['audio_paths']:
+ audio_embeds, _ = self.encode_audio(inputs['audio_paths'])
+ features.append(audio_embeds)
+ if inputs['video_paths']:
+ video_embeds, _ = self.encode_video(inputs['video_paths'])
+ features.append(video_embeds)
+
+ feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
+ return feature_embeds
+
+ def _prepare_image_embed(self, text, batch_size):
+ pattern = r'Image>(.*?)<\/Image'
+ matches = re.findall(pattern, text)
+ features = []
+ p_before_token = self.llama_tokenizer(' ', add_special_tokens=False, return_tensors='pt').to(self.device)
+ p_after_token = self.llama_tokenizer('', add_special_tokens=False, return_tensors='pt').to(self.device)
+ if self.args['freeze_lm']:
+ p_before_embeds = self.llama_model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ else:
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ for m in matches:
+ print('image path: ', m)
+ if m.startswith('temp'):
+ m = os.path.join('./', m)
+ print('image path: ', m)
+ _temp_embedding, _ = self.encode_image([m])
+ features.append(_temp_embedding)
+ feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
+ return torch.cat([p_before_embeds, feature_embeds, p_after_embeds], dim=1)
+
+ def _prepare_video_embed(self, text, batch_size):
+ pattern = r'Video>(.*?)<\/Video'
+ matches = re.findall(pattern, text)
+ features = []
+ p_before_token = self.llama_tokenizer(' ', add_special_tokens=False, return_tensors='pt').to(self.device)
+ p_after_token = self.llama_tokenizer('', add_special_tokens=False, return_tensors='pt').to(self.device)
+ if self.args['freeze_lm']:
+ p_before_embeds = self.llama_model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ else:
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ for m in matches:
+ print('Video path: ', m)
+ if m.startswith('temp'):
+ m = os.path.join('./', m)
+ print('Video path: ', m)
+ _temp_embedding, _ = self.encode_video([m])
+ features.append(_temp_embedding)
+ feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
+ return torch.cat([p_before_embeds, feature_embeds, p_after_embeds], dim=1)
+
+ def _prepare_audio_embed(self, text, batch_size):
+ pattern = r'Audio>(.*?)<\/Audio'
+ matches = re.findall(pattern, text)
+ features = []
+ p_before_token = self.llama_tokenizer(' ', add_special_tokens=False, return_tensors='pt').to(self.device)
+ p_after_token = self.llama_tokenizer('', add_special_tokens=False, return_tensors='pt').to(self.device)
+ if self.args['freeze_lm']:
+ p_before_embeds = self.llama_model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ else:
+ p_before_embeds = self.llama_model.model.model.embed_tokens(p_before_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s1 x embed_dim
+ p_after_embeds = self.llama_model.model.model.embed_tokens(p_after_token.input_ids).expand(batch_size, -1,
+ -1) # bsz x s2 x embed_dim
+ for m in matches:
+ print('Audio path: ', m)
+ if m.startswith('temp'):
+ m = os.path.join('./', m)
+ print('Video path: ', m)
+ _temp_embedding, _ = self.encode_audio([m])
+ features.append(_temp_embedding)
+ feature_embeds = torch.cat(features).sum(dim=0).unsqueeze(0)
+ return torch.cat([p_before_embeds, feature_embeds, p_after_embeds], dim=1)
+
+ def prepare_generation_embedding(self, inputs):
+ prompt = inputs['prompt']
+ text = prompt + '\n### Assistant:'
+ print("text prompt: ", text)
+ batch_size = 1
+ input_embeds = []
+ split_text = re.split(r' <|> ', text)
+ for st in split_text:
+ if st.startswith('Image>'):
+ input_embeds.append(self._prepare_image_embed(st, batch_size))
+ elif st.startswith('Audio>'):
+ input_embeds.append(self._prepare_audio_embed(st, batch_size))
+ elif st.startswith('Video>'):
+ input_embeds.append(self._prepare_video_embed(st, batch_size))
+ else:
+ text_tokens = self.llama_tokenizer(st, add_special_tokens=False, return_tensors='pt').to(self.device)
+ bos = torch.ones([batch_size, 1],
+ dtype=text_tokens.input_ids.dtype,
+ device=text_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id # bsz x 1
+ if self.args['freeze_lm']:
+ text_embeds = self.llama_model.model.embed_tokens(text_tokens.input_ids).expand(batch_size, -1, -1)
+ bos_embeds = self.llama_model.model.embed_tokens(bos) # bsz x 1 x embed_dim
+ else:
+ text_embeds = self.llama_model.model.model.embed_tokens(text_tokens.input_ids).expand(batch_size,
+ -1, -1)
+ bos_embeds = self.llama_model.model.model.embed_tokens(bos) # bsz x 1 x embed_dim
+ input_embeds.append(bos_embeds)
+ input_embeds.append(text_embeds)
+ inputs_embeds = torch.cat(input_embeds, dim=1) # bsz x (1+s2) x embed_dim
+ return inputs_embeds
+
+ def generate_tokens_embeddings(self, inputs, input_embeds, temperature: float = 0.0, top_p: float = 1.0):
+ """
+ This function is used to generate the tokens and output embeddings that employed to generate images/videos/audios
+ inputs: dict
+ input_embeds: tensor
+ return:
+ out: the output tokens index
+ output_embeddings: output embeddings for synthesizing images
+ video_output_embedding: output embeddings for synthesizing video
+ audio_output_embedding: output embeddings for synthesizing audio
+ """
+ stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=inputs['stops_id'], encounters=1)])
+
+ outputs = self.llama_model.generate(
+ inputs_embeds=input_embeds,
+ max_new_tokens=inputs['max_tgt_len'],
+ top_p=inputs['top_p'],
+ temperature=inputs['temperature'],
+ # repeat_pen,
+ do_sample=True,
+ use_cache=True,
+ stopping_criteria=stopping_criteria,
+ output_hidden_states=True,
+ return_dict_in_generate=True,
+ output_attentions=True
+ )
+
+ output_embeddings = []
+ video_output_embedding = []
+ audio_output_embedding = []
+ out = outputs.sequences
+ for _hidden_states in outputs.hidden_states[1:]:
+ for idx in self.args['text_emb_to_img_layers']:
+ output_embeddings.append(_hidden_states[idx])
+ for idx in self.args['text_emb_to_video_layers']:
+ video_output_embedding.append(_hidden_states[idx])
+ for idx in self.args['text_emb_to_audio_layers']:
+ audio_output_embedding.append(_hidden_states[idx])
+ output_embeddings = torch.cat(output_embeddings, dim=1)
+ video_output_embedding = torch.cat(video_output_embedding, dim=1)
+ audio_output_embedding = torch.cat(audio_output_embedding, dim=1)
+
+ return out, output_embeddings, video_output_embedding, audio_output_embedding
+
+ def generate_images(self, generated_ids, embeddings, all_gen_idx, generation_model=None,
+ guidance_scale=7.5, num_inference_steps=40):
+ """
+ To generate the images based on the embeddings
+ generated_ids: the index of the generated tokens
+ embedding: the embeddings for synthesizing images
+ all_gen_idx: the index of [IMG0] in the generated_ids
+ """
+ last_ret_idx = 0
+ return_outputs = []
+ generation_model = StableDiffusionPipeline.from_pretrained(self.sd_ckpt_path, torch_dtype=torch.float16).to(
+ "cuda")
+ for gen_idx in all_gen_idx:
+ assert generated_ids[0,
+ gen_idx:gen_idx + self.args['num_gen_img_tokens']].cpu().detach().numpy().tolist() == self.args[
+ 'gen_img_token_idx'], (
+ generated_ids[0, gen_idx:gen_idx + self.args['num_gen_img_tokens']], self.args['gen_img_token_idx'])
+ raw_emb = embeddings[:, gen_idx - 1:gen_idx - 1 + self.args['num_gen_img_tokens'], :] # (1, 8, 4096)
+
+ # Produce generation embedding.
+ gen_prefix = ' '.join([f'[IMG{i}]' for i in range(self.args['num_gen_img_tokens'])])
+ gen_prefx_ids = self.llama_tokenizer(gen_prefix, add_special_tokens=False,
+ return_tensors="pt").input_ids.to(self.device)
+ gen_prefix_embs = self.input_embeddings(gen_prefx_ids) # (1, T_I_V_A.txt, D)
+ gen_emb = self.gen_text_hidden_fcs[-1](raw_emb, gen_prefix_embs) # (1, 77, 768)
+
+ if gen_emb.shape[1] != 77:
+ bs = gen_emb.shape[0]
+ clip_emb = 768
+ gen_emb = gen_emb.reshape(bs, -1, clip_emb) # (bs, T_I_V_A.txt, 768)
+ seq_len = gen_emb.shape[1]
+ gen_emb = torch.cat([gen_emb, torch.zeros((bs, 77 - seq_len, clip_emb), device=gen_emb.device,
+ dtype=gen_emb.dtype)], dim=1)
+
+ image_outputs = generation_model(prompt_embeds=gen_emb,
+ guidance_scale=guidance_scale,
+ num_inference_steps=num_inference_steps).images
+
+ caption = \
+ self.llama_tokenizer.batch_decode(generated_ids[:, last_ret_idx:gen_idx], skip_special_tokens=True)[
+ 0]
+ last_ret_idx = gen_idx + 1
+ return_outputs.append(caption + f' {gen_prefix}')
+ # return_outputs.append(truncate_caption(caption) + f' {gen_prefix}')
+ return_outputs.append(image_outputs)
+ return return_outputs
+
+ def generate_videos(self, generated_ids, embeddings, all_gen_idx, generation_model=None,
+ guidance_scale=7.5, num_inference_steps=40, height=320, width=576, num_frames=16):
+ """
+ To generate videos based on the embeddings
+ generated_ids: the index of the generated tokens
+ embedding: the embeddings for synthesizing videos
+ all_gen_idx: the index of [VID0] in the generated_ids
+ """
+ return_outputs = []
+ last_ret_idx = 0
+ generation_model = TextToVideoSDPipeline.from_pretrained(self.vd_ckpt_path, torch_dtype=torch.float16).to(
+ "cuda")
+ for gen_idx in all_gen_idx:
+ assert generated_ids[0,
+ gen_idx:gen_idx + self.args['num_gen_video_tokens']].cpu().detach().numpy().tolist() == \
+ self.args[
+ 'gen_video_token_idx'], (
+ generated_ids[0, gen_idx:gen_idx + self.args['num_gen_video_tokens']],
+ self.args['gen_video_token_idx'])
+ raw_emb = embeddings[:, gen_idx - 1:gen_idx - 1 + self.args['num_gen_video_tokens'], :] # (1, 8, 4096)
+ # print(f'gen_idx: {gen_idx}')
+ # print('4', raw_emb.size())
+ # assert len(self.args['text_emb_to_video_layers']) == 1
+
+ # Produce generation embedding.
+ gen_prefix = ' '.join([f'[VID{i}]' for i in range(self.args['num_gen_video_tokens'])])
+ gen_prefx_ids = self.llama_tokenizer(gen_prefix, add_special_tokens=False,
+ return_tensors="pt").input_ids.to(self.device)
+ gen_prefix_embs = self.input_embeddings(gen_prefx_ids) # (1, T_I_V_A.txt, D)
+ gen_emb = self.gen_text_hidden_fcs_video[-1](raw_emb, gen_prefix_embs) # (1, 77, 768)
+
+ if gen_emb.shape[1] != 77:
+ print(f"Padding {gen_emb.shape} with zeros")
+ bs = gen_emb.shape[0]
+ clip_emb = 768
+ gen_emb = gen_emb.reshape(bs, -1, clip_emb) # (bs, T_I_V_A.txt, 768)
+ seq_len = gen_emb.shape[1]
+ gen_emb = torch.cat([gen_emb, torch.zeros((bs, 77 - seq_len, clip_emb), device=gen_emb.device,
+ dtype=gen_emb.dtype)], dim=1)
+ print('Padded to', gen_emb.shape)
+
+ video_outputs = generation_model(prompt_embeds=gen_emb,
+ guidance_scale=guidance_scale,
+ num_inference_steps=num_inference_steps, height=height,
+ width=width, num_frames=num_frames).frames
+ caption = \
+ self.llama_tokenizer.batch_decode(generated_ids[:, last_ret_idx:gen_idx], skip_special_tokens=True)[
+ 0]
+ last_ret_idx = gen_idx + 1
+ return_outputs.append(caption + f' {gen_prefix}')
+ # return_outputs.append(truncate_caption(caption) + f' {gen_prefix}')
+ return_outputs.append(video_outputs)
+ return return_outputs
+
+ def generate_audios(self, generated_ids, embeddings, all_gen_idx, generation_model=None,
+ guidance_scale=7.5, num_inference_steps=40, audio_length_in_s=5.0):
+ """
+ To generate videos based on the embeddings
+ generated_ids: the index of the generated tokens
+ embedding: the embeddings for synthesizing audios
+ all_gen_idx: the index of [AUD0] in the generated_ids
+ """
+ return_outputs = []
+ last_ret_idx = 0
+ generation_model = AudioLDMPipeline.from_pretrained(self.ad_ckpt_path, torch_dtype=torch.float16).to("cuda")
+ for gen_idx in all_gen_idx:
+ assert generated_ids[0,
+ gen_idx:gen_idx + self.args['num_gen_audio_tokens']].cpu().detach().numpy().tolist() == \
+ self.args[
+ 'gen_audio_token_idx'], (
+ generated_ids[0, gen_idx:gen_idx + self.args['num_gen_audio_tokens']],
+ self.args['gen_audio_token_idx'])
+ raw_emb = embeddings[:, gen_idx - 1:gen_idx - 1 + self.args['num_gen_audio_tokens'], :] # (1, 8, 4096)
+ # print(f'gen_idx: {gen_idx}')
+ # print('raw_emb 4', raw_emb.size())
+ # assert len(self.args['text_emb_to_video_layers']) == 1
+
+ # Produce generation embedding.
+ gen_prefix = ' '.join([f'[AUD{i}]' for i in range(self.args['num_gen_audio_tokens'])])
+ gen_prefx_ids = self.llama_tokenizer(gen_prefix, add_special_tokens=False,
+ return_tensors="pt").input_ids.to(self.device)
+ gen_prefix_embs = self.input_embeddings(gen_prefx_ids) # (1, T_I_V_A.txt, D)
+ gen_emb = self.gen_text_hidden_fcs_audio[-1](raw_emb, gen_prefix_embs) # (1, 77, 768)
+ # print('gen_emb size:', gen_emb.size())
+ bs = gen_emb.shape[0]
+ hid_emb_size = gen_emb.shape[2]
+ gen_emb = gen_emb.view(bs, hid_emb_size)
+
+ audio_outputs = generation_model(prompt_embeds=gen_emb,
+ guidance_scale=guidance_scale,
+ num_inference_steps=num_inference_steps,
+ audio_length_in_s=audio_length_in_s).audios[0]
+ caption = \
+ self.llama_tokenizer.batch_decode(generated_ids[:, last_ret_idx:gen_idx], skip_special_tokens=True)[
+ 0]
+ last_ret_idx = gen_idx + 1
+ return_outputs.append(caption + f' {gen_prefix}')
+ # return_outputs.append(truncate_caption(caption) + f' {gen_prefix}')
+ return_outputs.append(audio_outputs)
+ return return_outputs
+
+ def generate(self, inputs):
+ """
+ inputs = {
+ 'image_paths': optional,
+ 'audio_paths': optional
+ 'video_paths': optional
+ 'thermal_paths': optional
+ 'mode': generation mode,
+ 'prompt': human input prompt,
+ 'max_tgt_len': generation length,
+ 'top_p': top_p,
+ 'temperature': temperature, Used to modulate logit distribution.
+ 'modality_embeds': None or torch.tensor,
+ 'modality_cache': save the image cache,
+
+ 'filter_value': Value to assign to tokens that should never be generated,
+ 'min_word_tokens': Minimum number of words to generate before allowing a [IMG] output.
+ 'gen_scale_factor': float = 1.0,
+ 'stops_id': the default value is [[835], [2277, 29937]] the stop token is '###', which has two types of tokenization ways, [835] and [2277, 29937]
+ 'ENCOUNTERS': the times that the generated sentence will be ended.
+
+ 'load_sd': whether use SD for image generation
+ 'max_num_imgs': Maximum number of images to return in one generation pass.
+ 'guidance_scale_for_img': the guidance ratio of conditioner, if it is None, the default value will be applied in SD
+ 'num_inference_steps_for_img': the number of inference step for image generation in the stable diffusion model
+
+ 'load_vd': whether use VD for video generation
+ 'max_num_vids': Maximum number of videos to return in one generation pass.
+ 'guidance_scale_for_vid': the guidance ratio of conditioner, if it is None, the default value will be applied in VD
+ 'num_inference_steps_for_vid': the number of inference step for video generation in the stable diffusion model
+ 'height': (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The height in pixels of the generated video.
+ 'width': (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The width in pixels of the generated video.
+ 'num_frames': (`int`, *optional*, defaults to 16):
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
+ amounts to 2 seconds of video.
+
+ 'load_ad': whether use AD for audio generation
+ 'max_num_auds': Maximum number of audios to return in one generation pass.
+ 'guidance_scale_for_aud': the guidance ratio of conditioner, if it is None, the default value will be applied in AD
+ 'num_inference_steps_for_aud': the number of inference step for audio generation in the stable diffusion model
+ 'audio_length_in_s': the seconds for generated audio length
+ }
+ """
+ # init output with image tokens
+
+ input_embeds = self.prepare_generation_embedding(inputs)
+ generated_ids, generated_image_embeddings, generated_video_embeddings, generated_audio_embeddings = self.generate_tokens_embeddings(
+ inputs, input_embeds)
+
+ return_outputs = []
+
+ # Find up to max_num_rets [IMG] tokens, and their corresponding scores.
+ all_gen_img_idx = [i for i, x in enumerate(generated_ids[0, :] == self.args['gen_img_token_idx'][0]) if x][
+ :inputs['max_num_imgs']]
+ print('all_gen_img_idx: ', all_gen_img_idx)
+
+ # Find up to max_num_rest [VID] tokens, and their corresponding scores.
+ all_gen_vid_idx = [i for i, x in enumerate(generated_ids[0, :] == self.args['gen_video_token_idx'][0]) if x][
+ :inputs['max_num_vids']]
+ print('all_gen_vid_idx: ', all_gen_vid_idx)
+
+ # Find up to max_num_rest [AUD] tokens, and their corresponding scores.
+ all_gen_aud_idx = [i for i, x in enumerate(generated_ids[0, :] == self.args['gen_audio_token_idx'][0]) if x][
+ :inputs['max_num_auds']]
+ print('all_gen_aud_idx: ', all_gen_aud_idx)
+
+ if len(all_gen_img_idx) == 0 and len(all_gen_vid_idx) == 0 and len(all_gen_aud_idx) == 0:
+ # No [IMG], [VID], [AUD] tokens.
+ caption = self.llama_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ # return_outputs.append(truncate_caption(caption))
+ return_outputs.append(caption)
+ else:
+ if len(all_gen_img_idx) > 0:
+ img_outputs = self.generate_images(generated_ids, generated_image_embeddings, all_gen_img_idx, None,
+ guidance_scale=inputs['guidance_scale_for_img'],
+ num_inference_steps=inputs['num_inference_steps_for_img'],
+ )
+ return_outputs.append({'img': img_outputs})
+ if len(all_gen_vid_idx) > 0:
+ vid_outputs = self.generate_videos(generated_ids, generated_video_embeddings, all_gen_vid_idx, None,
+ guidance_scale=inputs['guidance_scale_for_vid'],
+ num_inference_steps=inputs['num_inference_steps_for_vid'],
+ height=inputs['height'], width=inputs['width'],
+ num_frames=inputs['num_frames'])
+ return_outputs.append({'vid': vid_outputs})
+
+ if len(all_gen_aud_idx) > 0:
+ aud_outputs = self.generate_audios(generated_ids, generated_audio_embeddings, all_gen_aud_idx, None,
+ guidance_scale=inputs['guidance_scale_for_aud'],
+ num_inference_steps=inputs['num_inference_steps_for_aud'],
+ audio_length_in_s=inputs['audio_length_in_s'])
+ return_outputs.append({'aud': aud_outputs})
+
+ return return_outputs
diff --git a/code/model/blip2.py b/code/model/blip2.py
new file mode 100644
index 0000000000000000000000000000000000000000..9512cdb85e25c717b6107a9c10752072ece28a0b
--- /dev/null
+++ b/code/model/blip2.py
@@ -0,0 +1,157 @@
+"""
+Adapted from salesforce@LAVIS. Below is the original copyright:
+ Copyright (c) 2023, salesforce.com, inc.
+ All rights reserved.
+ SPDX-License-Identifier: BSD-3-Clause
+ For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
+"""
+import contextlib
+import logging
+import os
+import time
+import datetime
+
+import torch
+import torch.nn as nn
+import torch.distributed as dist
+import torch.nn.functional as F
+
+from .common import dist_utils
+# from video_llama.common.dist_utils import download_cached_file
+# from .common.utils import is_url
+from .common.logger import MetricLogger
+# from video_llama.models.base_model import BaseModel
+# from video_llama.models.Qformer import BertConfig, BertLMHeadModel
+# from video_llama.models.eva_vit import create_eva_vit_g
+# from transformers import BertTokenizer
+
+
+def disabled_train(self, mode=True):
+ """Overwrite model.train with this function to make sure train/eval mode
+ does not change anymore."""
+ return self
+
+
+class LayerNorm(nn.LayerNorm):
+ """Subclass torch's LayerNorm to handle fp16."""
+
+ def forward(self, x: torch.Tensor):
+ orig_type = x.dtype
+ ret = super().forward(x.type(torch.float32))
+ return ret.type(orig_type)
+
+
+def compute_sim_matrix(model, data_loader, **kwargs):
+ k_test = kwargs.pop("k_test")
+
+ metric_logger = MetricLogger(delimiter=" ")
+ header = "Evaluation:"
+
+ logging.info("Computing features for evaluation...")
+ start_time = time.time()
+
+ texts = data_loader.dataset.text
+ num_text = len(texts)
+ text_bs = 256
+ text_ids = []
+ text_embeds = []
+ text_atts = []
+ for i in range(0, num_text, text_bs):
+ text = texts[i : min(num_text, i + text_bs)]
+ text_input = model.tokenizer(
+ text,
+ padding="max_length",
+ truncation=True,
+ max_length=35,
+ return_tensors="pt",
+ ).to(model.device)
+ text_feat = model.forward_text(text_input)
+ text_embed = F.normalize(model.text_proj(text_feat))
+ text_embeds.append(text_embed)
+ text_ids.append(text_input.input_ids)
+ text_atts.append(text_input.attention_mask)
+
+ text_embeds = torch.cat(text_embeds, dim=0)
+ text_ids = torch.cat(text_ids, dim=0)
+ text_atts = torch.cat(text_atts, dim=0)
+
+ vit_feats = []
+ image_embeds = []
+ for samples in data_loader:
+ image = samples["image"]
+
+ image = image.to(model.device)
+ image_feat, vit_feat = model.forward_image(image)
+ image_embed = model.vision_proj(image_feat)
+ image_embed = F.normalize(image_embed, dim=-1)
+
+ vit_feats.append(vit_feat.cpu())
+ image_embeds.append(image_embed)
+
+ vit_feats = torch.cat(vit_feats, dim=0)
+ image_embeds = torch.cat(image_embeds, dim=0)
+
+ sims_matrix = []
+ for image_embed in image_embeds:
+ sim_q2t = image_embed @ text_embeds.t()
+ sim_i2t, _ = sim_q2t.max(0)
+ sims_matrix.append(sim_i2t)
+ sims_matrix = torch.stack(sims_matrix, dim=0)
+
+ score_matrix_i2t = torch.full(
+ (len(data_loader.dataset.image), len(texts)), -100.0
+ ).to(model.device)
+
+ num_tasks = dist_utils.get_world_size()
+ rank = dist_utils.get_rank()
+ step = sims_matrix.size(0) // num_tasks + 1
+ start = rank * step
+ end = min(sims_matrix.size(0), start + step)
+
+ for i, sims in enumerate(
+ metric_logger.log_every(sims_matrix[start:end], 50, header)
+ ):
+ topk_sim, topk_idx = sims.topk(k=k_test, dim=0)
+ image_inputs = vit_feats[start + i].repeat(k_test, 1, 1).to(model.device)
+ score = model.compute_itm(
+ image_inputs=image_inputs,
+ text_ids=text_ids[topk_idx],
+ text_atts=text_atts[topk_idx],
+ ).float()
+ score_matrix_i2t[start + i, topk_idx] = score + topk_sim
+
+ sims_matrix = sims_matrix.t()
+ score_matrix_t2i = torch.full(
+ (len(texts), len(data_loader.dataset.image)), -100.0
+ ).to(model.device)
+
+ step = sims_matrix.size(0) // num_tasks + 1
+ start = rank * step
+ end = min(sims_matrix.size(0), start + step)
+
+ for i, sims in enumerate(
+ metric_logger.log_every(sims_matrix[start:end], 50, header)
+ ):
+ topk_sim, topk_idx = sims.topk(k=k_test, dim=0)
+ image_inputs = vit_feats[topk_idx.cpu()].to(model.device)
+ score = model.compute_itm(
+ image_inputs=image_inputs,
+ text_ids=text_ids[start + i].repeat(k_test, 1),
+ text_atts=text_atts[start + i].repeat(k_test, 1),
+ ).float()
+ score_matrix_t2i[start + i, topk_idx] = score + topk_sim
+
+ if dist_utils.is_dist_avail_and_initialized():
+ dist.barrier()
+ torch.distributed.all_reduce(
+ score_matrix_i2t, op=torch.distributed.ReduceOp.SUM
+ )
+ torch.distributed.all_reduce(
+ score_matrix_t2i, op=torch.distributed.ReduceOp.SUM
+ )
+
+ total_time = time.time() - start_time
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
+ logging.info("Evaluation time {}".format(total_time_str))
+
+ return score_matrix_i2t.cpu().numpy(), score_matrix_t2i.cpu().numpy()
diff --git a/code/model/common/__init__.py b/code/model/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/model/common/logger.py b/code/model/common/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5cf4659a9cda04cfefa307af4ba357830eca58a
--- /dev/null
+++ b/code/model/common/logger.py
@@ -0,0 +1,195 @@
+"""
+ Copyright (c) 2022, salesforce.com, inc.
+ All rights reserved.
+ SPDX-License-Identifier: BSD-3-Clause
+ For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
+"""
+
+import datetime
+import logging
+import time
+from collections import defaultdict, deque
+
+import torch
+import torch.distributed as dist
+
+from . import dist_utils
+
+
+class SmoothedValue(object):
+ """Track a series of values and provide access to smoothed values over a
+ window or the global series average.
+ """
+
+ def __init__(self, window_size=20, fmt=None):
+ if fmt is None:
+ fmt = "{median:.4f} ({global_avg:.4f})"
+ self.deque = deque(maxlen=window_size)
+ self.total = 0.0
+ self.count = 0
+ self.fmt = fmt
+
+ def update(self, value, n=1):
+ self.deque.append(value)
+ self.count += n
+ self.total += value * n
+
+ def synchronize_between_processes(self):
+ """
+ Warning: does not synchronize the deque!
+ """
+ if not dist_utils.is_dist_avail_and_initialized():
+ return
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
+ dist.barrier()
+ dist.all_reduce(t)
+ t = t.tolist()
+ self.count = int(t[0])
+ self.total = t[1]
+
+ @property
+ def median(self):
+ d = torch.tensor(list(self.deque))
+ return d.median().item()
+
+ @property
+ def avg(self):
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
+ return d.mean().item()
+
+ @property
+ def global_avg(self):
+ return self.total / self.count
+
+ @property
+ def max(self):
+ return max(self.deque)
+
+ @property
+ def value(self):
+ return self.deque[-1]
+
+ def __str__(self):
+ return self.fmt.format(
+ median=self.median,
+ avg=self.avg,
+ global_avg=self.global_avg,
+ max=self.max,
+ value=self.value,
+ )
+
+
+class MetricLogger(object):
+ def __init__(self, delimiter="\t"):
+ self.meters = defaultdict(SmoothedValue)
+ self.delimiter = delimiter
+
+ def update(self, **kwargs):
+ for k, v in kwargs.items():
+ if isinstance(v, torch.Tensor):
+ v = v.item()
+ assert isinstance(v, (float, int))
+ self.meters[k].update(v)
+
+ def __getattr__(self, attr):
+ if attr in self.meters:
+ return self.meters[attr]
+ if attr in self.__dict__:
+ return self.__dict__[attr]
+ raise AttributeError(
+ "'{}' object has no attribute '{}'".format(type(self).__name__, attr)
+ )
+
+ def __str__(self):
+ loss_str = []
+ for name, meter in self.meters.items():
+ loss_str.append("{}: {}".format(name, str(meter)))
+ return self.delimiter.join(loss_str)
+
+ def global_avg(self):
+ loss_str = []
+ for name, meter in self.meters.items():
+ loss_str.append("{}: {:.4f}".format(name, meter.global_avg))
+ return self.delimiter.join(loss_str)
+
+ def synchronize_between_processes(self):
+ for meter in self.meters.values():
+ meter.synchronize_between_processes()
+
+ def add_meter(self, name, meter):
+ self.meters[name] = meter
+
+ def log_every(self, iterable, print_freq, header=None):
+ i = 0
+ if not header:
+ header = ""
+ start_time = time.time()
+ end = time.time()
+ iter_time = SmoothedValue(fmt="{avg:.4f}")
+ data_time = SmoothedValue(fmt="{avg:.4f}")
+ space_fmt = ":" + str(len(str(len(iterable)))) + "d"
+ log_msg = [
+ header,
+ "[{0" + space_fmt + "}/{1}]",
+ "eta: {eta}",
+ "{meters}",
+ "time: {time}",
+ "data: {data}",
+ ]
+ if torch.cuda.is_available():
+ log_msg.append("max mem: {memory:.0f}")
+ log_msg = self.delimiter.join(log_msg)
+ MB = 1024.0 * 1024.0
+ for obj in iterable:
+ data_time.update(time.time() - end)
+ yield obj
+ iter_time.update(time.time() - end)
+ if i % print_freq == 0 or i == len(iterable) - 1:
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
+ if torch.cuda.is_available():
+ print(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ memory=torch.cuda.max_memory_allocated() / MB,
+ )
+ )
+ else:
+ print(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ )
+ )
+ i += 1
+ end = time.time()
+ total_time = time.time() - start_time
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
+ print(
+ "{} Total time: {} ({:.4f} s / it)".format(
+ header, total_time_str, total_time / len(iterable)
+ )
+ )
+
+
+class AttrDict(dict):
+ def __init__(self, *args, **kwargs):
+ super(AttrDict, self).__init__(*args, **kwargs)
+ self.__dict__ = self
+
+
+def setup_logger():
+ logging.basicConfig(
+ level=logging.INFO if dist_utils.is_main_process() else logging.WARN,
+ format="%(asctime)s [%(levelname)s] %(message)s",
+ handlers=[logging.StreamHandler()],
+ )
diff --git a/code/model/common/utils.py b/code/model/common/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..94d96091f25a4fefb946f6253dc243b8035a0b16
--- /dev/null
+++ b/code/model/common/utils.py
@@ -0,0 +1,377 @@
+import random
+
+import torch
+from torch.nn.utils import rnn
+
+import io
+import json
+import logging
+import os
+import pickle
+import re
+import shutil
+import urllib
+import urllib.error
+import urllib.request
+from typing import Optional
+from urllib.parse import urlparse
+
+
+def truncate_caption(caption: str) -> str:
+ """Truncate captions at periods and newlines."""
+ caption = caption.strip('\n')
+ trunc_index = caption.find('\n') + 1
+ if trunc_index <= 0:
+ trunc_index = caption.find('.') + 1
+ if trunc_index > 0:
+ caption = caption[:trunc_index]
+ return caption
+
+
+def build_one_instance_for_pgpt4(tokenizer, conversation):
+ text_list = []
+ turn_num = len(conversation)
+ input_ids, target_ids = [], []
+ for i in range(turn_num):
+ turn = conversation[i]
+ role = turn['from']
+ if i == 0: # the first human turn
+ assert role == 'human'
+ text = '### Human: ' + turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id) # do not perform loss regression on human prompt
+ else:
+ if role == 'human':
+ text = 'Human: ' + turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id)
+ elif role == 'gpt':
+ text = turn['value'] + '\n###'
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ else:
+ raise Exception('Wrong Role!!!')
+ text_list.append(text)
+ assert len(input_ids) == len(target_ids)
+ return text_list, input_ids, target_ids
+
+
+def build_one_instance_for_cc3m(tokenizer, conversation):
+ text_list = []
+ input_ids, target_ids = [], []
+ turn_num = len(conversation)
+ for i in range(turn_num):
+ turn = conversation[i]
+ role = turn['from']
+ if i == 0: # the first human turn
+ assert role == 'human'
+ text = '### Human: ' + turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id) # do not perform loss regression on human prompt
+ else:
+ if role == 'human':
+ text = 'Human: ' + turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id)
+ elif role == 'gpt':
+ if 'image_name' in turn.keys():
+ img_tokens = ' '.join([f'[IMG{i}]' for i in range(8)])
+ text = turn['value'] + ' ' + img_tokens + '\n###'
+ else:
+ text = turn['value'] + '\n###'
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ # if 'image_name' in turn.keys():
+ # img_tokens = ' '.join([f'[IMG{i}]' for i in range(8)])
+ # img_input_ids = tokenizer(img_tokens, add_special_tokens=False).input_ids
+ # input_ids += img_input_ids
+ # target_ids += img_input_ids
+ else:
+ raise Exception('Wrong Role!!!')
+ text_list.append(text)
+ assert len(input_ids) == len(target_ids)
+ return text_list, input_ids, target_ids
+
+
+def build_one_instance_for_cc3m_1(tokenizer, conversation, num_img_tokens=8):
+ text_list = []
+ input_ids, target_ids = [], []
+ turn_num = len(conversation)
+ for i in range(turn_num):
+ turn = conversation[i]
+ role = turn['from']
+ if i == 0: # the first human turn
+ assert role == 'human'
+ text = turn['value'] + '\n### Assistant: '
+ # text = turn['value']
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id # do not perform loss regression on human prompt
+ else:
+ if role == 'human':
+ text = turn['value']
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ elif role == 'gpt':
+ # if 'image_name' in turn.keys():
+ # img_tokens = ' '.join([f'[IMG{i}]' for i in range(num_img_tokens)])
+ # text = turn['value'] + img_tokens
+ # else:
+ # text = turn['value']
+ text = ' '.join([f'[IMG{i}]' for i in range(num_img_tokens)])
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ # if 'image_name' in turn.keys():
+ # img_tokens = ' '.join([f'[IMG{i}]' for i in range(8)])
+ # img_input_ids = tokenizer(img_tokens, add_special_tokens=False).input_ids
+ # input_ids += img_input_ids
+ # target_ids += img_input_ids
+ else:
+ raise Exception('Wrong Role!!!')
+ text_list.append(text)
+ assert len(input_ids) == len(target_ids)
+ return text_list, input_ids, target_ids
+
+
+def build_one_instance_for_webvid(tokenizer, conversation, num_video_tokens=8):
+ text_list = []
+ input_ids, target_ids = [], []
+
+ # text = '### Human: ' + conversation + '\n### Assistant: '
+ # one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ # input_ids += one_input_id
+ # target_ids += one_input_id # do not perform loss regression on human prompt
+
+ video_tokens = ' '.join([f'[VID{i}]' for i in range(num_video_tokens)])
+ text = conversation + video_tokens
+ text_list.append(text)
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ assert len(input_ids) == len(target_ids)
+
+ return text_list, input_ids, target_ids
+
+
+def process_batch_instance(tokenizer, batch_of_conversations, max_tgt_len, dataset='cc3m',
+ num_img_tokens=8, num_video_tokens=8):
+ batch_input_ids, batch_target_ids = [], []
+ for conversation in batch_of_conversations:
+ if dataset == "pgpt4":
+ _, one_input_ids, one_target_ids = build_one_instance_for_pgpt4(tokenizer, conversation)
+ elif dataset == 'cc3m' or dataset == 'coco2017':
+ _, one_input_ids, one_target_ids = build_one_instance_for_cc3m_1(tokenizer, conversation, num_img_tokens)
+ elif dataset == 'webvid':
+ _, one_input_ids, one_target_ids = build_one_instance_for_webvid(tokenizer, conversation, num_video_tokens)
+ else:
+ raise Exception("not support dataset name, it should be pgpt4 or cc3m")
+ batch_input_ids.append(torch.LongTensor(one_input_ids))
+ batch_target_ids.append(torch.LongTensor(one_target_ids))
+ input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
+ target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
+ assert input_ids.size() == target_ids.size()
+ input_ids = input_ids[:, :max_tgt_len]
+ target_ids = target_ids[:, :max_tgt_len]
+ attention_mask = input_ids.ne(tokenizer.pad_token_id)
+ assert attention_mask.size() == input_ids.size()
+ return input_ids, target_ids, attention_mask.long()
+
+
+def mask_token(inputs, tokenizer, mlm_probability, vocab_size=None, special_tokens_mask=None):
+ """
+ randomly mask some input tokens
+ """
+ indices_replaced = torch.bernoulli(torch.full(inputs.shape, mlm_probability)).bool()
+ inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
+
+ return inputs
+
+
+def build_one_instance_stage_1(tokenizer, captions, prompt=''):
+ input_ids, target_ids = [], []
+ texts = ''
+ text = ' ' + prompt + '\n### Assistant: '
+ texts += text
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id) # do not perform loss regression on human prompt
+
+ text = captions + '\n###'
+ texts += text
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ return input_ids, target_ids
+
+
+def process_batch_stage_1(tokenizer, batch_of_captions, max_tgt_len, prompt=''):
+ batch_input_ids, batch_target_ids = [], []
+ for caption in batch_of_captions:
+ one_input_ids, one_target_ids = build_one_instance_stage_1(tokenizer, caption, prompt)
+ batch_input_ids.append(torch.LongTensor(one_input_ids))
+ batch_target_ids.append(torch.LongTensor(one_target_ids))
+ input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
+ target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
+ assert input_ids.size() == target_ids.size()
+ input_ids = input_ids[:, :max_tgt_len]
+ target_ids = target_ids[:, :max_tgt_len]
+ attention_mask = input_ids.ne(tokenizer.pad_token_id)
+ assert attention_mask.size() == input_ids.size()
+ return input_ids, target_ids, attention_mask.long()
+
+
+def build_one_instance_stage_2(tokenizer, captions, num_signal_tokens=4, MODALITY='image'):
+ input_ids, target_ids = [], []
+ text = captions + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id) # do not perform loss regression on human prompt
+
+ if MODALITY == 'image':
+ signal_tokens = ' '.join([f'[IMG{i}]' for i in range(num_signal_tokens)])
+ elif MODALITY == 'video':
+ signal_tokens = ' '.join([f'[VID{i}]' for i in range(num_signal_tokens)])
+ elif MODALITY == 'audio':
+ signal_tokens = ' '.join([f'[AUD{i}]' for i in range(num_signal_tokens)])
+ else:
+ signal_tokens = ''
+
+ text = captions + signal_tokens + '\n###'
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ return input_ids, target_ids
+
+
+def process_batch_stage_2(tokenizer, batch_of_captions, max_tgt_len, num_signal_tokens=4, MODALITY='image'):
+ """
+ :param mode: the target modality
+ :param num_tokens: the number of generated signal tokens for generation
+ """
+ batch_input_ids, batch_target_ids = [], []
+ # batch_caption_lists = []
+ for captions in batch_of_captions:
+ one_input_ids, one_target_ids = build_one_instance_stage_2(tokenizer, captions,
+ num_signal_tokens=num_signal_tokens,
+ MODALITY=MODALITY)
+ batch_input_ids.append(torch.LongTensor(one_input_ids))
+ batch_target_ids.append(torch.LongTensor(one_target_ids))
+ # batch_caption_lists.append(caption)
+ input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
+ target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
+ assert input_ids.size() == target_ids.size()
+ input_ids = input_ids[:, :max_tgt_len]
+ target_ids = target_ids[:, :max_tgt_len]
+ attention_mask = input_ids.ne(tokenizer.pad_token_id)
+ assert attention_mask.size() == input_ids.size()
+ return input_ids, target_ids, attention_mask.long()
+
+
+# def process_batch_stage_2(tokenizer, batch_of_captions, )
+
+
+def build_one_instance_stage_3(tokenizer, conversation, img_tokens=4, vid_tokens=24, aud_tokens=8):
+ text_list = []
+ turn_num = len(conversation)
+ input_ids, target_ids = [], []
+ for i in range(turn_num):
+ turn = conversation[i]
+ role = turn['from']
+ if i == 0: # the first human turn
+ assert role == 'human'
+ if turn['input_modality'] != 'text':
+ text = ' ' + turn['value'] + '\n### Assistant: '
+ else:
+ text = turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id) # do not perform loss regression on human prompt
+ else:
+ if role == 'human':
+ text = 'Human: ' + turn['value'] + '\n### Assistant: '
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += [-100] * len(one_input_id)
+ elif role == 'gpt':
+ if turn['output_modality'] == 'image':
+ signal_tokens = ' '.join([f'[IMG{i}]' for i in range(img_tokens)])
+ elif turn['output_modality'] == 'video':
+ signal_tokens = ' '.join([f'[VID{i}]' for i in range(vid_tokens)])
+ elif turn['output_modality'] == 'audio':
+ signal_tokens = ' '.join([f'[AUD{i}]' for i in range(aud_tokens)])
+ else:
+ signal_tokens = ''
+ caption = turn['caption']
+ text = turn['value'] + signal_tokens + '\n###'
+ one_input_id = tokenizer(text, add_special_tokens=False).input_ids
+ input_ids += one_input_id
+ target_ids += one_input_id
+ else:
+ raise Exception('Wrong Role!!!')
+ text_list.append(text)
+ assert len(input_ids) == len(target_ids)
+ return text_list, input_ids, target_ids, caption
+
+
+def process_batch_stage_3(tokenizer, batch_of_conversations, max_tgt_len, img_tokens=4, vid_tokens=24, aud_tokens=8):
+ """
+ :param mode: the target modality
+ :param num_tokens: the number of generated signal tokens for generation
+ """
+ batch_input_ids, batch_target_ids = [], []
+ # batch_caption_lists = []
+ for conversation in batch_of_conversations:
+ _, one_input_ids, one_target_ids, caption = build_one_instance_stage_3(tokenizer, conversation,
+ img_tokens=img_tokens,
+ vid_tokens=vid_tokens,
+ aud_tokens=aud_tokens)
+ batch_input_ids.append(torch.LongTensor(one_input_ids))
+ batch_target_ids.append(torch.LongTensor(one_target_ids))
+ # batch_caption_lists.append(caption)
+ input_ids = rnn.pad_sequence(batch_input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
+ target_ids = rnn.pad_sequence(batch_target_ids, batch_first=True, padding_value=-100)
+ assert input_ids.size() == target_ids.size()
+ input_ids = input_ids[:, :max_tgt_len]
+ # if is_mask_token:
+ # input_ids = mask_token(input_ids, tokenizer, 0.5)
+ target_ids = target_ids[:, :max_tgt_len]
+ attention_mask = input_ids.ne(tokenizer.pad_token_id)
+ assert attention_mask.size() == input_ids.size()
+ return input_ids, target_ids, attention_mask.long()
+
+
+def is_url(url_or_filename):
+ parsed = urlparse(url_or_filename)
+ return parsed.scheme in ("http", "https")
+
+
+def l2_loss(u: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ u: (N, T_I_V_A.txt, D) tensor.
+ v: (N, T_I_V_A.txt, D) tensor.
+ Returns:
+ l1_loss: (N,) tensor of summed L1 loss.
+ """
+ assert u.shape == v.shape, (u.shape, v.shape)
+ return ((u - v) ** 2).sum(dim=-1) ** 0.5
+
+
+def get_modality(path_list):
+ _postfix = os.path.splitext(path_list[0])[-1]
+ if _postfix == '.jpg':
+ return 'image'
+ elif _postfix == '.wav':
+ return 'audio'
+ elif _postfix == '.mp4':
+ return 'video'
+ else:
+ raise NotImplementedError
diff --git a/code/model/custom_ad.py b/code/model/custom_ad.py
new file mode 100644
index 0000000000000000000000000000000000000000..09c0194f999cf06c24cbbdc8c83cd85cf0f1655e
--- /dev/null
+++ b/code/model/custom_ad.py
@@ -0,0 +1,607 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# 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 inspect
+from typing import Any, Callable, Dict, List, Optional, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from transformers import ClapTextModelWithProjection, RobertaTokenizer, RobertaTokenizerFast, SpeechT5HifiGan
+
+from diffusers.models import AutoencoderKL, UNet2DConditionModel
+from diffusers.schedulers import KarrasDiffusionSchedulers
+from diffusers.utils import is_accelerate_available, logging, randn_tensor, replace_example_docstring
+from diffusers.pipelines.pipeline_utils import AudioPipelineOutput, DiffusionPipeline
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+EXAMPLE_DOC_STRING = """
+ Examples:
+ ```py
+ >>> import torch
+ >>> from diffusers import AudioLDMPipeline
+
+ >>> pipe = AudioLDMPipeline.from_pretrained("cvssp/audioldm", torch_dtype=torch.float16)
+ >>> pipe = pipe.to("cuda")
+
+ >>> prompt = "A hammer hitting a wooden surface"
+ >>> audio = pipe(prompt).audio[0]
+ ```
+"""
+
+
+class AudioLDMPipeline(DiffusionPipeline):
+ r"""
+ Pipeline for text-to-audio generation using AudioLDM.
+
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
+
+ Args:
+ vae ([`AutoencoderKL`]):
+ Variational Auto-Encoder (VAE) Model to encode and decode audios to and from latent representations.
+ text_encoder ([`ClapTextModelWithProjection`]):
+ Frozen text-encoder. AudioLDM uses the text portion of
+ [CLAP](https://huggingface.co/docs/transformers/main/model_doc/clap#transformers.ClapTextModelWithProjection),
+ specifically the [RoBERTa HSTAT-unfused](https://huggingface.co/laion/clap-htsat-unfused) variant.
+ tokenizer ([`PreTrainedTokenizer`]):
+ Tokenizer of class
+ [RobertaTokenizer](https://huggingface.co/docs/transformers/model_doc/roberta#transformers.RobertaTokenizer).
+ unet ([`UNet2DConditionModel`]): U-Net architecture to denoise the encoded audio latents.
+ scheduler ([`SchedulerMixin`]):
+ A scheduler to be used in combination with `unet` to denoise the encoded audio latents. Can be one of
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
+ vocoder ([`SpeechT5HifiGan`]):
+ Vocoder of class
+ [SpeechT5HifiGan](https://huggingface.co/docs/transformers/main/en/model_doc/speecht5#transformers.SpeechT5HifiGan).
+ """
+
+ def __init__(
+ self,
+ vae: AutoencoderKL,
+ text_encoder: ClapTextModelWithProjection,
+ tokenizer: Union[RobertaTokenizer, RobertaTokenizerFast],
+ unet: UNet2DConditionModel,
+ scheduler: KarrasDiffusionSchedulers,
+ vocoder: SpeechT5HifiGan,
+ ):
+ super().__init__()
+
+ self.register_modules(
+ vae=vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ unet=unet,
+ scheduler=scheduler,
+ vocoder=vocoder,
+ )
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
+ def enable_vae_slicing(self):
+ r"""
+ Enable sliced VAE decoding.
+
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
+ steps. This is useful to save some memory and allow larger batch sizes.
+ """
+ self.vae.enable_slicing()
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
+ def disable_vae_slicing(self):
+ r"""
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
+ computing decoding in one step.
+ """
+ self.vae.disable_slicing()
+
+ def enable_sequential_cpu_offload(self, gpu_id=0):
+ r"""
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
+ text_encoder, vae and vocoder have their state dicts saved to CPU and then are moved to a `torch.device('meta')
+ and loaded to GPU only when their specific submodule has its `forward` method called.
+ """
+ if is_accelerate_available():
+ from accelerate import cpu_offload
+ else:
+ raise ImportError("Please install accelerate via `pip install accelerate`")
+
+ device = torch.device(f"cuda:{gpu_id}")
+
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.vocoder]:
+ cpu_offload(cpu_offloaded_model, device)
+
+ @property
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
+ def _execution_device(self):
+ r"""
+ Returns the device on which the pipeline's models will be executed. After calling
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
+ hooks.
+ """
+ if not hasattr(self.unet, "_hf_hook"):
+ return self.device
+ for module in self.unet.modules():
+ if (
+ hasattr(module, "_hf_hook")
+ and hasattr(module._hf_hook, "execution_device")
+ and module._hf_hook.execution_device is not None
+ ):
+ return torch.device(module._hf_hook.execution_device)
+ return self.device
+
+ def _encode_prompt(
+ self,
+ prompt,
+ device,
+ num_waveforms_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt=None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ ):
+ r"""
+ Encodes the prompt into text encoder hidden states.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ prompt to be encoded
+ device (`torch.device`):
+ torch device
+ num_waveforms_per_prompt (`int`):
+ number of waveforms that should be generated per prompt
+ do_classifier_free_guidance (`bool`):
+ whether to use classifier free guidance or not
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the audio generation. If not defined, one has to pass
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+ less than `1`).
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ """
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ if prompt_embeds is None:
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ attention_mask = text_inputs.attention_mask
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
+ text_input_ids, untruncated_ids
+ ):
+ removed_text = self.tokenizer.batch_decode(
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
+ )
+ logger.warning(
+ "The following part of your input was truncated because CLAP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ prompt_embeds = self.text_encoder(
+ text_input_ids.to(device),
+ attention_mask=attention_mask.to(device),
+ )
+ prompt_embeds = prompt_embeds.text_embeds
+ # additional L_2 normalization over each hidden-state
+ prompt_embeds = F.normalize(prompt_embeds, dim=-1)
+
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ (
+ bs_embed,
+ seq_len,
+ ) = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_waveforms_per_prompt)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_waveforms_per_prompt, seq_len)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = prompt_embeds.shape[1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ uncond_input_ids = uncond_input.input_ids.to(device)
+ attention_mask = uncond_input.attention_mask.to(device)
+
+ negative_prompt_embeds = self.text_encoder(
+ uncond_input_ids,
+ attention_mask=attention_mask,
+ )
+ negative_prompt_embeds = negative_prompt_embeds.text_embeds
+ # additional L_2 normalization over each hidden-state
+ negative_prompt_embeds = F.normalize(negative_prompt_embeds, dim=-1)
+
+ if do_classifier_free_guidance:
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = negative_prompt_embeds.shape[1]
+
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_waveforms_per_prompt)
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_waveforms_per_prompt, seq_len)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
+
+ return prompt_embeds
+
+ def decode_latents(self, latents):
+ latents = 1 / self.vae.config.scaling_factor * latents
+ mel_spectrogram = self.vae.decode(latents).sample
+ return mel_spectrogram
+
+ def mel_spectrogram_to_waveform(self, mel_spectrogram):
+ if mel_spectrogram.dim() == 4:
+ mel_spectrogram = mel_spectrogram.squeeze(1)
+
+ waveform = self.vocoder(mel_spectrogram)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
+ waveform = waveform.cpu().float()
+ return waveform
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
+ def prepare_extra_step_kwargs(self, generator, eta):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def check_inputs(
+ self,
+ prompt,
+ audio_length_in_s,
+ vocoder_upsample_factor,
+ callback_steps,
+ negative_prompt=None,
+ prompt_embeds=None,
+ negative_prompt_embeds=None,
+ ):
+ min_audio_length_in_s = vocoder_upsample_factor * self.vae_scale_factor
+ if audio_length_in_s < min_audio_length_in_s:
+ raise ValueError(
+ f"`audio_length_in_s` has to be a positive value greater than or equal to {min_audio_length_in_s}, but "
+ f"is {audio_length_in_s}."
+ )
+
+ if self.vocoder.config.model_in_dim % self.vae_scale_factor != 0:
+ raise ValueError(
+ f"The number of frequency bins in the vocoder's log-mel spectrogram has to be divisible by the "
+ f"VAE scale factor, but got {self.vocoder.config.model_in_dim} bins and a scale factor of "
+ f"{self.vae_scale_factor}."
+ )
+
+ if (callback_steps is None) or (
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
+ ):
+ raise ValueError(
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
+ f" {type(callback_steps)}."
+ )
+
+ if prompt is not None and prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
+ " only forward one of the two."
+ )
+ elif prompt is None and prompt_embeds is None:
+ raise ValueError(
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
+ )
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
+
+ if negative_prompt is not None and negative_prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
+ )
+
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
+ raise ValueError(
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
+ f" {negative_prompt_embeds.shape}."
+ )
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents with width->self.vocoder.config.model_in_dim
+ def prepare_latents(self, batch_size, num_channels_latents, height, dtype, device, generator, latents=None):
+ shape = (
+ batch_size,
+ num_channels_latents,
+ height // self.vae_scale_factor,
+ self.vocoder.config.model_in_dim // self.vae_scale_factor,
+ )
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
+ else:
+ latents = latents.to(device)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.scheduler.init_noise_sigma
+ return latents
+
+ @torch.no_grad()
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
+ def __call__(
+ self,
+ prompt: Union[str, List[str]] = None,
+ audio_length_in_s: Optional[float] = None,
+ num_inference_steps: int = 10,
+ guidance_scale: float = 2.5,
+ negative_prompt: Optional[Union[str, List[str]]] = None,
+ num_waveforms_per_prompt: Optional[int] = 1,
+ eta: float = 0.0,
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
+ latents: Optional[torch.FloatTensor] = None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ return_dict: bool = True,
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
+ callback_steps: Optional[int] = 1,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ output_type: Optional[str] = "np",
+ return_prompts_only: bool = False,
+ ):
+ r"""
+ Function invoked when calling the pipeline for generation.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts to guide the audio generation. If not defined, one has to pass `prompt_embeds`.
+ instead.
+ audio_length_in_s (`int`, *optional*, defaults to 5.12):
+ The length of the generated audio sample in seconds.
+ num_inference_steps (`int`, *optional*, defaults to 10):
+ The number of denoising steps. More denoising steps usually lead to a higher quality audio at the
+ expense of slower inference.
+ guidance_scale (`float`, *optional*, defaults to 2.5):
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
+ 1`. Higher guidance scale encourages to generate audios that are closely linked to the text `prompt`,
+ usually at the expense of lower sound quality.
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the audio generation. If not defined, one has to pass
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+ less than `1`).
+ num_waveforms_per_prompt (`int`, *optional*, defaults to 1):
+ The number of waveforms to generate per prompt.
+ eta (`float`, *optional*, defaults to 0.0):
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
+ [`schedulers.DDIMScheduler`], will be ignored for others.
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
+ to make generation deterministic.
+ latents (`torch.FloatTensor`, *optional*):
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for audio
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
+ tensor will ge generated by sampling using the supplied random `generator`.
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
+ plain tuple.
+ callback (`Callable`, *optional*):
+ A function that will be called every `callback_steps` steps during inference. The function will be
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
+ callback_steps (`int`, *optional*, defaults to 1):
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
+ called at every step.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processors` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+ output_type (`str`, *optional*, defaults to `"np"`):
+ The output format of the generate image. Choose between:
+ - `"np"`: Return Numpy `np.ndarray` objects.
+ - `"pt"`: Return PyTorch `torch.Tensor` objects.
+
+ Examples:
+
+ Returns:
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
+ When returning a tuple, the first element is a list with the generated audios.
+ """
+ # 0. Convert audio input length from seconds to spectrogram height
+ vocoder_upsample_factor = np.prod(self.vocoder.config.upsample_rates) / self.vocoder.config.sampling_rate
+
+ if audio_length_in_s is None:
+ audio_length_in_s = self.unet.config.sample_size * self.vae_scale_factor * vocoder_upsample_factor
+
+ height = int(audio_length_in_s / vocoder_upsample_factor)
+
+ original_waveform_length = int(audio_length_in_s * self.vocoder.config.sampling_rate)
+ if height % self.vae_scale_factor != 0:
+ height = int(np.ceil(height / self.vae_scale_factor)) * self.vae_scale_factor
+ logger.info(
+ f"Audio length in seconds {audio_length_in_s} is increased to {height * vocoder_upsample_factor} "
+ f"so that it can be handled by the model. It will be cut to {audio_length_in_s} after the "
+ f"denoising process."
+ )
+
+ # 1. Check inputs. Raise error if not correct
+ self.check_inputs(
+ prompt,
+ audio_length_in_s,
+ vocoder_upsample_factor,
+ callback_steps,
+ negative_prompt,
+ prompt_embeds,
+ negative_prompt_embeds,
+ )
+
+ # 2. Define call parameters
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ device = self._execution_device
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
+ # corresponds to doing no classifier free guidance.
+ do_classifier_free_guidance = guidance_scale > 1.0
+ if return_prompts_only:
+ # Don't concat two prompts
+ do_classifier_free_guidance = False
+
+ # 3. Encode input prompt
+ prompt_embeds = self._encode_prompt(
+ prompt,
+ device,
+ num_waveforms_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt,
+ prompt_embeds=prompt_embeds,
+ negative_prompt_embeds=negative_prompt_embeds,
+ )
+ if return_prompts_only:
+ return prompt_embeds
+
+ # 4. Prepare timesteps
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
+ timesteps = self.scheduler.timesteps
+
+ # 5. Prepare latent variables
+ num_channels_latents = self.unet.config.in_channels
+ latents = self.prepare_latents(
+ batch_size * num_waveforms_per_prompt,
+ num_channels_latents,
+ height,
+ prompt_embeds.dtype,
+ device,
+ generator,
+ latents,
+ )
+
+ # 6. Prepare extra step kwargs
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
+
+ # 7. Denoising loop
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=None,
+ class_labels=prompt_embeds,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ # call the callback, if provided
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
+ progress_bar.update()
+ if callback is not None and i % callback_steps == 0:
+ callback(i, t, latents)
+
+ # 8. Post-processing
+ mel_spectrogram = self.decode_latents(latents)
+
+ audio = self.mel_spectrogram_to_waveform(mel_spectrogram)
+
+ audio = audio[:, :original_waveform_length]
+
+ if output_type == "np":
+ audio = audio.numpy()
+
+ if not return_dict:
+ return (audio,)
+
+ return AudioPipelineOutput(audios=audio)
\ No newline at end of file
diff --git a/code/model/custom_sd.py b/code/model/custom_sd.py
new file mode 100644
index 0000000000000000000000000000000000000000..58bf3c3c2e18ca7ff2743f632a2e41d9e64a4211
--- /dev/null
+++ b/code/model/custom_sd.py
@@ -0,0 +1,664 @@
+"""A slightly modified version of the HuggingFace StableDiffusion pipeline, to allow us to extract text embeddings."""
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# 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 inspect
+from typing import Any, Callable, Dict, List, Optional, Union
+
+import torch
+
+from packaging import version
+from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
+
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL, UNet2DConditionModel
+from diffusers.schedulers import KarrasDiffusionSchedulers
+from diffusers.utils import deprecate, is_accelerate_available, logging, randn_tensor, replace_example_docstring
+from diffusers.pipeline_utils import DiffusionPipeline
+from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
+from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+EXAMPLE_DOC_STRING = """
+ Examples:
+ ```py
+ >>> import torch
+ >>> from diffusers import StableDiffusionPipeline
+
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
+ >>> pipe = pipe.to("cuda")
+
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
+ >>> image = pipe(prompt).images[0]
+ ```
+"""
+
+
+class StableDiffusionPipeline(DiffusionPipeline):
+ r"""
+ Pipeline for text-to-image generation using Stable Diffusion.
+
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
+
+ Args:
+ vae ([`AutoencoderKL`]):
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
+ text_encoder ([`CLIPTextModel`]):
+ Frozen text-encoder. Stable Diffusion uses the text portion of
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
+ tokenizer (`CLIPTokenizer`):
+ Tokenizer of class
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
+ scheduler ([`SchedulerMixin`]):
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
+ safety_checker ([`StableDiffusionSafetyChecker`]):
+ Classification module that estimates whether generated images could be considered offensive or harmful.
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
+ feature_extractor ([`CLIPFeatureExtractor`]):
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
+ """
+ _optional_components = ["safety_checker", "feature_extractor"]
+
+ def __init__(
+ self,
+ vae: AutoencoderKL,
+ text_encoder: CLIPTextModel,
+ tokenizer: CLIPTokenizer,
+ unet: UNet2DConditionModel,
+ scheduler: KarrasDiffusionSchedulers,
+ safety_checker: StableDiffusionSafetyChecker,
+ feature_extractor: CLIPFeatureExtractor,
+ requires_safety_checker: bool = True,
+ ):
+ super().__init__()
+
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(scheduler.config)
+ new_config["steps_offset"] = 1
+ scheduler._internal_dict = FrozenDict(new_config)
+
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(scheduler.config)
+ new_config["clip_sample"] = False
+ scheduler._internal_dict = FrozenDict(new_config)
+
+ if safety_checker is None and requires_safety_checker:
+ logger.warning(
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
+ )
+
+ if safety_checker is not None and feature_extractor is None:
+ raise ValueError(
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
+ )
+
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse("0.9.0.dev0")
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ self.register_modules(
+ vae=vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ unet=unet,
+ scheduler=scheduler,
+ safety_checker=safety_checker,
+ feature_extractor=feature_extractor,
+ )
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
+
+ def enable_vae_slicing(self):
+ r"""
+ Enable sliced VAE decoding.
+
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
+ steps. This is useful to save some memory and allow larger batch sizes.
+ """
+ self.vae.enable_slicing()
+
+ def disable_vae_slicing(self):
+ r"""
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
+ computing decoding in one step.
+ """
+ self.vae.disable_slicing()
+
+ def enable_sequential_cpu_offload(self, gpu_id=0):
+ r"""
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
+ """
+ if is_accelerate_available():
+ from accelerate import cpu_offload
+ else:
+ raise ImportError("Please install accelerate via `pip install accelerate`")
+
+ device = torch.device(f"cuda:{gpu_id}")
+
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
+ cpu_offload(cpu_offloaded_model, device)
+
+ if self.safety_checker is not None:
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
+
+ @property
+ def _execution_device(self):
+ r"""
+ Returns the device on which the pipeline's models will be executed. After calling
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
+ hooks.
+ """
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
+ return self.device
+ for module in self.unet.modules():
+ if (
+ hasattr(module, "_hf_hook")
+ and hasattr(module._hf_hook, "execution_device")
+ and module._hf_hook.execution_device is not None
+ ):
+ return torch.device(module._hf_hook.execution_device)
+ return self.device
+
+ def _encode_prompt(
+ self,
+ prompt,
+ device,
+ num_images_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt=None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ ):
+ r"""
+ Encodes the prompt into text encoder hidden states.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ prompt to be encoded
+ device: (`torch.device`):
+ torch device
+ num_images_per_prompt (`int`):
+ number of images that should be generated per prompt
+ do_classifier_free_guidance (`bool`):
+ whether to use classifier free guidance or not
+ negative_ prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ """
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ if prompt_embeds is None:
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ truncate_side = 'left'
+
+ if truncate_side == 'left':
+ # Truncate from the left.
+ if untruncated_ids.shape[-1] > self.tokenizer.model_max_length:
+ print('Original prompt:', prompt)
+ prompt = self.tokenizer.batch_decode(
+ untruncated_ids[:, -1 - self.tokenizer.model_max_length: -1]
+ )
+ print('Trunc prompt:', prompt)
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+
+ if truncate_side == 'right':
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
+ text_input_ids, untruncated_ids
+ ):
+ removed_text = self.tokenizer.batch_decode(
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]
+ )
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(device)
+ else:
+ attention_mask = None
+
+ prompt_embeds = self.text_encoder(
+ text_input_ids.to(device),
+ attention_mask=attention_mask,
+ )
+ prompt_embeds = prompt_embeds[0]
+
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ bs_embed, seq_len, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = prompt_embeds.shape[1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(device)
+ else:
+ attention_mask = None
+
+ negative_prompt_embeds = self.text_encoder(
+ uncond_input.input_ids.to(device),
+ attention_mask=attention_mask,
+ )
+ negative_prompt_embeds = negative_prompt_embeds[0]
+
+ if do_classifier_free_guidance:
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = negative_prompt_embeds.shape[1]
+
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
+
+ return prompt_embeds
+
+ def run_safety_checker(self, image, device, dtype):
+ if self.safety_checker is not None:
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
+ image, has_nsfw_concept = self.safety_checker(
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
+ )
+ else:
+ has_nsfw_concept = None
+ return image, has_nsfw_concept
+
+ def decode_latents(self, latents):
+ # latents = 1 / self.vae.config.scaling_factor * latents
+ latents = 1 / 0.18215 * latents
+ image = self.vae.decode(latents).sample
+ image = (image / 2 + 0.5).clamp(0, 1)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
+ return image
+
+ def prepare_extra_step_kwargs(self, generator, eta):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def check_inputs(
+ self,
+ prompt,
+ height,
+ width,
+ callback_steps,
+ negative_prompt=None,
+ prompt_embeds=None,
+ negative_prompt_embeds=None,
+ ):
+ if height % 8 != 0 or width % 8 != 0:
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
+
+ if (callback_steps is None) or (
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
+ ):
+ raise ValueError(
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
+ f" {type(callback_steps)}."
+ )
+
+ if prompt is not None and prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
+ " only forward one of the two."
+ )
+ elif prompt is None and prompt_embeds is None:
+ raise ValueError(
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
+ )
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
+
+ if negative_prompt is not None and negative_prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
+ )
+
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
+ raise ValueError(
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
+ f" {negative_prompt_embeds.shape}."
+ )
+
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
+ else:
+ latents = latents.to(device)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.scheduler.init_noise_sigma
+ return latents
+
+ @torch.no_grad()
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
+ def __call__(
+ self,
+ prompt: Union[str, List[str]] = None,
+ height: Optional[int] = None,
+ width: Optional[int] = None,
+ num_inference_steps: int = 50,
+ guidance_scale: float = 7.5,
+ negative_prompt: Optional[Union[str, List[str]]] = None,
+ num_images_per_prompt: Optional[int] = 1,
+ eta: float = 0.0,
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
+ latents: Optional[torch.FloatTensor] = None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ output_type: Optional[str] = "pil",
+ return_dict: bool = True,
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
+ callback_steps: Optional[int] = 1,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_prompts_only: bool = False,
+ ):
+ r"""
+ Function invoked when calling the pipeline for generation.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
+ instead.
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The height in pixels of the generated image.
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The width in pixels of the generated image.
+ num_inference_steps (`int`, *optional*, defaults to 50):
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
+ expense of slower inference.
+ guidance_scale (`float`, *optional*, defaults to 7.5):
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
+ usually at the expense of lower image quality.
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
+ The number of images to generate per prompt.
+ eta (`float`, *optional*, defaults to 0.0):
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
+ [`schedulers.DDIMScheduler`], will be ignored for others.
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
+ to make generation deterministic.
+ latents (`torch.FloatTensor`, *optional*):
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
+ tensor will ge generated by sampling using the supplied random `generator`.
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ output_type (`str`, *optional*, defaults to `"pil"`):
+ The output format of the generate image. Choose between
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
+ plain tuple.
+ callback (`Callable`, *optional*):
+ A function that will be called every `callback_steps` steps during inference. The function will be
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
+ callback_steps (`int`, *optional*, defaults to 1):
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
+ called at every step.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processors` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Examples:
+
+ Returns:
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
+ (nsfw) content, according to the `safety_checker`.
+ """
+ # 0. Default height and width to unet
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
+
+ # 1. Check inputs. Raise error if not correct
+ self.check_inputs(
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
+ )
+
+ # 2. Define call parameters
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ device = self._execution_device
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
+ # corresponds to doing no classifier free guidance.
+ do_classifier_free_guidance = guidance_scale > 1.0
+ if return_prompts_only:
+ # Don't concat two prompts
+ do_classifier_free_guidance = False
+
+ # 3. Encode input prompt
+ prompt_embeds = self._encode_prompt(
+ prompt,
+ device,
+ num_images_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt,
+ prompt_embeds=prompt_embeds,
+ negative_prompt_embeds=negative_prompt_embeds,
+ )
+ if return_prompts_only:
+ return prompt_embeds
+
+ # 4. Prepare timesteps
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
+ timesteps = self.scheduler.timesteps
+
+ # 5. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ latents = self.prepare_latents(
+ batch_size * num_images_per_prompt,
+ num_channels_latents,
+ height,
+ width,
+ prompt_embeds.dtype,
+ device,
+ generator,
+ latents,
+ )
+
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
+
+ # 7. Denoising loop
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
+
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=prompt_embeds,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ # call the callback, if provided
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
+ if callback is not None and i % callback_steps == 0:
+ callback(i, t, latents)
+
+ # 8. Post-processing
+ image = self.decode_latents(latents)
+
+ # 9. Run safety checker
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
+
+ # 10. Convert to PIL
+ if output_type == "pil":
+ image = self.numpy_to_pil(image)
+
+ if not return_dict:
+ return (image, has_nsfw_concept)
+
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
diff --git a/code/model/custom_vd.py b/code/model/custom_vd.py
new file mode 100644
index 0000000000000000000000000000000000000000..99a8759f7569846776b0448aa680562c391fa962
--- /dev/null
+++ b/code/model/custom_vd.py
@@ -0,0 +1,711 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# 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 inspect
+from typing import Any, Callable, Dict, List, Optional, Union
+from dataclasses import dataclass
+import numpy as np
+import torch
+from transformers import CLIPTextModel, CLIPTokenizer
+
+from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
+from diffusers.models import AutoencoderKL, UNet3DConditionModel
+from diffusers.schedulers import KarrasDiffusionSchedulers
+from diffusers.utils import (
+ is_accelerate_available,
+ is_accelerate_version,
+ logging,
+ randn_tensor,
+ replace_example_docstring,
+)
+from diffusers.pipeline_utils import DiffusionPipeline
+from diffusers.utils import BaseOutput
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+EXAMPLE_DOC_STRING = """
+ Examples:
+ ```py
+ >>> import torch
+ >>> from diffusers import TextToVideoSDPipeline
+ >>> from diffusers.utils import export_to_video
+
+ >>> pipe = TextToVideoSDPipeline.from_pretrained(
+ ... "damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16"
+ ... )
+ >>> pipe.enable_model_cpu_offload()
+
+ >>> prompt = "Spiderman is surfing"
+ >>> video_frames = pipe(prompt).frames
+ >>> video_path = export_to_video(video_frames)
+ >>> video_path
+ ```
+"""
+
+
+def tensor2vid(video: torch.Tensor, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) -> List[np.ndarray]:
+ # This code is copied from https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
+ # reshape to ncfhw
+ mean = torch.tensor(mean, device=video.device).reshape(1, -1, 1, 1, 1)
+ std = torch.tensor(std, device=video.device).reshape(1, -1, 1, 1, 1)
+ # unnormalize back to [0,1]
+ video = video.mul_(std).add_(mean)
+ video.clamp_(0, 1)
+ # prepare the final outputs
+ i, c, f, h, w = video.shape
+ images = video.permute(2, 3, 0, 4, 1).reshape(
+ f, h, i * w, c
+ ) # 1st (frames, h, batch_size, w, c) 2nd (frames, h, batch_size * w, c)
+ images = images.unbind(dim=0) # prepare a list of indvidual (consecutive frames)
+ images = [(image.cpu().numpy() * 255).astype("uint8") for image in images] # f h w c
+ return images
+
+
+@dataclass
+class TextToVideoSDPipelineOutput(BaseOutput):
+ """
+ Output class for text to video pipelines.
+
+ Args:
+ frames (`List[np.ndarray]` or `torch.FloatTensor`)
+ List of denoised frames (essentially images) as NumPy arrays of shape `(height, width, num_channels)` or as
+ a `torch` tensor. NumPy array present the denoised images of the diffusion pipeline. The length of the list
+ denotes the video length i.e., the number of frames.
+ """
+
+ frames: Union[List[np.ndarray], torch.FloatTensor]
+
+
+class TextToVideoSDPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
+ r"""
+ Pipeline for text-to-video generation.
+
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
+
+ Args:
+ vae ([`AutoencoderKL`]):
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
+ text_encoder ([`CLIPTextModel`]):
+ Frozen text-encoder. Same as Stable Diffusion 2.
+ tokenizer (`CLIPTokenizer`):
+ Tokenizer of class
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
+ unet ([`UNet3DConditionModel`]): Conditional U-Net architecture to denoise the encoded video latents.
+ scheduler ([`SchedulerMixin`]):
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
+ """
+
+ def __init__(
+ self,
+ vae: AutoencoderKL,
+ text_encoder: CLIPTextModel,
+ tokenizer: CLIPTokenizer,
+ unet: UNet3DConditionModel,
+ scheduler: KarrasDiffusionSchedulers,
+ ):
+ super().__init__()
+
+ self.register_modules(
+ vae=vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ unet=unet,
+ scheduler=scheduler,
+ )
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
+ def enable_vae_slicing(self):
+ r"""
+ Enable sliced VAE decoding.
+
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
+ steps. This is useful to save some memory and allow larger batch sizes.
+ """
+ self.vae.enable_slicing()
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
+ def disable_vae_slicing(self):
+ r"""
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
+ computing decoding in one step.
+ """
+ self.vae.disable_slicing()
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
+ def enable_vae_tiling(self):
+ r"""
+ Enable tiled VAE decoding.
+
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
+ """
+ self.vae.enable_tiling()
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
+ def disable_vae_tiling(self):
+ r"""
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
+ computing decoding in one step.
+ """
+ self.vae.disable_tiling()
+
+ def enable_sequential_cpu_offload(self, gpu_id=0):
+ r"""
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
+ text_encoder, vae have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded
+ to GPU only when their specific submodule has its `forward` method called. Note that offloading happens on a
+ submodule basis. Memory savings are higher than with `enable_model_cpu_offload`, but performance is lower.
+ """
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
+ from accelerate import cpu_offload
+ else:
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
+
+ device = torch.device(f"cuda:{gpu_id}")
+
+ if self.device.type != "cpu":
+ self.to("cpu", silence_dtype_warnings=True)
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
+
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
+ cpu_offload(cpu_offloaded_model, device)
+
+ def enable_model_cpu_offload(self, gpu_id=0):
+ r"""
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
+ """
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
+ from accelerate import cpu_offload_with_hook
+ else:
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
+
+ device = torch.device(f"cuda:{gpu_id}")
+
+ if self.device.type != "cpu":
+ self.to("cpu", silence_dtype_warnings=True)
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
+
+ hook = None
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
+
+ # We'll offload the last model manually.
+ self.final_offload_hook = hook
+
+ @property
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
+ def _execution_device(self):
+ r"""
+ Returns the device on which the pipeline's models will be executed. After calling
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
+ hooks.
+ """
+ if not hasattr(self.unet, "_hf_hook"):
+ return self.device
+ for module in self.unet.modules():
+ if (
+ hasattr(module, "_hf_hook")
+ and hasattr(module._hf_hook, "execution_device")
+ and module._hf_hook.execution_device is not None
+ ):
+ return torch.device(module._hf_hook.execution_device)
+ return self.device
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
+ def _encode_prompt(
+ self,
+ prompt,
+ device,
+ num_images_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt=None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ lora_scale: Optional[float] = None,
+ ):
+ r"""
+ Encodes the prompt into text encoder hidden states.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ prompt to be encoded
+ device: (`torch.device`):
+ torch device
+ num_images_per_prompt (`int`):
+ number of images that should be generated per prompt
+ do_classifier_free_guidance (`bool`):
+ whether to use classifier free guidance or not
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+ less than `1`).
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ lora_scale (`float`, *optional*):
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
+ """
+ # set lora scale so that monkey patched LoRA
+ # function of text encoder can correctly access it
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
+ self._lora_scale = lora_scale
+
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ if prompt_embeds is None:
+ # textual inversion: procecss multi-vector tokens if necessary
+ if isinstance(self, TextualInversionLoaderMixin):
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
+ text_input_ids, untruncated_ids
+ ):
+ removed_text = self.tokenizer.batch_decode(
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
+ )
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(device)
+ else:
+ attention_mask = None
+
+ prompt_embeds = self.text_encoder(
+ text_input_ids.to(device),
+ attention_mask=attention_mask,
+ )
+ prompt_embeds = prompt_embeds[0]
+
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ bs_embed, seq_len, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ # textual inversion: procecss multi-vector tokens if necessary
+ if isinstance(self, TextualInversionLoaderMixin):
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
+
+ max_length = prompt_embeds.shape[1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(device)
+ else:
+ attention_mask = None
+
+ negative_prompt_embeds = self.text_encoder(
+ uncond_input.input_ids.to(device),
+ attention_mask=attention_mask,
+ )
+ negative_prompt_embeds = negative_prompt_embeds[0]
+
+ if do_classifier_free_guidance:
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = negative_prompt_embeds.shape[1]
+
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
+
+ return prompt_embeds
+
+ def decode_latents(self, latents):
+ latents = 1 / self.vae.config.scaling_factor * latents
+
+ batch_size, channels, num_frames, height, width = latents.shape
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
+
+ image = self.vae.decode(latents).sample
+ video = (
+ image[None, :]
+ .reshape(
+ (
+ batch_size,
+ num_frames,
+ -1,
+ )
+ + image.shape[2:]
+ )
+ .permute(0, 2, 1, 3, 4)
+ )
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
+ video = video.float()
+ return video
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
+ def prepare_extra_step_kwargs(self, generator, eta):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
+ def check_inputs(
+ self,
+ prompt,
+ height,
+ width,
+ callback_steps,
+ negative_prompt=None,
+ prompt_embeds=None,
+ negative_prompt_embeds=None,
+ ):
+ if height % 8 != 0 or width % 8 != 0:
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
+
+ if (callback_steps is None) or (
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
+ ):
+ raise ValueError(
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
+ f" {type(callback_steps)}."
+ )
+
+ if prompt is not None and prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
+ " only forward one of the two."
+ )
+ elif prompt is None and prompt_embeds is None:
+ raise ValueError(
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
+ )
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
+
+ if negative_prompt is not None and negative_prompt_embeds is not None:
+ raise ValueError(
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
+ )
+
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
+ raise ValueError(
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
+ f" {negative_prompt_embeds.shape}."
+ )
+
+ def prepare_latents(
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
+ ):
+ shape = (
+ batch_size,
+ num_channels_latents,
+ num_frames,
+ height // self.vae_scale_factor,
+ width // self.vae_scale_factor,
+ )
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
+ else:
+ latents = latents.to(device)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.scheduler.init_noise_sigma
+ return latents
+
+ @torch.no_grad()
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
+ def __call__(
+ self,
+ prompt: Union[str, List[str]] = None,
+ height: Optional[int] = None,
+ width: Optional[int] = None,
+ num_frames: int = 16,
+ num_inference_steps: int = 50,
+ guidance_scale: float = 9.0,
+ negative_prompt: Optional[Union[str, List[str]]] = None,
+ eta: float = 0.0,
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
+ latents: Optional[torch.FloatTensor] = None,
+ prompt_embeds: Optional[torch.FloatTensor] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ output_type: Optional[str] = "np",
+ return_dict: bool = True,
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
+ callback_steps: int = 1,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_prompts_only: bool = False,
+ ):
+ r"""
+ Function invoked when calling the pipeline for generation.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.
+ instead.
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The height in pixels of the generated video.
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
+ The width in pixels of the generated video.
+ num_frames (`int`, *optional*, defaults to 16):
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
+ amounts to 2 seconds of video.
+ num_inference_steps (`int`, *optional*, defaults to 50):
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
+ expense of slower inference.
+ guidance_scale (`float`, *optional*, defaults to 7.5):
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
+ 1`. Higher guidance scale encourages to generate videos that are closely linked to the text `prompt`,
+ usually at the expense of lower video quality.
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the video generation. If not defined, one has to pass
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+ less than `1`).
+ eta (`float`, *optional*, defaults to 0.0):
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
+ [`schedulers.DDIMScheduler`], will be ignored for others.
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
+ to make generation deterministic.
+ latents (`torch.FloatTensor`, *optional*):
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
+ tensor will ge generated by sampling using the supplied random `generator`. Latents should be of shape
+ `(batch_size, num_channel, num_frames, height, width)`.
+ prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ output_type (`str`, *optional*, defaults to `"np"`):
+ The output format of the generate video. Choose between `torch.FloatTensor` or `np.array`.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] instead of a
+ plain tuple.
+ callback (`Callable`, *optional*):
+ A function that will be called every `callback_steps` steps during inference. The function will be
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
+ callback_steps (`int`, *optional*, defaults to 1):
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
+ called at every step.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processors` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Examples:
+
+ Returns:
+ [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] or `tuple`:
+ [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
+ When returning a tuple, the first element is a list with the generated frames.
+ """
+ # 0. Default height and width to unet
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
+
+ num_images_per_prompt = 1
+
+ # 1. Check inputs. Raise error if not correct
+ self.check_inputs(
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
+ )
+
+ # 2. Define call parameters
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ device = self._execution_device
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
+ # corresponds to doing no classifier free guidance.
+ do_classifier_free_guidance = guidance_scale > 1.0
+
+ if return_prompts_only:
+ # Don't concat two prompts
+ do_classifier_free_guidance = False
+
+ # 3. Encode input prompt
+ text_encoder_lora_scale = (
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
+ )
+ prompt_embeds = self._encode_prompt(
+ prompt,
+ device,
+ num_images_per_prompt,
+ do_classifier_free_guidance,
+ negative_prompt,
+ prompt_embeds=prompt_embeds,
+ negative_prompt_embeds=negative_prompt_embeds,
+ lora_scale=text_encoder_lora_scale,
+ )
+ if return_prompts_only:
+ return prompt_embeds
+
+ # 4. Prepare timesteps
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
+ timesteps = self.scheduler.timesteps
+
+ # 5. Prepare latent variables
+ num_channels_latents = self.unet.config.in_channels
+ latents = self.prepare_latents(
+ batch_size * num_images_per_prompt,
+ num_channels_latents,
+ num_frames,
+ height,
+ width,
+ prompt_embeds.dtype,
+ device,
+ generator,
+ latents,
+ )
+
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
+
+ # 7. Denoising loop
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=prompt_embeds,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # reshape latents
+ bsz, channel, frames, width, height = latents.shape
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
+ noise_pred = noise_pred.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ # reshape latents back
+ latents = latents[None, :].reshape(bsz, frames, channel, width, height).permute(0, 2, 1, 3, 4)
+
+ # call the callback, if provided
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
+ progress_bar.update()
+ if callback is not None and i % callback_steps == 0:
+ callback(i, t, latents)
+
+ video_tensor = self.decode_latents(latents)
+
+ if output_type == "pt":
+ video = video_tensor
+ else:
+ video = tensor2vid(video_tensor)
+
+ # Offload last model to CPU
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
+ self.final_offload_hook.offload()
+
+ if not return_dict:
+ return (video,)
+
+ return TextToVideoSDPipelineOutput(frames=video)
\ No newline at end of file
diff --git a/code/model/layers.py b/code/model/layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d88d047ef173595c3c4b44f62a1a7ae1739c85f8
--- /dev/null
+++ b/code/model/layers.py
@@ -0,0 +1,124 @@
+import torch
+from torch import nn
+from .qformer import BertLMHeadModel, BertConfig
+# from header import *
+
+class TextFcLayer(nn.Module):
+ """Layers used in mapping text embeddings to visual outputs."""
+
+ @classmethod
+ def init_Qformer(cls, num_query_token, vision_width, num_hidden_layers=2, cross_attention_freq=1):
+ encoder_config = BertConfig.from_pretrained("bert-base-uncased")
+ encoder_config.encoder_width = vision_width
+ encoder_config.num_hidden_layers = num_hidden_layers
+ # insert cross-attention layer every other block
+ encoder_config.add_cross_attention = True
+ encoder_config.cross_attention_freq = cross_attention_freq
+ encoder_config.query_length = num_query_token
+ Qformer = BertLMHeadModel.from_pretrained("bert-base-uncased", config=encoder_config)
+ query_tokens = nn.Parameter(
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
+ )
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
+ return Qformer, query_tokens
+
+ def __init__(self, in_dim: int, out_dim: int, num_input_tokens: int = 1, num_output_tokens: int = 1,
+ mode: str = 'linear',
+ freeze_qformer=False):
+ """
+ :param mode: ['linear', 'transformer', 'qformer']
+ :param freeze_qformer: whether freeze the weights of qformer
+ """
+ super().__init__()
+
+ self.num_input_tokens = num_input_tokens
+ self.num_output_tokens = num_output_tokens
+ self.mode = mode
+ self.out_dim = out_dim
+
+ if mode == 'linear':
+ self.model = nn.Linear(in_dim, out_dim)
+ elif mode == 'transformer':
+ hidden_dim = 512
+ self.fc = nn.Linear(in_dim, hidden_dim)
+ self.tfm = nn.Transformer(batch_first=True, norm_first=True,
+ d_model=hidden_dim, num_encoder_layers=4, num_decoder_layers=4,
+ dim_feedforward=hidden_dim * 4, dropout=0.0, nhead=4)
+ self.model = nn.Linear(hidden_dim, out_dim)
+ self.query_embs = nn.Parameter(torch.randn(1, num_output_tokens, hidden_dim))
+ elif mode == 'qformer':
+ # raise NotImplementedError(mode) # TODO: ADD Q-former FOR MAPPING LAYER
+ print('Loading Q-Former')
+ hidden_dim = 768
+ self.fc = nn.Linear(in_dim, hidden_dim)
+ self.Qformer, self.query_tokens = self.init_Qformer(
+ num_output_tokens, hidden_dim
+ )
+ self.Qformer.cls = None
+ self.Qformer.bert.embeddings.word_embeddings = None
+ self.Qformer.bert.embeddings.position_embeddings = None
+ for layer in self.Qformer.bert.encoder.layer:
+ layer.output = None
+ layer.intermediate = None
+ # self.load_from_pretrained(url_or_filename=q_former_model)
+ self.model = nn.Linear(hidden_dim, out_dim)
+ # if freeze_qformer:
+ # for name, param in self.Qformer.named_parameters():
+ # param.requires_grad = False
+ # self.Qformer = self.Qformer.eval()
+ # # self.Qformer.train = disabled_train
+ # self.query_tokens.requires_grad = False
+ # # logging.info("freeze Qformer")
+ print('Loading Q-Former Done')
+
+ else:
+ raise NotImplementedError(mode)
+
+ def forward(self, x: torch.Tensor, input_embs: torch.Tensor) -> torch.Tensor:
+ outputs = None
+
+ if isinstance(self.model, nn.ModuleList):
+ assert len(self.model) == x.shape[1] == self.num_input_tokens, (
+ len(self.model), x.shape, self.num_input_tokens)
+ outputs = []
+ for i in range(self.num_input_tokens):
+ outputs.append(self.model[i](x[:, i, :])) # (N, D)
+ outputs = torch.stack(outputs, dim=1) # (N, T_I_V_A.txt, D)
+ elif self.mode == 'transformer':
+ # print("x.size: ", x.size())
+ # print("input_embs.size: ", input_embs.size())
+ x = x + input_embs
+ # print('layer x: ', x)
+ x = self.fc(x)
+ # print('layer fc x: ', x)
+ x = self.tfm(x, self.query_embs.repeat(x.shape[0], 1, 1))
+ # print('layer tfm x: ', x)
+ outputs = self.model(x)
+ # print('layer tfm model: ', x)
+
+ if outputs.shape[1] != self.num_output_tokens and self.mode == 'linear':
+ if self.mode == 'linear':
+ outputs = outputs[:, :self.num_output_tokens, :]
+ else:
+ raise NotImplementedError
+ elif self.mode == 'qformer':
+ x = x + input_embs
+ x = self.fc(x)
+ image_atts = torch.ones(x.size()[:-1], dtype=torch.long).to(x.device)
+ # print(x.size())
+ query_tokens = self.query_tokens.expand(x.shape[0], -1, -1)
+ # print(image_atts.size())
+ # print(query_tokens.size())
+ outputs = self.Qformer.bert(
+ query_embeds=query_tokens,
+ encoder_hidden_states=x,
+ encoder_attention_mask=image_atts,
+ return_dict=True,
+ ).last_hidden_state
+ # print(outputs.size())
+ outputs = self.model(outputs)
+
+ assert outputs.shape[1] == 1 or (outputs.shape[1] * outputs.shape[2] == self.num_output_tokens * self.out_dim), (
+ outputs.shape, self.num_output_tokens)
+ return outputs # (N, T_I_V_A.txt, D)
+
diff --git a/code/model/modeling_llama.py b/code/model/modeling_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..12d980e189d902fb1a6d9ea05dc3ca91959b1c8c
--- /dev/null
+++ b/code/model/modeling_llama.py
@@ -0,0 +1,755 @@
+# This script is based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
+
+""" PyTorch LLaMA model."""
+import math
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from transformers.activations import ACT2FN
+from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from transformers.modeling_utils import PreTrainedModel
+from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
+from transformers.models.llama.configuration_llama import LlamaConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "LlamaConfig"
+
+
+# Copied from transformers.models.bart.modeling_bart._make_causal_mask
+def _make_causal_mask(
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
+):
+ """
+ Make causal mask used for bi-directional self-attention.
+ """
+ bsz, tgt_len = input_ids_shape
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
+ mask_cond = torch.arange(mask.size(-1), device=device)
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
+ mask = mask.to(dtype)
+
+ if past_key_values_length > 0:
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
+
+
+# Copied from transformers.models.bart.modeling_bart._expand_mask
+def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
+ """
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
+ """
+ bsz, src_len = mask.size()
+ tgt_len = tgt_len if tgt_len is not None else src_len
+
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
+
+ inverted_mask = 1.0 - expanded_mask
+
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
+
+
+class LlamaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ """
+ LlamaRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+
+ return self.weight * hidden_states
+
+
+class LlamaRotaryEmbedding(torch.nn.Module):
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
+ super().__init__()
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
+ self.register_buffer("inv_freq", inv_freq)
+
+ # Build here to make `torch.jit.trace` work.
+ self.max_seq_len_cached = max_position_embeddings
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
+ emb = torch.cat((freqs, freqs), dim=-1)
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
+
+ def forward(self, x, seq_len=None):
+ # x: [bs, num_attention_heads, seq_len, head_size]
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
+ if seq_len > self.max_seq_len_cached:
+ self.max_seq_len_cached = seq_len
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
+ return (
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
+ )
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+class LlamaMLP(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ intermediate_size: int,
+ hidden_act: str,
+ ):
+ super().__init__()
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
+ self.act_fn = ACT2FN[hidden_act]
+
+ def forward(self, x):
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+
+
+class LlamaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: LlamaConfig):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.hidden_size // self.num_heads
+ self.max_position_embeddings = config.max_position_embeddings
+
+ if (self.head_dim * self.num_heads) != self.hidden_size:
+ raise ValueError(
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
+ f" and `num_heads`: {self.num_heads})."
+ )
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ output_attentions: bool = False,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
+ bsz, q_len, _ = hidden_states.size()
+
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+
+ kv_seq_len = key_states.shape[-2]
+ if past_key_value is not None:
+ kv_seq_len += past_key_value[0].shape[-2]
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
+ # [bsz, nh, t, hd]
+
+ if past_key_value is not None:
+ # reuse k, v, self_attention
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
+
+ past_key_value = (key_states, value_states) if use_cache else None
+
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
+
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights + attention_mask
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
+
+ # upcast attention to fp32
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
+ attn_output = torch.matmul(attn_weights, value_states)
+
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
+
+ attn_output = self.o_proj(attn_output)
+
+ if not output_attentions:
+ attn_weights = None
+
+ return attn_output, attn_weights, past_key_value
+
+
+class LlamaDecoderLayer(nn.Module):
+ def __init__(self, config: LlamaConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = LlamaAttention(config=config)
+ self.mlp = LlamaMLP(
+ hidden_size=self.hidden_size,
+ intermediate_size=config.intermediate_size,
+ hidden_act=config.hidden_act,
+ )
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
+ """
+
+ residual = hidden_states
+
+ hidden_states = self.input_layernorm(hidden_states)
+
+ # Self Attention
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ if use_cache:
+ outputs += (present_key_value,)
+
+ return outputs
+
+
+LLAMA_START_DOCSTRING = r"""
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`LlamaConfig`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+@add_start_docstrings(
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
+ LLAMA_START_DOCSTRING,
+)
+class LlamaPreTrainedModel(PreTrainedModel):
+ config_class = LlamaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["LlamaDecoderLayer"]
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, LlamaModel):
+ module.gradient_checkpointing = value
+
+
+LLAMA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
+ it.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
+ `past_key_values`).
+
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
+ information on the default strategy.
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.n_positions - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
+ LLAMA_START_DOCSTRING,
+)
+class LlamaModel(LlamaPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
+
+ Args:
+ config: LlamaConfig
+ """
+
+ def __init__(self, config: LlamaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
+ # create causal mask
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ combined_attention_mask = None
+ if input_shape[-1] > 1:
+ combined_attention_mask = _make_causal_mask(
+ input_shape,
+ inputs_embeds.dtype,
+ device=inputs_embeds.device,
+ past_key_values_length=past_key_values_length,
+ )
+
+ if attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
+ inputs_embeds.device
+ )
+ combined_attention_mask = (
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
+ )
+
+ return combined_attention_mask
+
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
+ 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,
+ query_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # retrieve input_ids and inputs_embeds
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+ elif input_ids is not None:
+ batch_size, seq_length = input_ids.shape
+ elif inputs_embeds is not None:
+ batch_size, seq_length, _ = inputs_embeds.shape
+ else:
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+ if query_embeds is not None:
+ inputs_embeds = torch.cat([query_embeds, inputs_embeds], dim=1)
+ batch_size, seq_length, _ = inputs_embeds.shape
+
+ seq_length_with_past = seq_length
+ past_key_values_length = 0
+
+ if past_key_values is not None:
+ past_key_values_length = past_key_values[0][0].shape[2]
+ seq_length_with_past = seq_length_with_past + past_key_values_length
+
+ if position_ids is None:
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+ position_ids = torch.arange(
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
+ )
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
+ else:
+ position_ids = position_ids.view(-1, seq_length).long()
+
+ # embed positions
+ if attention_mask is None:
+ attention_mask = torch.ones(
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
+ )
+ attention_mask = self._prepare_decoder_attention_mask(
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
+ )
+
+ hidden_states = inputs_embeds
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ next_decoder_cache = () if use_cache else None
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
+
+ if self.gradient_checkpointing and self.training:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ # None for past_key_value
+ return module(*inputs, output_attentions, None)
+
+ return custom_forward
+
+ layer_outputs = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(decoder_layer),
+ hidden_states,
+ attention_mask,
+ position_ids,
+ None,
+ )
+ else:
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.norm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ next_cache = next_decoder_cache if use_cache else None
+ if not return_dict:
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=next_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+
+
+class LlamaForCausalLM(LlamaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = LlamaModel(config)
+
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def set_decoder(self, decoder):
+ self.model = decoder
+
+ def get_decoder(self):
+ return self.model
+
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
+ 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,
+ query_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,
+ return_dict: Optional[bool] = None,
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+ r"""
+ Args:
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
+
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
+
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ query_embeds=query_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # Shift so that tokens < n predict n
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous()
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
+ shift_labels = shift_labels.view(-1)
+ # Enable model parallelism
+ shift_labels = shift_labels.to(shift_logits.device)
+ loss = loss_fct(shift_logits, shift_labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids, query_embeds=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
+ ):
+ if past_key_values:
+ input_ids = input_ids[:, -1:]
+
+ position_ids = kwargs.get("position_ids", None)
+ if attention_mask is not None and position_ids is None:
+ # create position_ids on the fly for batch generation
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ if past_key_values:
+ position_ids = position_ids[:, -1].unsqueeze(-1)
+ query_embeds = None
+
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
+ if inputs_embeds is not None and past_key_values is None:
+ model_inputs = {"inputs_embeds": inputs_embeds}
+ else:
+ model_inputs = {"input_ids": input_ids}
+
+ model_inputs.update(
+ {
+ "position_ids": position_ids,
+ "query_embeds": query_embeds,
+ "past_key_values": past_key_values,
+ "use_cache": kwargs.get("use_cache"),
+ "attention_mask": attention_mask,
+ }
+ )
+ return model_inputs
+
+ @staticmethod
+ def _reorder_cache(past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
+ return reordered_past
+
diff --git a/code/model/qformer.py b/code/model/qformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..4902165ec6574d89f04cbeb2141b018278324ca6
--- /dev/null
+++ b/code/model/qformer.py
@@ -0,0 +1,1217 @@
+"""
+Adapted from salesforce@LAVIS. Below is the original copyright:
+ * Copyright (c) 2023, salesforce.com, inc.
+ * All rights reserved.
+ * SPDX-License-Identifier: BSD-3-Clause
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
+ * By Junnan Li
+ * Based on huggingface code base
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
+"""
+
+import math
+import os
+import warnings
+from dataclasses import dataclass
+from typing import Optional, Tuple, Dict, Any
+
+import torch
+from torch import Tensor, device, dtype, nn
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import CrossEntropyLoss
+import torch.nn.functional as F
+
+from transformers.activations import ACT2FN
+from transformers.file_utils import (
+ ModelOutput,
+)
+from transformers.modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ NextSentencePredictorOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from transformers.modeling_utils import (
+ PreTrainedModel,
+ apply_chunking_to_forward,
+ find_pruneable_heads_and_indices,
+ prune_linear_layer,
+)
+from transformers.utils import logging
+from transformers.models.bert.configuration_bert import BertConfig
+
+logger = logging.get_logger(__name__)
+
+
+class BertEmbeddings(nn.Module):
+ """Construct the embeddings from word and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
+ )
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size
+ )
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
+ )
+ self.position_embedding_type = getattr(
+ config, "position_embedding_type", "absolute"
+ )
+
+ self.config = config
+
+ def forward(
+ self,
+ input_ids=None,
+ position_ids=None,
+ query_embeds=None,
+ past_key_values_length=0,
+ ):
+ if input_ids is not None:
+ seq_length = input_ids.size()[1]
+ else:
+ seq_length = 0
+
+ if position_ids is None:
+ position_ids = self.position_ids[
+ :, past_key_values_length : seq_length + past_key_values_length
+ ].clone()
+
+ if input_ids is not None:
+ embeddings = self.word_embeddings(input_ids)
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ if query_embeds is not None:
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
+ else:
+ embeddings = query_embeds
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class BertSelfAttention(nn.Module):
+ def __init__(self, config, is_cross_attention):
+ super().__init__()
+ self.config = config
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
+ config, "embedding_size"
+ ):
+ raise ValueError(
+ "The hidden size (%d) is not a multiple of the number of attention "
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ if is_cross_attention:
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
+ else:
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if (
+ self.position_embedding_type == "relative_key"
+ or self.position_embedding_type == "relative_key_query"
+ ):
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
+ )
+ self.save_attention = False
+
+ def save_attn_gradients(self, attn_gradients):
+ self.attn_gradients = attn_gradients
+
+ def get_attn_gradients(self):
+ return self.attn_gradients
+
+ def save_attention_map(self, attention_map):
+ self.attention_map = attention_map
+
+ def get_attention_map(self):
+ return self.attention_map
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_value=None,
+ output_attentions=False,
+ ):
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ elif past_key_value is not None:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ mixed_query_layer = self.query(hidden_states)
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ past_key_value = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if (
+ self.position_embedding_type == "relative_key"
+ or self.position_embedding_type == "relative_key_query"
+ ):
+ seq_length = hidden_states.size()[1]
+ position_ids_l = torch.arange(
+ seq_length, dtype=torch.long, device=hidden_states.device
+ ).view(-1, 1)
+ position_ids_r = torch.arange(
+ seq_length, dtype=torch.long, device=hidden_states.device
+ ).view(1, -1)
+ distance = position_ids_l - position_ids_r
+ positional_embedding = self.distance_embedding(
+ distance + self.max_position_embeddings - 1
+ )
+ positional_embedding = positional_embedding.to(
+ dtype=query_layer.dtype
+ ) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum(
+ "bhld,lrd->bhlr", query_layer, positional_embedding
+ )
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum(
+ "bhld,lrd->bhlr", query_layer, positional_embedding
+ )
+ relative_position_scores_key = torch.einsum(
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
+ )
+ attention_scores = (
+ attention_scores
+ + relative_position_scores_query
+ + relative_position_scores_key
+ )
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ if is_cross_attention and self.save_attention:
+ self.save_attention_map(attention_probs)
+ attention_probs.register_hook(self.save_attn_gradients)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs_dropped = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs_dropped = attention_probs_dropped * head_mask
+
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
+ )
+
+ outputs = outputs + (past_key_value,)
+ return outputs
+
+
+class BertSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class BertAttention(nn.Module):
+ def __init__(self, config, is_cross_attention=False):
+ super().__init__()
+ self.self = BertSelfAttention(config, is_cross_attention)
+ self.output = BertSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads,
+ self.self.num_attention_heads,
+ self.self.attention_head_size,
+ self.pruned_heads,
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = (
+ self.self.attention_head_size * self.self.num_attention_heads
+ )
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_value=None,
+ output_attentions=False,
+ ):
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_value,
+ output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+
+ outputs = (attention_output,) + self_outputs[
+ 1:
+ ] # add attentions if we output them
+ return outputs
+
+
+class BertIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class BertOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class BertLayer(nn.Module):
+ def __init__(self, config, layer_num):
+ super().__init__()
+ self.config = config
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = BertAttention(config)
+ self.layer_num = layer_num
+ if (
+ self.config.add_cross_attention
+ and layer_num % self.config.cross_attention_freq == 0
+ ):
+ self.crossattention = BertAttention(
+ config, is_cross_attention=self.config.add_cross_attention
+ )
+ self.has_cross_attention = True
+ else:
+ self.has_cross_attention = False
+ self.intermediate = BertIntermediate(config)
+ self.output = BertOutput(config)
+
+ self.intermediate_query = BertIntermediate(config)
+ self.output_query = BertOutput(config)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_value=None,
+ output_attentions=False,
+ query_length=0,
+ ):
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = (
+ past_key_value[:2] if past_key_value is not None else None
+ )
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ output_attentions=output_attentions,
+ past_key_value=self_attn_past_key_value,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:-1]
+
+ present_key_value = self_attention_outputs[-1]
+
+ if query_length > 0:
+ query_attention_output = attention_output[:, :query_length, :]
+
+ if self.has_cross_attention:
+ assert (
+ encoder_hidden_states is not None
+ ), "encoder_hidden_states must be given for cross-attention layers"
+ cross_attention_outputs = self.crossattention(
+ query_attention_output,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ output_attentions=output_attentions,
+ )
+ query_attention_output = cross_attention_outputs[0]
+ outputs = (
+ outputs + cross_attention_outputs[1:-1]
+ ) # add cross attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk_query,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ query_attention_output,
+ )
+ if attention_output.shape[1] > query_length:
+ layer_output_text = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output[:, query_length:, :],
+ )
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
+ else:
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output,
+ )
+ outputs = (layer_output,) + outputs
+
+ outputs = outputs + (present_key_value,)
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+ def feed_forward_chunk_query(self, attention_output):
+ intermediate_output = self.intermediate_query(attention_output)
+ layer_output = self.output_query(intermediate_output, attention_output)
+ return layer_output
+
+
+class BertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList(
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
+ )
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ query_length=0,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = (
+ () if output_attentions and self.config.add_cross_attention else None
+ )
+
+ next_decoder_cache = () if use_cache else None
+
+ for i in range(self.config.num_hidden_layers):
+ layer_module = self.layer[i]
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+ past_key_value = past_key_values[i] if past_key_values is not None else None
+
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
+
+ if use_cache:
+ logger.warn(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(
+ *inputs, past_key_value, output_attentions, query_length
+ )
+
+ return custom_forward
+
+ layer_outputs = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(layer_module),
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ )
+ else:
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_value,
+ output_attentions,
+ query_length,
+ )
+
+ hidden_states = layer_outputs[0]
+ if use_cache:
+ next_decoder_cache += (layer_outputs[-1],)
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ next_decoder_cache,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+class BertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states):
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class BertPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class BertLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = BertPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+ self.decoder.bias = self.bias
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+class BertOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = BertLMPredictionHead(config)
+
+ def forward(self, sequence_output):
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+class BertPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = BertConfig
+ base_model_prefix = "bert"
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Embedding)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ module.bias.data.zero_()
+
+
+class BertModel(BertPreTrainedModel):
+ """
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
+ all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
+ input to the forward pass.
+ """
+
+ def __init__(self, config, add_pooling_layer=False):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = BertEmbeddings(config)
+
+ self.encoder = BertEncoder(config)
+
+ self.pooler = BertPooler(config) if add_pooling_layer else None
+
+ self.init_weights()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ def get_extended_attention_mask(
+ self,
+ attention_mask: Tensor,
+ input_shape: Tuple[int],
+ device: device,
+ is_decoder: bool,
+ has_query: bool = False,
+ ) -> Tensor:
+ """
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
+
+ Arguments:
+ attention_mask (:obj:`torch.Tensor`):
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
+ input_shape (:obj:`Tuple[int]`):
+ The shape of the input to the model.
+ device: (:obj:`torch.device`):
+ The device of the input to the model.
+
+ Returns:
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
+ """
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ if attention_mask.dim() == 3:
+ extended_attention_mask = attention_mask[:, None, :, :]
+ elif attention_mask.dim() == 2:
+ # Provided a padding mask of dimensions [batch_size, seq_length]
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if is_decoder:
+ batch_size, seq_length = input_shape
+
+ seq_ids = torch.arange(seq_length, device=device)
+ causal_mask = (
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
+ <= seq_ids[None, :, None]
+ )
+
+ # add a prefix ones mask to the causal mask
+ # causal and attention masks must have same type with pytorch version < 1.3
+ causal_mask = causal_mask.to(attention_mask.dtype)
+
+ if causal_mask.shape[1] < attention_mask.shape[1]:
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
+ if has_query: # UniLM style attention mask
+ causal_mask = torch.cat(
+ [
+ torch.zeros(
+ (batch_size, prefix_seq_len, seq_length),
+ device=device,
+ dtype=causal_mask.dtype,
+ ),
+ causal_mask,
+ ],
+ axis=1,
+ )
+ causal_mask = torch.cat(
+ [
+ torch.ones(
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
+ device=device,
+ dtype=causal_mask.dtype,
+ ),
+ causal_mask,
+ ],
+ axis=-1,
+ )
+ extended_attention_mask = (
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
+ )
+ else:
+ extended_attention_mask = attention_mask[:, None, None, :]
+ else:
+ raise ValueError(
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
+ input_shape, attention_mask.shape
+ )
+ )
+
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
+ # masked positions, this operation will create a tensor which is 0.0 for
+ # positions we want to attend and -10000.0 for masked positions.
+ # Since we are adding it to the raw scores before the softmax, this is
+ # effectively the same as removing these entirely.
+ extended_attention_mask = extended_attention_mask.to(
+ dtype=self.dtype
+ ) # fp16 compatibility
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
+ return extended_attention_mask
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ position_ids=None,
+ head_mask=None,
+ query_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ is_decoder=False,
+ ):
+ r"""
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
+ use_cache (:obj:`bool`, `optional`):
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
+ decoding (see :obj:`past_key_values`).
+ """
+ output_attentions = (
+ output_attentions
+ if output_attentions is not None
+ else self.config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states
+ if output_hidden_states is not None
+ else self.config.output_hidden_states
+ )
+ return_dict = (
+ return_dict if return_dict is not None else self.config.use_return_dict
+ )
+
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ if input_ids is None:
+ assert (
+ query_embeds is not None
+ ), "You have to specify query_embeds when input_ids is None"
+
+ # past_key_values_length
+ past_key_values_length = (
+ past_key_values[0][0].shape[2] - self.config.query_length
+ if past_key_values is not None
+ else 0
+ )
+
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ query_embeds=query_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ input_shape = embedding_output.size()[:-1]
+ batch_size, seq_length = input_shape
+ device = embedding_output.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(
+ ((batch_size, seq_length + past_key_values_length)), device=device
+ )
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ if is_decoder:
+ extended_attention_mask = self.get_extended_attention_mask(
+ attention_mask,
+ input_ids.shape,
+ device,
+ is_decoder,
+ has_query=(query_embeds is not None),
+ )
+ else:
+ extended_attention_mask = self.get_extended_attention_mask(
+ attention_mask, input_shape, device, is_decoder
+ )
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if encoder_hidden_states is not None:
+ if type(encoder_hidden_states) == list:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
+ 0
+ ].size()
+ else:
+ (
+ encoder_batch_size,
+ encoder_sequence_length,
+ _,
+ ) = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+
+ if type(encoder_attention_mask) == list:
+ encoder_extended_attention_mask = [
+ self.invert_attention_mask(mask) for mask in encoder_attention_mask
+ ]
+ elif encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(
+ encoder_attention_mask
+ )
+ else:
+ encoder_extended_attention_mask = self.invert_attention_mask(
+ encoder_attention_mask
+ )
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ query_length=query_length,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = (
+ self.pooler(sequence_output) if self.pooler is not None else None
+ )
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+class BertLMHeadModel(BertPreTrainedModel):
+
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ self.cls = BertOnlyMLMHead(config)
+
+ self.init_weights()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ position_ids=None,
+ head_mask=None,
+ query_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ labels=None,
+ past_key_values=None,
+ use_cache=True,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ return_logits=False,
+ is_decoder=True,
+ reduction="mean",
+ ):
+ r"""
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
+ use_cache (:obj:`bool`, `optional`):
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
+ decoding (see :obj:`past_key_values`).
+ Returns:
+ Example::
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
+ >>> import torch
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> prediction_logits = outputs.logits
+ """
+ return_dict = (
+ return_dict if return_dict is not None else self.config.use_return_dict
+ )
+ if labels is not None:
+ use_cache = False
+ if past_key_values is not None:
+ query_embeds = None
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ query_embeds=query_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ is_decoder=is_decoder,
+ )
+
+ sequence_output = outputs[0]
+ if query_embeds is not None:
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
+
+ prediction_scores = self.cls(sequence_output)
+
+ if return_logits:
+ return prediction_scores[:, :-1, :].contiguous()
+
+ lm_loss = None
+ if labels is not None:
+ # we are doing next-token prediction; shift prediction scores and input ids by one
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
+ labels = labels[:, 1:].contiguous()
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
+ lm_loss = loss_fct(
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
+ labels.view(-1),
+ )
+ if reduction == "none":
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
+ ):
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_ids.shape)
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
+
+ # cut decoder_input_ids if past is used
+ if past is not None:
+ input_ids = input_ids[:, -1:]
+
+ return {
+ "input_ids": input_ids,
+ "query_embeds": query_embeds,
+ "attention_mask": attention_mask,
+ "past_key_values": past,
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
+ "is_decoder": True,
+ }
+
+ def _reorder_cache(self, past, beam_idx):
+ reordered_past = ()
+ for layer_past in past:
+ reordered_past += (
+ tuple(
+ past_state.index_select(0, beam_idx) for past_state in layer_past
+ ),
+ )
+ return reordered_past
+
+
+class BertForMaskedLM(BertPreTrainedModel):
+
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ self.cls = BertOnlyMLMHead(config)
+
+ self.init_weights()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ position_ids=None,
+ head_mask=None,
+ query_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ labels=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ return_logits=False,
+ is_decoder=False,
+ ):
+ r"""
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
+ """
+
+ return_dict = (
+ return_dict if return_dict is not None else self.config.use_return_dict
+ )
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ query_embeds=query_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ is_decoder=is_decoder,
+ )
+
+ if query_embeds is not None:
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
+ prediction_scores = self.cls(sequence_output)
+
+ if return_logits:
+ return prediction_scores
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
+ )
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return (
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+ )
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
diff --git a/code/nextgpt.png b/code/nextgpt.png
new file mode 100644
index 0000000000000000000000000000000000000000..7d28abeb07171731def6090854d402941c58e901
Binary files /dev/null and b/code/nextgpt.png differ
diff --git a/code/process_embeddings.py b/code/process_embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..648043f2dcbaa9bc34f342b096b17a77b42e993b
--- /dev/null
+++ b/code/process_embeddings.py
@@ -0,0 +1,115 @@
+
+import numpy as np
+import os
+import sys
+from joblib import Parallel, delayed
+from tqdm import tqdm
+import torch
+import json
+import pandas as pd
+import argparse
+
+# Load a slightly modified version of the Stable Diffusion pipeline.
+# This allows us to extract text embeddings directly (without generating images).
+from model.custom_sd import StableDiffusionPipeline
+from model.custom_vd import TextToVideoSDPipeline
+from model.custom_ad import AudioLDMPipeline
+
+
+
+def save_to_path(emb, path):
+ """Save embeddings to disk."""
+ try:
+ with open(path, 'wb') as wf:
+ np.save(wf, emb)
+ except:
+ print("Error with", path)
+ return path
+
+
+if __name__ == '__main__':
+
+ batch_size = 128
+
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
+ # clip_output_dir = './embed/'
+ # synthesize_path = '../data/synthesize_data/synthesize_data.json'
+
+ # video_path = '../data/T-X_pair_data/webvid/webvid.json'
+ # audio_path = '../data/T-X_pair_data/audiocap/audiocap.json'
+ # img_path = '../data/T-X_pair_data/cc3m/cc3m.json'
+
+ # image_generation_ckpt_path = 'runwayml/stable-diffusion-v1-5'
+ # video_generation_ckpt_path = 'cerspense/zeroscope_v2_576w'
+ # audio_generation_ckpt_path = 'cvssp/audioldm-l-full'
+
+ data_path = sys.argv[1]
+ modality = sys.argv[2]
+ clip_output_dir = sys.argv[3]
+ ckpt_path = sys.argv[4]
+
+ if not os.path.exists(clip_output_dir):
+ os.makedirs(clip_output_dir, exist_ok=True)
+
+ # Get existing files, so that we don't recompute them.
+ existing_files = set([f.strip('.npy') for f in os.listdir(clip_output_dir)])
+
+ caption_list = []
+ name_list = []
+ if modality == 'audio':
+ print('extract audio caption embedding')
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+
+ for row in tqdm(data, total=len(data)):
+ one_audio_name, one_caption = row["audio_name"], row["caption"]
+ if one_audio_name not in existing_files:
+ caption_list.append(one_caption)
+ name_list.append(one_audio_name)
+ pipe = AudioLDMPipeline.from_pretrained(ckpt_path, torch_dtype=dtype)
+ if not torch.cuda.is_available():
+ print('WARNING: using CPU, this will be slow!')
+ else:
+ pipe = pipe.to("cuda")
+ elif modality == 'image':
+ print('extract image caption embedding')
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ for row in tqdm(data, total=len(data)):
+ one_image_name, one_caption = row["image_name"], row["caption"]
+ if one_image_name not in existing_files:
+ caption_list.append(one_caption)
+ name_list.append(one_image_name)
+ pipe = StableDiffusionPipeline.from_pretrained(ckpt_path, torch_dtype=dtype)
+ if not torch.cuda.is_available():
+ print('WARNING: using CPU, this will be slow!')
+ else:
+ pipe = pipe.to("cuda")
+ elif modality == 'video':
+ print('extract video caption embedding')
+ with open(data_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ for row in tqdm(data, total=len(data)):
+ one_video_name, one_caption = row["video_name"], row["caption"]
+ if one_video_name not in existing_files:
+ caption_list.append(one_caption)
+ name_list.append(one_video_name)
+ pipe = TextToVideoSDPipeline.from_pretrained(ckpt_path, torch_dtype=dtype)
+ if not torch.cuda.is_available():
+ print('WARNING: using CPU, this will be slow!')
+ else:
+ pipe = pipe.to("cuda")
+
+ print('Extract embeddings in batches.')
+ num_batches = int(np.ceil(len(caption_list) / batch_size))
+ for i in tqdm(range(num_batches)):
+ start_idx = i * batch_size
+ end_idx = start_idx + batch_size
+ batch_captions = caption_list[start_idx:end_idx]
+ batch_ids = name_list[start_idx:end_idx]
+ prompt_embeds = pipe(batch_captions, return_prompts_only=True).detach().cpu().numpy()
+
+ # Save embeddings to disk in parallel.
+ Parallel(n_jobs=8)(delayed(save_to_path)(
+ prompt_embeds[j, :, ...], os.path.join(clip_output_dir, f'{batch_ids[j]}.npy')
+ ) for j in range(prompt_embeds.shape[0]))
diff --git a/code/scripts/app.sh b/code/scripts/app.sh
new file mode 100644
index 0000000000000000000000000000000000000000..77242be57128fd43a54a79b053d83ab0a54d750b
--- /dev/null
+++ b/code/scripts/app.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+python demo_app.py --nextgpt_ckpt_path ../ckpt/delta_ckpt/nextgpt/7b_tiva_v0
diff --git a/code/scripts/train.sh b/code/scripts/train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a196fccb02a214a7e860327b8b031030bec77666
--- /dev/null
+++ b/code/scripts/train.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+deepspeed --include localhost:6 --master_addr 127.0.0.1 --master_port 28459 train.py \
+ --model nextgpt \
+ --stage 1\
+ --save_path ../ckpt/delta_ckpt/nextgpt/7b_tiva_v0\
+ --log_path ../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/log
+
diff --git a/code/train.py b/code/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..479eea68de89a38facf87852dc1744bab6bff9b8
--- /dev/null
+++ b/code/train.py
@@ -0,0 +1,109 @@
+from header import *
+from dataset import load_dataset
+from model import *
+from config import *
+
+
+def parser_args():
+ parser = argparse.ArgumentParser(description='train parameters')
+ parser.add_argument('--model', type=str, default='nextgpt')
+ parser.add_argument('--mode', type=str, default='train', help='train or test or validation')
+ parser.add_argument('--local_rank', default=0, type=int)
+ parser.add_argument('--save_path', type=str, default='../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/')
+ parser.add_argument('--log_path', type=str, default='../ckpt/delta_ckpt/nextgpt/7b_tiva_v0/log/')
+ parser.add_argument('--assets_path', type=str, default='./assets/')
+
+ # model configurations
+ parser.add_argument('--max_length', type=int, default=512) # the maximum input sequence length for LLMs
+ parser.add_argument('--stage', type=int, default=1) # the training stage
+ parser.add_argument('--modality', type=list, default=['image', 'video', 'audio', 'text'])
+ return parser.parse_args()
+
+
+def initialize_distributed(args):
+ args['master_ip'] = os.getenv('MASTER_ADDR', 'localhost')
+ args['master_port'] = os.getenv('MASTER_PORT', '6000')
+ args['world_size'] = int(os.getenv('WORLD_SIZE', '1'))
+ args['local_rank'] = int(os.getenv('RANK', '0')) % torch.cuda.device_count()
+ device = args['local_rank'] % torch.cuda.device_count()
+ torch.cuda.set_device(device)
+ deepspeed.init_distributed(dist_backend='nccl')
+
+
+def set_random_seed(seed):
+ if seed is not None and seed > 0:
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.random.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+
+def config_env(args):
+ args['root_dir'] = '../'
+ # args['mode'] = 'train'
+ config = load_config(args)
+ args.update(config)
+ initialize_distributed(args)
+ set_random_seed(args['seed'])
+
+
+def build_directory(path):
+ if os.path.exists(path):
+ pass
+ else: # recursively construct directory
+ os.makedirs(path, exist_ok=True)
+
+
+def main(**args):
+ config_env(args)
+ print(args)
+ args['ds_config_path'] = f'dsconfig/stage_{args["stage"]}.json'
+ dschf = HfDeepSpeedConfig(args['ds_config_path'])
+ args['dschf'] = dschf
+
+ build_directory(args['save_path'])
+ build_directory(args['log_path'])
+
+ if args['log_path']:
+ logging.basicConfig(
+ format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
+ level=logging.DEBUG,
+ filename=f'{args["log_path"]}/train_{time.asctime()}.log',
+ filemode='w'
+ )
+ train_data, train_iter, sampler = load_dataset(args, args['dataset_name_list'])
+
+ train_num = max([_cur_dataset.__len__() for _cur_dataset in train_data.datasets.datasets]) * len(train_data.datasets.datasets)
+ length = args['epochs'] * train_num // args['world_size'] // dschf.config[
+ 'train_micro_batch_size_per_gpu']
+ total_steps = args['epochs'] * train_num // dschf.config['train_batch_size']
+ args['total_steps'] = total_steps
+ agent = load_model(args)
+ torch.distributed.barrier()
+
+ # begin to train
+ pbar = tqdm(total=length) # maximum total number
+ current_step = 0
+ for epoch_i in tqdm(range(args['epochs'])):
+ # for train_iter in train_iter_list:
+ for batch in train_iter:
+ agent.train_model(
+ batch,
+ current_step=current_step,
+ pbar=pbar
+ )
+ current_step += 1
+ # if current_step % 2000 == 0:
+ # torch.distributed.barrier()
+ # agent.save_model(args['save_path'], current_step)
+ # save at the end of the training
+ torch.distributed.barrier()
+ agent.save_model(args['save_path'], current_step)
+
+
+if __name__ == "__main__":
+ args = parser_args()
+ args = vars(args)
+ main(**args)
diff --git a/code/user.png b/code/user.png
new file mode 100644
index 0000000000000000000000000000000000000000..5dfdd89145ba278a582e454d011b524c2696e0ab
Binary files /dev/null and b/code/user.png differ
diff --git a/data/IT_data/MosIT_data/__init__.py b/data/IT_data/MosIT_data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T+X-T_data/__init__.py b/data/IT_data/T+X-T_data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T+X-T_data/alpaca/__init__.py b/data/IT_data/T+X-T_data/alpaca/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T+X-T_data/llava/prapare.md b/data/IT_data/T+X-T_data/llava/prapare.md
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T+X-T_data/videochat/__init__.py b/data/IT_data/T+X-T_data/videochat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T-T+X_data/__init__.py b/data/IT_data/T-T+X_data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/IT_data/T-T+X_data/audio_t2x.json b/data/IT_data/T-T+X_data/audio_t2x.json
new file mode 100644
index 0000000000000000000000000000000000000000..ae82958f801da60e9bd9f484b884b50c8d0925a8
--- /dev/null
+++ b/data/IT_data/T-T+X_data/audio_t2x.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:03c37ba9b284752bcb6847bc0ccf7b600f07875b38efed4b7cd1b786825a9d70
+size 10824519
diff --git a/data/IT_data/T-T+X_data/image_t2x.json b/data/IT_data/T-T+X_data/image_t2x.json
new file mode 100644
index 0000000000000000000000000000000000000000..b186183fb8a99ca2214dd083c496214cb3a857cb
--- /dev/null
+++ b/data/IT_data/T-T+X_data/image_t2x.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:42c7c61a4540c20787602941979cc978b02431f02222af36ad599d0821ad4a3a
+size 11353446
diff --git a/data/IT_data/T-T+X_data/video_t2x.json b/data/IT_data/T-T+X_data/video_t2x.json
new file mode 100644
index 0000000000000000000000000000000000000000..01ba3e7a020c889ed19d718926eaea270feb5ace
--- /dev/null
+++ b/data/IT_data/T-T+X_data/video_t2x.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3c923c80b2c1db3926343bef054bdf58a3fb167bf2cd09726a932b540d3bc5a9
+size 14333305
diff --git a/data/T-X_pair_data/audiocap/prepare.md b/data/T-X_pair_data/audiocap/prepare.md
new file mode 100644
index 0000000000000000000000000000000000000000..58370c32e21d0bbdc8a0f47d5fc4b8e84aa05305
--- /dev/null
+++ b/data/T-X_pair_data/audiocap/prepare.md
@@ -0,0 +1,75 @@
+
+## Preparation
+
+
+### Requirements
+
+Python 3.9 (it may work with other versions, but it has not been tested)
+
+### Installation
+
+```angular2html
+# Install ffmpeg
+sudo apt install ffmpeg
+# Install audiocaps-download
+pip install audiocaps-download
+```
+
+### Usage
+- Download `csv` file in [here](https://audiocaps.github.io/). The header of the CSV file are:
+```angular2html
+audiocap_id,youtube_id,start_time,caption
+```
+
+- Download audio by following codes:
+```angular2html
+from audiocaps_download import Downloader
+d = Downloader(root_path='data/T-X_pair_data/audiocap/', n_jobs=16)
+d.download(format = 'wav')
+```
+
+
+The main class is `audiocaps_download.Downloader`. It is initialized using the following parameters:
+
+- `root_path`: the path to the directory where the dataset will be downloaded.
+- `n_jobs`: the number of parallel downloads. Default is 1.
+The methods of the class are:
+
+- `download(format='vorbis', quality=5)`: downloads the dataset.
+- The format can be one of the following (supported by `yt-dlp` `--audio-format parameter`):
+ - `vorbis`: downloads the dataset in Ogg Vorbis format. This is the default.
+ - `wav`: downloads the dataset in WAV format.
+ - `mp3`: downloads the dataset in MP3 format.
+ - `m4a`: downloads the dataset in M4A format.
+ - `flac`: downloads the dataset in FLAC format.
+ - `opus`: downloads the dataset in Opus format.
+ - `webm`: downloads the dataset in WebM format.
+ - ... and many more.
+ - The quality can be an integer between 0 and 10. Default is 5.
+- `load_dataset()`: reads the csv files from the original repository. It is not used externally.
+- `download_file(...)`: downloads a single file. It is not used externally.
+
+### Postprocess
+Once you've downloaded the dataset, please verify the download status, as some audio files may not have been successfully downloaded. Afterward, organize the dataset into a json file with the following format:
+```angular2html
+[
+ {
+ "caption": "A woman talks nearby as water pours",
+ "audio_name": "91139.wav"
+ },
+ {
+ "caption": "The wind is blowing and rustling occurs",
+ "audio_name": "11543.wav"
+ },
+ ...
+]
+```
+The data file structure should be:
+```angular2html
+data/T-X_pair_data/audiocap
+├── audiocap.json
+├── audios
+| ├── 91139.wav
+| ├── 11543.wav
+| └── ...
+```
diff --git a/data/T-X_pair_data/cc3m/prepare.md b/data/T-X_pair_data/cc3m/prepare.md
new file mode 100644
index 0000000000000000000000000000000000000000..ecc3d78d31ef49065c6cb1ebc738d658009e3a39
--- /dev/null
+++ b/data/T-X_pair_data/cc3m/prepare.md
@@ -0,0 +1,56 @@
+
+
+## Preparation
+
+1. Download `Train_GCC-training.tsv` dataset from [here](https://ai.google.com/research/ConceptualCaptions/download)
+
+
+2. Download images via the following commands:
+```commandline
+pip install img2dataset
+
+img2dataset --url_list Train_GCC-training.tsv --input_format "tsv" --url_col "url" --caption_col "caption" --output_format webdataset --output_folder cc3m --processes_count 16 --thread_count 64 --image_size 256 --enable_wandb True
+```
+Note that:
+
+- `url_list` A file with the list of url of images to download. It can be a folder of such files. (required)
+- `image_size` The size to resize image to (default 256)
+- `output_folder` The path to the output folder. (default "images")
+- `processes_count` The number of processes used for downloading the pictures. This is important to be high for performance. (default 1)
+- `thread_count` The number of threads used for downloading the pictures. This is important to be high for performance. (default 256)
+- `output_format` decides how to save pictures (default files)
+ - `files saves` as a set of subfolder containing pictures
+ - `webdataset` saves as tars containing pictures
+ - ...
+- `url_col` the name of the url column for parquet and csv (default url)
+- `caption_col` the name of the caption column for parquet and csv (default None)
+- `enable_wandb` whether to enable wandb logging (default False)
+
+For more details, please refer to [img2dataset](https://github.com/rom1504/img2dataset/blob/main/README.md)
+
+
+
+3. Once you've downloaded the dataset, please verify the download status, as some image files may not have been successfully downloaded. Afterward, organize the dataset into a json file with the following format:
+
+```angular2html
+[
+ {
+ "caption": "pitcher pitches against sports team",
+ "image_name": "000002362.jpg"
+ },
+ {
+ "caption": "sea beach with mountains on the horizon , yellow umbrella and sand",
+ "image_name": "000007816.jpg"
+ },
+ ...
+]
+```
+The data file structure should be:
+```angular2html
+data/T-X_pair_data/cc3m
+├── cc3m.json
+├── images
+| ├── 000002362.jpg
+| ├── 000007816.jpg
+| └── ...
+```
\ No newline at end of file
diff --git a/data/T-X_pair_data/webvid/prepare.md b/data/T-X_pair_data/webvid/prepare.md
new file mode 100644
index 0000000000000000000000000000000000000000..b67f5686f365f2972295f91c5f533cfaca72987d
--- /dev/null
+++ b/data/T-X_pair_data/webvid/prepare.md
@@ -0,0 +1,46 @@
+## Preparation
+
+WebVid is a large-scale text-video dataset, containing 10 million video-text pairs scraped from the stock footage sites.
+To download the dataset, run the following command:
+
+```angular2html
+wget -nc http://www.robots.ox.ac.uk/~maxbain/webvid/results_2M_train.csv
+
+video2dataset --url_list="results_10M_train.csv" \
+ --input_format="csv" \
+ --output-format="webdataset" \
+ --output_folder="dataset" \
+ --url_col="contentUrl" \
+ --caption_col="name" \
+ --save_additional_columns='[videoid,page_idx,page_dir,duration]' \
+ --enable_wandb=True \
+ --config="path/to/config.yaml" \
+```
+For more datails, please refer to [video2dataset](https://github.com/iejMac/video2dataset/blob/main/dataset_examples/WebVid.md).
+
+
+### Postprocess
+Once you've downloaded the dataset, please verify the download status, as some video files may not have been successfully downloaded. Afterward, organize the dataset into a json file with the following format:
+```angular2html
+[
+ {
+ "caption": "Merida, mexico - may 23, 2017: tourists are walking on a roadside near catholic church in the street of mexico at sunny summer day.",
+ "video_name": "31353427.mp4"
+ },
+ {
+ "caption": "Happy family using laptop on bed at home",
+ "video_name": "14781349.mp4"
+ },
+ ...
+]
+```
+
+The data file structure should be:
+```angular2html
+data/T-X_pair_data/webvid
+├── webvid.json
+├── videos
+| ├── 31353427.mp4
+| ├── 14781349.mp4
+| └── ...
+```
\ No newline at end of file
diff --git a/figures/demo.png b/figures/demo.png
new file mode 100644
index 0000000000000000000000000000000000000000..1780305ba22ade8c25afc03afcf12ba0d8676d81
--- /dev/null
+++ b/figures/demo.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dcfde50a0ee172b181c88ec045ac782f09c37c5ed577272d907b8aa2ef44e6d3
+size 2613099
diff --git a/figures/framework.png b/figures/framework.png
new file mode 100644
index 0000000000000000000000000000000000000000..15a854bdd5caf552f0ffd4d803a0fc1c36921622
Binary files /dev/null and b/figures/framework.png differ
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6171ebf2a44e7674dd784c6773673dbdb9b44992
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,31 @@
+accelerate==0.19.0
+datasets==2.12.0
+decord==0.6.0
+deepspeed==0.9.3
+diffusers==0.17.0
+einops==0.6.1
+ftfy==6.1.1
+gradio==3.44.0
+imageio==2.31.1
+iopath==0.1.10
+ipdb==0.13.13
+joblib==1.3.1
+matplotlib==3.7.1
+mdtex2html==1.2.0
+numpy==1.24.3
+packaging==23.1
+pandas==2.0.2
+peft==0.3.0
+Pillow==9.5.0
+pytorchvideo==0.1.5
+PyYAML==6.0
+regex==2023.6.3
+scipy==1.11.2
+timm==0.9.2
+torch==1.13.1
+torchaudio==0.13.1
+torchvision==0.14.1
+tqdm==4.65.0
+transformers==4.29.2
+omegaconf==2.3.0
+tensorboard==2.13.0