diff --git a/approach/ovod/APE/.gitignore b/approach/ovod/APE/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2838ec8611189532a2ff5c98b69ea485a021e62 --- /dev/null +++ b/approach/ovod/APE/.gitignore @@ -0,0 +1,53 @@ +# output dir +output +instant_test_output +inference_test_output + + +*.png +*.json +*.diff +*.jpg +!/projects/DensePose/doc/images/*.jpg + +# compilation and distribution +__pycache__ +_ext +*.pyc +*.pyd +*.so +*.dll +*.egg-info/ +build/ +dist/ +wheels/ + +# pytorch/python/numpy formats +*.pth +*.pkl +*.npy +*.ts +model_ts*.txt + +# ipython/jupyter notebooks +*.ipynb +**/.ipynb_checkpoints/ + +# Editor temporaries +*.swn +*.swo +*.swp +*~ + +# editor settings +.idea +.vscode +_darcs + +# project dirs +/ape/model_zoo/configs +/datasets/* +!/datasets/*.* +/projects/*/datasets +/models +/snippet diff --git a/approach/ovod/APE/LICENSE b/approach/ovod/APE/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/approach/ovod/APE/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/approach/ovod/APE/README.md b/approach/ovod/APE/README.md new file mode 100644 index 0000000000000000000000000000000000000000..250d549c90ceabadb1afa63504a719f42f320380 --- /dev/null +++ b/approach/ovod/APE/README.md @@ -0,0 +1,315 @@ +# APE: Aligning and Prompting Everything All at Once for Universal Visual Perception + + + + +

+ +

+ + +
:grapes: \[[Read our arXiv Paper](https://arxiv.org/abs/2312.02153)\]   :apple: \[[Try our Online Demo](https://huggingface.co/spaces/shenyunhang/APE)\]
+ + +--- + +

+ +

+ + +## :bulb: Highlight + +- **High Performance.** SotA (or competitive) performance on **160** datasets with only one model. +- **Perception in the Wild.** Detect and segment **everything** with thousands of vocabularies or language descriptions all at once. +- **Flexible.** Support both foreground objects and background stuff for instance segmentation and semantic segmentation. + +## :fire: News +* **`2024.02.27`** APE has been accepted to CVPR 2024! +* **`2023.12.05`** Release training codes! +* **`2023.12.05`** Release checkpoints! +* **`2023.12.05`** Release inference codes and demo! + +## :label: TODO + +- [x] Release inference code and demo. +- [x] Release checkpoints. +- [x] Release training codes. +- [ ] Add clean docs. + + +## :hammer_and_wrench: Install + +1. Clone the APE repository from GitHub: + +```bash +git clone https://github.com/shenyunhang/APE +cd APE +``` + +2. Install the required dependencies and APE: + +```bash +pip3 install -r requirements.txt +python3 -m pip install -e . +``` + + +## :arrow_forward: Demo Localy + +**Web UI demo** +``` +pip3 install gradio +cd APE/demo +python3 app.py +``` +This demo will detect GPUs and use one GPU if you have GPUs. + +Please feel free to try our [Online Demo](https://huggingface.co/spaces/shenyunhang/APE)! + +

+ +

+ + +## :books: Data Prepare +Following [here](https://github.com/shenyunhang/APE/blob/main/datasets/README.md) to prepare the following datasets: + +| | COCO | LVIS | Objects365 | Openimages | VisualGenome | SA-1B | RefCOCO | GQA | PhraseCut | Flickr30k | ODinW | SegInW | Roboflow100 | ADE20k | ADE-full | BDD10k | Cityscapes | PC459 | PC59 | VOC | D3 | +|:-----:|:-------:|:-------:|:----------:|:----------:|:------------:|:-------:|:-------:|:-------:|:---------:|:---------:|:-------:|:-------:|:-----------:|:-------:|:--------:|:-------:|:----------:|:-------:|:-------:|:-------:|:-------:| +| Train | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | +| Test | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +Noted we do not use `coco_2017_train` for training. + +Instead, we augment `lvis_v1_train` with annotations from coco, and keep the image set unchanged. + +And we register it as `lvis_v1_train+coco` for instance segmentation and `lvis_v1_train+coco_panoptic_separated` for panoptic segmentation. + + +## :test_tube: Inference + +### Infer on 160+ dataset +We provide several scripts to evaluate all models. + +It is necessary to adjust the checkpoint location and GPU number in the scripts before running them. + +```bash +scripts/eval_all_D.sh +scripts/eval_all_C.sh +scripts/eval_all_B.sh +scripts/eval_all_A.sh +``` + +### Infer on images or videos + +APE-D +``` +python3.9 demo/demo_lazy.py \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k.py \ +--input image1.jpg image2.jpg image3.jpg \ +--output /path/to/output/dir \ +--confidence-threshold 0.1 \ +--text-prompt 'person,car,chess piece of horse head' \ +--with-box \ +--with-mask \ +--with-sseg \ +--opts \ +train.init_checkpoint=/path/to/APE-D/checkpoint \ +model.model_language.cache_dir="" \ +model.model_vision.select_box_nums_for_evaluation=500 \ +model.model_vision.text_feature_bank_reset=True \ +``` + +To disable `xformers`, add the following option: +``` +model.model_vision.backbone.net.xattn=False \ +``` + +To use `pytorch` version of `MultiScaleDeformableAttention`, add the following option: +``` +model.model_vision.transformer.encoder.pytorch_attn=True \ +model.model_vision.transformer.decoder.pytorch_attn=True \ +``` + + +## :train: Training + +### Prepare backbone and language models +```bash +git lfs install +git clone https://huggingface.co/QuanSun/EVA-CLIP models/QuanSun/EVA-CLIP/ +git clone https://huggingface.co/BAAI/EVA models/BAAI/EVA/ +git clone https://huggingface.co/Yuxin-CV/EVA-02 models/Yuxin-CV/EVA-02/ +``` + +Resize patch size: +```bash +python3.9 tools/eva_interpolate_patch_14to16.py --input models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt --output models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14to16_plus_s9B.pt --image_size 224 +python3.9 tools/eva_interpolate_patch_14to16.py --input models/QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt --output models/QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14to16_s11B.pt --image_size 224 +python3.9 tools/eva_interpolate_patch_14to16.py --input models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt --output models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt --image_size 336 +``` + +### Train APE-D + +Single node: +```bash +python3.9 tools/train_net.py \ +--num-gpus 8 \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl_`date +'%Y%m%d_%H%M%S'` +``` + +Multiple nodes: +```bash +python3.9 tools/train_net.py \ +--dist-url="tcp://${MASTER_IP}:${MASTER_PORT}" \ +--num-gpus ${HOST_GPU_NUM} \ +--num-machines ${HOST_NUM} \ +--machine-rank ${INDEX} \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl_`date +'%Y%m%d_%H'`0000 +``` + +### Train APE-C + +Single node: +```bash +python3.9 tools/train_net.py \ +--num-gpus 8 \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k_`date +'%Y%m%d_%H%M%S'` +``` + +Multiple nodes: +```bash +python3.9 tools/train_net.py \ +--dist-url="tcp://${MASTER_IP}:${MASTER_PORT}" \ +--num-gpus ${HOST_GPU_NUM} \ +--num-machines ${HOST_NUM} \ +--machine-rank ${INDEX} \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k_`date +'%Y%m%d_%H'`0000 +``` + +### Train APE-B + +Single node: +```bash +python3.9 tools/train_net.py \ +--num-gpus 8 \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k_`date +'%Y%m%d_%H%M%S'` +``` + +Multiple nodes: +```bash +python3.9 tools/train_net.py \ +--dist-url="tcp://${MASTER_IP}:${MASTER_PORT}" \ +--num-gpus ${HOST_GPU_NUM} \ +--num-machines ${HOST_NUM} \ +--machine-rank ${INDEX} \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k_`date +'%Y%m%d_%H'`0000 +``` + +### Train APE-A + +Single node: +```bash +python3.9 tools/train_net.py \ +--num-gpus 8 \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VG/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VG/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k_`date +'%Y%m%d_%H%M%S'` +``` + +Multiple nodes: +```bash +python3.9 tools/train_net.py \ +--dist-url="tcp://${MASTER_IP}:${MASTER_PORT}" \ +--num-gpus ${HOST_GPU_NUM} \ +--num-machines ${HOST_NUM} \ +--machine-rank ${INDEX} \ +--resume \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VG/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k.py \ +train.output_dir=output/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VG/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k_`date +'%Y%m%d_%H'`0000 +``` + + + +## :luggage: Checkpoints + +``` +git lfs install +git clone https://huggingface.co/shenyunhang/APE +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
nameCheckpointConfig
1APE-AHF linklink
2APE-BHF link + link
3APE-CHF link + link
4APE-DHF link + link
+ + +## :medal_military: Results + +radar + + +## :black_nib: Citation + +If you find our work helpful for your research, please consider citing the following BibTeX entry. + +```bibtex +@inproceedings{APE, + title={Aligning and Prompting Everything All at Once for Universal Visual Perception}, + author={Shen, Yunhang and Fu, Chaoyou and Chen, Peixian and Zhang, Mengdan and Li, Ke and Sun, Xing and Wu, Yunsheng and Lin, Shaohui and Ji, Rongrong}, + journal={CVPR}, + year={2024} +} +``` diff --git a/approach/ovod/APE/__init__.py b/approach/ovod/APE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_r50_160k.py b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_r50_160k.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2ed64d540f09fea245017dbc954ff926aeb4e4 --- /dev/null +++ b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_r50_160k.py @@ -0,0 +1,46 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_r50_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) +from ...common.data.ade20k_panoptic import dataloader + +num_classes = 150 +model.num_classes = num_classes +model.criterion.num_classes = num_classes +model.criterion.matcher_stage2.num_classes = num_classes + +model.model_vision.dataset_prompts = ["name"] +model.model_vision.dataset_names = ["ade20k_panoptic"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = True + +model.model_vision.stuff_prob_thing = -1.0 + +train.max_iter = 160000 +train.eval_period = 5000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1, 0.01], + milestones=[135000, 150000], + num_updates=160000, + ), + warmup_length=1000 / 160000, + warmup_method="linear", + warmup_factor=0.001, +) + +model.model_vision.semantic_post_nms = False +model.model_vision.panoptic_post_nms = True +model.model_vision.aux_mask = True + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..90390fbc476a05a1675396ab88f4088de0767ac3 --- /dev/null +++ b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py @@ -0,0 +1,101 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detrex.modeling.neck import ChannelMapper +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from .ape_deta_vitl_eva02_lsj1024 import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = -1.0 +model.model_vision.transformer.proposal_ambiguous = 1 + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 diff --git a/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b04c2419a8bf90c3b318d69d0d7598dc6f2eff --- /dev/null +++ b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py @@ -0,0 +1,22 @@ +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) +from ...common.data.ade20k_panoptic_lsj1024 import dataloader + +model.model_vision.dataset_prompts = ["name"] +model.model_vision.name_prompt_fusion_text = [False] +model.model_vision.dataset_names = ["ade20k"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +model.model_vision.select_box_nums_for_evaluation = 300 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = True + +model.model_vision.stuff_prob_thing = -1.0 + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..1a3ad5980ce9d1f48e3bc8d130bf389eeba0ec44 --- /dev/null +++ b/approach/ovod/APE/configs/ADE20k_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py @@ -0,0 +1,47 @@ +from detectron2.config import LazyCall as L +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_vitl_eva02_lsj1024 import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_12ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..79354148c17b8d14984ed0d41725a1923564c173 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_12ep.py @@ -0,0 +1,29 @@ +from detectron2.config import LazyCall as L +from detrex.config import get_config + +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_r50_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) +from ...common.data.coco_refcoco_instance import dataloader + +model.model_vision.num_classes = 80 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +model.model_vision.criterion = [criterion for _ in range(2)] +for criterion, num_classes in zip(model.model_vision.criterion, [80, 1]): + criterion.num_classes = num_classes + +model.model_vision.criterion[1].weight_dict["loss_class_enc"] = 0.0 + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16] + +model.model_vision.dataset_prompts = ["name", "expression"] +model.model_vision.dataset_names = ["coco_2017", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_24ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_24ep.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8b561a73849c1c9dd269c7d97ef19f4f03af79 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_24ep.py @@ -0,0 +1,12 @@ +from detrex.config import get_config + +from .ape_deta_r50_12ep import dataloader, model, optimizer, train + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_24ep + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +train.max_iter = 180000 + +train.eval_period = 10000 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_36ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_36ep.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff0df9068767007eebd5d7638b01e8c8645bae4 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_36ep.py @@ -0,0 +1,12 @@ +from detrex.config import get_config + +from .ape_deta_r50_12ep import dataloader, model, optimizer, train + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_36ep + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +train.max_iter = 270000 + +train.eval_period = 15000 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_12ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..964fb02c5b1d1e63728d5a7c8416073dc1598533 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_12ep.py @@ -0,0 +1,52 @@ +from detectron2.config import LazyCall as L +from omegaconf import OmegaConf +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_r50_12ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + cfg=OmegaConf.from_dotlist( + [ + "MODEL.DYHEAD.FUSE_CONFIG.STABLE_SOFTMAX_2D=False", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MIN_FOR_UNDERFLOW=True", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MAX_FOR_OVERFLOW=True", + "MODEL.VL_FUSION_USE_CHECKPOINT=True", + ], + ), +) + + +model.model_vision.text_feature_bank = False +model.model_vision.text_feature_reduce_before_fusion = False +model.model_vision.text_feature_batch_repeat = False +model.model_vision.expression_cumulative_gt_class = False + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_36ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_36ep.py new file mode 100644 index 0000000000000000000000000000000000000000..af3ecaba7d66027bdd0a1c1376bbccd34b76d348 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_36ep.py @@ -0,0 +1,12 @@ +from detrex.config import get_config + +from .ape_deta_r50_vlf_12ep import dataloader, model, optimizer, train + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_36ep + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +train.max_iter = 270000 + +train.eval_period = 15000 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_bert_36ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_bert_36ep.py new file mode 100644 index 0000000000000000000000000000000000000000..13be9e18bc60755d5e1265faedacb3855d9a1e91 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_r50_vlf_bert_36ep.py @@ -0,0 +1,21 @@ +from detectron2.config import LazyCall as L +from ape.modeling.text import Bert + +from .ape_deta_r50_vlf_36ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.criterion[1].num_classes = 1 + +model.model_language = L(Bert)( + pretrained_model_name_or_path="models/huggingface/bert-base-uncased/" +) +model.model_vision.embed_dim_language = 768 +model.model_vision.text_feature_reduce_type = "average" + +model.model_vision.text_feature_bank = False +model.model_vision.text_feature_reduce_before_fusion = False +model.model_vision.text_feature_batch_repeat = False +model.model_vision.expression_cumulative_gt_class = False + + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_12ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..98758b3f9c34bb0e67039732776b20d69645e77a --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_12ep.py @@ -0,0 +1,118 @@ +from functools import partial + +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detrex.config import get_config +from ape.modeling.backbone.vit import get_vit_lr_decay_rate +from ape.modeling.backbone.vit_eva02 import SimpleFeaturePyramid, ViT +from ape.modeling.text import EVA01CLIP + +from .....detectron2.configs.common.data.constants import constants +from ...common.data.coco_refcoco_instance_lsj1024 import dataloader +from .models.ape_deta_r50 import model + +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = L(SimpleFeaturePyramid)( + net=L(ViT)( # Single-scale ViT backbone + img_size=1024, + patch_size=16, + embed_dim=1024, + depth=24, + num_heads=16, + drop_path_rate=0.4, + window_size=16, + mlp_ratio=4 * 2 / 3, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + window_block_indexes=list(range(0, 5)) + + list(range(6, 11)) + + list(range(12, 17)) + + list(range(18, 23)), + residual_block_indexes=[], + use_rel_pos=True, + out_feature="last_feat", + use_act_checkpoint=True, + xattn=True, + ), + in_feature="${.net.out_feature}", + out_channels=256, + scale_factors=(4.0, 2.0, 1.0, 0.5), + top_block=L(LastLevelMaxPool)(), + norm="LN", + square_pad=1024, +) + +model.model_vision.neck = None + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone.net" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} +optimizer.params.weight_decay_norm = None + +optimizer.lr = 2e-4 +optimizer.betas = (0.9, 0.999) +optimizer.weight_decay = 1e-4 + +train = get_config("common/train.py").train +train.max_iter = 90000 +train.eval_period = 5000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "models/Yunxin-CV/EVA-02/eva02/pt/eva02_L_pt_in21k_p14to16.pt?matching_heuristics=True" +) + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_12ep +lr_multiplier.scheduler.milestones = [75000, 90000] +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +model.model_vision.dataset_prompts = ["name", "expression"] +model.model_vision.dataset_names = ["coco_2017", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +model.model_language = L(EVA01CLIP)( + clip_model="EVA_CLIP_g_14_X", cache_dir="models/BAAI/EVA/eva_clip_psz14.pt" +) +model.model_vision.embed_dim_language = 1024 diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_36ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_36ep.py new file mode 100644 index 0000000000000000000000000000000000000000..462c7d32a2174a9eb676fc99ee5165cbcc9ea2d3 --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_36ep.py @@ -0,0 +1,118 @@ +from functools import partial + +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detrex.config import get_config +from ape.modeling.backbone.vit import get_vit_lr_decay_rate +from ape.modeling.backbone.vit_eva02 import SimpleFeaturePyramid, ViT +from ape.modeling.text import EVA01CLIP + +from .....detectron2.configs.common.data.constants import constants +from ...common.data.coco_refcoco_instance_lsj1024 import dataloader +from .models.ape_deta_r50_vlf import model + +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = L(SimpleFeaturePyramid)( + net=L(ViT)( # Single-scale ViT backbone + img_size=1024, + patch_size=16, + embed_dim=1024, + depth=24, + num_heads=16, + drop_path_rate=0.4, + window_size=16, + mlp_ratio=4 * 2 / 3, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + window_block_indexes=list(range(0, 5)) + + list(range(6, 11)) + + list(range(12, 17)) + + list(range(18, 23)), + residual_block_indexes=[], + use_rel_pos=True, + out_feature="last_feat", + use_act_checkpoint=False, + xattn=True, + ), + in_feature="${.net.out_feature}", + out_channels=256, + scale_factors=(4.0, 2.0, 1.0, 0.5), + top_block=L(LastLevelMaxPool)(), + norm="LN", + square_pad=1024, +) + +model.model_vision.neck = None + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone.net" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} +optimizer.params.weight_decay_norm = None + +optimizer.lr = 2e-4 +optimizer.betas = (0.9, 0.999) +optimizer.weight_decay = 1e-4 + +train = get_config("common/train.py").train +train.max_iter = 270000 +train.eval_period = 27000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "models/Yunxin-CV/EVA-02/eva02/pt/eva02_L_pt_in21k_p14to16.pt?matching_heuristics=True" +) + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_36ep +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +model.model_vision.dataset_prompts = ["name", "expression"] +model.model_vision.dataset_names = ["coco_2017", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +model.model_language = L(EVA01CLIP)( + clip_model="EVA_CLIP_g_14_X", cache_dir="models/BAAI/EVA/eva_clip_psz14.pt" +) +model.model_vision.embed_dim_language = 1024 + diff --git a/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_lsj1024_12ep.py b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..61103dfb69326d22431ce3dcee807f7a107df01d --- /dev/null +++ b/approach/ovod/APE/configs/COCO_REFCOCO/ape_deta/ape_deta_vitl_lsj1024_12ep.py @@ -0,0 +1,114 @@ +from functools import partial + +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detectron2.modeling.backbone.vit import SimpleFeaturePyramid, ViT, get_vit_lr_decay_rate +from detrex.config import get_config +from ape.modeling.text import EVA01CLIP + +from .....detectron2.configs.common.data.constants import constants +from ...common.data.coco_refcoco_instance_lsj1024 import dataloader +from .models.ape_deta_r50 import model + +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = L(SimpleFeaturePyramid)( + net=L(ViT)( # Single-scale ViT backbone + img_size=1024, + patch_size=16, + embed_dim=1024, + depth=24, + num_heads=16, + drop_path_rate=0.4, + window_size=14, + mlp_ratio=4, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + window_block_indexes=list(range(0, 5)) + + list(range(6, 11)) + + list(range(12, 17)) + + list(range(18, 23)), + residual_block_indexes=[], + use_rel_pos=True, + out_feature="last_feat", + use_act_checkpoint=True, + ), + in_feature="${.net.out_feature}", + out_channels=256, + scale_factors=(4.0, 2.0, 1.0, 0.5), + top_block=L(LastLevelMaxPool)(), + norm="LN", + square_pad=1024, +) + +model.model_vision.neck = None + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} + +optimizer.lr = 2e-4 +optimizer.weight_decay = 0.05 + +train = get_config("common/train.py").train +train.max_iter = 90000 +train.eval_period = 5000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True" +) +train.init_checkpoint = "models/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True" + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_12ep +lr_multiplier.scheduler.milestones = [75000, 90000] +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +model.model_vision.dataset_tasks = ["name", "expression"] +model.model_vision.dataset_names = ["coco_2017", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +model.model_language = L(EVA01CLIP)( + clip_model="EVA_CLIP_g_14_X", cache_dir="models/BAAI/EVA/eva_clip_psz14.pt" +) +model.model_vision.embed_dim_language = 1024 diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..74abeabb136a544b9a6ef2fb9084829412ed59b0 --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep.py @@ -0,0 +1,20 @@ +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_r50_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) +from ...common.data.gqa_region_instance import dataloader + +model.model_vision.num_classes = 200 + +model.model_vision.criterion[0].num_classes = 200 + +dataloader.train.mapper.max_num_phrase = 100 + +model.model_vision.dataset_prompts = ["phrase", "expression"] +model.model_vision.dataset_names = ["gqa", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 1280 diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc51482401207da941dce8bb6054359b5a4f9f3 --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py @@ -0,0 +1,10 @@ +from ...common.data.odinw13_instance import dataloader +from .ape_deta_r50_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0a68150e8b3a322c09b9535ca4bd447302c93f --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py @@ -0,0 +1,10 @@ +from ...common.data.odinw35_instance import dataloader +from .ape_deta_r50_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f6e6d337b8483f9c94eb30774fbe4993b27fc2 --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py @@ -0,0 +1,46 @@ +from detectron2.config import LazyCall as L +from omegaconf import OmegaConf +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_r50_12ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + cfg=OmegaConf.from_dotlist( + [ + "MODEL.DYHEAD.FUSE_CONFIG.STABLE_SOFTMAX_2D=False", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MIN_FOR_UNDERFLOW=True", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MAX_FOR_OVERFLOW=True", + "MODEL.VL_FUSION_USE_CHECKPOINT=True", + ], + ), +) + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 1280 diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py new file mode 100644 index 0000000000000000000000000000000000000000..e017fae82e703156d858b0937ee3ae040620c634 --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py @@ -0,0 +1,10 @@ +from ...common.data.odinw13_instance import dataloader +from .ape_deta_r50_vlf_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py new file mode 100644 index 0000000000000000000000000000000000000000..e09309f978cbb10fdc0a2868c7eb7fb2c6045f72 --- /dev/null +++ b/approach/ovod/APE/configs/GQA_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py @@ -0,0 +1,10 @@ +from ...common.data.odinw35_instance import dataloader +from .ape_deta_r50_vlf_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_180k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_180k.py new file mode 100644 index 0000000000000000000000000000000000000000..5af83887954d110c825dd952697d478b50ecd2fc --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_180k.py @@ -0,0 +1,21 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from .ape_deta_vitl_eva02_lsj1024_cp_720k import dataloader, lr_multiplier, model, optimizer, train + +train.max_iter = 180000 +train.eval_period = 180000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[150000], + num_updates=180000, + ), + warmup_length=1000 / 180000, + warmup_method="linear", + warmup_factor=0.001, +) + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k.py new file mode 100644 index 0000000000000000000000000000000000000000..769e70a4b2be02d65b7949bc180a2ca0b0140fd4 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_720k.py @@ -0,0 +1,83 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights + +from ...common.data.lviscocococostuff_o365_oid_vgr_refcoco_group_by_image_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(6)] +for criterion, num_classes in zip(model.model_vision.criterion, [1256, 365, 601, 200, 200, 200]): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[4].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +model.model_vision.neck = None + +train.max_iter = 720000 +train.eval_period = 720000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[640000], + num_updates=720000, + ), + warmup_length=1000 / 720000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16] + +model.model_vision.dataset_prompts = ["name", "name", "name", "phrase", "phrase", "expression"] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "refcoco-mixed_group-by-image", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py new file mode 100644 index 0000000000000000000000000000000000000000..a2202c06e3319d78825b4ac659be9c905720ce08 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py @@ -0,0 +1,27 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from .ape_deta_vitl_eva02_vlf_lsj1024_cp_720k import ( + dataloader, + lr_multiplier, + model, + optimizer, + train, +) + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 1080000, + warmup_method="linear", + warmup_factor=0.001, +) + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py new file mode 100644 index 0000000000000000000000000000000000000000..af32118d2a1cfe822478159a23ce04d2cfcdbad9 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py @@ -0,0 +1,27 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from .ape_deta_vitl_eva02_vlf_lsj1024_cp_720k import ( + dataloader, + lr_multiplier, + model, + optimizer, + train, +) + +train.max_iter = 180000 +train.eval_period = 180000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[150000], + num_updates=180000, + ), + warmup_length=1000 / 180000, + warmup_method="linear", + warmup_factor=0.001, +) + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py new file mode 100644 index 0000000000000000000000000000000000000000..06ecd91d10b077c563c66cd65de4ef7df91d551b --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py @@ -0,0 +1,47 @@ +from detectron2.config import LazyCall as L +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_vitl_eva02_lsj1024_cp_720k import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_08x8x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_08x8x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..fb64dc7385ee3182f35b480f59ce42b0db227daa --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_08x8x270k.py @@ -0,0 +1,228 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 8 +dataloader.train.total_batch_size_list = [8, 8, 8, 8, 8, 8, 8, 8, 8] +dataloader.train.num_workers = 2 +train.iter_size = 8 + +dataloader.wait_group = 2 +dataloader.wait_time = 30 * 60 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_1080k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_1080k.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee51a4be70c9b40adca8e35022ba4350818aca1 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_1080k.py @@ -0,0 +1,225 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16, 16, 16, 16, 16] +dataloader.train.num_workers = 4 + + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k.py new file mode 100644 index 0000000000000000000000000000000000000000..ab66e17b3a35318a9964515f96db6744ec6163e6 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k.py @@ -0,0 +1,227 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16, 16, 16, 16, 16] +dataloader.train.num_workers = 0 +train.iter_size = 4 +train.iter_loop = False + + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a3774d0c871c29697296ca1dd9f36589661e24 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl.py @@ -0,0 +1,230 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[0].dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[2].dataset.names, 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].mapper.max_num_phrase = 128 + dataloader.train[i].mapper.nms_thresh_phrase = 0.6 + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + dataloader.train[i].num_workers = 2 + +train.iter_size = 4 +train.iter_loop = False +train.dataset_ratio = [1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1] + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = [xx for x in dataloader.train for xx in x.dataset.names] + [ + "refcoco-mixed" +] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl_llama2.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl_llama2.py new file mode 100644 index 0000000000000000000000000000000000000000..d312bc379ce7bb8b38fc46f3a57d1fa24b7b8d75 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k_mdl_llama2.py @@ -0,0 +1,235 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import Llama2 + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(Llama2)( + pretrained_model_name_or_path="models/meta-llama/Llama-2-7b-hf/", + dtype="float32", + vision_port="decoder", + eval_only=True, + load_in_4bit=True, + load_in_8bit=False, +) +model.model_vision.embed_dim_language = 4096 +model.model_vision.text_feature_reduce_type = "average" + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True +model.model_vision.transformer.decoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[0].dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[2].dataset.names, 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].mapper.max_num_phrase = 128 + dataloader.train[i].mapper.nms_thresh_phrase = 0.6 + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + dataloader.train[i].num_workers = 2 + +train.iter_size = 4 +train.iter_loop = False +train.dataset_ratio = [1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1] + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = [xx for x in dataloader.train for xx in x.dataset.names] + [ + "refcoco-mixed" +] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..29857f7c0a37db22b2bfb61eb44b6d39dba1f8ef --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k.py @@ -0,0 +1,227 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16, 16, 16, 16, 16] +dataloader.train.num_workers = 0 +train.iter_size = 4 + + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl.py new file mode 100644 index 0000000000000000000000000000000000000000..39b14d3cf95e1e3c97ac5cfa5509fb7ad09fd529 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl.py @@ -0,0 +1,230 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[0].dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[2].dataset.names, 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].mapper.max_num_phrase = 128 + dataloader.train[i].mapper.nms_thresh_phrase = 0.6 + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + dataloader.train[i].num_workers = 2 + +train.iter_size = 4 +train.dataset_ratio = [1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1] + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = [xx for x in dataloader.train for xx in x.dataset.names] + [ + "refcoco-mixed" +] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl_llama2.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl_llama2.py new file mode 100644 index 0000000000000000000000000000000000000000..8f40027bf3381afffcb8d159f98ae33a1e361d6a --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x270k_mdl_llama2.py @@ -0,0 +1,235 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import Llama2 + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(Llama2)( + pretrained_model_name_or_path="models/meta-llama/Llama-2-7b-hf/", + dtype="float32", + vision_port="decoder", + eval_only=True, + load_in_4bit=True, + load_in_8bit=False, +) +model.model_vision.embed_dim_language = 4096 +model.model_vision.text_feature_reduce_type = "average" + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True +model.model_vision.transformer.decoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[0].dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[2].dataset.names, 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].mapper.max_num_phrase = 128 + dataloader.train[i].mapper.nms_thresh_phrase = 0.6 + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + dataloader.train[i].num_workers = 2 + +train.iter_size = 4 +train.dataset_ratio = [1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1] + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = [xx for x in dataloader.train for xx in x.dataset.names] + [ + "refcoco-mixed" +] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x337k_mdl.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x337k_mdl.py new file mode 100644 index 0000000000000000000000000000000000000000..b746718093c4564c4a1197c21f976d7b6fe9e33f --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4x337k_mdl.py @@ -0,0 +1,230 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[0].dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train[2].dataset.names, 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 337500 +train.eval_period = 337500 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1, 0.01], + milestones=[225000, 300000], + num_updates=337500, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].mapper.max_num_phrase = 128 + dataloader.train[i].mapper.nms_thresh_phrase = 0.6 + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + dataloader.train[i].num_workers = 2 + +train.iter_size = 4 +train.dataset_ratio = [1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1] + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = [xx for x in dataloader.train for xx in x.dataset.names] + [ + "refcoco-mixed" +] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_32x2x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_32x2x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..a4db1c343222467a7301e4eeece44102a05b7407 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_32x2x270k.py @@ -0,0 +1,228 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 32 +dataloader.train.total_batch_size_list = [32, 32, 32, 32, 32, 32, 32, 32, 32] +dataloader.train.num_workers = 2 +train.iter_size = 2 + +dataloader.wait_group = 2 +dataloader.wait_time = 30 * 60 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_48x2x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_48x2x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..00f04e1673863920eae6a008b0c259d4b86cc7d2 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_48x2x270k.py @@ -0,0 +1,225 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 * 2 +train.eval_period = 270000 * 2 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000 * 2], + num_updates=270000 * 2, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 48 +dataloader.train.total_batch_size_list = [48, 48, 48, 48, 48, 48, 48, 48, 48] +dataloader.train.num_workers = 2 +train.iter_size = 2 + + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_64x1x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_64x1x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..76bd25635603af44a66349479e05a4da588ae54d --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_64x1x270k.py @@ -0,0 +1,228 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 256, 1, 256, 256, 256, 256, 256] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 64 +dataloader.train.total_batch_size_list = [64, 64, 64, 64, 64, 64, 64, 64, 64] +dataloader.train.num_workers = 2 +train.iter_size = 1 + +dataloader.wait_group = 2 +dataloader.wait_time = 30 * 60 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_08x8x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_08x8x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd05d6e4acf94bd6faee56befbd33d9b0d88afd --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_08x8x270k.py @@ -0,0 +1,225 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip_1536 import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) +model.model_vision.transformer.encoder.use_act_checkpoint = True +model.model_vision.transformer.decoder.use_act_checkpoint = True + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 * 8 +train.eval_period = 270000 * 8 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000 * 8], + num_updates=270000 * 8, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 8 +dataloader.train.total_batch_size_list = [8, 8, 8, 8, 8, 8, 8, 8, 8] +train.iter_size = 8 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_32x2x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_32x2x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5265d8e8b86620ae3090db34dfca9e817772f6 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_32x2x270k.py @@ -0,0 +1,222 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip_1536 import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 9 +model.model_vision.transformer.decoder.num_layers = 9 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 * 2 +train.eval_period = 270000 * 2 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000 * 2], + num_updates=270000 * 2, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 32 +dataloader.train.total_batch_size_list = [32, 32, 32, 32, 32, 32, 32, 32, 32] +train.iter_size = 2 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_64x270k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_64x270k.py new file mode 100644 index 0000000000000000000000000000000000000000..49a00e1e0c73abb764b71ef08f49df228ab89cbb --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1536_cp_64x270k.py @@ -0,0 +1,222 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.solver import WarmupParamScheduler +from detrex.modeling.neck import ChannelMapper +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip_1536 import backbone +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 9 +model.model_vision.transformer.decoder.num_layers = 9 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 270000 +train.eval_period = 270000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[225000], + num_updates=270000, + ), + warmup_length=2000 / 270000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 64 +dataloader.train.total_batch_size_list = [64, 64, 64, 64, 64, 64, 64, 64, 64] + + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py new file mode 100644 index 0000000000000000000000000000000000000000..ff47d95471a2985bed72e5f6f89f314ac9c928ef --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_1080k.py @@ -0,0 +1,173 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from ...common.data.lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp import ( + dataloader, +) +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +del criterion.fed_loss_num_classes +model.model_vision.criterion = [criterion for _ in range(10)] +for criterion, num_classes in zip( + model.model_vision.criterion, [1256, 365, 601, 200, 1, 200, 200, 200, 200, 200] +): + criterion.num_classes = num_classes + +dataloader.train.mapper.max_num_phrase = 100 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.criterion[2].use_fed_loss = True +model.model_vision.criterion[2].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[2], 0.5 +) +model.model_vision.criterion[2].fed_loss_num_classes = 50 +model.model_vision.criterion[2].fed_loss_pad_type = "cat" + +model.model_vision.criterion[3].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[3].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[3].weight_dict.update({k: 0.0}) + +for k, v in model.model_vision.criterion[4].weight_dict.items(): + if "_class" in k and "_enc" not in k: + model.model_vision.criterion[4].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + +model.model_vision.criterion[6].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[6].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[6].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[7].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[7].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[7].weight_dict.update({k: 0.0}) + +model.model_vision.criterion[8].weight_dict["loss_class_enc"] = 0.0 +for k, v in model.model_vision.criterion[8].weight_dict.items(): + if "_enc" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + if "_bbox" in k or "_giou" in k or "_dice" in k or "_mask" in k: + model.model_vision.criterion[8].weight_dict.update({k: 0.0}) + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = 0.9 +model.model_vision.transformer.proposal_ambiguous = 1 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 1080000 +train.eval_period = 1080000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[900000], + num_updates=1080000, + ), + warmup_length=2000 / 1080000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16, 16, 16, 16, 16] +dataloader.train.num_workers = 4 + +model.model_vision.dataset_prompts = [ + "name", + "name", + "name", + "phrase", + "name", + "phrase", + "phrase", + "phrase", + "phrase", + "expression", +] +model.model_vision.dataset_names = [ + "lvis+stuffonly", + "objects365", + "openimages", + "vgregion", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa", + "phrasecut", + "flickr30k", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_r50_lsj1024_cp_50ep.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_r50_lsj1024_cp_50ep.py new file mode 100644 index 0000000000000000000000000000000000000000..d28db18c4a401bb634d8f24ae12f4a4b63ba44dd --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_r50_lsj1024_cp_50ep.py @@ -0,0 +1,36 @@ +from detectron2.data.detection_utils import get_fed_loss_cls_weights +from detrex.config import get_config + +from ...common.data.lviscocococostuff_panoptic_lsj1024_cp import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_r50_24ep import ( + lr_multiplier, + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.criterion[0].num_classes = 1256 +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names, 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 +model.model_vision.criterion[0].fed_loss_pad_type = "cat" + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +train.max_iter = 375000 +train.eval_period = 20000 + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_50ep + +dataloader.train.total_batch_size = 16 + +model.model_vision.dataset_prompts = ["name"] +model.model_vision.dataset_names = ["lvis+stuffonly"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_24ep.py b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_24ep.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b4e6e42920a5a13b7585b12dcf28d1b5a6c84a --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCOCOCOSTUFF_PanopticSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024_cp_24ep.py @@ -0,0 +1,20 @@ +from ...common.data.lviscocococostuff_panoptic_lsj1024_cp import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + lr_multiplier, + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.criterion[0].num_classes = 1256 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +model.model_vision.dataset_prompts = ["name"] +model.model_vision.dataset_names = ["lvis+stuffonly"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py b/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py new file mode 100644 index 0000000000000000000000000000000000000000..af32118d2a1cfe822478159a23ce04d2cfcdbad9 --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_180k.py @@ -0,0 +1,27 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from .ape_deta_vitl_eva02_vlf_lsj1024_cp_720k import ( + dataloader, + lr_multiplier, + model, + optimizer, + train, +) + +train.max_iter = 180000 +train.eval_period = 180000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[150000], + num_updates=180000, + ), + warmup_length=1000 / 180000, + warmup_method="linear", + warmup_factor=0.001, +) + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py b/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py new file mode 100644 index 0000000000000000000000000000000000000000..1405c871297d1efa37ec61e2c686296c91ef109a --- /dev/null +++ b/approach/ovod/APE/configs/LVISCOCO_COCOSTUFF_O365_OID_VG_REFCOCO/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_cp_720k.py @@ -0,0 +1,120 @@ +import random + +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler + +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from ...common.data.lviscoco_cocostuff_o365_oid_vg_refcoco_panoptic_lsj1024_cp import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + lr_multiplier, + model, + optimizer, + train, +) + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=False, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True + +model.model_vision.num_classes = 1203 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +model.model_vision.criterion = [criterion for _ in range(6)] +for criterion, num_classes in zip(model.model_vision.criterion, [1203, 54, 365, 601, 150, 200]): + criterion.num_classes = num_classes + +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 + +model.model_vision.criterion[5].weight_dict["loss_class_enc"] = 0.0 + + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +model.model_vision.neck = None + +train.max_iter = 720000 +train.eval_period = 720000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[640000], + num_updates=720000, + ), + warmup_length=1000 / 720000, + warmup_method="linear", + warmup_factor=0.001, +) + +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = [16, 16, 16, 16, 16] + +model.model_vision.dataset_prompts = ["name", "name", "name", "name", "name", "expression"] +model.model_vision.dataset_names = [ + "lvis", + "stuffonly", + "objects365", + "openimages", + "visualgenome", + "refcoco", +] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] + +dataloader.train.sampler = lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=6, + dataset_ratio=[1, 1, 1, 1, 1, 0], + use_rfs=[True, False, True, True, True, True], + use_cas=[False, False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), +) diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep.py new file mode 100644 index 0000000000000000000000000000000000000000..df956aebd64affce77d3ade6a1d0b2bb1f25018e --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep.py @@ -0,0 +1,29 @@ +from detectron2.data.detection_utils import get_fed_loss_cls_weights +from detrex.config import get_config + +from ...COCO_SA1B_InstanceSegmentation.ape_deta.ape_deta_r50_24ep import model, optimizer, train + +from ...common.data.lvis_sa1b_instance import dataloader + +model.model_vision.num_classes = 1203 +model.model_vision.criterion[0].num_classes = 1203 +model.model_vision.select_box_nums_for_evaluation = 300 +model.model_vision.criterion[0].use_fed_loss = True +model.model_vision.criterion[0].get_fed_loss_cls_weights = lambda: get_fed_loss_cls_weights( + dataloader.train.dataset.names[0], 0.5 +) +model.model_vision.criterion[0].fed_loss_num_classes = 50 + +model.model_vision.semantic_on = False +model.model_vision.panoptic_on = False + +train.max_iter = 375000 +train.eval_period = 20000 + +lr_multiplier = get_config("common/coco_schedule.py").lr_multiplier_50ep + +model.model_vision.dataset_prompts = ["name", "name"] +model.model_vision.dataset_names = ["lvis", "sa1b"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw13.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw13.py new file mode 100644 index 0000000000000000000000000000000000000000..e8850dcd4cd87feae49f1b185384e79e68e8cfab --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw13.py @@ -0,0 +1,10 @@ +from ...common.data.odinw13_instance import dataloader +from .ape_deta_r50_50ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw35.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw35.py new file mode 100644 index 0000000000000000000000000000000000000000..47bc758015460dfb97f9f830fb125529488ae74c --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_odinw35.py @@ -0,0 +1,10 @@ +from ...common.data.odinw35_instance import dataloader +from .ape_deta_r50_50ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_seginw.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_seginw.py new file mode 100644 index 0000000000000000000000000000000000000000..d51d5d6cc9230e02a7bda531151c5c9d382bec5e --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_eval_seginw.py @@ -0,0 +1,11 @@ +from ...common.data.seginw_instance import dataloader +from .ape_deta_r50_50ep import lr_multiplier, model, optimizer, train + + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_iouloss_lp.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_iouloss_lp.py new file mode 100644 index 0000000000000000000000000000000000000000..772782020ef8962eff7d11fe546f8428591c7d50 --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_iouloss_lp.py @@ -0,0 +1,21 @@ +from ape.modeling.ape_deta import Stage1Assigner_loc, Stage2Assigner_loc + +from .ape_deta_r50_50ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.criterion[0].losses += ["pred_iou"] +model.model_vision.criterion[0].weight_dict["loss_iou"] = 1.0 + +model.model_vision.last_class_embed_use_mlp = True +model.model_vision.transformer.pre_nms_topk = 1000 +model.model_vision.transformer.nms_thresh_enc = 0.9 + +model.model_vision.criterion[0].matcher_stage1.update( + _target_=Stage1Assigner_loc, +) +model.model_vision.criterion[1].matcher_stage1.update( + _target_=Stage1Assigner_loc, +) + + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 1280 diff --git a/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_mp.py b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8c845cf97e5764d605d2d1528c093cec4aab34 --- /dev/null +++ b/approach/ovod/APE/configs/LVIS_SA1B_InstanceSegmentation/ape_deta/ape_deta_r50_50ep_mp.py @@ -0,0 +1,7 @@ +from .ape_deta_r50_50ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.transformer.proposal_ambiguous = 1 +model.model_vision.transformer.encoder.use_act_checkpoint = True + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 diff --git a/approach/ovod/APE/configs/PascalVOC20_SemanticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py b/approach/ovod/APE/configs/PascalVOC20_SemanticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..56dbd7be1b3f47989b890e7cb54856919f523b76 --- /dev/null +++ b/approach/ovod/APE/configs/PascalVOC20_SemanticSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py @@ -0,0 +1,100 @@ +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detrex.modeling.neck import ChannelMapper +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from .ape_deta_vitl_eva02_lsj1024 import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.backbone = backbone + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.neck = L(ChannelMapper)( + input_shapes={ + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), + }, + in_features=["p2", "p3", "p4", "p5", "p6"], + out_channels=256, + num_outs=5, + kernel_size=1, + norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), +) + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +model.model_vision.transformer.encoder.num_layers = 6 +model.model_vision.transformer.decoder.num_layers = 6 +model.model_vision.transformer.encoder.embed_dim = 256 +model.model_vision.transformer.decoder.embed_dim = 256 +model.model_vision.embed_dim = 256 +model.model_vision.backbone.out_channels = 256 + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = -1.0 +model.model_vision.transformer.proposal_ambiguous = 1 + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..6c0e8174f74bec3fd16b0f0954246fdd9f971f61 --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_12ep.py @@ -0,0 +1,27 @@ +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_r50_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) + +from ...common.data.refcoco_group_by_image_instance import dataloader + +model.model_vision.num_classes = 256 + +model.model_vision.select_box_nums_for_evaluation = 1 + +criterion = model.model_vision.criterion[0] +model.model_vision.criterion = [criterion for _ in range(2)] + +model.model_vision.dataset_prompts = ["phrase", "expression"] +model.model_vision.dataset_names = ["refcoco-mixed_group-by-image", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_bert_vlf_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_bert_vlf_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..9040f845a934004a80adfaff666ceaeb0d474a7f --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_bert_vlf_12ep.py @@ -0,0 +1,32 @@ +from detectron2.config import LazyCall as L +from ape.modeling.text import Bert + +from ...common.data.refcoco_instance import dataloader +from .ape_deta_r50_vlf_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.num_classes = 1 +model.model_vision.select_box_nums_for_evaluation = 1 + +model.model_vision.criterion[0].num_classes = 1 +criterion = model.model_vision.criterion[0] +model.model_vision.criterion = [criterion for _ in range(2)] + +model.model_vision.dataset_prompts = ["expression"] +model.model_vision.dataset_names = ["refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + + +model.model_language = L(Bert)( + pretrained_model_name_or_path="models/huggingface/bert-base-uncased/" +) +model.model_vision.embed_dim_language = 768 +model.model_vision.text_feature_reduce_type = "average" + +model.model_vision.text_feature_bank = False +model.model_vision.text_feature_reduce_before_fusion = False +model.model_vision.text_feature_batch_repeat = False +model.model_vision.expression_cumulative_gt_class = False + + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..5a456e63d5cb956c2ad6eefedb5d8fa39526650d --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py @@ -0,0 +1,48 @@ +from detectron2.config import LazyCall as L +from omegaconf import OmegaConf +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_r50_12ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True + + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_lsj1024_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..2367609e21e2876a3808c23045f8defc5ad0c9e3 --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_lsj1024_12ep.py @@ -0,0 +1,104 @@ +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.model_zoo import get_config as get_config_d2 +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detrex.config import get_config as get_config_detrex +from ape.modeling.backbone.vit import get_vit_lr_decay_rate +from ape.modeling.backbone.vit_eva02 import SimpleFeaturePyramid, ViT +from ape.modeling.text import EVA02CLIP + +from ...common.backbone.vitl_eva02_clip import backbone +from ...common.data.refcoco_instance_lsj1024 import dataloader +from .ape_deta_r50_12ep import model + +constants = get_config_d2("common/data/constants.py").constants + +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = backbone + +model.model_vision.neck.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} +model.model_vision.neck.in_features = ["p2", "p3", "p4", "p5", "p6"] +model.model_vision.neck.num_outs = 5 + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config_detrex("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone.net" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} +optimizer.params.weight_decay_norm = None + +optimizer.lr = 2e-4 +optimizer.weight_decay = 1e-4 + +train = get_config_detrex("common/train.py").train +train.max_iter = 90000 +train.eval_period = 5000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "models/QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14to16_s6B.pt?matching_heuristics=True" +) + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config_detrex("common/coco_schedule.py").lr_multiplier_12ep +lr_multiplier.scheduler.milestones = [75000, 90000] +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = ["${..total_batch_size}", "${..total_batch_size}"] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +model.model_vision.dataset_prompts = ["expression"] +model.model_vision.dataset_names = ["refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +model.model_language = L(EVA02CLIP)( + clip_model="EVA02-CLIP-bigE-14-plus", + cache_dir="models/QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt", + dtype="float16", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True + diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..01ed3f740eaadc2effb4c671f1c7daf3f3744eac --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_12ep.py @@ -0,0 +1,54 @@ +from detectron2.config import LazyCall as L +from omegaconf import OmegaConf +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_vitl_eva02_clip_lsj1024_12ep import ( + dataloader, + lr_multiplier, + model, + optimizer, + train, +) + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, + use_attention_mask_v=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True + + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 5120 diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbeaec0d9c98866627df67b9d372943ece023b6 --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024_12ep.py @@ -0,0 +1,105 @@ +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.model_zoo import get_config as get_config_d2 +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detrex.config import get_config as get_config_detrex +from ape.modeling.backbone.vit import get_vit_lr_decay_rate +from ape.modeling.backbone.vit_eva02 import SimpleFeaturePyramid, ViT +from ape.modeling.text import EVA01CLIP + +from ...common.backbone.vitl_eva02 import backbone + +from ...common.data.refcoco_group_by_image_instance_lsj1024 import dataloader +from .ape_deta_r50_vlf_12ep import model + +model.model_vision.num_classes = 256 +model.model_vision.select_box_nums_for_evaluation = 1 +model.model_vision.criterion[0].num_classes = 256 +model.model_vision.criterion[1].num_classes = 256 + +constants = get_config_d2("common/data/constants.py").constants + +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = backbone + +model.model_vision.neck = None + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config_detrex("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone.net" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} +optimizer.params.weight_decay_norm = None + +optimizer.lr = 2e-4 +optimizer.weight_decay = 1e-4 + +train = get_config_detrex("common/train.py").train +train.max_iter = 90000 +train.eval_period = 5000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "models/Yunxin-CV/EVA-02/eva02/pt/eva02_L_pt_in21k_p14to16.pt?matching_heuristics=True" +) + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config_detrex("common/coco_schedule.py").lr_multiplier_12ep +lr_multiplier.scheduler.milestones = [75000, 90000] +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.total_batch_size_list = ["${..total_batch_size}", "${..total_batch_size}"] +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +dataloader.train.mapper.max_num_phrase = 128 +dataloader.train.mapper.nms_thresh_phrase = 0.6 + +model.model_vision.dataset_prompts = ["phrase", "expression"] +model.model_vision.dataset_names = ["refcoco-mixed_group-by-image", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +model.model_language = L(EVA01CLIP)( + clip_model="EVA_CLIP_g_14_X", + cache_dir="models/BAAI/EVA/eva_clip_psz14.pt", +) +model.model_vision.embed_dim_language = 1024 + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True + +model.model_vision.transformer.encoder.use_act_checkpoint = True +model.model_vision.transformer.decoder.use_act_checkpoint = True + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_lsj1024_12ep.py b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_lsj1024_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..18683f6bdee2e6d7e8e36f2d3d37cda7273c4e07 --- /dev/null +++ b/approach/ovod/APE/configs/REFCOCO_VisualGrounding/ape_deta/ape_deta_vitl_lsj1024_12ep.py @@ -0,0 +1,115 @@ +from functools import partial + +import torch.nn as nn + +from detectron2.config import LazyCall as L +from detectron2.layers import ShapeSpec +from detectron2.model_zoo import get_config as get_config_d2 +from detectron2.modeling.backbone.fpn import LastLevelMaxPool +from detectron2.modeling.backbone.vit import SimpleFeaturePyramid, ViT +from detrex.config import get_config as get_config_detrex +from ape.modeling.backbone.vit import get_vit_lr_decay_rate +from ape.modeling.text import EVA01CLIP + +from ...common.data.refcoco_instance_lsj1024 import dataloader +from .ape_deta_r50_vlf_12ep import model + +constants = get_config_d2("common/data/constants.py").constants +model.model_vision.pixel_mean = constants.imagenet_rgb256_mean +model.model_vision.pixel_std = constants.imagenet_rgb256_std +model.model_vision.input_format = "RGB" + +model.model_vision.backbone = L(SimpleFeaturePyramid)( + net=L(ViT)( # Single-scale ViT backbone + img_size=1024, + patch_size=16, + embed_dim=1024, + depth=24, + num_heads=16, + drop_path_rate=0.4, + window_size=14, + mlp_ratio=4, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + window_block_indexes=list(range(0, 5)) + + list(range(6, 11)) + + list(range(12, 17)) + + list(range(18, 23)), + residual_block_indexes=[], + use_rel_pos=True, + out_feature="last_feat", + use_act_checkpoint=True, + ), + in_feature="${.net.out_feature}", + out_channels=256, + scale_factors=(4.0, 2.0, 1.0, 0.5), + top_block=L(LastLevelMaxPool)(), + norm="LN", + square_pad=1024, +) + +model.model_vision.neck = None + +model.model_vision.mask_in_features = ["p2"] +model.model_vision.input_shapes = { + "p2": ShapeSpec(channels=256), + "p3": ShapeSpec(channels=256), + "p4": ShapeSpec(channels=256), + "p5": ShapeSpec(channels=256), + "p6": ShapeSpec(channels=256), +} + +optimizer = get_config_detrex("common/optim.py").AdamW +optimizer.params.lr_factor_func = ( + lambda module_name: 0.1 + if "reference_points" in module_name or "sampling_offsets" in module_name + else get_vit_lr_decay_rate(module_name, lr_decay_rate=0.8, num_layers=24) + if "backbone.net" in module_name + else 1 +) +optimizer.params.overrides = {"pos_embed": {"weight_decay": 0.0}} + +optimizer.lr = 2e-4 +optimizer.weight_decay = 0.05 + +train = get_config_detrex("common/train.py").train +train.max_iter = 90000 +train.eval_period = 5000 +train.log_period = 20 + +train.checkpointer.period = 5000 +train.checkpointer.max_to_keep = 2 + +train.clip_grad.enabled = True +train.clip_grad.params.max_norm = 0.1 +train.clip_grad.params.norm_type = 2 + +train.device = "cuda" + +train.init_checkpoint = ( + "detectron2://ImageNetPretrained/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True" +) +train.init_checkpoint = "models/MAE/mae_pretrain_vit_large.pth?matching_heuristics=True" + +train.amp.enabled = True +train.ddp.fp16_compression = True + +lr_multiplier = get_config_detrex("common/coco_schedule.py").lr_multiplier_12ep +lr_multiplier.scheduler.milestones = [75000, 90000] +lr_multiplier.warmup_length = 1000 / train.max_iter + +dataloader.train.num_workers = 16 +dataloader.train.total_batch_size = 16 +dataloader.train.mapper.image_format = "RGB" +dataloader.train.mapper.use_instance_mask = True + +model.model_vision.dataset_prompts = ["expression"] +model.model_vision.dataset_names = ["refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.output_dir = train.output_dir + +model.model_language = L(EVA01CLIP)( + clip_model="EVA_CLIP_g_14_X", cache_dir="models/BAAI/EVA/eva_clip_psz14.pt" +) +model.model_vision.embed_dim_language = 1024 diff --git a/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..93721474e19084f32713e3d687fd8894fef93b82 --- /dev/null +++ b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024.py @@ -0,0 +1,108 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from ...common.data.seginw_instance_lsj1024 import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_clip_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +model.model_vision.criterion = [criterion for _ in range(25)] +for criterion, num_classes in zip( + model.model_vision.criterion, + [ + 1000, + ] + * 25, +): + criterion.num_classes = num_classes + + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = -1.0 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + + +train.max_iter = 720000 +train.eval_period = 720000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[640000], + num_updates=720000, + ), + warmup_length=1000 / 720000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [x.dataset.names.replace("_val", "") for x in dataloader.tests] +model.model_vision.dataset_metas = [x.dataset.names for x in dataloader.tests] + + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 + +train.output_dir = "output/" + __file__[:-3] + + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..212471bc4962be8295cfa4ae78670cc4d68650f8 --- /dev/null +++ b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_lsj1024.py @@ -0,0 +1,74 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler +from ape.data.detection_utils import get_fed_loss_cls_weights + +from ...common.data.seginw_instance_lsj1024 import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +model.model_vision.criterion = [criterion for _ in range(25)] +for criterion, num_classes in zip( + model.model_vision.criterion, + [ + 1000, + ] + * 25, +): + criterion.num_classes = num_classes + + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = -1.0 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +model.model_vision.neck = None + +train.max_iter = 720000 +train.eval_period = 720000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[640000], + num_updates=720000, + ), + warmup_length=1000 / 720000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [x.dataset.names.replace("_val", "") for x in dataloader.tests] +model.model_vision.dataset_metas = [x.dataset.names for x in dataloader.tests] + + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 + +train.output_dir = "output/" + __file__[:-3] + + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9ebce873f24f49012870fa5bfd1711769e83d9 --- /dev/null +++ b/approach/ovod/APE/configs/SegInW_InstanceSegmentation/ape_deta/ape_deta_vitl_eva02_vlf_lsj1024.py @@ -0,0 +1,109 @@ +from detectron2.config import LazyCall as L +from detectron2.solver import WarmupParamScheduler +from fvcore.common.param_scheduler import MultiStepParamScheduler +from ape.data.detection_utils import get_fed_loss_cls_weights +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from ...common.data.seginw_instance_lsj1024 import dataloader +from ...LVIS_InstanceSegmentation.ape_deta.ape_deta_vitl_eva02_lsj1024_cp_24ep import ( + model, + optimizer, + train, +) + +model.model_vision.num_classes = 1256 +model.model_vision.select_box_nums_for_evaluation = 300 + +criterion = model.model_vision.criterion[0] +del criterion.use_fed_loss +del criterion.get_fed_loss_cls_weights +model.model_vision.criterion = [criterion for _ in range(25)] +for criterion, num_classes in zip( + model.model_vision.criterion, + [ + 1000, + ] + * 25, +): + criterion.num_classes = num_classes + + +model.model_vision.stuff_dataset_learn_thing = False +model.model_vision.stuff_prob_thing = -1.0 + +model.model_vision.instance_on = True +model.model_vision.semantic_on = True +model.model_vision.panoptic_on = False + +model.model_vision.neck = None + +train.max_iter = 720000 +train.eval_period = 720000 + +lr_multiplier = L(WarmupParamScheduler)( + scheduler=L(MultiStepParamScheduler)( + values=[1.0, 0.1], + milestones=[640000], + num_updates=720000, + ), + warmup_length=1000 / 720000, + warmup_method="linear", + warmup_factor=0.001, +) + +for i in range(len(dataloader.train)): + dataloader.train[i].total_batch_size = 16 + dataloader.train[i].total_batch_size_list = [16] + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [x.dataset.names.replace("_val", "") for x in dataloader.tests] +model.model_vision.dataset_metas = [x.dataset.names for x in dataloader.tests] + + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + stable_softmax_2d=True, + clamp_min_for_underflow=True, + clamp_max_for_overflow=True, + use_checkpoint=True, +) + +model.model_vision.text_feature_bank = True +model.model_vision.text_feature_reduce_before_fusion = True +model.model_vision.text_feature_batch_repeat = True +model.model_vision.expression_cumulative_gt_class = True +model.model_vision.name_prompt_fusion_type = "zero" + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 12800 + +train.output_dir = "output/" + __file__[:-3] + + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..cce2bfe18fe3b078358166a9417c743668c48b4f --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep.py @@ -0,0 +1,20 @@ +from ...COCO_InstanceSegmentation.ape_deta.ape_deta_r50_12ep import ( + lr_multiplier, + model, + optimizer, + train, +) +from ...common.data.vgregion_instance import dataloader + +model.model_vision.num_classes = 200 + +model.model_vision.criterion[0].num_classes = 200 + +dataloader.train.mapper.max_num_phrase = 100 + +model.model_vision.dataset_prompts = ["phrase", "expression"] +model.model_vision.dataset_names = ["vgregion", "refcoco"] +model.model_vision.dataset_metas = dataloader.train.dataset.names + ["refcoco-mixed"] + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 1280 diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc51482401207da941dce8bb6054359b5a4f9f3 --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw13.py @@ -0,0 +1,10 @@ +from ...common.data.odinw13_instance import dataloader +from .ape_deta_r50_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0a68150e8b3a322c09b9535ca4bd447302c93f --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_12ep_eval_odinw35.py @@ -0,0 +1,10 @@ +from ...common.data.odinw35_instance import dataloader +from .ape_deta_r50_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f6e6d337b8483f9c94eb30774fbe4993b27fc2 --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep.py @@ -0,0 +1,46 @@ +from detectron2.config import LazyCall as L +from omegaconf import OmegaConf +from ape.layers import VisionLanguageFusion +from ape.modeling.ape_deta import ( + DeformableDETRSegmVL, + DeformableDetrTransformerDecoderVL, + DeformableDetrTransformerEncoderVL, + DeformableDetrTransformerVL, +) + +from .ape_deta_r50_12ep import dataloader, lr_multiplier, model, optimizer, train + +model.model_vision.update( + _target_=DeformableDETRSegmVL, +) +model.model_vision.transformer.update( + _target_=DeformableDetrTransformerVL, +) +model.model_vision.transformer.encoder.update( + _target_=DeformableDetrTransformerEncoderVL, +) +model.model_vision.transformer.decoder.update( + _target_=DeformableDetrTransformerDecoderVL, +) + + +model.model_vision.transformer.encoder.vl_layer = L(VisionLanguageFusion)( + v_dim="${....embed_dim}", + l_dim="${....embed_dim_language}", + embed_dim=2048, + num_heads=8, + dropout=0.1, + drop_path=0.0, + init_values=1.0 / 6, + cfg=OmegaConf.from_dotlist( + [ + "MODEL.DYHEAD.FUSE_CONFIG.STABLE_SOFTMAX_2D=False", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MIN_FOR_UNDERFLOW=True", + "MODEL.DYHEAD.FUSE_CONFIG.CLAMP_MAX_FOR_OVERFLOW=True", + "MODEL.VL_FUSION_USE_CHECKPOINT=True", + ], + ), +) + +train.output_dir = "output/" + __file__[:-3] +model.model_vision.vis_period = 1280 diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py new file mode 100644 index 0000000000000000000000000000000000000000..e017fae82e703156d858b0937ee3ae040620c634 --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw13.py @@ -0,0 +1,10 @@ +from ...common.data.odinw13_instance import dataloader +from .ape_deta_r50_vlf_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py new file mode 100644 index 0000000000000000000000000000000000000000..e09309f978cbb10fdc0a2868c7eb7fb2c6045f72 --- /dev/null +++ b/approach/ovod/APE/configs/VisualGenome_VisualGrounding/ape_deta/ape_deta_r50_vlf_12ep_eval_odinw35.py @@ -0,0 +1,10 @@ +from ...common.data.odinw35_instance import dataloader +from .ape_deta_r50_vlf_12ep import lr_multiplier, model, optimizer, train + +model.model_vision.dataset_prompts = ["name" for _ in dataloader.tests] +model.model_vision.dataset_names = [ + test.dataset.names.replace("_val", "") for test in dataloader.tests +] +model.model_vision.dataset_metas = [test.dataset.names for test in dataloader.tests] + +train.output_dir = "output/" + __file__[:-3] diff --git a/approach/ovod/APE/configs/common/data/ade20k_panoptic.py b/approach/ovod/APE/configs/common/data/ade20k_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..f8211593b5c2a5145c6a031c9c34ad5f496cb212 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/ade20k_panoptic.py @@ -0,0 +1,81 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOPanopticEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_panoptic +from ape.evaluation import InstanceSegEvaluator + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_panoptic_train"), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("ade20k_panoptic_train").ignore_label, + stuff_classes_offset=0, + stuff_classes_decomposition=True, + dataset_names="${..dataset.names}", + ), + total_batch_size=16, + aspect_ratio_grouping=True, + num_workers=16, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_panoptic_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = [ + L(InstanceSegEvaluator)( + dataset_name="${...test.dataset.names}", + ), + L(SemSegEvaluator)( + dataset_name="${...test.dataset.names}", + ), + L(COCOPanopticEvaluator)( + dataset_name="${...test.dataset.names}", + ), +] diff --git a/approach/ovod/APE/configs/common/data/ade20k_panoptic_lsj1024.py b/approach/ovod/APE/configs/common/data/ade20k_panoptic_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..5f619a56289c5fe7427ecd378205b5c75195da08 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/ade20k_panoptic_lsj1024.py @@ -0,0 +1,72 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOPanopticEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_panoptic +from ape.evaluation import InstanceSegEvaluator + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_panoptic_train"), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("ade20k_panoptic_train").ignore_label, + stuff_classes_offset=0, + stuff_classes_decomposition=True, + dataset_names="${..dataset.names}", + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_panoptic_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = [ + L(InstanceSegEvaluator)( + dataset_name="${...test.dataset.names}", + ), + L(SemSegEvaluator)( + dataset_name="${...test.dataset.names}", + ), + L(COCOPanopticEvaluator)( + dataset_name="${...test.dataset.names}", + ), +] diff --git a/approach/ovod/APE/configs/common/data/ade20k_semantic.py b/approach/ovod/APE/configs/common/data/ade20k_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9f713536bcd942d1dff30b073ff8f1feac3255 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/ade20k_semantic.py @@ -0,0 +1,68 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_semantic + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_sem_seg_train"), + mapper=L(DatasetMapper_detr_semantic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ignore_label=MetadataCatalog.get("ade20k_sem_seg_train").ignore_label, + stuff_classes_decomposition=True, + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_sem_seg_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(SemSegEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/ade20k_semantic_lsj1024.py b/approach/ovod/APE/configs/common/data/ade20k_semantic_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7c45fc960b5792471878273e3b357a21290481 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/ade20k_semantic_lsj1024.py @@ -0,0 +1,60 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_semantic + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_sem_seg_train"), + mapper=L(DatasetMapper_detr_semantic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ignore_label=MetadataCatalog.get("ade20k_sem_seg_train").ignore_label, + stuff_classes_decomposition=True, + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="ade20k_sem_seg_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(SemSegEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/bdd10k_semantic_lsj1024.py b/approach/ovod/APE/configs/common/data/bdd10k_semantic_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..ab31a6ce9b6847f4a8bf57e06c78bf72f4d5a00f --- /dev/null +++ b/approach/ovod/APE/configs/common/data/bdd10k_semantic_lsj1024.py @@ -0,0 +1,65 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_panoptic + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="bdd10k_val_sem_seg"), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("bdd10k_val_sem_seg").ignore_label, + stuff_classes_offset=0, + stuff_classes_decomposition=True, + dataset_names=["bdd10k_val_sem_seg"], + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="bdd10k_val_sem_seg", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = [ + L(SemSegEvaluator)( + dataset_name="${...test.dataset.names}", + ), +] diff --git a/approach/ovod/APE/configs/common/data/coco_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/coco_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..15c257cdd84c07eeaa86d8654080d9a5bb01c3c1 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/coco_instance_lsj1024.py @@ -0,0 +1,67 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("coco_2017_train",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=4, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="coco_2017_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(COCOEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=100, +) diff --git a/approach/ovod/APE/configs/common/data/coco_refcoco_instance.py b/approach/ovod/APE/configs/common/data/coco_refcoco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..c2850a53bc3eb141148da56367f23a97ddde755a --- /dev/null +++ b/approach/ovod/APE/configs/common/data/coco_refcoco_instance.py @@ -0,0 +1,116 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance_exp, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=( + "coco_2017_train", + "refcoco-mixed", + ), + filter_emptys=[True, True], + ), + mapper=L(DatasetMapper_detr_instance_exp)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + dataset_names=( + "coco_2017_train", + "refcoco-mixed", + ), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + num_workers=4, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="coco_2017_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(COCOEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=100, +) + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators = [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/coco_sa1b_instance.py b/approach/ovod/APE/configs/common/data/coco_sa1b_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..46b60ef11eb9d70670141e443b3c048d7901ccc6 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/coco_sa1b_instance.py @@ -0,0 +1,96 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator, COCOPanopticEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.data.samplers import MultiDatasetTrainingSampler + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=( + "coco_2017_train", + "sa1b_4m", + ), + filter_emptys=[True, False], + ), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=80, + dataset_names=["coco_2017_train", "sa1b"], + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[False, False], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + num_workers=4, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="coco_2017_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(COCOEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/constants.py b/approach/ovod/APE/configs/common/data/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..3aaa07cfbdea56ca8bc8436db5f1209a4c86c179 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/constants.py @@ -0,0 +1,4 @@ +constants = dict( + openai_imagenet_rgb256_mean=[122.7709383, 116.7460125, 104.09373615000001], + openai_imagenet_rgb256_std=[68.5005327, 66.6321579, 70.32316304999999], +) diff --git a/approach/ovod/APE/configs/common/data/d3_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/d3_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..239d3f40e15bf69da2b2a56b9fabc56e1a05286f --- /dev/null +++ b/approach/ovod/APE/configs/common/data/d3_instance_lsj1024.py @@ -0,0 +1,100 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.data.catalog import DatasetCatalog +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import D3Evaluator + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("d3_inter_scenario",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=4, + num_datasets=1, +) + +dataloader.tests = [] +dataloader.evaluators = [] + +dataloader.tests.append( + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="d3_intra_scenario", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) +) + +dataloader.evaluators.append( + [ + L(D3Evaluator)(dataset_name="d3_intra_scenario", max_dets_per_image=100, mode="FULL"), + L(D3Evaluator)(dataset_name="d3_intra_scenario", max_dets_per_image=100, mode="PRES"), + L(D3Evaluator)(dataset_name="d3_intra_scenario", max_dets_per_image=100, mode="ABS"), + ] +) + +dataloader.tests.append( + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="d3_inter_scenario", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) +) + +dataloader.evaluators.append( + [ + L(D3Evaluator)(dataset_name="d3_inter_scenario", max_dets_per_image=100, mode="FULL"), + L(D3Evaluator)(dataset_name="d3_inter_scenario", max_dets_per_image=100, mode="PRES"), + L(D3Evaluator)(dataset_name="d3_inter_scenario", max_dets_per_image=100, mode="ABS"), + ] +) + +DatasetCatalog.get("d3_intra_scenario") +DatasetCatalog.get("d3_inter_scenario") diff --git a/approach/ovod/APE/configs/common/data/grit_instance_lsj224.py b/approach/ovod/APE/configs/common/data/grit_instance_lsj224.py new file mode 100644 index 0000000000000000000000000000000000000000..7b248261827878c6f0a4094797c0dc0e892a0b6e --- /dev/null +++ b/approach/ovod/APE/configs/common/data/grit_instance_lsj224.py @@ -0,0 +1,103 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +image_size = 224 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("grit",), + filter_emptys=[True], + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + dataset_names=("grit",), + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=2, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="refcoco-unc-val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(RefCOCOEvaluator)( + dataset_name="${..test.dataset.names}", +) + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names[1:] +] + +dataloader.evaluators = [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names[1:] +] diff --git a/approach/ovod/APE/configs/common/data/grit_sa1b_instance.py b/approach/ovod/APE/configs/common/data/grit_sa1b_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..2fdddb15f6de6b6a9e03c39b5899a2f95f6b4b90 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/grit_sa1b_instance.py @@ -0,0 +1,130 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("grit_16_snappy", "sa1b_4m"), + filter_emptys=[True, False], + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + dataset_names=( + "grit", + "sa1b", + ), + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[True, True], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + num_workers=4, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="refcoco-unc-val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(RefCOCOEvaluator)( + dataset_name="${..test.dataset.names}", +) + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names[1:] +] + +dataloader.evaluators = [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names[1:] +] diff --git a/approach/ovod/APE/configs/common/data/lvis_sa1b_instance.py b/approach/ovod/APE/configs/common/data/lvis_sa1b_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..9226d8ddf21e8410f3a9c4e7150bfc11f55ca28c --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lvis_sa1b_instance.py @@ -0,0 +1,95 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import LVISEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.data.samplers import MultiDatasetTrainingSampler + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("lvis_v1_train", "sa1b_4m"), + filter_emptys=[True, False], + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + dataset_names=( + "lvis_v1_train", + "sa1b", + ), + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[True, True], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + num_workers=8, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) diff --git a/approach/ovod/APE/configs/common/data/lviscoco_cocostuff_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscoco_cocostuff_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..8c4953f716bb4cebfa92781e5849c93f7fe7e5d0 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscoco_cocostuff_panoptic_lsj1024_cp.py @@ -0,0 +1,121 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=["lvis_v1_train+coco", "coco_2017_train_panoptic_stuffonly"], + filter_emptys=[True, False], + copypastes=[True, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=0, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=["lvis_v1_train+coco", "coco_2017_train_panoptic_stuffonly"], + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[True, False], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + aspect_ratio_grouping=True, + num_workers=4, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vg_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vg_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..1662d6852d21b4ca526816415ab9cf5ef14bb8a0 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vg_panoptic_lsj1024_cp.py @@ -0,0 +1,235 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_150_box_train", + ), + filter_emptys=[True, True, True, True], + copypastes=[True, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names="${..dataset.names}", + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=4, + dataset_ratio=[1, 1, 1, 1], + use_rfs=[True, True, True, True], + use_cas=[False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=4, + num_datasets=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_minival", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) +] + +dataloader.evaluators += [ + L(LVISEvaluator)( + dataset_name="lvis_v1_minival", + max_dets_per_image=300, + ) +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="objects365_minival_fixname", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_minival_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="visualgenome_150_box_val", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="visualgenome_150_box_val", + tasks=("bbox",), + ), +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_group_by_image_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_group_by_image_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb7675c91e46577026c16350d0d7c4b30b9ddac --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_group_by_image_panoptic_lsj1024_cp.py @@ -0,0 +1,207 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "refcoco-mixed_group-by-image", + ), + filter_emptys=[True, True, True, True, True], + copypastes=[True, False, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names="${..dataset.names}", + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=5, + dataset_ratio=[1, 1, 1, 1, 0.1], + use_rfs=[True, True, True, False, False], + use_cas=[False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=4, + num_datasets=5, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..57e9524dbb277b5b7579c907cfde359cca1e6cc6 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_refcoco_panoptic_lsj1024_cp.py @@ -0,0 +1,211 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "refcoco-mixed", + ), + filter_emptys=[True, True, True, True, True], + copypastes=[True, False, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=[ + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "refcoco-mixed", + ], + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=5, + dataset_ratio=[1, 1, 1, 1, 1], + use_rfs=[True, True, True, False, False], + use_cas=[False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=4, + num_datasets=5, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..9246c05dc507575ef0bc76610ed5ca4acd4729cd --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1024_cp.py @@ -0,0 +1,217 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region", + ), + filter_emptys=[True, True, True, True, False, True, True], + copypastes=[True, False, False, False, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=[ + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region", + ], + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=7, + dataset_ratio=[1, 1, 1, 1, 1, 0.2, 0.1], + use_rfs=[True, True, True, False, False, False, False], + use_cas=[False, False, False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=2, + num_datasets=7, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1536_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1536_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f5b66478c16145356743a5e2a052e2ccecce99 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_panoptic_lsj1536_cp.py @@ -0,0 +1,217 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1536 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region", + ), + filter_emptys=[True, True, True, True, False, True, True], + copypastes=[True, False, False, False, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=[ + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region", + ], + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=7, + dataset_ratio=[1, 1, 1, 1, 1, 0.2, 0.1], + use_rfs=[True, True, True, False, False, False, False], + use_cas=[False, False, False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=2, + num_datasets=7, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..4703f0a1e5aea609a0b4ee8993748ebf30cd6689 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp.py @@ -0,0 +1,257 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b_6m", + "refcoco-mixed_group-by-image", + "gqa_region_train", + "phrasecut_train", + "flickr30k_separateGT_train", + ), + filter_emptys=[True, True, True, True, False, True, True, True, True], + copypastes=[True, False, False, False, False, False, False, False, False], + reduce_memory=True, + reduce_memory_size=1e6, + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names="${..dataset.names}", + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=9, + dataset_ratio=[1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1], + use_rfs=[True, True, True, False, False, False, False, False, False], + use_cas=[False, False, False, False, False, False, False, False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=2, + num_datasets=9, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_minival", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) +] + +dataloader.evaluators += [ + L(LVISEvaluator)( + dataset_name="lvis_v1_minival", + max_dets_per_image=300, + ) +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="objects365_minival_fixname", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_minival_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl.py new file mode 100644 index 0000000000000000000000000000000000000000..450c2ef67fb7a7af6d6d728bbf930abe57d83112 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1024_cp_mdl.py @@ -0,0 +1,266 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = [ + L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=(dataset_name,), + filter_emptys=[use_filter], + copypastes=[use_cp], + dataloader_id=dataloader_id, + reduce_memory=True, + reduce_memory_size=1e6, + ), + dataset_bg=L(get_detection_dataset_dicts)( + names=(dataset_name,), + filter_empty=use_filter, + ) + if use_cp + else [[]], + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get(dataset_name).get("ignore_label", None), + stuff_classes_offset=len(MetadataCatalog.get(dataset_name).get("thing_classes", [])), + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=(dataset_name,), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=L(RepeatFactorTrainingSampler)( + repeat_factors=L(RepeatFactorTrainingSampler.repeat_factors_from_category_frequency)( + dataset_dicts="${...dataset}", repeat_thresh=0.001 + ) + ) + if use_rfs + else None, + sampler_bg=L(RepeatFactorTrainingSampler)( + repeat_factors=L(RepeatFactorTrainingSampler.repeat_factors_from_category_frequency)( + dataset_dicts="${...dataset}", repeat_thresh=0.001 + ) + ) + if use_rfs and use_cp + else None, + total_batch_size=16, + total_batch_size_list=[16], + aspect_ratio_grouping=True, + num_workers=2, + num_datasets=1, + ) + for dataloader_id, use_rfs, use_cp, use_filter, dataset_name in [ + [0, True, True, True, "lvis_v1_train+coco_panoptic_separated"], + [1, True, False, True, "objects365_train_fixname"], + [2, True, False, True, "openimages_v6_train_bbox_nogroup"], + [3, False, False, True, "visualgenome_77962_box_and_region"], + [4, False, False, False, "sa1b"], + [5, False, False, True, "refcoco-mixed_group-by-image"], + [6, False, False, True, "gqa_region_train"], + [7, False, False, True, "phrasecut_train"], + [8, False, False, True, "flickr30k_separateGT_train"], + ] +] + + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_minival", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) +] + +dataloader.evaluators += [ + L(LVISEvaluator)( + dataset_name="lvis_v1_minival", + max_dets_per_image=300, + ) +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="objects365_minival_fixname", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_minival_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..68f5b770ba09c65dbb699f9f26694b10584a0498 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_o365_oid_vgr_sa1b_refcoco_group_by_image_gqa_phrasecut_flickr30k_panoptic_lsj1536_cp.py @@ -0,0 +1,231 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import COCOEvaluator, LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator +from ape.evaluation.oideval import OIDEvaluator + +dataloader = OmegaConf.create() + +image_size = 1536 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region_train", + "phrasecut_train", + "flickr30k_separateGT_train", + ), + filter_emptys=[True, True, True, True, False, True, True, True, True], + copypastes=[True, False, False, False, False, False, False, False, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=[ + "lvis_v1_train+coco_panoptic_separated", + "objects365_train_fixname", + "openimages_v6_train_bbox_nogroup", + "visualgenome_77962_box_and_region", + "sa1b", + "refcoco-mixed_group-by-image", + "gqa_region_train", + "phrasecut_train", + "flickr30k_separateGT_train", + ], + max_num_phrase=100, + nms_thresh_phrase=0.6, + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=9, + dataset_ratio=[1, 1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1], + use_rfs=[True, True, True, False, False, False, False, False, False], + use_cas=[ + False, + False, + False, + False, + False, + False, + False, + False, + False, + ], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16, 16, 16, 16, 16, 16, 16, 16], + aspect_ratio_grouping=True, + num_workers=2, + num_datasets=9, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(COCOEvaluator)( + dataset_name="objects365_val_fixname", + tasks=("bbox",), + ), +] + +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="openimages_v6_val_bbox", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators += [ + L(OIDEvaluator)( + dataset_name="openimages_v6_val_bbox", + ), +] + + + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_refcoco_panoptic_lsj1024_cp.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_refcoco_panoptic_lsj1024_cp.py new file mode 100644 index 0000000000000000000000000000000000000000..28c9cf51b4ba708a01d92ec2ee36dbacb20983ad --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_refcoco_panoptic_lsj1024_cp.py @@ -0,0 +1,155 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.data.samplers import RepeatFactorTrainingSampler +from detectron2.evaluation import LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset_copypaste, +) +from ape.data.samplers import MultiDatasetTrainingSampler +from ape.evaluation import RefCOCOEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=("lvis_v1_train+coco_panoptic_separated", "refcoco-mixed"), + filter_emptys=[True, True], + copypastes=[True, False], + ), + dataset_bg=L(get_detection_dataset_dicts)(names=["lvis_v1_train+coco_panoptic_separated"]), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=["lvis_v1_train+coco_panoptic_separated", "refcoco-mixed"], + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[True, False], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + sampler_bg=lambda dataset_dicts: RepeatFactorTrainingSampler( + repeat_factors=RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( + dataset_dicts=dataset_dicts, repeat_thresh=0.001 + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + aspect_ratio_grouping=True, + num_workers=4, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests += [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names +] + +dataloader.evaluators += [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/lviscocococostuff_sa1b_panoptic.py b/approach/ovod/APE/configs/common/data/lviscocococostuff_sa1b_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..74e254e7c1b2867b87206eb3db950308e1747a28 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/lviscocococostuff_sa1b_panoptic.py @@ -0,0 +1,120 @@ +import random + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import LVISEvaluator, SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.data.samplers import MultiDatasetTrainingSampler + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=( + "lvis_v1_train+coco_panoptic_separated", + "sa1b_4m", + ), + filter_emptys=[True, False], + ), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get("coco_2017_train_panoptic_stuffonly").ignore_label, + stuff_classes_offset=1203, + stuff_classes_decomposition=True, + dataset_names=["lvis_v1_train+coco_panoptic_separated", "sa1b"], + ), + sampler=lambda dataset_dicts: MultiDatasetTrainingSampler( + repeat_factors=MultiDatasetTrainingSampler.get_repeat_factors( + dataset_dicts=dataset_dicts, + num_datasets=2, + dataset_ratio=[1, 1], + use_rfs=[True, True], + use_cas=[False, False], + repeat_thresh=0.001, + cas_lambda=1.0, + ), + seed=random.randint(0, 2**31), + ), + total_batch_size=16, + total_batch_size_list=[16, 16], + num_workers=8, + num_datasets=2, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="lvis_v1_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(LVISEvaluator)( + dataset_name="${..test.dataset.names}", + max_dets_per_image=300, +) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="coco_2017_val_panoptic_stuffonly", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ), +] + +dataloader.evaluators = [ + L(SemSegEvaluator)( + dataset_name="coco_2017_val_panoptic_stuffonly", + ), +] diff --git a/approach/ovod/APE/configs/common/data/o365_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/o365_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..e792ea6933a399ab42d60f302780663b24fd191b --- /dev/null +++ b/approach/ovod/APE/configs/common/data/o365_instance_lsj1024.py @@ -0,0 +1,66 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("objects365_train_fixname",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=4, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="objects365_val_fixname", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(COCOEvaluator)( + dataset_name="${..test.dataset.names}", + tasks=("bbox",), +) diff --git a/approach/ovod/APE/configs/common/data/odinw13_instance.py b/approach/ovod/APE/configs/common/data/odinw13_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..36881a2547585414450f5b98c8f163ebde0b0ce1 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/odinw13_instance.py @@ -0,0 +1,165 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset, + get_detection_dataset_dicts_multi_dataset_copypaste, +) + +dataloader = OmegaConf.create() + +odinw_dataset_metas = [ + "odinw_AerialMaritimeDrone_large_train", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_train", + "odinw_CottontailRabbits_train", + "odinw_EgoHands_generic_train", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_train", + "odinw_Packages_Raw_train", + "odinw_PascalVOC_train", + "odinw_pistols_export_train", + "odinw_pothole_train", + "odinw_Raccoon_Raccoon.v2-raw.coco_train", + "odinw_ShellfishOpenImages_raw_train", + "odinw_thermalDogsAndPeople_train", + "odinw_VehiclesOpenImages_416x416_train", +] + +dataloader.train = [ + L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=(dataset_name,), + filter_emptys=[True], + dataloader_id=dataloader_id, + reduce_memory=True, + reduce_memory_size=1e6, + ), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get(dataset_name).get("ignore_label", None), + stuff_classes_offset=len(MetadataCatalog.get(dataset_name).get("thing_classes", [])), + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=(dataset_name,), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=None, + total_batch_size=16, + total_batch_size_list=[16], + aspect_ratio_grouping=True, + num_workers=16, + num_datasets=1, + ) + for dataloader_id, dataset_name in enumerate(odinw_dataset_metas) +] + +odinw_test_dataset_names = [ + "odinw_AerialMaritimeDrone_large_test", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_test", + "odinw_CottontailRabbits_test", + "odinw_EgoHands_generic_test", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_test", + "odinw_Packages_Raw_test", + "odinw_PascalVOC_val", + "odinw_pistols_export_test", + "odinw_pothole_test", + "odinw_Raccoon_Raccoon.v2-raw.coco_test", + "odinw_ShellfishOpenImages_raw_test", + "odinw_thermalDogsAndPeople_test", + "odinw_VehiclesOpenImages_416x416_test", +] + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in odinw_test_dataset_names +] + +dataloader.name_prompt_fusion_text = [ + True, + True, + False, + False, + True, + True, + False, + False, + True, + True, + False, + True, + False, +] + +dataloader.select_box_nums_for_evaluation_list = [ + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, +] + +dataloader.evaluators = [ + L(COCOEvaluator)( + dataset_name=name, + tasks=("bbox",), + ) + for name in odinw_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..390d7c77d833966fde4a78ed5559987dbd120eb8 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1024.py @@ -0,0 +1,245 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset, + get_detection_dataset_dicts_multi_dataset_copypaste, +) + +dataloader = OmegaConf.create() + +image_size = 1024 + +odinw_dataset_metas = [ + "odinw_AerialMaritimeDrone_large_train", + "odinw_AerialMaritimeDrone_tiled_train", + "odinw_AmericanSignLanguageLetters_American_Sign_Language_Letters.v1-v1.coco_train", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_train", + "odinw_BCCD_BCCD.v3-raw.coco_train", + "odinw_boggleBoards_416x416AutoOrient_export_train", + "odinw_brackishUnderwater_960x540_train", + "odinw_ChessPieces_Chess_Pieces.v23-raw.coco_train", + "odinw_CottontailRabbits_train", + "odinw_dice_mediumColor_export_train", + "odinw_DroneControl_Drone_Control.v3-raw.coco_train", + "odinw_EgoHands_generic_train", + "odinw_EgoHands_specific_train", + "odinw_HardHatWorkers_raw_train", + "odinw_MaskWearing_raw_train", + "odinw_MountainDewCommercial_train", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_train", + "odinw_openPoetryVision_512x512_train", + "odinw_OxfordPets_by-breed_train", + "odinw_OxfordPets_by-species_train", + "odinw_Packages_Raw_train", + "odinw_PascalVOC_train", + "odinw_pistols_export_train", + "odinw_PKLot_640_train", + "odinw_plantdoc_416x416_train", + "odinw_pothole_train", + "odinw_Raccoon_Raccoon.v2-raw.coco_train", + "odinw_selfdrivingCar_fixedLarge_export_train", + "odinw_ShellfishOpenImages_raw_train", + "odinw_ThermalCheetah_train", + "odinw_thermalDogsAndPeople_train", + "odinw_UnoCards_raw_train", + "odinw_VehiclesOpenImages_416x416_train", + "odinw_websiteScreenshots_train", + "odinw_WildfireSmoke_train", +] + +dataloader.train = [ + L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=(dataset_name,), + filter_emptys=[True], + dataloader_id=dataloader_id, + reduce_memory=True, + reduce_memory_size=1e6, + ), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get(dataset_name).get("ignore_label", None), + stuff_classes_offset=len(MetadataCatalog.get(dataset_name).get("thing_classes", [])), + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=(dataset_name,), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=None, + total_batch_size=16, + total_batch_size_list=[16], + aspect_ratio_grouping=True, + num_workers=16, + num_datasets=1, + ) + for dataloader_id, dataset_name in enumerate(odinw_dataset_metas) +] + +odinw_test_dataset_names = [ + "odinw_AerialMaritimeDrone_large_test", + "odinw_AerialMaritimeDrone_tiled_test", + "odinw_AmericanSignLanguageLetters_American_Sign_Language_Letters.v1-v1.coco_test", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_test", + "odinw_BCCD_BCCD.v3-raw.coco_test", + "odinw_boggleBoards_416x416AutoOrient_export_test", + "odinw_brackishUnderwater_960x540_test", + "odinw_ChessPieces_Chess_Pieces.v23-raw.coco_test", + "odinw_CottontailRabbits_test", + "odinw_dice_mediumColor_export_test", + "odinw_DroneControl_Drone_Control.v3-raw.coco_test", + "odinw_EgoHands_generic_test", + "odinw_EgoHands_specific_test", + "odinw_HardHatWorkers_raw_test", + "odinw_MaskWearing_raw_test", + "odinw_MountainDewCommercial_test", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_test", + "odinw_openPoetryVision_512x512_test", + "odinw_OxfordPets_by-breed_test", + "odinw_OxfordPets_by-species_test", + "odinw_Packages_Raw_test", + "odinw_PascalVOC_val", + "odinw_pistols_export_test", + "odinw_PKLot_640_test", + "odinw_plantdoc_416x416_test", + "odinw_pothole_test", + "odinw_Raccoon_Raccoon.v2-raw.coco_test", + "odinw_selfdrivingCar_fixedLarge_export_test", + "odinw_ShellfishOpenImages_raw_test", + "odinw_ThermalCheetah_test", + "odinw_thermalDogsAndPeople_test", + "odinw_UnoCards_raw_test", + "odinw_VehiclesOpenImages_416x416_test", + "odinw_websiteScreenshots_test", + "odinw_WildfireSmoke_test", +] + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in odinw_test_dataset_names +] + +dataloader.name_prompt_fusion_text = [ + True, + False, + True, + True, + True, + True, + True, + True, + False, + False, + True, + False, + False, + True, + True, + True, + True, + True, + True, + True, + True, + False, + False, + False, + True, + True, + True, + True, + False, + False, + True, + True, + False, + True, + True, +] + +dataloader.select_box_nums_for_evaluation_list = [ + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 1, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, +] + +dataloader.evaluators = [ + L(COCOEvaluator)( + dataset_name=name, + tasks=("bbox",), + ) + for name in odinw_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1536.py b/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1536.py new file mode 100644 index 0000000000000000000000000000000000000000..9a604abf22fbbf5163b90b81b97854576764c587 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/odinw35_instance_lsj1536.py @@ -0,0 +1,244 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset, + get_detection_dataset_dicts_multi_dataset_copypaste, +) + +dataloader = OmegaConf.create() + +image_size = 1536 + +odinw_dataset_metas = [ + "odinw_AerialMaritimeDrone_large_train", + "odinw_AerialMaritimeDrone_tiled_train", + "odinw_AmericanSignLanguageLetters_American_Sign_Language_Letters.v1-v1.coco_train", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_train", + "odinw_BCCD_BCCD.v3-raw.coco_train", + "odinw_boggleBoards_416x416AutoOrient_export_train", + "odinw_brackishUnderwater_960x540_train", + "odinw_ChessPieces_Chess_Pieces.v23-raw.coco_train", + "odinw_CottontailRabbits_train", + "odinw_dice_mediumColor_export_train", + "odinw_DroneControl_Drone_Control.v3-raw.coco_train", + "odinw_EgoHands_generic_train", + "odinw_EgoHands_specific_train", + "odinw_HardHatWorkers_raw_train", + "odinw_MaskWearing_raw_train", + "odinw_MountainDewCommercial_train", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_train", + "odinw_openPoetryVision_512x512_train", + "odinw_OxfordPets_by-breed_train", + "odinw_OxfordPets_by-species_train", + "odinw_Packages_Raw_train", + "odinw_PascalVOC_train", + "odinw_pistols_export_train", + "odinw_PKLot_640_train", + "odinw_plantdoc_416x416_train", + "odinw_pothole_train", + "odinw_Raccoon_Raccoon.v2-raw.coco_train", + "odinw_selfdrivingCar_fixedLarge_export_train", + "odinw_ShellfishOpenImages_raw_train", + "odinw_ThermalCheetah_train", + "odinw_thermalDogsAndPeople_train", + "odinw_UnoCards_raw_train", + "odinw_VehiclesOpenImages_416x416_train", + "odinw_websiteScreenshots_train", + "odinw_WildfireSmoke_train", +] + +dataloader.train = [ + L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=(dataset_name,), + filter_emptys=[True], + dataloader_id=dataloader_id, + reduce_memory=True, + reduce_memory_size=1e6, + ), + mapper=L(DatasetMapper_detr_panoptic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get(dataset_name).get("ignore_label", None), + stuff_classes_offset=len(MetadataCatalog.get(dataset_name).get("thing_classes", [])), + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=(dataset_name,), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=None, + total_batch_size=16, + total_batch_size_list=[16], + aspect_ratio_grouping=True, + num_workers=16, + num_datasets=1, + ) + for dataloader_id, dataset_name in enumerate(odinw_dataset_metas) +] + +odinw_test_dataset_names = [ + "odinw_AerialMaritimeDrone_large_test", + "odinw_AerialMaritimeDrone_tiled_test", + "odinw_AmericanSignLanguageLetters_American_Sign_Language_Letters.v1-v1.coco_test", + "odinw_Aquarium_Aquarium_Combined.v2-raw-1024.coco_test", + "odinw_BCCD_BCCD.v3-raw.coco_test", + "odinw_boggleBoards_416x416AutoOrient_export_test", + "odinw_brackishUnderwater_960x540_test", + "odinw_ChessPieces_Chess_Pieces.v23-raw.coco_test", + "odinw_CottontailRabbits_test", + "odinw_dice_mediumColor_export_test", + "odinw_DroneControl_Drone_Control.v3-raw.coco_test", + "odinw_EgoHands_generic_test", + "odinw_EgoHands_specific_test", + "odinw_HardHatWorkers_raw_test", + "odinw_MaskWearing_raw_test", + "odinw_MountainDewCommercial_test", + "odinw_NorthAmericaMushrooms_North_American_Mushrooms.v1-416x416.coco_test", + "odinw_openPoetryVision_512x512_test", + "odinw_OxfordPets_by-breed_test", + "odinw_OxfordPets_by-species_test", + "odinw_Packages_Raw_test", + "odinw_PascalVOC_val", + "odinw_pistols_export_test", + "odinw_PKLot_640_test", + "odinw_plantdoc_416x416_test", + "odinw_pothole_test", + "odinw_Raccoon_Raccoon.v2-raw.coco_test", + "odinw_selfdrivingCar_fixedLarge_export_test", + "odinw_ShellfishOpenImages_raw_test", + "odinw_ThermalCheetah_test", + "odinw_thermalDogsAndPeople_test", + "odinw_UnoCards_raw_test", + "odinw_VehiclesOpenImages_416x416_test", + "odinw_websiteScreenshots_test", + "odinw_WildfireSmoke_test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in odinw_test_dataset_names +] + +dataloader.name_prompt_fusion_text = [ + True, + False, + True, + True, + True, + True, + True, + True, + False, + False, + True, + False, + False, + True, + True, + True, + True, + True, + True, + True, + True, + False, + False, + False, + True, + True, + True, + True, + False, + False, + True, + True, + False, + True, + True, +] + +dataloader.select_box_nums_for_evaluation_list = [ + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 1, + 300, + 300, + 300, + 300, + 300, + 300, + 300, + 300, +] + +dataloader.evaluators = [ + L(COCOEvaluator)( + dataset_name=name, + tasks=("bbox",), + ) + for name in odinw_test_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/pascalcontext59_semantic_lsj1024.py b/approach/ovod/APE/configs/common/data/pascalcontext59_semantic_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..66bc6435d59ba5e0df7d81a8504a4cefe2766732 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/pascalcontext59_semantic_lsj1024.py @@ -0,0 +1,62 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_semantic + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="pascal_context_59_sem_seg_val"), + mapper=L(DatasetMapper_detr_semantic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ignore_label=MetadataCatalog.get("pascal_context_59_sem_seg_val").ignore_label, + stuff_classes_decomposition=True, + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)( + names="pascal_context_59_sem_seg_val", filter_empty=False + ), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(SemSegEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/pascalvoc20_semantic_lsj1024.py b/approach/ovod/APE/configs/common/data/pascalvoc20_semantic_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..f8119aeaf2c27f6379a9e70f8eed4c2c45fdc1b3 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/pascalvoc20_semantic_lsj1024.py @@ -0,0 +1,60 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import SemSegEvaluator +from omegaconf import OmegaConf +from ape.data import DatasetMapper_detr_semantic + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader)( + dataset=L(get_detection_dataset_dicts)(names="pascalvoc20_sem_seg_val"), + mapper=L(DatasetMapper_detr_semantic)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + ignore_label=MetadataCatalog.get("pascalvoc20_sem_seg_val").ignore_label, + stuff_classes_decomposition=True, + ), + total_batch_size=16, + num_workers=4, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="pascalvoc20_sem_seg_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(SemSegEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/phrasecut_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/phrasecut_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..6e07dcb64a766f480e29b9384c4d98a66254851c --- /dev/null +++ b/approach/ovod/APE/configs/common/data/phrasecut_instance_lsj1024.py @@ -0,0 +1,70 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + DatasetMapper_detr_instance_exp, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +dataloader = OmegaConf.create() + +image_size = 1024 + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("phrasecut_train",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance_exp)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + dataset_names=("phrasecut_train",), + max_num_phrase=256, + nms_thresh_phrase=0.6, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=4, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="phrasecut_val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(RefCOCOEvaluator)( + dataset_name="${..test.dataset.names}", +) diff --git a/approach/ovod/APE/configs/common/data/refcoco_group_by_image_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/refcoco_group_by_image_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..94b532b291ab4467491e91044d7018d05032e970 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/refcoco_group_by_image_instance_lsj1024.py @@ -0,0 +1,102 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +image_size = 1024 + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("refcoco-mixed_group-by-image",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=1.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(horizontal=True), # flip first + L(T.ResizeScale)( + min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size + ), + L(T.FixedSizeCrop)(crop_size=(image_size, image_size), pad=False), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + dataset_names=("refcoco-mixed_group-by-image",), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=4, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="refcoco-unc-val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(RefCOCOEvaluator)( + dataset_name="${..test.dataset.names}", +) + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=image_size, max_size=image_size), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names[1:] +] + +dataloader.evaluators = [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names[1:] +] diff --git a/approach/ovod/APE/configs/common/data/refcoco_instance.py b/approach/ovod/APE/configs/common/data/refcoco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..924940f438844cb892ae6255b43b1322d00510c8 --- /dev/null +++ b/approach/ovod/APE/configs/common/data/refcoco_instance.py @@ -0,0 +1,107 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + build_detection_test_loader, + build_detection_train_loader, + get_detection_dataset_dicts, +) +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_instance_exp, + build_detection_train_loader_multi_dataset, + get_detection_dataset_dicts_multi_dataset, +) +from ape.evaluation import RefCOCOEvaluator + +dataloader = OmegaConf.create() + +dataloader.train = L(build_detection_train_loader_multi_dataset)( + dataset=L(get_detection_dataset_dicts_multi_dataset)( + names=("refcoco-mixed",), filter_emptys=[True] + ), + mapper=L(DatasetMapper_detr_instance_exp)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + dataset_names=("refcoco-mixed",), + ), + total_batch_size=16, + total_batch_size_list=[16], + num_workers=16, + num_datasets=1, +) + +dataloader.test = L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="refcoco-unc-val", filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${...train.mapper.image_format}", + ), + num_workers=4, +) + +dataloader.evaluator = L(RefCOCOEvaluator)( + dataset_name="${..test.dataset.names}", +) + +refcoco_test_dataset_names = [ + "refcoco-unc-val", + "refcoco-unc-testA", + "refcoco-unc-testB", + "refcocoplus-unc-val", + "refcocoplus-unc-testA", + "refcocoplus-unc-testB", + "refcocog-google-val", + "refcocog-umd-val", + "refcocog-umd-test", +] +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="${....train.mapper.image_format}", + ), + num_workers=4, + ) + for name in refcoco_test_dataset_names[1:] +] + +dataloader.evaluators = [ + L(RefCOCOEvaluator)( + dataset_name=name, + ) + for name in refcoco_test_dataset_names[1:] +] diff --git a/approach/ovod/APE/configs/common/data/roboflow100_instance_lsj1024.py b/approach/ovod/APE/configs/common/data/roboflow100_instance_lsj1024.py new file mode 100644 index 0000000000000000000000000000000000000000..b7367088743c8df14147a090a4fc99f88a1db2ac --- /dev/null +++ b/approach/ovod/APE/configs/common/data/roboflow100_instance_lsj1024.py @@ -0,0 +1,76 @@ +import json +import os + +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import DatasetMapper, build_detection_test_loader, get_detection_dataset_dicts +from detectron2.data.datasets.register_coco import register_coco_instances +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf + +dataloader = OmegaConf.create() + +data_root = "datasets/rf100" + +rf100_dataset_names = [] +for root, dirs, files in os.walk(data_root): + for d in dirs: + if root == data_root: + pass + else: + continue + + rf100_dataset_names.append(d) + + d = os.path.join(root, d) + print(len(rf100_dataset_names), d) +print(rf100_dataset_names, len(rf100_dataset_names)) +assert len(rf100_dataset_names) == 100 + + +def _get_builtin_metadata(name): + meta = {} + json_file = os.path.join(data_root, name, "valid", "_annotations.coco.json") + with open(json_file, "r") as fr: + json_data = json.load(fr) + meta["thing_classes"] = [category["name"] for category in json_data["categories"]] + + return meta + + +for key in rf100_dataset_names: + print("register_coco_instances", key) + register_coco_instances( + "rf100_" + key, + _get_builtin_metadata(key), + os.path.join(data_root, key, "valid", "_annotations.coco.json"), + os.path.join(data_root, key, "valid"), + ) + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names="rf100_" + name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=1024, max_size=1024), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in rf100_dataset_names +] + +dataloader.name_prompt_fusion_text = [True] * len(rf100_dataset_names) + + +dataloader.select_box_nums_for_evaluation_list = [300] * len(rf100_dataset_names) + +dataloader.evaluators = [ + L(COCOEvaluator)( + dataset_name="rf100_" + name, + tasks=("bbox",), + ) + for name in rf100_dataset_names +] diff --git a/approach/ovod/APE/configs/common/data/seginw_instance.py b/approach/ovod/APE/configs/common/data/seginw_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..741efe7769d804841e1bd6897e86febfb5476a7f --- /dev/null +++ b/approach/ovod/APE/configs/common/data/seginw_instance.py @@ -0,0 +1,162 @@ +import detectron2.data.transforms as T +from detectron2.config import LazyCall as L +from detectron2.data import ( + DatasetMapper, + MetadataCatalog, + build_detection_test_loader, + get_detection_dataset_dicts, +) +from detectron2.evaluation import COCOEvaluator +from omegaconf import OmegaConf +from ape.data import ( + DatasetMapper_detr_panoptic, + DatasetMapper_detr_panoptic_copypaste, + build_detection_train_loader_multi_dataset, + build_detection_train_loader_multi_dataset_copypaste, + get_detection_dataset_dicts_multi_dataset, + get_detection_dataset_dicts_multi_dataset_copypaste, +) + +dataloader = OmegaConf.create() + +seginw_dataset_metas = [ + "seginw_Elephants_train", + "seginw_Hand-Metal_train", + "seginw_Watermelon_train", + "seginw_House-Parts_train", + "seginw_HouseHold-Items_train", + "seginw_Strawberry_train", + "seginw_Fruits_train", + "seginw_Nutterfly-Squireel_train", + "seginw_Hand_train", + "seginw_Garbage_train", + "seginw_Chicken_train", + "seginw_Rail_train", + "seginw_Airplane-Parts_train", + "seginw_Brain-Tumor_train", + "seginw_Poles_train", + "seginw_Electric-Shaver_train", + "seginw_Bottles_train", + "seginw_Toolkits_train", + "seginw_Trash_train", + "seginw_Salmon-Fillet_train", + "seginw_Puppies_train", + "seginw_Tablets_train", + "seginw_Phones_train", + "seginw_Cows_train", + "seginw_Ginger-Garlic_train", +] + +dataloader.train = [ + L(build_detection_train_loader_multi_dataset_copypaste)( + dataset=L(get_detection_dataset_dicts_multi_dataset_copypaste)( + names=(dataset_name,), + filter_emptys=[True], + copypastes=[True], + dataloader_id=dataloader_id, + reduce_memory=True, + reduce_memory_size=1e6, + ), + dataset_bg=L(get_detection_dataset_dicts)( + names=(dataset_name,), + filter_empty=True, + ), + mapper=L(DatasetMapper_detr_panoptic_copypaste)( + is_train=True, + augmentations=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + augmentations_with_crop=[ + L(T.RandomFlip)(), + L(T.ResizeShortestEdge)( + short_edge_length=(400, 500, 600), + sample_style="choice", + ), + L(T.RandomCrop)( + crop_type="absolute_range", + crop_size=(384, 600), + ), + L(T.ResizeShortestEdge)( + short_edge_length=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), + max_size=1333, + sample_style="choice", + ), + ], + image_format="RGB", + use_instance_mask=True, + recompute_boxes=True, + instance_mask_format="bitmask", + ignore_label=MetadataCatalog.get(dataset_name).get("ignore_label", None), + stuff_classes_offset=len(MetadataCatalog.get(dataset_name).get("thing_classes", [])), + stuff_classes_decomposition=True, + output_dir=None, + vis_period=12800, + dataset_names=(dataset_name,), + max_num_phrase=128, + nms_thresh_phrase=0.6, + ), + sampler=None, + sampler_bg=None, + total_batch_size=16, + total_batch_size_list=[16], + aspect_ratio_grouping=True, + num_workers=16, + num_datasets=1, + ) + for dataloader_id, dataset_name in enumerate(seginw_dataset_metas) +] + +seginw_test_dataset_names = [ + "seginw_Elephants_val", + "seginw_Hand-Metal_val", + "seginw_Watermelon_val", + "seginw_House-Parts_val", + "seginw_HouseHold-Items_val", + "seginw_Strawberry_val", + "seginw_Fruits_val", + "seginw_Nutterfly-Squireel_val", + "seginw_Hand_val", + "seginw_Garbage_val", + "seginw_Chicken_val", + "seginw_Rail_val", + "seginw_Airplane-Parts_val", + "seginw_Brain-Tumor_val", + "seginw_Poles_val", + "seginw_Electric-Shaver_val", + "seginw_Bottles_val", + "seginw_Toolkits_val", + "seginw_Trash_val", + "seginw_Salmon-Fillet_val", + "seginw_Puppies_val", + "seginw_Tablets_val", + "seginw_Phones_val", + "seginw_Cows_val", + "seginw_Ginger-Garlic_val", +] + +dataloader.tests = [ + L(build_detection_test_loader)( + dataset=L(get_detection_dataset_dicts)(names=name, filter_empty=False), + mapper=L(DatasetMapper)( + is_train=False, + augmentations=[ + L(T.ResizeShortestEdge)(short_edge_length=800, max_size=1333), + ], + image_format="RGB", + ), + num_workers=4, + ) + for name in seginw_test_dataset_names +] + +dataloader.evaluators = [ + L(COCOEvaluator)( + dataset_name=name, + ) + for name in seginw_test_dataset_names +] diff --git a/approach/ovod/APE/inference_on_image.sh b/approach/ovod/APE/inference_on_image.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f527d454f566ebbd38538fc551a296d46acecba --- /dev/null +++ b/approach/ovod/APE/inference_on_image.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +python demo/demo_lazy.py \ +--config-file configs/LVISCOCOCOCOSTUFF_O365_OID_VGR_SA1B_REFCOCO_GQA_PhraseCut_Flickr30k/ape_deta/ape_deta_vitl_eva02_clip_vlf_lsj1024_cp_16x4_1080k.py \ +--input demo/examples/Pisa.jpg \ +--output ./test_output \ +--confidence-threshold 0.1 \ +--text-prompt 'sky' \ +--with-box \ +--opts \ +train.init_checkpoint='./ape_d_model_final.pth' \ +model.model_language.cache_dir='' \ +model.model_vision.select_box_nums_for_evaluation=500 \ +model.model_vision.text_feature_bank_reset=True \ +model.model_vision.backbone.net.xattn=False \ +model.model_vision.transformer.encoder.pytorch_attn=True \ +model.model_vision.transformer.decoder.pytorch_attn=True \ No newline at end of file diff --git a/approach/ovod/APE/requirements.txt b/approach/ovod/APE/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7221c7870b15e16e4793dcb9117e49cef69e0d47 --- /dev/null +++ b/approach/ovod/APE/requirements.txt @@ -0,0 +1,14 @@ +torch +torchvision +transformers +cython +opencv-python +scipy +einops +lvis +fairscale +xformers +apex +git+https://github.com/facebookresearch/detectron2@017abbf +git+https://github.com/IDEA-Research/detrex@776058e +git+https://github.com/openai/CLIP.git@d50d76d diff --git a/approach/ovod/APE/setup.py b/approach/ovod/APE/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e227b36fd2d82d8764927a849f53b4c6e55af68e --- /dev/null +++ b/approach/ovod/APE/setup.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# Copyright (c) Facebook, Inc. and its affiliates. + +import glob +import os +import shutil +from os import path +from typing import List + +import torch +from setuptools import find_packages, setup +from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension + +torch_ver = [int(x) for x in torch.__version__.split(".")[:2]] +assert torch_ver >= [1, 8], "Requires PyTorch >= 1.8" + + +def get_version(): + init_py_path = path.join(path.abspath(path.dirname(__file__)), "ape", "__init__.py") + init_py = open(init_py_path, "r").readlines() + version_line = [l.strip() for l in init_py if l.startswith("__version__")][0] + version = version_line.split("=")[-1].strip().strip("'\"") + + # The following is used to build release packages. + # Users should never use it. + suffix = os.getenv("D2_VERSION_SUFFIX", "") + version = version + suffix + if os.getenv("BUILD_NIGHTLY", "0") == "1": + from datetime import datetime + + date_str = datetime.today().strftime("%y%m%d") + version = version + ".dev" + date_str + + new_init_py = [l for l in init_py if not l.startswith("__version__")] + new_init_py.append('__version__ = "{}"\n'.format(version)) + with open(init_py_path, "w") as f: + f.write("".join(new_init_py)) + return version + + +def get_extensions(): + this_dir = path.dirname(path.abspath(__file__)) + extensions_dir = path.join(this_dir, "ape", "layers", "csrc") + + main_source = path.join(extensions_dir, "vision.cpp") + sources = glob.glob(path.join(extensions_dir, "**", "*.cpp")) + + from torch.utils.cpp_extension import ROCM_HOME + + is_rocm_pytorch = ( + True if ((torch.version.hip is not None) and (ROCM_HOME is not None)) else False + ) + if is_rocm_pytorch: + assert torch_ver >= [1, 8], "ROCM support requires PyTorch >= 1.8!" + + # common code between cuda and rocm platforms, for hipify version [1,0,0] and later. + source_cuda = glob.glob(path.join(extensions_dir, "**", "*.cu")) + glob.glob( + path.join(extensions_dir, "*.cu") + ) + sources = [main_source] + sources + + extension = CppExtension + + extra_compile_args = {"cxx": []} + define_macros = [] + + if (torch.cuda.is_available() and ((CUDA_HOME is not None) or is_rocm_pytorch)) or os.getenv( + "FORCE_CUDA", "0" + ) == "1": + extension = CUDAExtension + sources += source_cuda + + if not is_rocm_pytorch: + define_macros += [("WITH_CUDA", None)] + extra_compile_args["nvcc"] = [ + "-O3", + "-DCUDA_HAS_FP16=1", + "-D__CUDA_NO_HALF_OPERATORS__", + "-D__CUDA_NO_HALF_CONVERSIONS__", + "-D__CUDA_NO_HALF2_OPERATORS__", + ] + else: + define_macros += [("WITH_HIP", None)] + extra_compile_args["nvcc"] = [] + + nvcc_flags_env = os.getenv("NVCC_FLAGS", "") + if nvcc_flags_env != "": + extra_compile_args["nvcc"].extend(nvcc_flags_env.split(" ")) + + if torch_ver < [1, 7]: + # supported by https://github.com/pytorch/pytorch/pull/43931 + CC = os.environ.get("CC", None) + if CC is not None: + extra_compile_args["nvcc"].append("-ccbin={}".format(CC)) + + include_dirs = [extensions_dir] + + ext_modules = [ + extension( + "ape._C", + sources, + include_dirs=include_dirs, + define_macros=define_macros, + extra_compile_args=extra_compile_args, + ) + ] + + return ext_modules + + +def get_model_zoo_configs() -> List[str]: + """ + Return a list of configs to include in package for model zoo. Copy over these configs inside + detectron2/model_zoo. + """ + + # Use absolute paths while symlinking. + source_configs_dir = path.join(path.dirname(path.realpath(__file__)), "configs") + destination = path.join(path.dirname(path.realpath(__file__)), "ape", "model_zoo", "configs") + # Symlink the config directory inside package to have a cleaner pip install. + + # Remove stale symlink/directory from a previous build. + if path.exists(source_configs_dir): + if path.islink(destination): + os.unlink(destination) + elif path.isdir(destination): + shutil.rmtree(destination) + + if not path.exists(destination): + try: + os.symlink(source_configs_dir, destination) + except OSError: + # Fall back to copying if symlink fails: ex. on Windows. + shutil.copytree(source_configs_dir, destination) + + config_paths = glob.glob("configs/**/*.yaml", recursive=True) + glob.glob( + "configs/**/*.py", recursive=True + ) + return config_paths + + +# For projects that are relative small and provide features that are very close +# to detectron2's core functionalities, we install them under detectron2.projects +PROJECTS = { +} + +setup( + name="ape", + version=get_version(), + author="Yunhang Shen", + url="https://github.com/shenyunhang", + description="APE is next-generation research " + "framework for object detection and segmentation.", + packages=find_packages(exclude=("configs", "tests*")) + list(PROJECTS.keys()), + package_dir=PROJECTS, + package_data={"ape.model_zoo": get_model_zoo_configs(), "ape.modeling.text.eva02_clip": ["*.gz", "**/*.json"], "ape.modeling.text.eva01_clip": ["*.gz", "**/*.json"]}, + python_requires=">=3.7", + install_requires=[ + ], + ext_modules=get_extensions(), + cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension}, +) diff --git a/approach/ovod/d-cube/LICENSE b/approach/ovod/d-cube/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67846aa0c4d75d272acbec5d9f4fc91fdfe05bc4 --- /dev/null +++ b/approach/ovod/d-cube/LICENSE @@ -0,0 +1,352 @@ +Creative Commons Attribution-NonCommercial 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 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 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. 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. + - d. 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. + - e. 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. + - f. Licensed Material means the artistic or literary work, + database, or other material to which the Licensor applied this + Public License. + - g. 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. + - h. Licensor means the individual(s) or entity(ies) granting + rights under this Public License. + - i. 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. + - j. 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. + - k. 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. + - l. 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. 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. + - 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + +- 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; + 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. diff --git a/approach/ovod/d-cube/doc.md b/approach/ovod/d-cube/doc.md new file mode 100644 index 0000000000000000000000000000000000000000..bcee034f1c995c62b4b90c25e873a2463fb6415b --- /dev/null +++ b/approach/ovod/d-cube/doc.md @@ -0,0 +1,275 @@ +# $D^3$ Toolkit Documentation + + +## Table of Contents + +- [Inference](#inference-on-d3) +- [Key Concepts](#key-concepts-for-users) +- [Evaluation Settings](#evaluation-settings) +- [Evaluation Code and Examples](#evaluation-code-and-examples) +- [Dataset statistics](#dataset-statistics) + + + + +## Inference on $D^3$ + +```python +# import the dataset class +from d_cube import D3 +# init a dataset instance +d3 = D3(IMG_ROOT, PKL_ANNO_PATH) +all_img_ids = d3.get_img_ids() # get the image ids in the dataset +all_img_info = d3.load_imgs(all_img_ids) # load images by passing a list containing some image ids +img_path = all_img_info[0]["file_name"] # obtain one image path so you can load it and inference +# then you can load the image as input for your model + +group_ids = d3.get_group_ids(img_ids=[img_id]) # get the group ids by passing anno ids, image ids, etc. +sent_ids = d3.get_sent_ids(group_ids=group_ids) # get the sentence ids by passing image ids, group ids, etc. +sent_list = d3.load_sents(sent_ids=sent_ids) +ref_list = [sent['raw_sent'] for sent in sent_list] # list[str] +# use these language references in `ref_list` as the references to your REC/OVD/DOD model + +# save the result to a JSON file +``` + +Concepts and structures of `anno`, `image`, `sent` and `group` are explained in [this part](#key-concepts-for-users). + +In [this directory](eval_sota/) we provide the inference (and evaluation) script on some existing SOTA OVD/REC methods. + + + +### Output Format +When the inference is done, you need to save a JSON file in the format below (COCO standard output JSON form): +```json +[ + { + "category_id": "int, the value of sent_id, range [1, 422]", + "bbox": "list[int], [x1, y1, w, h], predicted by your model, same as COCO result format, absolute value in the range of [w, h, w, h]", + "image_id": "int, img_id, can be 0, 1, 2, ....", + "score": "float, predicted by your model, no restriction on its absolute value range" + } +] +``` +This JSON file should contain a list, where each item in the list is a dictionary of one detection result. + +With this JSON saved, you can evaluate the JSON in the next step. See [the evaluation step](#evaluation-code-and-examples). + + + + + +## Key Concepts for Users + +### `anno` +A Python dictionary where the keys are integers and the values are dictionaries with the following key-value pairs: + +* `id`: an integer representing the ID of the annotation. +* `sent_id`: a list of integers representing the IDs of sentences associated with this annotation. +* `segmentation`: a Run Length Encoding (RLE) representation of the annotation. +* `area`: an integer representing the area of the annotation. +* `iscrowd`: an integer indicating whether this annotation represents a crowd or not. +* `image_id`: an integer representing the ID of the image associated with this annotation. +* `bbox`: a list of four integers representing the bounding box coordinates of the annotation in the format [x, y, width, height]. +* `group_id`: a value that can be any object and represents the ID of the group associated with this annotation. + +``` python +{ + 1 : { + "id": int, + "sent_id": list, + "segmentation": RLE, + "area": int, + "iscrowd": int, + "image_id": int, + "bbox": list, # [x, y, width, height] + "group_id": int + } +} +``` + +### `image` +A Python dictionary where the keys are integers and the values are dictionaries with the following key-value pairs: + +* `id`: an integer representing the ID of the image. +* `file_name`: a string representing the file name of the image. +* `height`: an integer representing the height of the image. +* `width`: an integer representing the width of the image. +* `flickr_url`: a string representing the Flickr URL of the image. +* `anno_id`: a list of integers representing the IDs of annotations associated with this image. +* `group_id`: an integer representing the ID of the group associated with this image. +* `license`: a string representing the license of the image. + +``` python +{ + int : { + "id": int, + "file_name": str, + "height": int, + "width": int, + "flickr_url": str, + "anno_id": list, + "group_id": int, + "license": str, + } +} +``` + +### `sent` +A Python dictionary where the keys are integers and the values are dictionaries with the following key-value pairs: + +* `id`: an integer representing the ID of the sentence. +* `anno_id`: a list of integers representing the IDs of annotations associated with this sentence. +* `group_id`: a list of integers representing the IDs of groups associated with this sentence. +* `is_negative`: a boolean indicating whether this sentence is *absence expression* or not. `True` means *absence expression*. +* `raw_sent`: a string representing the raw text of the sentence in English. +* `raw_sent_zh`: a string representing the raw text of the sentence in Chinese. + +``` python +{ + int : { + "id": int, + "anno_id": list, + "group_id": list, + "is_negative": bool, + "raw_sent": str, + "raw_sent_zh": str + } +} +``` + +### `group` +A Python dictionary where the keys are integers and the values are dictionaries with the following key-value pairs: + +* `id`: an integer representing the ID of the group. +* `pos_sent_id`: a list of integers representing the IDs of sentences that has referred obejct in the group. +* `inner_sent_id`: a list of integers representing the IDs of sentences belonging to this group. +* `outer_sent_id`: a list of integers representing the IDs of outer-group sentences that has referred obejct in the group. +* `img_id`: a list of integers representing the IDs of images of this group. +* `scene`: a list of strings representing the scenes of this group. +* `group_name`: a string representing the name of this group in English. +* `group_name_zh`: a string representing the name of this group in Chinese. + +``` python +{ + int : { + "id": int, + "pos_sent_id": list, + "inner_sent_id": list, + "outer_sent_id": list, + "img_id": list, + "scene": list, + "group_name": str, + "group_name_zh": str + } +} +``` + + + + + +## Evaluation Settings + + +### Intra- or Inter-Group Settings + +The default evaluation protocol is the intra-group setting, where only a certain references are evaluated for each image. + +In the $D^3$ dataset, images are collected for different groups (scenarios), and the categories (descriptions) are designed based on the scenarios. For the intra-group setting, each image are only evaluated with the descriptions from the group the image belongs to. We call this **intra-scenario setting**. + +Note that each category is actually annotated on each image (with positive or negative instances). +So you can also evaluate all categories on all images, just like traditional detection datasets. We call this **inter-scenario setting**. +This is quite challenging for the DOD task as this will produce many false positive instances on current methods. + +For intra-group evaluation, you should use: +``` +sent_ids = d3.get_sent_ids(group_ids=group_ids) +# only get the refs (sents) for the group the image belongs to, which is usually 4 +``` + +For inter-group evaluation, change the correponding code to: + +``` +sent_ids = d3.get_sent_ids() +# get all the refs in the dataset +``` + +This will use all the sentences in the dataset, rather than a few sentences in the group that this image belongs to. + +This is the only difference in the implentation and evaluation. No further code changes need to be applied. + +For more information, you can refer to the Section 3.4 of the DOD paper. + + +### FULL, PRES and ABS + +FULL, PRES and ABS means the full descriptions (422 categories), presence descriptions (316 categories) and absence descriptions (106 categories). + +The meaning of absence descriptions are the descriptions involving the absence of some concepts, like lacking certain relationships, attributes or objects. For example, descriptions like "dog *without* leash", "person *without* helmet" and "a hat that is *not* blue" are absence ones. +Similary, the descriptions involving *only* the presence of some concepts are presence descriptions. + +Most existing REC datasets have presence descriptions but few absence descriptions. + +For more details and the meaning of evaluating absence descriptions, please refer to Section 3.1 of the DOD paper. + + + + +## Evaluation Code and Examples + +In this part, we introduce how to evaluate the performance and get the metric values given the prediction result of a JSON file. + +### Write a Snippet in Your Code + +This is based on [cocoapi (pycocotools)](https://github.com/cocodataset/cocoapi/tree/master/PythonAPI), and is quite simple: + +```python +from pycocotools.coco import COCO +from pycocotools.cocoeval import COCOeval + +# Eval results +coco = COCO(gt_path) # `gt_path` is the ground-truth JSON path (different JSON for FULL, PRES or ABS settings in our paper) +d3_model = coco.loadRes(pred_path) # `pred_path` is the prediction JSON file +cocoEval = COCOeval(coco, d3_model, "bbox") +cocoEval.evaluate() +cocoEval.accumulate() +cocoEval.summarize() +``` + +### An Off-the-shelf Script + +We also provide [a script](scripts/eval_and_analysis_json.py) that can produce the evaluation results (and some additional analysis) in our paper, given a prediction JSON. +You can use it by: +```shell +python eval_and_analysis_json.py YOUR_PREDICTION_JSON_PATH +``` + +A few options are provided for format conversion or more analysis: +```shell +python eval_and_analysis_json.py --help + +usage: An example script for $D^3$ evaluation with prediction file (JSON) [-h] [--partition-by-nbox] [--partition-by-lens] [--xyxy2xywh] pred_path + +positional arguments: + pred_path path to prediction json + +optional arguments: + -h, --help show this help message and exit + --partition-by-nbox divide the images by num of boxes for each ref + --partition-by-lens divide the references by their lengths + --xyxy2xywh transform box coords from xyxy to xywh +``` + + +### Evaluation Examples on SOTA Methods + +See [this directory](eval_sota/) for details. We include the evaluation scripts of some methods there. + + + +## Dataset Statistics + +[A python script](scripts/get_d3_stat.py) is provided for calculating the statistics of $D^3$ or visualizing figures like histograms, word clouds, etc. + +The specific statistics of the dataset are available in Section 3.3 of the DOD paper. diff --git a/approach/ovod/mm-ovod/.gitmodules b/approach/ovod/mm-ovod/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..98d980505aae72f9291ebcfd19e82b3aa12822d2 --- /dev/null +++ b/approach/ovod/mm-ovod/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third_party/CenterNet2"] + path = third_party/CenterNet2 + url = https://github.com/xingyizhou/CenterNet2.git diff --git a/approach/ovod/mm-ovod/README.md b/approach/ovod/mm-ovod/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0177519514a9d4f09620d36652d64e4362678cff --- /dev/null +++ b/approach/ovod/mm-ovod/README.md @@ -0,0 +1,38 @@ +# Multi-Modal Classifiers for Open-Vocabulary Object Detection + +

+ +> [**Multi-Modal Classifiers for Open Vocabulary Object Detection**](https://arxiv.org/abs/2306.05493), +> Prannay Kaul, Weidi Xie, Andrew Zisserman +> *ICML 2023 ([arXiv 2201.02605](https://arxiv.org/abs/2306.05493))* + + +## Updates + +- **June 2023** Code and checkpoints for LVIS models in the main paper are released. Training code for visual aggregator to follow soon. + + +## Installation + +See [installation instructions](docs/INSTALL.md). + + +## Benchmark evaluation and training + +Please first [prepare datasets](datasets/README.md), then check our [MODEL ZOO](docs/MODEL_ZOO.md) to reproduce results in our paper. + + +## License + +See [Detic](https://github.com/facebookresearch/Detic). Our code is based on this repository. + +## Citation + +If you find this project useful for your research, please use the following BibTeX entry. + + @inproceedings{Kaul2023, + title={Multi-Modal Classifiers for Open-Vocabulary Object Detection}, + author={Kaul, Prannay and Xie, Weidi and Zisserman, Andrew}, + booktitle={ICML}, + year={2023} + } diff --git a/approach/ovod/mm-ovod/requirements.txt b/approach/ovod/mm-ovod/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..58595e6b4fec4b3d76d9c56199a95a96f39ca2c6 --- /dev/null +++ b/approach/ovod/mm-ovod/requirements.txt @@ -0,0 +1,13 @@ +opencv-python +mss +timm==0.5.4 +dataclasses +ftfy +regex +fasttext +scikit-learn +lvis +nltk +openai +numpy==1.23.3 +git+https://github.com/openai/CLIP.git diff --git a/approach/ovod/mm-ovod/train_net_auto.py b/approach/ovod/mm-ovod/train_net_auto.py new file mode 100644 index 0000000000000000000000000000000000000000..bead06a63d1faf86f878853a2481c632187ca7f8 --- /dev/null +++ b/approach/ovod/mm-ovod/train_net_auto.py @@ -0,0 +1,343 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +import logging +import os +import sys +from collections import OrderedDict +import torch +from torch.nn.parallel import DistributedDataParallel +import time +import datetime +from typing import Any + +from fvcore.common.timer import Timer +from iopath.common.file_io import PathManager +import detectron2.utils.comm as comm +from detectron2.checkpoint import ( + DetectionCheckpointer, PeriodicCheckpointer, Checkpointer +) +from detectron2.config import get_cfg +from detectron2.data import ( + MetadataCatalog, + build_detection_test_loader, +) +from detectron2.engine import default_argument_parser, default_setup, launch + +from detectron2.evaluation import ( + inference_on_dataset, + print_csv_format, + LVISEvaluator, + COCOEvaluator, +) +from detectron2.modeling import build_model +from detectron2.solver import build_lr_scheduler, build_optimizer +from detectron2.utils.events import ( + CommonMetricPrinter, + EventStorage, + JSONWriter, + TensorboardXWriter, +) +from detectron2.data.dataset_mapper import DatasetMapper +from detectron2.data.build import build_detection_train_loader +from detectron2.utils.logger import setup_logger +from torch.cuda.amp import GradScaler + +sys.path.insert(0, 'third_party/CenterNet2/') +from centernet.config import add_centernet_config + +from mmovod.config import add_mmovod_config +from mmovod.data.custom_build_augmentation import build_custom_augmentation +from mmovod.data.custom_dataset_dataloader import build_custom_train_loader +from mmovod.data.custom_dataset_mapper import CustomDatasetMapper +from mmovod.custom_solver import build_custom_optimizer +from mmovod.modeling.utils import reset_cls_test + + +logger = logging.getLogger("detectron2") + + +class LatestCheckpointer: + """ + Save checkpoints periodically. When `.step(iteration)` is called, it will + execute `checkpointer.save` on the given checkpointer, if iteration is a + multiple of period or if `max_iter` is reached. + + Attributes: + checkpointer (Checkpointer): the underlying checkpointer object + """ + + def __init__( + self, + checkpointer: Checkpointer, + period: int, + file_prefix: str = "model", + ) -> None: + """ + Args: + checkpointer: the checkpointer object used to save checkpoints. + period (int): the period to save checkpoint. + max_iter (int): maximum number of iterations. When it is reached, + a checkpoint named "{file_prefix}_final" will be saved. + max_to_keep (int): maximum number of most current checkpoints to keep, + previous checkpoints will be deleted + file_prefix (str): the prefix of checkpoint's filename + """ + self.checkpointer = checkpointer + self.period = int(period) + self.path_manager: PathManager = checkpointer.path_manager + self.file_prefix = file_prefix + + def step(self, iteration: int, **kwargs: Any) -> None: + """ + Perform the appropriate action at the given iteration. + + Args: + iteration (int): the current iteration, ranged in [0, max_iter-1]. + kwargs (Any): extra data to save, same as in + :meth:`Checkpointer.save`. + """ + iteration = int(iteration) + additional_state = {"iteration": iteration} + additional_state.update(kwargs) + + if (iteration + 1) % self.period == 0: + self.checkpointer.save( + f"{self.file_prefix}_latest", **additional_state + ) + + def save(self, name: str, **kwargs: Any) -> None: + """ + Same argument as :meth:`Checkpointer.save`. + Use this method to manually save checkpoints outside the schedule. + + Args: + name (str): file name. + kwargs (Any): extra data to save, same as in + :meth:`Checkpointer.save`. + """ + self.checkpointer.save(name, **kwargs) + + +def do_test(cfg, model): + results = OrderedDict() + for d, dataset_name in enumerate(cfg.DATASETS.TEST): + if cfg.MODEL.RESET_CLS_TESTS: + reset_cls_test( + model, + cfg.MODEL.TEST_CLASSIFIERS[d], + cfg.MODEL.TEST_NUM_CLASSES[d]) + mapper = None if cfg.INPUT.TEST_INPUT_TYPE == 'default' \ + else DatasetMapper( + cfg, False, augmentations=build_custom_augmentation(cfg, False)) + data_loader = build_detection_test_loader(cfg, dataset_name, mapper=mapper) + output_folder = os.path.join( + cfg.OUTPUT_DIR, "inference_{}".format(dataset_name)) + evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type + + if evaluator_type == "lvis" or cfg.GEN_PSEDO_LABELS: + evaluator = LVISEvaluator(dataset_name, cfg, True, output_folder) + elif evaluator_type == 'coco': + evaluator = COCOEvaluator(dataset_name, cfg, True, output_folder) + else: + assert 0, evaluator_type + + results[dataset_name] = inference_on_dataset( + model, data_loader, evaluator) + if comm.is_main_process(): + logger.info("Evaluation results for {} in csv format:".format( + dataset_name)) + print_csv_format(results[dataset_name]) + if len(results) == 1: + results = list(results.values())[0] + return results + + +def do_train(cfg, model, resume=False): + model.train() + if cfg.SOLVER.USE_CUSTOM_SOLVER: + optimizer = build_custom_optimizer(cfg, model) + else: + assert cfg.SOLVER.OPTIMIZER == 'SGD' + assert cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE != 'full_model' + assert cfg.SOLVER.BACKBONE_MULTIPLIER == 1. + optimizer = build_optimizer(cfg, model) + scheduler = build_lr_scheduler(cfg, optimizer) + logger.info("Following parameters will be trained:") + for n, p in model.named_parameters(): + if p.requires_grad: + logger.info("{}".format(n)) + + checkpointer = DetectionCheckpointer( + model, cfg.OUTPUT_DIR, optimizer=optimizer, scheduler=scheduler + ) + + start_iter = checkpointer.resume_or_load( + cfg.MODEL.WEIGHTS, resume=resume).get("iteration", -1) + 1 + if not resume: + start_iter = 0 + max_iter = cfg.SOLVER.MAX_ITER if cfg.SOLVER.TRAIN_ITER < 0 else cfg.SOLVER.TRAIN_ITER + + periodic_checkpointer = PeriodicCheckpointer( + checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD, max_iter=max_iter + ) + + latest_checkpointer = LatestCheckpointer( + checkpointer, 15000,) + + writers = ( + [ + CommonMetricPrinter(max_iter), + JSONWriter(os.path.join(cfg.OUTPUT_DIR, "metrics.json")), + TensorboardXWriter(cfg.OUTPUT_DIR), + ] + if comm.is_main_process() + else [] + ) + + use_custom_mapper = cfg.WITH_IMAGE_LABELS + MapperClass = CustomDatasetMapper if use_custom_mapper else DatasetMapper + mapper = MapperClass(cfg, True) if cfg.INPUT.CUSTOM_AUG == '' else \ + MapperClass(cfg, True, augmentations=build_custom_augmentation(cfg, True)) + if cfg.DATALOADER.SAMPLER_TRAIN in ['TrainingSampler', 'RepeatFactorTrainingSampler']: + data_loader = build_detection_train_loader(cfg, mapper=mapper) + else: + data_loader = build_custom_train_loader(cfg, mapper=mapper) + + if cfg.FP16: + scaler = GradScaler() + + logger.info("Starting training from iteration {}".format(start_iter)) + with EventStorage(start_iter) as storage: + step_timer = Timer() + data_timer = Timer() + start_time = time.perf_counter() + for data, iteration in zip(data_loader, range(start_iter, max_iter)): + data_time = data_timer.seconds() + storage.put_scalars(data_time=data_time) + step_timer.reset() + iteration = iteration + 1 + storage.step() + loss_dict = model(data) + + losses = sum( + loss for k, loss in loss_dict.items()) + assert torch.isfinite(losses).all(), loss_dict + + loss_dict_reduced = { + k: v.item() + for k, v in comm.reduce_dict(loss_dict).items() + } + losses_reduced = sum(loss for loss in loss_dict_reduced.values()) + if comm.is_main_process(): + storage.put_scalars( + total_loss=losses_reduced, **loss_dict_reduced) + + optimizer.zero_grad() + if cfg.FP16: + scaler.scale(losses).backward() + scaler.step(optimizer) + scaler.update() + else: + losses.backward() + optimizer.step() + + storage.put_scalar( + "lr", optimizer.param_groups[0]["lr"], smoothing_hint=False) + + step_time = step_timer.seconds() + storage.put_scalars(time=step_time) + data_timer.reset() + scheduler.step() + + if (cfg.TEST.EVAL_PERIOD > 0 + and iteration % cfg.TEST.EVAL_PERIOD == 0 + and iteration != max_iter): + do_test(cfg, model) + comm.synchronize() + + if (iteration - start_iter > 5 + and (iteration % 20 == 0 or iteration == max_iter)): + for writer in writers: + writer.write() + latest_checkpointer.step(iteration) + periodic_checkpointer.step(iteration) + + total_time = time.perf_counter() - start_time + logger.info( + "Total training time: {}".format( + str(datetime.timedelta(seconds=int(total_time))))) + + +def setup(args): + """ + Create configs and perform basic setups. + """ + cfg = get_cfg() + add_centernet_config(cfg) + add_mmovod_config(cfg) + cfg.merge_from_file(args.config_file) + cfg.merge_from_list(args.opts) + if '/auto' in cfg.OUTPUT_DIR: + if "configs/" in args.config_file: + new_sub_folder = args.config_file.replace("configs", "")[:-5] + new_output_dir = cfg.OUTPUT_DIR.replace("/auto", new_sub_folder) + cfg.OUTPUT_DIR = new_output_dir + else: + file_name = os.path.basename(args.config_file)[:-5] + cfg.OUTPUT_DIR = cfg.OUTPUT_DIR.replace('/auto', '/{}'.format(file_name)) + print(cfg.OUTPUT_DIR) + cfg.freeze() + default_setup(cfg, args) + setup_logger( + output=cfg.OUTPUT_DIR, distributed_rank=comm.get_rank(), name="mmovod") + return cfg + + +def main(args): + cfg = setup(args) + + model = build_model(cfg) + logger.info("Model:\n{}".format(model)) + if args.eval_only: + DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load( + cfg.MODEL.WEIGHTS, resume=args.resume + ) + + return do_test(cfg, model) + + distributed = comm.get_world_size() > 1 + if distributed: + model = DistributedDataParallel( + model, device_ids=[comm.get_local_rank()], broadcast_buffers=False, + find_unused_parameters=cfg.FIND_UNUSED_PARAM + ) + + do_train(cfg, model, resume=args.resume) + return do_test(cfg, model) + + +if __name__ == "__main__": + args = default_argument_parser() + args = args.parse_args() + if args.num_machines == 1: + args.dist_url = 'tcp://127.0.0.1:{}'.format( + torch.randint(11111, 60000, (1,))[0].item()) + else: + if args.dist_url == 'host': + args.dist_url = 'tcp://{}:12345'.format( + os.environ['SLURM_JOB_NODELIST']) + elif not args.dist_url.startswith('tcp'): + tmp = os.popen( + 'echo $(scontrol show job {} | grep BatchHost)'.format( + args.dist_url) + ).read() + tmp = tmp[tmp.find('=') + 1: -1] + args.dist_url = 'tcp://{}:12345'.format(tmp) + print("Command Line Args:", args) + launch( + main, + args.num_gpus, + num_machines=args.num_machines, + machine_rank=args.machine_rank, + dist_url=args.dist_url, + args=(args,), + ) diff --git a/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/1-usage.yaml b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/1-usage.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb4094e5ab241057019bf767e2fd7b7e9dfc7e7a --- /dev/null +++ b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/1-usage.yaml @@ -0,0 +1,31 @@ +name: Usage issues +description: Report issues in usage. +title: "[Usage] " +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this form. Please give as detailed description as possible for us to better assist with the issue :) + - type: textarea + id: what-happened + attributes: + label: Describe the issue + description: Please give as detailed description as possible for us to better assist with the issue. Please paste the **FULL** error log here, so that we can better understand the issue. Wrap the log with ``` for better readability in GitHub. + placeholder: Issue + value: | + Issue: + + Command: + ``` + PASTE THE COMMANDS HERE. + ``` + + Log: + ``` + PASTE THE LOGS HERE. + ``` + + Screenshots: + You may attach screenshots if it better explains the issue. + validations: + required: true diff --git a/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/2-feature-request.yaml b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/2-feature-request.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a55dc3136718f89096452e9a3018de23b5c385d9 --- /dev/null +++ b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/2-feature-request.yaml @@ -0,0 +1,13 @@ +name: Feature Request +description: Request for a new feature +title: "[Feature request] " +body: + - type: markdown + attributes: + value: | + Thanks for your interest in our work. Please share your thoughts of the new features below. + - type: textarea + id: feature + attributes: + label: feature + placeholder: Start your thoughts here... \ No newline at end of file diff --git a/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/3-question.yaml b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/3-question.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c4a4fc28f8ef61c6d5a4eca8f03a5c268998fcf --- /dev/null +++ b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/3-question.yaml @@ -0,0 +1,13 @@ +name: Questions +description: General questions about the work +title: "[Question] " +body: + - type: markdown + attributes: + value: | + Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :) + - type: textarea + id: question + attributes: + label: Question + placeholder: Start question here... \ No newline at end of file diff --git a/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/4-discussion.yaml b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/4-discussion.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6dc05c3d144d028eaf696b9518354f482d34a0f --- /dev/null +++ b/approach/vlm/LLaVA/.github/ISSUE_TEMPLATE/4-discussion.yaml @@ -0,0 +1,13 @@ +name: Discussions +description: General discussions about the work +title: "[Discussion] " +body: + - type: markdown + attributes: + value: | + Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :) + - type: textarea + id: discussion + attributes: + label: Discussion + placeholder: Start discussion here... \ No newline at end of file diff --git a/approach/vlm/LLaVA/docs/Customize_Component.md b/approach/vlm/LLaVA/docs/Customize_Component.md new file mode 100644 index 0000000000000000000000000000000000000000..e99a60879920b389799fb3a0baf1fd864ee0bccc --- /dev/null +++ b/approach/vlm/LLaVA/docs/Customize_Component.md @@ -0,0 +1,20 @@ +# Customize Components in LLaVA + +This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components. + +## LLM + +It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM. + +Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs. + +In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM. + +In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation. + +These are basically all the changes you need to make to replace the LLM. + +## Visual Encoder + +You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder. + diff --git a/approach/vlm/LLaVA/docs/Data.md b/approach/vlm/LLaVA/docs/Data.md new file mode 100644 index 0000000000000000000000000000000000000000..84807ec252858cd78bf96b3fce6f42f66b20126f --- /dev/null +++ b/approach/vlm/LLaVA/docs/Data.md @@ -0,0 +1,29 @@ +## Data + +| Data file name | Size | +| --- | ---: | +| [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB | +| [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB | +| [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB | +| [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB | +| [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB | + +### Pretraining Dataset +The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images. + +If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary. + +| Data | Chat File | Meta Data | Size | +| --- | --- | --- | ---: | +| CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB +| LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB + +**Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images. + +### GPT-4 Prompts + +We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning. + +They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output. + +Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed! diff --git a/approach/vlm/LLaVA/docs/LLaVA_Bench.md b/approach/vlm/LLaVA/docs/LLaVA_Bench.md new file mode 100644 index 0000000000000000000000000000000000000000..5921964c43f599b2d820de5092a1c3b4c39de60f --- /dev/null +++ b/approach/vlm/LLaVA/docs/LLaVA_Bench.md @@ -0,0 +1,31 @@ +# LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)] + +**-Introduction-** Large commercial multimodal chatbots have been released in this week, including +- [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023) +- [Multimodal Bard by Google](https://bard.google.com/). + +These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less unexplored how to evaluate multimodal chat ability, it provides useful feedback to study open-source LMMs against the commercial multimodal chatbots. In addition to the *LLaVA-Bench (COCO)* dataset we used to develop the early versions of LLaVA, we are releasing [*LLaVA-Bench (In-the-Wild)*](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to the community for the public use. + +## LLaVA-Bench (In-the-Wild *[Ongoing work]*) + +To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses. + +### Results + +The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results. + +| Approach | Conversation | Detail | Reasoning | Overall | +|----------------|--------------|--------|-----------|---------| +| Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 | +| Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 | +| LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 | +| LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 | + +Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans. + +| Approach | Conversation | Detail | Reasoning | Overall | +|----------------|--------------|--------|-----------|---------| +| Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 | +| Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 | +| LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 | +| LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 | diff --git a/approach/vlm/LLaVA/docs/LLaVA_from_LLaMA2.md b/approach/vlm/LLaVA/docs/LLaVA_from_LLaMA2.md new file mode 100644 index 0000000000000000000000000000000000000000..b4163668a33ff705c28f5b103b727514161e5652 --- /dev/null +++ b/approach/vlm/LLaVA/docs/LLaVA_from_LLaMA2.md @@ -0,0 +1,29 @@ +# LLaVA (based on Llama 2 LLM, Preview) + +*NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.* + +:llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use. + +You need to apply for and download the lastest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/)) + + +## Training + +Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh). + +## LLaVA (based on Llama 2), What is different? + +:volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described: +- **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2 +- **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2. +- **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied. + + +### Results + +- Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation +- The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability. + + + + diff --git a/approach/vlm/LLaVA/docs/LoRA.md b/approach/vlm/LLaVA/docs/LoRA.md new file mode 100644 index 0000000000000000000000000000000000000000..369fe92579051f98a0724a92e52e65e014a0de2f --- /dev/null +++ b/approach/vlm/LLaVA/docs/LoRA.md @@ -0,0 +1,46 @@ +# LLaVA (LoRA, Preview) + +NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us. + +You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base)) + +## Demo (Web UI) + +Please execute each of the command below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)). + +#### Launch a controller +```Shell +python -m llava.serve.controller --host 0.0.0.0 --port 10000 +``` + +#### Launch a gradio web server. +```Shell +python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload +``` +You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker. + +#### Launch a model worker +```Shell +python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1 +``` +Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list. + +You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker. + + +## Training + +Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh). + +We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same. + +If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning. + +## Create Merged Checkpoints + +```Shell +python scripts/merge_lora_weights.py \ + --model-path /path/to/lora_model \ + --model-base /path/to/base_model \ + --save-model-path /path/to/merge_model +``` diff --git a/approach/vlm/LLaVA/docs/MODEL_ZOO.md b/approach/vlm/LLaVA/docs/MODEL_ZOO.md new file mode 100644 index 0000000000000000000000000000000000000000..3faf9fab3bb6eeaf332ad172a0fe747a386d298f --- /dev/null +++ b/approach/vlm/LLaVA/docs/MODEL_ZOO.md @@ -0,0 +1,136 @@ +# Model Zoo + +**To Use LLaVA-1.5 checkpoints, your llava package version must be newer than 1.1.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.** + +If you are interested in including any other details in Model Zoo, please open an issue :) + +The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license: [Llama 2](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md). + +## LLaVA-v1.5 + +| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | T-VQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet | +|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---| +| LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 63.4 | 30.5 | +| LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 70.7 | 35.4 | +| LLaVA-1.5 | 7B | lora-1e | coming soon | +| LLaVA-1.5 | 13B | lora-1e | coming soon | + +

+
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks. +

+ + +## LLaVA-v1 + +*Note: We recommend using the most capable LLaVA-v1.5 series above for the best performance.* + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | LLaVA-Bench-Conv | LLaVA-Bench-Detail | LLaVA-Bench-Complex | LLaVA-Bench-Overall | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------| +| Vicuna-13B-v1.3 | CLIP-L-336px | LCS-558K | 1e | LLaVA-Instruct-80K | proj-1e, lora-1e | 64.3 | 55.9 | 81.7 | 70.1 | [LoRA](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3) [LoRA-Merged](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-merge-vicuna-13b-v1.3) | +| LLaMA-2-13B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | 56.7 | 58.6 | 80.0 | 67.9 | [ckpt](https://huggingface.co/liuhaotian/llava-llama-2-13b-chat-lightning-preview) | +| LLaMA-2-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | lora-1e | 51.2 | 58.9 | 71.6 | 62.8 | [LoRA](https://huggingface.co/liuhaotian/llava-llama-2-7b-chat-lightning-lora-preview) | + + +## Projector weights + +The model weights below are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. We'll add more projector weights into model zoo very soon. + +**NOTE**: These projector weights are only compatible with the `llava>=1.0.0`, please check out the latest code base if your local code version is below `v1.0.0`. + +**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad. + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end False +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------|----------| +| Vicuna-13B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5) | +| Vicuna-7B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-7b-v1.5) | +| LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) | +| LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) | +| LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) | +| LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) | +| Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) | +| Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) | +| Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) | +| Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) | + + +## Science QA Checkpoints + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------| +| Vicuna-13B-v1.3 | CLIP-L | LCS-558K | 1e | ScienceQA | full_ft-12e | [ckpt](https://huggingface.co/liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3) | + + +## Legacy Models (merged weights) + +The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license. + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------| +| MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) | + + +## Legacy Models (delta weights) + +The model weights below are *delta* weights. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md). + +You can add our delta to the original LLaMA weights to obtain the LLaVA weights. + +Instructions: + +1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama). +2. Use the following scripts to get LLaVA weights by applying our delta. It will automatically download delta weights from our Hugging Face account. In the script below, we use the delta weights of [`liuhaotian/LLaVA-7b-delta-v0`](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) as an example. It can be adapted for other delta weights by changing the `--delta` argument (and base/target accordingly). + +```bash +python3 -m llava.model.apply_delta \ + --base /path/to/llama-7b \ + --target /output/path/to/LLaVA-7B-v0 \ + --delta liuhaotian/LLaVA-7b-delta-v0 +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download | +|----------|----------------|---------------|----------------------|-----------------|--------------------|------------------| +| Vicuna-13B-v1.1 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v1-1) | +| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-Lightning-7B-delta-v1-1) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) | +| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) | + + + +## Legacy Projector weights + +The following projector weights are deprecated, and the support for them may be removed in the future. They do not support zero-shot inference. Please use the projector weights in the [table above](#projector-weights) if possible. + +**NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad. + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end True +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------| +| Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v1-1-LCS-558K-blip_caption.bin) | +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption.bin) | +| Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) | + +When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows, + +```Shell +--mm_use_im_start_end False +--mm_use_im_patch_token False +``` + +| Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download | +|----------|----------------|---------------|----------------------|----------| +| Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) | diff --git a/approach/vlm/LLaVA/docs/ScienceQA.md b/approach/vlm/LLaVA/docs/ScienceQA.md new file mode 100644 index 0000000000000000000000000000000000000000..8881c41c67002a3798435b051c9a609dd1c0d506 --- /dev/null +++ b/approach/vlm/LLaVA/docs/ScienceQA.md @@ -0,0 +1,53 @@ +### ScienceQA + +#### Prepare Data +1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset. +2. Generate ScienceQA dataset for LLaVA conversation-style format. + +```Shell +python scripts/convert_sqa_to_llava.py \ + convert_to_llava \ + --base-dir /path/to/ScienceQA/data/scienceqa \ + --prompt-format "QCM-LEA" \ + --split {train,val,minival,test,minitest} +``` + +#### Training + +1. Pretraining + +You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh). + +2. Finetuning + +See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh). + +#### Evaluation + +1. Multiple-GPU inference +You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh). + +2. Single-GPU inference + +(a) Generate LLaVA responses on ScienceQA dataset + +```Shell +python -m llava.eval.model_vqa_science \ + --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \ + --question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \ + --image-folder /path/to/ScienceQA/data/scienceqa/images/test \ + --answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \ + --conv-mode llava_v1 +``` + +(b) Evaluate the generated responses + +```Shell +python eval_science_qa.py \ + --base-dir /path/to/ScienceQA/data/scienceqa \ + --result-file vqa/results/ScienceQA/test_llava-13b.jsonl \ + --output-file vqa/results/ScienceQA/test_llava-13b_output.json \ + --output-result vqa/results/ScienceQA/test_llava-13b_result.json \ +``` + +For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail. diff --git a/approach/vlm/LLaVA/llava/__init__.py b/approach/vlm/LLaVA/llava/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1f016db1028101d45ba7d68cb3f0bcb558c2bb --- /dev/null +++ b/approach/vlm/LLaVA/llava/__init__.py @@ -0,0 +1 @@ +from .model import LlavaLlamaForCausalLM diff --git a/approach/vlm/LLaVA/llava/constants.py b/approach/vlm/LLaVA/llava/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..be8cf0204969a6c973f442b383d8e425d684e826 --- /dev/null +++ b/approach/vlm/LLaVA/llava/constants.py @@ -0,0 +1,12 @@ +CONTROLLER_HEART_BEAT_EXPIRATION = 30 +WORKER_HEART_BEAT_INTERVAL = 15 + +LOGDIR = "." + +# Model Constants +IGNORE_INDEX = -100 +IMAGE_TOKEN_INDEX = -200 +DEFAULT_IMAGE_TOKEN = "" +DEFAULT_IMAGE_PATCH_TOKEN = "" +DEFAULT_IM_START_TOKEN = "" +DEFAULT_IM_END_TOKEN = "" diff --git a/approach/vlm/LLaVA/llava/conversation.py b/approach/vlm/LLaVA/llava/conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee30cf9942d6f3184e845c0436f5c1d80e00043 --- /dev/null +++ b/approach/vlm/LLaVA/llava/conversation.py @@ -0,0 +1,381 @@ +import dataclasses +from enum import auto, Enum +from typing import List, Tuple + + +class SeparatorStyle(Enum): + """Different separator style.""" + SINGLE = auto() + TWO = auto() + MPT = auto() + PLAIN = auto() + LLAMA_2 = auto() + + +@dataclasses.dataclass +class Conversation: + """A class that keeps all conversation history.""" + system: str + roles: List[str] + messages: List[List[str]] + offset: int + sep_style: SeparatorStyle = SeparatorStyle.SINGLE + sep: str = "###" + sep2: str = None + version: str = "Unknown" + + skip_next: bool = False + + def get_prompt(self): + messages = self.messages + if len(messages) > 0 and type(messages[0][1]) is tuple: + messages = self.messages.copy() + init_role, init_msg = messages[0].copy() + init_msg = init_msg[0].replace("", "").strip() + if 'mmtag' in self.version: + messages[0] = (init_role, init_msg) + messages.insert(0, (self.roles[0], "")) + messages.insert(1, (self.roles[1], "Received.")) + else: + messages[0] = (init_role, "\n" + init_msg) + + if self.sep_style == SeparatorStyle.SINGLE: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + self.sep + else: + ret += role + ":" + elif self.sep_style == SeparatorStyle.TWO: + seps = [self.sep, self.sep2] + ret = self.system + seps[0] + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + elif self.sep_style == SeparatorStyle.MPT: + ret = self.system + self.sep + for role, message in messages: + if message: + if type(message) is tuple: + message, _, _ = message + ret += role + message + self.sep + else: + ret += role + elif self.sep_style == SeparatorStyle.LLAMA_2: + wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" + wrap_inst = lambda msg: f"[INST] {msg} [/INST]" + ret = "" + + for i, (role, message) in enumerate(messages): + if i == 0: + assert message, "first message should not be none" + assert role == self.roles[0], "first message should come from user" + if message: + if type(message) is tuple: + message, _, _ = message + if i == 0: message = wrap_sys(self.system) + message + if i % 2 == 0: + message = wrap_inst(message) + ret += self.sep + message + else: + ret += " " + message + " " + self.sep2 + else: + ret += "" + ret = ret.lstrip(self.sep) + elif self.sep_style == SeparatorStyle.PLAIN: + seps = [self.sep, self.sep2] + ret = self.system + for i, (role, message) in enumerate(messages): + if message: + if type(message) is tuple: + message, _, _ = message + ret += message + seps[i % 2] + else: + ret += "" + else: + raise ValueError(f"Invalid style: {self.sep_style}") + + return ret + + def append_message(self, role, message): + self.messages.append([role, message]) + + def get_images(self, return_pil=False): + images = [] + for i, (role, msg) in enumerate(self.messages[self.offset:]): + if i % 2 == 0: + if type(msg) is tuple: + import base64 + from io import BytesIO + from PIL import Image + msg, image, image_process_mode = msg + if image_process_mode == "Pad": + def expand2square(pil_img, background_color=(122, 116, 104)): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + image = expand2square(image) + elif image_process_mode in ["Default", "Crop"]: + pass + elif image_process_mode == "Resize": + image = image.resize((336, 336)) + else: + raise ValueError(f"Invalid image_process_mode: {image_process_mode}") + max_hw, min_hw = max(image.size), min(image.size) + aspect_ratio = max_hw / min_hw + max_len, min_len = 800, 400 + shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) + longest_edge = int(shortest_edge * aspect_ratio) + W, H = image.size + if longest_edge != max(image.size): + if H > W: + H, W = longest_edge, shortest_edge + else: + H, W = shortest_edge, longest_edge + image = image.resize((W, H)) + if return_pil: + images.append(image) + else: + buffered = BytesIO() + image.save(buffered, format="PNG") + img_b64_str = base64.b64encode(buffered.getvalue()).decode() + images.append(img_b64_str) + return images + + def to_gradio_chatbot(self): + ret = [] + for i, (role, msg) in enumerate(self.messages[self.offset:]): + if i % 2 == 0: + if type(msg) is tuple: + import base64 + from io import BytesIO + msg, image, image_process_mode = msg + max_hw, min_hw = max(image.size), min(image.size) + aspect_ratio = max_hw / min_hw + max_len, min_len = 800, 400 + shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw)) + longest_edge = int(shortest_edge * aspect_ratio) + W, H = image.size + if H > W: + H, W = longest_edge, shortest_edge + else: + H, W = shortest_edge, longest_edge + image = image.resize((W, H)) + buffered = BytesIO() + image.save(buffered, format="JPEG") + img_b64_str = base64.b64encode(buffered.getvalue()).decode() + img_str = f'user upload image' + msg = img_str + msg.replace('', '').strip() + ret.append([msg, None]) + else: + ret.append([msg, None]) + else: + ret[-1][-1] = msg + return ret + + def copy(self): + return Conversation( + system=self.system, + roles=self.roles, + messages=[[x, y] for x, y in self.messages], + offset=self.offset, + sep_style=self.sep_style, + sep=self.sep, + sep2=self.sep2, + version=self.version) + + def dict(self): + if len(self.get_images()) > 0: + return { + "system": self.system, + "roles": self.roles, + "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages], + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + return { + "system": self.system, + "roles": self.roles, + "messages": self.messages, + "offset": self.offset, + "sep": self.sep, + "sep2": self.sep2, + } + + +conv_vicuna_v0 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + messages=( + ("Human", "What are the key differences between renewable and non-renewable energy sources?"), + ("Assistant", + "Renewable energy sources are those that can be replenished naturally in a relatively " + "short amount of time, such as solar, wind, hydro, geothermal, and biomass. " + "Non-renewable energy sources, on the other hand, are finite and will eventually be " + "depleted, such as coal, oil, and natural gas. Here are some key differences between " + "renewable and non-renewable energy sources:\n" + "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable " + "energy sources are finite and will eventually run out.\n" + "2. Environmental impact: Renewable energy sources have a much lower environmental impact " + "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, " + "and other negative effects.\n" + "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically " + "have lower operational costs than non-renewable sources.\n" + "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote " + "locations than non-renewable sources.\n" + "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different " + "situations and needs, while non-renewable sources are more rigid and inflexible.\n" + "6. Sustainability: Renewable energy sources are more sustainable over the long term, while " + "non-renewable sources are not, and their depletion can lead to economic and social instability.\n") + ), + offset=2, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_vicuna_v1 = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the user's questions.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llama_2 = Conversation( + system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. + +If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=(), + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_llava_llama_2 = Conversation( + system="You are a helpful language and vision assistant. " + "You are able to understand the visual content that the user provides, " + "and assist the user with a variety of tasks using natural language.", + roles=("USER", "ASSISTANT"), + version="llama_v2", + messages=(), + offset=0, + sep_style=SeparatorStyle.LLAMA_2, + sep="", + sep2="", +) + +conv_mpt = Conversation( + system="""<|im_start|>system +A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""", + roles=("<|im_start|>user\n", "<|im_start|>assistant\n"), + version="mpt", + messages=(), + offset=0, + sep_style=SeparatorStyle.MPT, + sep="<|im_end|>", +) + +conv_llava_plain = Conversation( + system="", + roles=("", ""), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.PLAIN, + sep="\n", +) + +conv_llava_v0 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", +) + +conv_llava_v0_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." + "The visual content will be provided with the following format: visual content.", + roles=("Human", "Assistant"), + messages=( + ), + offset=0, + sep_style=SeparatorStyle.SINGLE, + sep="###", + version="v0_mmtag", +) + +conv_llava_v1 = Conversation( + system="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("USER", "ASSISTANT"), + version="v1", + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", +) + +conv_llava_v1_mmtag = Conversation( + system="A chat between a curious user and an artificial intelligence assistant. " + "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language." + "The visual content will be provided with the following format: visual content.", + roles=("USER", "ASSISTANT"), + messages=(), + offset=0, + sep_style=SeparatorStyle.TWO, + sep=" ", + sep2="", + version="v1_mmtag", +) + +default_conversation = conv_vicuna_v0 +conv_templates = { + "default": conv_vicuna_v0, + "v0": conv_vicuna_v0, + "v1": conv_vicuna_v1, + "vicuna_v1": conv_vicuna_v1, + "llama_2": conv_llama_2, + + "plain": conv_llava_plain, + "v0_plain": conv_llava_plain, + "llava_v0": conv_llava_v0, + "v0_mmtag": conv_llava_v0_mmtag, + "llava_v1": conv_llava_v1, + "v1_mmtag": conv_llava_v1_mmtag, + "llava_llama_2": conv_llava_llama_2, + + "mpt": conv_mpt, +} + + +if __name__ == "__main__": + print(default_conversation.get_prompt()) diff --git a/approach/vlm/LLaVA/llava/eval/eval_gpt_review.py b/approach/vlm/LLaVA/llava/eval/eval_gpt_review.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c8ff426a2362703735f7ae33bb87ebf90e2210 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_gpt_review.py @@ -0,0 +1,114 @@ +import argparse +import json +import os + +import openai +from openai import OpenAI + +client = OpenAI() +import tqdm +import ray +import time + +NUM_SECONDS_TO_SLEEP = 3 + +@ray.remote(num_cpus=4) +def get_eval(content: str, max_tokens: int): + while True: + try: + response = client.chat.completions.create(model='gpt-4', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens) + break + except openai.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + print('success!') + return response.choices[0].message.content + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + # parser.add_argument('-a', '--answer') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + ray.init() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + review_file = open(f'{args.output}', 'w') + + js_list = [] + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + # if idx == 1: + # break + + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + category = json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + rule = rule_dict['default'] + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + js_list.append({ + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1['answer_id'], + 'answer2_id': ans2['answer_id'], + 'category': category}) + idx += 1 + handles.append(get_eval.remote(content, args.max_tokens)) + # To avoid the rate limit set by OpenAI + time.sleep(NUM_SECONDS_TO_SLEEP) + + reviews = ray.get(handles) + for idx, review in enumerate(reviews): + scores = parse_score(review) + js_list[idx]['content'] = review + js_list[idx]['tuple'] = scores + review_file.write(json.dumps(js_list[idx]) + '\n') + review_file.close() diff --git a/approach/vlm/LLaVA/llava/eval/eval_gpt_review_bench.py b/approach/vlm/LLaVA/llava/eval/eval_gpt_review_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..fbba73679c0764f9dc00e2383f8cc6bb62492692 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_gpt_review_bench.py @@ -0,0 +1,122 @@ +import argparse +import json +import os + +import openai +from openai import OpenAI + +client = OpenAI() +import time + +NUM_SECONDS_TO_SLEEP = 0.5 + + +def get_eval(content: str, max_tokens: int): + while True: + try: + response = client.chat.completions.create(model='gpt-4-0314', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens) + break + except openai.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + return response.choices[0].message.content + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + parser.add_argument('-c', '--context') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + if os.path.isfile(os.path.expanduser(args.output)): + cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))] + else: + cur_reviews = [] + + review_file = open(f'{args.output}', 'a') + + context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))] + image_to_context = {context['image']: context for context in context_list} + + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + inst = image_to_context[ques['image']] + + if isinstance(inst['caption'], list): + cap_str = '\n'.join(inst['caption']) + else: + cap_str = inst['caption'] + + category = 'llava_bench_' + json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + assert False, f"Visual QA category not found in rule file: {category}." + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Context]\n{cap_str}\n\n' + f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + cur_js = { + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1.get('answer_id', ans1['question_id']), + 'answer2_id': ans2.get('answer_id', ans2['answer_id']), + 'category': category + } + if idx >= len(cur_reviews): + review = get_eval(content, args.max_tokens) + scores = parse_score(review) + cur_js['content'] = review + cur_js['tuple'] = scores + review_file.write(json.dumps(cur_js) + '\n') + review_file.flush() + else: + print(f'Skipping {idx} as we already have it.') + idx += 1 + print(idx) + review_file.close() diff --git a/approach/vlm/LLaVA/llava/eval/eval_gpt_review_visual.py b/approach/vlm/LLaVA/llava/eval/eval_gpt_review_visual.py new file mode 100644 index 0000000000000000000000000000000000000000..cf60e64b701a65b53515b1c336b33e6e87a808ba --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_gpt_review_visual.py @@ -0,0 +1,119 @@ +import argparse +import json +import os + +import openai +from openai import OpenAI + +client = OpenAI() +import time + +NUM_SECONDS_TO_SLEEP = 0.5 + + +def get_eval(content: str, max_tokens: int): + while True: + try: + response = client.chat.completions.create(model='gpt-4-0314', + messages=[{ + 'role': 'system', + 'content': 'You are a helpful and precise assistant for checking the quality of the answer.' + }, { + 'role': 'user', + 'content': content, + }], + temperature=0.2, # TODO: figure out which temperature is best for evaluation + max_tokens=max_tokens) + break + except openai.RateLimitError: + pass + except Exception as e: + print(e) + time.sleep(NUM_SECONDS_TO_SLEEP) + + return response.choices[0].message.content + + +def parse_score(review): + try: + score_pair = review.split('\n')[0] + score_pair = score_pair.replace(',', ' ') + sp = score_pair.split(' ') + if len(sp) == 2: + return [float(sp[0]), float(sp[1])] + else: + print('error', review) + return [-1, -1] + except Exception as e: + print(e) + print('error', review) + return [-1, -1] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-q', '--question') + parser.add_argument('-c', '--context') + parser.add_argument('-a', '--answer-list', nargs='+', default=[]) + parser.add_argument('-r', '--rule') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + f_q = open(os.path.expanduser(args.question)) + f_ans1 = open(os.path.expanduser(args.answer_list[0])) + f_ans2 = open(os.path.expanduser(args.answer_list[1])) + rule_dict = json.load(open(os.path.expanduser(args.rule), 'r')) + + if os.path.isfile(os.path.expanduser(args.output)): + cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))] + else: + cur_reviews = [] + + review_file = open(f'{args.output}', 'a') + + context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))] + image_to_context = {context['image']: context for context in context_list} + + handles = [] + idx = 0 + for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2): + ques = json.loads(ques_js) + ans1 = json.loads(ans1_js) + ans2 = json.loads(ans2_js) + + inst = image_to_context[ques['image']] + cap_str = '\n'.join(inst['captions']) + box_str = '\n'.join([f'{instance["category"]}: {instance["bbox"]}' for instance in inst['instances']]) + + category = json.loads(ques_js)['category'] + if category in rule_dict: + rule = rule_dict[category] + else: + assert False, f"Visual QA category not found in rule file: {category}." + prompt = rule['prompt'] + role = rule['role'] + content = (f'[Context]\n{cap_str}\n\n{box_str}\n\n' + f'[Question]\n{ques["text"]}\n\n' + f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n' + f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n' + f'[System]\n{prompt}\n\n') + cur_js = { + 'id': idx+1, + 'question_id': ques['question_id'], + 'answer1_id': ans1.get('answer_id', ans1['question_id']), + 'answer2_id': ans2.get('answer_id', ans2['answer_id']), + 'category': category + } + if idx >= len(cur_reviews): + review = get_eval(content, args.max_tokens) + scores = parse_score(review) + cur_js['content'] = review + cur_js['tuple'] = scores + review_file.write(json.dumps(cur_js) + '\n') + review_file.flush() + else: + print(f'Skipping {idx} as we already have it.') + idx += 1 + print(idx) + review_file.close() diff --git a/approach/vlm/LLaVA/llava/eval/eval_science_qa.py b/approach/vlm/LLaVA/llava/eval/eval_science_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b3ce52fd6d922f247cc0c48409e88d5af3f204 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_science_qa.py @@ -0,0 +1,99 @@ +import argparse +import json +import os +import re +import random + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--result-file', type=str) + parser.add_argument('--output-file', type=str) + parser.add_argument('--output-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + predictions = [json.loads(line) for line in open(args.result_file)] + predictions = {pred['question_id']: pred for pred in predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + results = {'correct': [], 'incorrect': []} + sqa_results = {} + sqa_results['acc'] = None + sqa_results['correct'] = None + sqa_results['count'] = None + sqa_results['results'] = {} + sqa_results['outputs'] = {} + + for prob_id, prob in split_problems.items(): + if prob_id not in predictions: + continue + pred = predictions[prob_id] + pred_text = pred['text'] + + pattern = re.compile(r'The answer is ([A-Z]).') + res = pattern.findall(pred_text) + if len(res) == 1: + answer = res[0] # 'A', 'B', ... + else: + answer = "FAILED" + + pred_idx = get_pred_idx(answer, prob['choices'], args.options) + + analysis = { + 'question_id': prob_id, + 'parsed_ans': answer, + 'ground_truth': args.options[prob['answer']], + 'question': pred['prompt'], + 'pred': pred_text, + 'is_multimodal': '' in pred['prompt'], + } + + sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options) + sqa_results['outputs'][prob_id] = pred_text + + if pred_idx == prob['answer']: + results['correct'].append(analysis) + else: + results['incorrect'].append(analysis) + + correct = len(results['correct']) + total = len(results['correct']) + len(results['incorrect']) + print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%') + + sqa_results['acc'] = correct / total * 100 + sqa_results['correct'] = correct + sqa_results['count'] = total + + with open(args.output_file, 'w') as f: + json.dump(results, f, indent=2) + with open(args.output_result, 'w') as f: + json.dump(sqa_results, f, indent=2) diff --git a/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4.py b/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ff17c915481fb556aba6ec816a9e08f519c515 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4.py @@ -0,0 +1,104 @@ +import argparse +import json +import os +import re +import random +from collections import defaultdict + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--gpt4-result', type=str) + parser.add_argument('--our-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + our_predictions = [json.loads(line) for line in open(args.our_result)] + our_predictions = {pred['question_id']: pred for pred in our_predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + gpt4_predictions = json.load(open(args.gpt4_result))['outputs'] + + results = defaultdict(lambda: 0) + + for prob_id, prob in split_problems.items(): + if prob_id not in our_predictions: + continue + if prob_id not in gpt4_predictions: + continue + our_pred = our_predictions[prob_id]['text'] + gpt4_pred = gpt4_predictions[prob_id] + + pattern = re.compile(r'The answer is ([A-Z]).') + our_res = pattern.findall(our_pred) + if len(our_res) == 1: + our_answer = our_res[0] # 'A', 'B', ... + else: + our_answer = "FAILED" + gpt4_res = pattern.findall(gpt4_pred) + if len(gpt4_res) == 1: + gpt4_answer = gpt4_res[0] # 'A', 'B', ... + else: + gpt4_answer = "FAILED" + + our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options) + gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options) + + if gpt4_answer == 'FAILED': + results['gpt4_failed'] += 1 + # continue + gpt4_pred_idx = our_pred_idx + # if our_pred_idx != prob['answer']: + # print(our_predictions[prob_id]['prompt']) + # print('-----------------') + # print(f'LECTURE: {prob["lecture"]}') + # print(f'SOLUTION: {prob["solution"]}') + # print('=====================') + else: + # continue + pass + # gpt4_pred_idx = our_pred_idx + + if gpt4_pred_idx == prob['answer']: + results['correct'] += 1 + else: + results['incorrect'] += 1 + + + if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']: + results['correct_upperbound'] += 1 + + correct = results['correct'] + total = results['correct'] + results['incorrect'] + print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%') + print(f'Total: {total}, Correct (upper): {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%') + diff --git a/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4_requery.py b/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4_requery.py new file mode 100644 index 0000000000000000000000000000000000000000..698546e995d365d1ccc2c25a87e6c5cd681e6eb6 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/eval_science_qa_gpt4_requery.py @@ -0,0 +1,149 @@ +import argparse +import json +import os +import re +import random +from collections import defaultdict + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--base-dir', type=str) + parser.add_argument('--gpt4-result', type=str) + parser.add_argument('--requery-result', type=str) + parser.add_argument('--our-result', type=str) + parser.add_argument('--output-result', type=str) + parser.add_argument('--split', type=str, default='test') + parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) + return parser.parse_args() + + +def convert_caps(results): + fakecaps = [] + for result in results: + image_id = result['question_id'] + caption = result['text'] + fakecaps.append({"image_id": int(image_id), "caption": caption}) + return fakecaps + + +def get_pred_idx(prediction, choices, options): + """ + Get the index (e.g. 2) from the prediction (e.g. 'C') + """ + if prediction in options[:len(choices)]: + return options.index(prediction) + else: + return random.choice(range(len(choices))) + + +if __name__ == "__main__": + args = get_args() + + base_dir = args.base_dir + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + our_predictions = [json.loads(line) for line in open(args.our_result)] + our_predictions = {pred['question_id']: pred for pred in our_predictions} + split_problems = {idx: problems[idx] for idx in split_indices} + + requery_predictions = [json.loads(line) for line in open(args.requery_result)] + requery_predictions = {pred['question_id']: pred for pred in requery_predictions} + + gpt4_predictions = json.load(open(args.gpt4_result))['outputs'] + + results = defaultdict(lambda: 0) + + sqa_results = {} + sqa_results['acc'] = None + sqa_results['correct'] = None + sqa_results['count'] = None + sqa_results['results'] = {} + sqa_results['outputs'] = {} + + for prob_id, prob in split_problems.items(): + if prob_id not in our_predictions: + assert False + if prob_id not in gpt4_predictions: + assert False + our_pred = our_predictions[prob_id]['text'] + gpt4_pred = gpt4_predictions[prob_id] + if prob_id not in requery_predictions: + results['missing_requery'] += 1 + requery_pred = "MISSING" + else: + requery_pred = requery_predictions[prob_id]['text'] + + pattern = re.compile(r'The answer is ([A-Z]).') + our_res = pattern.findall(our_pred) + if len(our_res) == 1: + our_answer = our_res[0] # 'A', 'B', ... + else: + our_answer = "FAILED" + + requery_res = pattern.findall(requery_pred) + if len(requery_res) == 1: + requery_answer = requery_res[0] # 'A', 'B', ... + else: + requery_answer = "FAILED" + + gpt4_res = pattern.findall(gpt4_pred) + if len(gpt4_res) == 1: + gpt4_answer = gpt4_res[0] # 'A', 'B', ... + else: + gpt4_answer = "FAILED" + + our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options) + gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options) + requery_pred_idx = get_pred_idx(requery_answer, prob['choices'], args.options) + + results['total'] += 1 + + if gpt4_answer == 'FAILED': + results['gpt4_failed'] += 1 + if gpt4_pred_idx == prob['answer']: + results['gpt4_correct'] += 1 + if our_pred_idx == prob['answer']: + results['gpt4_ourvisual_correct'] += 1 + elif gpt4_pred_idx == prob['answer']: + results['gpt4_correct'] += 1 + results['gpt4_ourvisual_correct'] += 1 + + if our_pred_idx == prob['answer']: + results['our_correct'] += 1 + + if requery_answer == 'FAILED': + sqa_results['results'][prob_id] = our_pred_idx + if our_pred_idx == prob['answer']: + results['requery_correct'] += 1 + else: + sqa_results['results'][prob_id] = requery_pred_idx + if requery_pred_idx == prob['answer']: + results['requery_correct'] += 1 + else: + print(f""" +Question ({args.options[prob['answer']]}): {our_predictions[prob_id]['prompt']} +Our ({our_answer}): {our_pred} +GPT-4 ({gpt4_answer}): {gpt4_pred} +Requery ({requery_answer}): {requery_pred} +print("=====================================") +""") + + if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']: + results['correct_upperbound'] += 1 + + total = results['total'] + print(f'Total: {total}, Our-Correct: {results["our_correct"]}, Accuracy: {results["our_correct"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4-Correct: {results["gpt4_correct"]}, Accuracy: {results["gpt4_correct"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%') + print(f'Total: {total}, GPT-4-OursVisual-Correct: {results["gpt4_ourvisual_correct"]}, Accuracy: {results["gpt4_ourvisual_correct"] / total * 100:.2f}%') + print(f'Total: {total}, Requery-Correct: {results["requery_correct"]}, Accuracy: {results["requery_correct"] / total * 100:.2f}%') + print(f'Total: {total}, Correct upper: {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%') + + sqa_results['acc'] = results["requery_correct"] / total * 100 + sqa_results['correct'] = results["requery_correct"] + sqa_results['count'] = total + + with open(args.output_result, 'w') as f: + json.dump(sqa_results, f, indent=2) + diff --git a/approach/vlm/LLaVA/llava/eval/generate_webpage_data_from_table.py b/approach/vlm/LLaVA/llava/eval/generate_webpage_data_from_table.py new file mode 100644 index 0000000000000000000000000000000000000000..92602258ccd953a1d7137056aaf15c8de8166e21 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/generate_webpage_data_from_table.py @@ -0,0 +1,111 @@ +"""Generate json file for webpage.""" +import json +import os +import re + +# models = ['llama', 'alpaca', 'gpt35', 'bard'] +models = ['vicuna'] + + +def read_jsonl(path: str, key: str=None): + data = [] + with open(os.path.expanduser(path)) as f: + for line in f: + if not line: + continue + data.append(json.loads(line)) + if key is not None: + data.sort(key=lambda x: x[key]) + data = {item[key]: item for item in data} + return data + + +def trim_hanging_lines(s: str, n: int) -> str: + s = s.strip() + for _ in range(n): + s = s.split('\n', 1)[1].strip() + return s + + +if __name__ == '__main__': + questions = read_jsonl('table/question.jsonl', key='question_id') + + # alpaca_answers = read_jsonl('table/answer/answer_alpaca-13b.jsonl', key='question_id') + # bard_answers = read_jsonl('table/answer/answer_bard.jsonl', key='question_id') + # gpt35_answers = read_jsonl('table/answer/answer_gpt35.jsonl', key='question_id') + # llama_answers = read_jsonl('table/answer/answer_llama-13b.jsonl', key='question_id') + vicuna_answers = read_jsonl('table/answer/answer_vicuna-13b.jsonl', key='question_id') + ours_answers = read_jsonl('table/results/llama-13b-hf-alpaca.jsonl', key='question_id') + + review_vicuna = read_jsonl('table/review/review_vicuna-13b_llama-13b-hf-alpaca.jsonl', key='question_id') + # review_alpaca = read_jsonl('table/review/review_alpaca-13b_vicuna-13b.jsonl', key='question_id') + # review_bard = read_jsonl('table/review/review_bard_vicuna-13b.jsonl', key='question_id') + # review_gpt35 = read_jsonl('table/review/review_gpt35_vicuna-13b.jsonl', key='question_id') + # review_llama = read_jsonl('table/review/review_llama-13b_vicuna-13b.jsonl', key='question_id') + + records = [] + for qid in questions.keys(): + r = { + 'id': qid, + 'category': questions[qid]['category'], + 'question': questions[qid]['text'], + 'answers': { + # 'alpaca': alpaca_answers[qid]['text'], + # 'llama': llama_answers[qid]['text'], + # 'bard': bard_answers[qid]['text'], + # 'gpt35': gpt35_answers[qid]['text'], + 'vicuna': vicuna_answers[qid]['text'], + 'ours': ours_answers[qid]['text'], + }, + 'evaluations': { + # 'alpaca': review_alpaca[qid]['text'], + # 'llama': review_llama[qid]['text'], + # 'bard': review_bard[qid]['text'], + 'vicuna': review_vicuna[qid]['content'], + # 'gpt35': review_gpt35[qid]['text'], + }, + 'scores': { + 'vicuna': review_vicuna[qid]['tuple'], + # 'alpaca': review_alpaca[qid]['score'], + # 'llama': review_llama[qid]['score'], + # 'bard': review_bard[qid]['score'], + # 'gpt35': review_gpt35[qid]['score'], + }, + } + + # cleanup data + cleaned_evals = {} + for k, v in r['evaluations'].items(): + v = v.strip() + lines = v.split('\n') + # trim the first line if it's a pair of numbers + if re.match(r'\d+[, ]+\d+', lines[0]): + lines = lines[1:] + v = '\n'.join(lines) + cleaned_evals[k] = v.replace('Assistant 1', "**Assistant 1**").replace('Assistant 2', '**Assistant 2**') + + r['evaluations'] = cleaned_evals + records.append(r) + + # Reorder the records, this is optional + for r in records: + if r['id'] <= 20: + r['id'] += 60 + else: + r['id'] -= 20 + for r in records: + if r['id'] <= 50: + r['id'] += 10 + elif 50 < r['id'] <= 60: + r['id'] -= 50 + for r in records: + if r['id'] == 7: + r['id'] = 1 + elif r['id'] < 7: + r['id'] += 1 + + records.sort(key=lambda x: x['id']) + + # Write to file + with open('webpage/data.json', 'w') as f: + json.dump({'questions': records, 'models': models}, f, indent=2) diff --git a/approach/vlm/LLaVA/llava/eval/model_qa.py b/approach/vlm/LLaVA/llava/eval/model_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8c1138ac166387d82cba868d00f64ab4e6a33c --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/model_qa.py @@ -0,0 +1,85 @@ +import argparse +from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.conversation import default_conversation +from llava.utils import disable_torch_init + + +# new stopping implementation +class KeywordsStoppingCriteria(StoppingCriteria): + def __init__(self, keywords, tokenizer, input_ids): + self.keywords = keywords + self.tokenizer = tokenizer + self.start_len = None + self.input_ids = input_ids + + def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + if self.start_len is None: + self.start_len = self.input_ids.shape[1] + else: + outputs = self.tokenizer.batch_decode(output_ids[:, self.start_len:], skip_special_tokens=True)[0] + for keyword in self.keywords: + if keyword in outputs: + return True + return False + + +@torch.inference_mode() +def eval_model(model_name, questions_file, answers_file): + # Model + disable_torch_init() + model_name = os.path.expanduser(model_name) + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_name, + torch_dtype=torch.float16).cuda() + + + ques_file = open(os.path.expanduser(questions_file), "r") + ans_file = open(os.path.expanduser(answers_file), "w") + for i, line in enumerate(tqdm(ques_file)): + idx = json.loads(line)["question_id"] + qs = json.loads(line)["text"] + cat = json.loads(line)["category"] + conv = default_conversation.copy() + conv.append_message(conv.roles[0], qs) + prompt = conv.get_prompt() + inputs = tokenizer([prompt]) + input_ids = torch.as_tensor(inputs.input_ids).cuda() + stopping_criteria = KeywordsStoppingCriteria([conv.sep], tokenizer, input_ids) + output_ids = model.generate( + input_ids, + do_sample=True, + use_cache=True, + temperature=0.7, + max_new_tokens=1024, + stopping_criteria=[stopping_criteria]) + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0] + try: + index = outputs.index(conv.sep, len(prompt)) + except ValueError: + outputs += conv.sep + index = outputs.index(conv.sep, len(prompt)) + + outputs = outputs[len(prompt) + len(conv.roles[1]) + 2:index].strip() + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-name", type=str, default="facebook/opt-350m") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + args = parser.parse_args() + + eval_model(args.model_name, args.question_file, args.answers_file) diff --git a/approach/vlm/LLaVA/llava/eval/model_vqa.py b/approach/vlm/LLaVA/llava/eval/model_vqa.py new file mode 100644 index 0000000000000000000000000000000000000000..5f120e1c99833a913791fcd1eaab32c9a4bcba3e --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/model_vqa.py @@ -0,0 +1,114 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria + +from PIL import Image, ImageFile +ImageFile.LOAD_TRUNCATED_IMAGES = True + +import math + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")] + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + for line in tqdm(questions): + idx = line["question_id"] + image_file = line["image"] + qs = line["text"] + cur_prompt = qs + if model.config.mm_use_im_start_end: + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + image = Image.open(os.path.join(args.image_folder, image_file)) + image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor.unsqueeze(0).half().cuda(), + do_sample=True, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + # no_repeat_ngram_size=3, + max_new_tokens=1024, + use_cache=True) + + input_token_len = input_ids.shape[1] + n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item() + if n_diff_input_output > 0: + print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids') + outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "prompt": cur_prompt, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v1") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + args = parser.parse_args() + + eval_model(args) diff --git a/approach/vlm/LLaVA/llava/eval/model_vqa_science.py b/approach/vlm/LLaVA/llava/eval/model_vqa_science.py new file mode 100644 index 0000000000000000000000000000000000000000..aa77b39c0df7bcf0c8200f1282b165dee493ad73 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/model_vqa_science.py @@ -0,0 +1,141 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria + +from PIL import Image +import math + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + + +def eval_model(args): + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + questions = json.load(open(os.path.expanduser(args.question_file), "r")) + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + for i, line in enumerate(tqdm(questions)): + idx = line["id"] + question = line['conversations'][0] + qs = question['value'].replace('', '').strip() + cur_prompt = qs + + if 'image' in line: + image_file = line["image"] + image = Image.open(os.path.join(args.image_folder, image_file)) + image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + images = image_tensor.unsqueeze(0).half().cuda() + if getattr(model.config, 'mm_use_im_start_end', False): + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + cur_prompt = '' + '\n' + cur_prompt + else: + images = None + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = [KeywordsStoppingCriteria(keywords, tokenizer, input_ids)] if conv.version == "v0" else None + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=images, + do_sample=True, + temperature=0.2, + max_new_tokens=1024, + use_cache=True, + stopping_criteria=stopping_criteria, + ) + + input_token_len = input_ids.shape[1] + n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item() + if n_diff_input_output > 0: + print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids') + outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + + # prompt for answer + if args.answer_prompter: + outputs_reasoning = outputs + input_ids = tokenizer_image_token(prompt + outputs_reasoning + ' ###\nANSWER:', tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=images, + do_sample=True, + temperature=0.2, + max_new_tokens=64, + use_cache=True, + stopping_criteria=[stopping_criteria]) + + input_token_len = input_ids.shape[1] + n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item() + if n_diff_input_output > 0: + print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids') + outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + outputs = outputs_reasoning + '\n The answer is ' + outputs + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({"question_id": idx, + "prompt": cur_prompt, + "text": outputs, + "answer_id": ans_id, + "model_id": model_name, + "metadata": {}}) + "\n") + ans_file.flush() + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.json") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v0") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--answer-prompter", action="store_true") + args = parser.parse_args() + + eval_model(args) diff --git a/approach/vlm/LLaVA/llava/eval/qa_baseline_gpt35.py b/approach/vlm/LLaVA/llava/eval/qa_baseline_gpt35.py new file mode 100644 index 0000000000000000000000000000000000000000..7525ce49e64efc5d7260d8b7bedc758ca38ef908 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/qa_baseline_gpt35.py @@ -0,0 +1,74 @@ +"""Generate answers with GPT-3.5""" +# Note: you need to be using OpenAI Python v0.27.0 for the code below to work +import argparse +import json +import os +import time +import concurrent.futures + +from openai import OpenAI + +client = OpenAI() +import tqdm +import shortuuid + +MODEL = 'gemini-3-flash-preview-nothinking' +MODEL_ID = 'gemini-3-flash-preview-nothinking:20230327' + +def get_answer(question_id: int, question: str, max_tokens: int): + ans = { + 'answer_id': shortuuid.uuid(), + 'question_id': question_id, + 'model_id': MODEL_ID, + } + for _ in range(3): + try: + response = client.chat.completions.create(model=MODEL, + messages=[{ + 'role': 'system', + 'content': 'You are a helpful assistant.' + }, { + 'role': 'user', + 'content': question, + }], + max_tokens=max_tokens) + ans['text'] = response.choices[0].message.content + return ans + except Exception as e: + print('[ERROR]', e) + ans['text'] = '#ERROR#' + time.sleep(1) + return ans + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='ChatGPT answer generation.') + parser.add_argument('-q', '--question') + parser.add_argument('-o', '--output') + parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output') + args = parser.parse_args() + + questions_dict = {} + with open(os.path.expanduser(args.question)) as f: + for line in f: + if not line: + continue + q = json.loads(line) + questions_dict[q['question_id']] = q['text'] + + answers = [] + + with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor: + futures = [] + for qid, question in questions_dict.items(): + future = executor.submit(get_answer, qid, question, args.max_tokens) + futures.append(future) + + for future in tqdm.tqdm(concurrent.futures.as_completed(futures), total=len(futures)): + answers.append(future.result()) + + answers.sort(key=lambda x: x['question_id']) + + with open(os.path.expanduser(args.output), 'w') as f: + table = [json.dumps(ans) for ans in answers] + f.write('\n'.join(table)) diff --git a/approach/vlm/LLaVA/llava/eval/run_llava.py b/approach/vlm/LLaVA/llava/eval/run_llava.py new file mode 100644 index 0000000000000000000000000000000000000000..11bebda29b0b92a3d6928d28a0bd584510e304aa --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/run_llava.py @@ -0,0 +1,97 @@ +import argparse +import torch + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria + +from PIL import Image + +import requests +from PIL import Image +from io import BytesIO + + +def load_image(image_file): + if image_file.startswith('http') or image_file.startswith('https'): + response = requests.get(image_file) + image = Image.open(BytesIO(response.content)).convert('RGB') + else: + image = Image.open(image_file).convert('RGB') + return image + + +def eval_model(args): + # Model + disable_torch_init() + + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name) + + qs = args.query + if model.config.mm_use_im_start_end: + qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs + else: + qs = DEFAULT_IMAGE_TOKEN + '\n' + qs + + if 'llama-2' in model_name.lower(): + conv_mode = "llava_llama_2" + elif "v1" in model_name.lower(): + conv_mode = "llava_v1" + elif "mpt" in model_name.lower(): + conv_mode = "mpt" + else: + conv_mode = "llava_v0" + + if args.conv_mode is not None and conv_mode != args.conv_mode: + print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode)) + else: + args.conv_mode = conv_mode + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + image = load_image(args.image_file) + image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor, + do_sample=True, + temperature=0.2, + max_new_tokens=1024, + use_cache=True, + stopping_criteria=[stopping_criteria]) + + input_token_len = input_ids.shape[1] + n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item() + if n_diff_input_output > 0: + print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids') + outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + print(outputs) + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-file", type=str, required=True) + parser.add_argument("--query", type=str, required=True) + parser.add_argument("--conv-mode", type=str, default=None) + args = parser.parse_args() + + eval_model(args) diff --git a/approach/vlm/LLaVA/llava/eval/summarize_gpt_review.py b/approach/vlm/LLaVA/llava/eval/summarize_gpt_review.py new file mode 100644 index 0000000000000000000000000000000000000000..ee26f0a514083ac9848e302d5dbc5fcdaafa1d03 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/summarize_gpt_review.py @@ -0,0 +1,50 @@ +import json +import os +from collections import defaultdict + +import numpy as np + +import argparse + +def parse_args(): + parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.') + parser.add_argument('-d', '--dir', default=None) + parser.add_argument('-f', '--files', nargs='*', default=None) + parser.add_argument('-i', '--ignore', nargs='*', default=None) + return parser.parse_args() + + +if __name__ == '__main__': + args = parse_args() + + if args.ignore is not None: + args.ignore = [int(x) for x in args.ignore] + + if args.files is not None and len(args.files) > 0: + review_files = args.files + else: + review_files = [x for x in os.listdir(args.dir) if x.endswith('.jsonl') and (x.startswith('gpt4_text') or x.startswith('reviews_') or x.startswith('review_'))] + + for review_file in sorted(review_files): + config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '') + scores = defaultdict(list) + print(config) + with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f: + for review_str in f: + review = json.loads(review_str) + if args.ignore is not None and review['question_id'] in args.ignore: + continue + if 'category' in review: + scores[review['category']].append(review['tuple']) + scores['all'].append(review['tuple']) + else: + if 'tuple' in review: + scores['all'].append(review['tuple']) + else: + scores['all'].append(review['score']) + for k, v in sorted(scores.items()): + stats = np.asarray(v).mean(0).tolist() + stats = [round(x, 3) for x in stats] + # print(k, stats, round(stats[1]/stats[0]*100, 1)) + print(k, round(stats[1]/stats[0]*100, 1)) + print('=================================') diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/alpaca.png b/approach/vlm/LLaVA/llava/eval/webpage/figures/alpaca.png new file mode 100644 index 0000000000000000000000000000000000000000..497a702ab5efb88b8f67333eae81645eecea78cd Binary files /dev/null and b/approach/vlm/LLaVA/llava/eval/webpage/figures/alpaca.png differ diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/bard.jpg b/approach/vlm/LLaVA/llava/eval/webpage/figures/bard.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5b32cb501799175e3829f92b014795ad1cbee79d Binary files /dev/null and b/approach/vlm/LLaVA/llava/eval/webpage/figures/bard.jpg differ diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/chatgpt.svg b/approach/vlm/LLaVA/llava/eval/webpage/figures/chatgpt.svg new file mode 100644 index 0000000000000000000000000000000000000000..8147382a3152de03c24b4cd91f9870ced1a95d54 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/webpage/figures/chatgpt.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/llama.jpg b/approach/vlm/LLaVA/llava/eval/webpage/figures/llama.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7217e5dc1bb683453204a20890f01f5806ce12cf Binary files /dev/null and b/approach/vlm/LLaVA/llava/eval/webpage/figures/llama.jpg differ diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg b/approach/vlm/LLaVA/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg new file mode 100644 index 0000000000000000000000000000000000000000..3bee468d34515fdcbef1a8b8803c9fc4f7dc0b34 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/eval/webpage/figures/vicuna.jpeg b/approach/vlm/LLaVA/llava/eval/webpage/figures/vicuna.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..e7883dc886b96d078883e01aefd16792133e204a Binary files /dev/null and b/approach/vlm/LLaVA/llava/eval/webpage/figures/vicuna.jpeg differ diff --git a/approach/vlm/LLaVA/llava/eval/webpage/index.html b/approach/vlm/LLaVA/llava/eval/webpage/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c2e3cf020ba7d8e064f2cd801788a5d2d50b97da --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/webpage/index.html @@ -0,0 +1,162 @@ + + + + + + Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots + + + + + + + + +
+

Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots

+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+ + +
+
+ +
+
+
+ other logo +
+
+
+
+ + +
+
+
+
+ vicuna logo +
+
+
+ +
+
+ + +
+
+
+ + +
+
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Assistant #2 (Vicuna, our model) +
+
+
+
+
+
+
+
+
+
+ + +
+
GPT-4 Evaluation
+
+
+
+
+
+
+
+
+ +
+
+ This website is co-authored with GPT-4. +
+
+ + + + + + + + + + + + + diff --git a/approach/vlm/LLaVA/llava/eval/webpage/script.js b/approach/vlm/LLaVA/llava/eval/webpage/script.js new file mode 100644 index 0000000000000000000000000000000000000000..4b71e3d5618a262e4746f58e5d10947b73370dca --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/webpage/script.js @@ -0,0 +1,245 @@ +// Description: Script for the evaluation webpage. + +let currentQuestionIndex = 1; + +// Store the model name mapping for later use. +modelNameMapping = { + "gpt35": "ChatGPT-3.5", + "gpt4": "GPT-4", + "alpaca": "Alpaca-13b", + "vicuna": "Vicuna-13b", + "llama": "LLaMA-13b", + "bard": "Bard", +}; + +modelFigureMapping = { + "vicuna": "figures/vicuna.jpeg", + // Image from: https://commons.wikimedia.org/wiki/File:ChatGPT_logo.svg + "gpt35": "figures/chatgpt.svg", + // Image from: https://www.reddit.com/r/logodesign/comments/1128aat/google_ai_bard_logo_design/ + "bard": "figures/bard.jpg", + // Image from: https://crfm.stanford.edu/2023/03/13/alpaca.html + "alpaca": "figures/alpaca.png", + // Image adapted from https://commons.wikimedia.org/wiki/File:Llama_on_Machu_Picchu.jpg + "llama": "figures/llama.jpg", +} + +// Store the question data in a mapping for later use. +questionMapping = {}; +// Store the question ids in a mapping for later use. +categoryMapping = {}; +// Store the number of questions for later use. +questionsCount = 0; + + +function text2Markdown(text) { + // Normalize the text for markdown rendering. + text = text.trim().replaceAll('\n\n', '\n').replaceAll('\n', '\n\n'); + return marked.parse(text); +} + +function capitalizeFirstChar(str) { + if (!str || str.length === 0) { + return str; + } + return str.charAt(0).toUpperCase() + str.slice(1); +} + +function updateQuestionSelect(question_id) { + const select = document.getElementById('question-select'); + // Clear the question select. + select.innerHTML = ''; + // Populate the question select. + category = questionMapping[question_id].category; + categoryMapping[category].forEach(question_id => { + const question = questionMapping[question_id]; + const option = document.createElement('option'); + option.value = question_id; + option.textContent = 'Q' + question_id.toString() + ': ' + question.question; + select.appendChild(option); + }); + select.value = question_id; +} + +function updateModelSelect() { + const select = document.getElementById('model-select'); + img_path = modelFigureMapping[select.value]; + document.getElementById('other-model-figure').src = img_path; +} + +function populateModels(models) { + const select = document.getElementById('model-select'); + models.forEach(model => { + const option = document.createElement('option'); + option.value = model; + option.textContent = modelNameMapping[model]; + select.appendChild(option); + }); + updateModelSelect(); +} + +function populateQuestions(questions) { + const category_select = document.getElementById('category-select'); + + questionsCount = questions.length; + questions.forEach(question => { + const option = document.createElement('option'); + // Store the question data in a mapping for later use. + questionMapping[question.id] = { + category: question.category, + question: question.question, + answers: question.answers, + evaluations: question.evaluations, + scores: question.scores, + }; + // Store the question id in the category mapping. + if (question.category in categoryMapping) { + categoryMapping[question.category].push(question.id); + } else { + categoryMapping[question.category] = [question.id]; + const category_option = document.createElement('option'); + category_option.value = question.category; + category_option.textContent = capitalizeFirstChar(question.category); + category_select.appendChild(category_option); + } + }); + // Set the default category. + updateQuestionSelect(currentQuestionIndex); +} + +function displayQuestion(index) { + const question = questionMapping[index].question; + document.getElementById('selected-question').innerHTML = text2Markdown('**Question:** ' + question); + displayAnswers(index); +} + +function displayAnswers(index) { + const question = questionMapping[index]; + const otherModel = document.getElementById('model-select').value; + // render the answers with markdown + document.getElementById('other-model-answer').innerHTML = text2Markdown(question.answers[otherModel]); + document.getElementById('our-model-answer').innerHTML = text2Markdown(question.answers.vicuna); + + // Display evaluation + score = question.scores[otherModel]; + score_text = modelNameMapping[otherModel] + " " + score[0] + "/10, Vicuna-13b " + score[1] + "/10"; + document.getElementById('evaluation-header').textContent = "GPT-4 Evaluation" + " (Score: " + score_text + ")"; + document.getElementById('evaluation-result').innerHTML = text2Markdown(question.evaluations[otherModel]); + + // Update model names + let assistant1_title = "Assistant #1"; // (" + modelNameMapping[otherModel] + ")"; + let assistant2_title = "Assistant #2 (Vicuna-13b, our model)"; + // Update scores/labels. + let assistant1_score_label = score[0].toString() + '/10'; + let assistant2_score_label = score[1].toString() + '/10'; + + const colorRed ='#fa9'; // '#eb978d'; + // const colorGreen = '#c9f2c9'; + const colorBlue = '#8ef'; // '#71dbf9'; + const colorYellow = '#fe7'; // '#fada57'; + let otherModelHeaderColor = ''; + let ourModelHeaderColor = ''; + // Update the winner. + if (score[0] == score[1]) { + assistant1_title = '🏆 ' + assistant1_title; + assistant1_score_label = '🏆 ' + assistant1_score_label; + assistant2_title = '🏆 ' + assistant2_title; + assistant2_score_label = '🏆 ' + assistant2_score_label; + otherModelHeaderColor = colorYellow; + ourModelHeaderColor = colorYellow; + } else if (score[0] > score[1]) { + assistant1_title = '🏆 ' + assistant1_title; + assistant1_score_label = '🏆 ' + assistant1_score_label; + otherModelHeaderColor = colorBlue; + ourModelHeaderColor = colorRed; + } else if (score[0] < score[1]) { + assistant2_title = '🏆 ' + assistant2_title; + assistant2_score_label = '🏆 ' + assistant2_score_label; + otherModelHeaderColor = colorRed; + ourModelHeaderColor = colorBlue; + } + + document.getElementById('other-model-header-bg').style.backgroundColor = otherModelHeaderColor; + document.getElementById('our-model-header').style.backgroundColor = ourModelHeaderColor; + + document.getElementById('other-model-header').textContent = assistant1_title; + document.getElementById('our-model-header').textContent = assistant2_title; + + document.getElementById('other-score-label').textContent = assistant1_score_label; + document.getElementById('our-score-label').textContent = assistant2_score_label; + + // Update expand buttons visibility for both cards after displaying answers + // Reset the expanded state and update expand buttons visibility for both cards after displaying answers + document.querySelectorAll('.expandable-card').forEach(card => { + card.classList.remove('expanded'); + updateExpandButtonVisibility(card); + const expandBtn = card.querySelector('.expand-btn'); + expandBtn.innerHTML = 'keyboard_arrow_down Show more'; // .textContent = 'Show more'; + }); +} + +document.getElementById('question-select').addEventListener('change', e => { + currentQuestionIndex = parseInt(e.target.value); + displayQuestion(currentQuestionIndex); +}); + +document.getElementById('category-select').addEventListener('change', e => { + let currentCategory = e.target.value; + const questionIds = categoryMapping[currentCategory]; + currentQuestionIndex = questionIds[0]; + updateQuestionSelect(currentQuestionIndex); + displayQuestion(currentQuestionIndex); +}); + +// Update expand buttons whenever the model is changed +document.getElementById('model-select').addEventListener('change', () => { + displayAnswers(currentQuestionIndex); + document.querySelectorAll('.expandable-card').forEach(card => { + updateExpandButtonVisibility(card); + }); + updateModelSelect(); +}); + +function switchQuestionAndCategory() { + document.getElementById('question-select').value = currentQuestionIndex; + old_category = document.getElementById('category-select').value; + new_category = questionMapping[currentQuestionIndex].category; + if (old_category != new_category) { + document.getElementById('category-select').value = new_category; + updateQuestionSelect(currentQuestionIndex); + } + displayQuestion(currentQuestionIndex); +} + +document.getElementById('prev-question').addEventListener('click', () => { + // Question index starts from 1. + currentQuestionIndex = Math.max(1, currentQuestionIndex - 1); + switchQuestionAndCategory(); +}); + +document.getElementById('next-question').addEventListener('click', () => { + // Question index starts from 1. + currentQuestionIndex = Math.min(questionsCount, currentQuestionIndex + 1); + switchQuestionAndCategory(); +}); + +function updateExpandButtonVisibility(card) { + const cardTextContainer = card.querySelector('.card-text-container'); + const expandBtn = card.querySelector('.expand-btn'); + if (cardTextContainer.scrollHeight > cardTextContainer.offsetHeight) { + expandBtn.style.display = 'flex'; + } else { + expandBtn.style.display = 'none'; + card.classList.add('expanded'); + } +} + +document.querySelectorAll('.expand-btn').forEach(btn => { + btn.addEventListener('click', e => { + const card = e.target.closest('.expandable-card'); + card.classList.toggle('expanded'); + const more = 'keyboard_arrow_down Show more'; + const less = 'keyboard_arrow_up Show less'; + e.target.innerHTML = card.classList.contains('expanded') ? less : more; + }); +}); diff --git a/approach/vlm/LLaVA/llava/eval/webpage/styles.css b/approach/vlm/LLaVA/llava/eval/webpage/styles.css new file mode 100644 index 0000000000000000000000000000000000000000..7b6d6fc69b336c0a5d103be9fb13a0e0897c76a3 --- /dev/null +++ b/approach/vlm/LLaVA/llava/eval/webpage/styles.css @@ -0,0 +1,105 @@ +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f8f9fa; +} + +.navbar-dark .navbar-nav .nav-link { + color: #f1cf68; + font-size: 1.1rem; + padding: 0.5rem 0.6rem; +} + +.card-header { + font-weight: bold; +} + +.card { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + transition: 0.3s; +} + +.card:hover { + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); +} + +button { + transition: background-color 0.3s; +} + +button:hover { + background-color: #007bff; +} + +@media (max-width: 767px) { + .form-row .form-group { + margin-bottom: 10px; + } +} + +/* Extra styles */ + +.expandable-card .card-text-container { + max-height: 200px; + overflow-y: hidden; + position: relative; +} + +.expandable-card.expanded .card-text-container { + max-height: none; +} + +.expand-btn { + position: relative; + display: none; + background-color: rgba(255, 255, 255, 0.8); + color: #510c75; + border-color: transparent; +} + +.expand-btn:hover { + background-color: rgba(200, 200, 200, 0.8); + text-decoration: none; + border-color: transparent; + color: #510c75; +} + +.expand-btn:focus { + outline: none; + text-decoration: none; +} + +.expandable-card:not(.expanded) .card-text-container:after { + content: ""; + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 90px; + background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 1)); +} + +.expandable-card:not(.expanded) .expand-btn { + margin-top: -40px; +} + +.card-body { + padding-bottom: 5px; +} + +.vertical-flex-layout { + justify-content: center; + align-items: center; + height: 100%; + display: flex; + flex-direction: column; + gap: 5px; +} + +.figure-img { + max-width: 100%; + height: auto; +} + +.adjustable-font-size { + font-size: calc(0.5rem + 2vw); +} diff --git a/approach/vlm/LLaVA/llava/mm_utils.py b/approach/vlm/LLaVA/llava/mm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2662b91db2ba1c9fcc470b4654cbe05a11b89ae2 --- /dev/null +++ b/approach/vlm/LLaVA/llava/mm_utils.py @@ -0,0 +1,99 @@ +from PIL import Image +from io import BytesIO +import base64 + +import torch +from transformers import StoppingCriteria +from llava.constants import IMAGE_TOKEN_INDEX + + +def load_image_from_base64(image): + return Image.open(BytesIO(base64.b64decode(image))) + + +def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + +def process_images(images, image_processor, model_cfg): + image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None) + new_images = [] + if image_aspect_ratio == 'pad': + for image in images: + image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean)) + image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + new_images.append(image) + else: + return image_processor(images, return_tensors='pt')['pixel_values'] + if all(x.shape == new_images[0].shape for x in new_images): + new_images = torch.stack(new_images, dim=0) + return new_images + + +def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None): + prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('')] + + def insert_separator(X, sep): + return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1] + + input_ids = [] + offset = 0 + if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id: + offset = 1 + input_ids.append(prompt_chunks[0][0]) + + for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)): + input_ids.extend(x[offset:]) + + if return_tensors is not None: + if return_tensors == 'pt': + return torch.tensor(input_ids, dtype=torch.long) + raise ValueError(f'Unsupported tensor type: {return_tensors}') + return input_ids + + +def get_model_name_from_path(model_path): + model_path = model_path.strip("/") + model_paths = model_path.split("/") + if model_paths[-1].startswith('checkpoint-'): + return model_paths[-2] + "_" + model_paths[-1] + else: + return model_paths[-1] + + + + +class KeywordsStoppingCriteria(StoppingCriteria): + def __init__(self, keywords, tokenizer, input_ids): + self.keywords = keywords + self.keyword_ids = [] + for keyword in keywords: + cur_keyword_ids = tokenizer(keyword).input_ids + if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id: + cur_keyword_ids = cur_keyword_ids[1:] + self.keyword_ids.append(torch.tensor(cur_keyword_ids)) + self.tokenizer = tokenizer + self.start_len = input_ids.shape[1] + + def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO + offset = min(output_ids.shape[1] - self.start_len, 3) + self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids] + for keyword_id in self.keyword_ids: + if output_ids[0, -keyword_id.shape[0]:] == keyword_id: + return True + outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0] + for keyword in self.keywords: + if keyword in outputs: + return True + return False diff --git a/approach/vlm/LLaVA/llava/model/__init__.py b/approach/vlm/LLaVA/llava/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa79960540bf9247f5df9f02656ca84499cdbfd6 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/__init__.py @@ -0,0 +1,2 @@ +from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig +from .language_model.llava_mpt import LlavaMPTForCausalLM, LlavaMPTConfig diff --git a/approach/vlm/LLaVA/llava/model/apply_delta.py b/approach/vlm/LLaVA/llava/model/apply_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..666dd9691bde7d54ddf2871e311d6f621e29f099 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/apply_delta.py @@ -0,0 +1,48 @@ +""" +Usage: +python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta +""" +import argparse + +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava import LlavaLlamaForCausalLM + + +def apply_delta(base_model_path, target_model_path, delta_path): + print("Loading base model") + base = AutoModelForCausalLM.from_pretrained( + base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Loading delta") + delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + delta_tokenizer = AutoTokenizer.from_pretrained(delta_path) + + print("Applying delta") + for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"): + if name not in base.state_dict(): + assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model' + continue + if param.data.shape == base.state_dict()[name].shape: + param.data += base.state_dict()[name] + else: + assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \ + f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}' + bparam = base.state_dict()[name] + param.data[:bparam.shape[0], :bparam.shape[1]] += bparam + + print("Saving target model") + delta.save_pretrained(target_model_path) + delta_tokenizer.save_pretrained(target_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--base-model-path", type=str, required=True) + parser.add_argument("--target-model-path", type=str, required=True) + parser.add_argument("--delta-path", type=str, required=True) + + args = parser.parse_args() + + apply_delta(args.base_model_path, args.target_model_path, args.delta_path) diff --git a/approach/vlm/LLaVA/llava/model/builder.py b/approach/vlm/LLaVA/llava/model/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..46d779365cf145e3d2c2e54f326a5a47ab924480 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/builder.py @@ -0,0 +1,148 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import os +import warnings +import shutil + +from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig +import torch +from llava.model import * +from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + + +def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda"): + kwargs = {"device_map": device_map} + + if load_8bit: + kwargs['load_in_8bit'] = True + elif load_4bit: + kwargs['load_in_4bit'] = True + kwargs['quantization_config'] = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=torch.float16, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type='nf4' + ) + else: + kwargs['torch_dtype'] = torch.float16 + + if 'llava' in model_name.lower(): + # Load LLaVA model + if 'lora' in model_name.lower() and model_base is None: + warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.') + if 'lora' in model_name.lower() and model_base is not None: + lora_cfg_pretrained = AutoConfig.from_pretrained(model_path) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + print('Loading LLaVA from base model...') + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs) + token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features + if model.lm_head.weight.shape[0] != token_num: + model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype)) + + print('Loading additional LLaVA weights...') + if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')): + non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu') + else: + # this is probably from HF Hub + from huggingface_hub import hf_hub_download + def load_from_hf(repo_id, filename, subfolder=None): + cache_file = hf_hub_download( + repo_id=repo_id, + filename=filename, + subfolder=subfolder) + return torch.load(cache_file, map_location='cpu') + non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin') + non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()} + if any(k.startswith('model.model.') for k in non_lora_trainables): + non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()} + model.load_state_dict(non_lora_trainables, strict=False) + + from peft import PeftModel + print('Loading LoRA weights...') + model = PeftModel.from_pretrained(model, model_path) + print('Merging LoRA weights...') + model = model.merge_and_unload() + print('Model is loaded...') + elif model_base is not None: + # this may be mm projector only + print('Loading LLaVA from base model...') + if 'mpt' in model_name.lower(): + if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')): + shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py')) + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True) + cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True) + model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + cfg_pretrained = AutoConfig.from_pretrained(model_path) + model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs) + + mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu') + mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()} + model.load_state_dict(mm_projector_weights, strict=False) + else: + if 'mpt' in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + else: + # Load language model + if model_base is not None: + # PEFT model + from peft import PeftModel + tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto") + print(f"Loading LoRA weights from {model_path}") + model = PeftModel.from_pretrained(model, model_path) + print(f"Merging weights") + model = model.merge_and_unload() + print('Convert to FP16...') + model.to(torch.float16) + else: + use_fast = False + if 'mpt' in model_name.lower(): + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs) + else: + tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False) + model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs) + + image_processor = None + + if 'llava' in model_name.lower(): + mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False) + mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True) + if mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + if mm_use_im_start_end: + tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + model.resize_token_embeddings(len(tokenizer)) + + vision_tower = model.get_vision_tower() + if not vision_tower.is_loaded: + vision_tower.load_model() + vision_tower.to(device=device, dtype=torch.float16) + image_processor = vision_tower.image_processor + + if hasattr(model.config, "max_sequence_length"): + context_len = model.config.max_sequence_length + else: + context_len = 2048 + + return tokenizer, model, image_processor, context_len diff --git a/approach/vlm/LLaVA/llava/model/consolidate.py b/approach/vlm/LLaVA/llava/model/consolidate.py new file mode 100644 index 0000000000000000000000000000000000000000..1e324210e229eeba23b75791bba82df7c6e639eb --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/consolidate.py @@ -0,0 +1,29 @@ +""" +Usage: +python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate +""" +import argparse + +import torch +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava.model import * +from llava.model.utils import auto_upgrade + + +def consolidate_ckpt(src_path, dst_path): + print("Loading model") + auto_upgrade(src_path) + src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False) + src_model.save_pretrained(dst_path) + src_tokenizer.save_pretrained(dst_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--src", type=str, required=True) + parser.add_argument("--dst", type=str, required=True) + + args = parser.parse_args() + + consolidate_ckpt(args.src, args.dst) diff --git a/approach/vlm/LLaVA/llava/model/language_model/llava_llama.py b/approach/vlm/LLaVA/llava/model/language_model/llava_llama.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ce3e86f788856e669a597b15939142138fd230 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/llava_llama.py @@ -0,0 +1,140 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +from transformers import AutoConfig, AutoModelForCausalLM, \ + LlamaConfig, LlamaModel, LlamaForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaConfig(LlamaConfig): + model_type = "llava" + + +class LlavaLlamaModel(LlavaMetaModel, LlamaModel): + config_class = LlavaConfig + + def __init__(self, config: LlamaConfig): + super(LlavaLlamaModel, self).__init__(config) + + +class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaConfig + + def __init__(self, config): + super(LlamaForCausalLM, self).__init__(config) + self.model = LlavaLlamaModel(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_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + 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 + + input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_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/pipeline 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, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + # 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( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + "images": kwargs.get("images", None), + } + ) + return model_inputs + +AutoConfig.register("llava", LlavaConfig) +AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM) diff --git a/approach/vlm/LLaVA/llava/model/language_model/llava_mpt.py b/approach/vlm/LLaVA/llava/model/language_model/llava_mpt.py new file mode 100644 index 0000000000000000000000000000000000000000..39dc8807ef8d339fb7cde331c0deabfe5ce7f93e --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/llava_mpt.py @@ -0,0 +1,113 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import List, Optional, Tuple +import warnings + +import torch +import torch.nn.functional as F +import math + +from transformers import AutoConfig, AutoModelForCausalLM +from transformers.modeling_outputs import CausalLMOutputWithPast + +from .mpt.modeling_mpt import MPTConfig, MPTForCausalLM, MPTModel +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMPTConfig(MPTConfig): + model_type = "llava_mpt" + + +class LlavaMPTModel(LlavaMetaModel, MPTModel): + config_class = LlavaMPTConfig + + def __init__(self, config: MPTConfig): + config.hidden_size = config.d_model + super(LlavaMPTModel, self).__init__(config) + + def embed_tokens(self, x): + return self.wte(x) + + +class LlavaMPTForCausalLM(MPTForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMPTConfig + supports_gradient_checkpointing = True + + def __init__(self, config): + super(MPTForCausalLM, self).__init__(config) + + if not config.tie_word_embeddings: + raise ValueError('MPTForCausalLM only supports tied word embeddings') + self.transformer = LlavaMPTModel(config) + self.logit_scale = None + if config.logit_scale is not None: + logit_scale = config.logit_scale + if isinstance(logit_scale, str): + if logit_scale == 'inv_sqrt_d_model': + logit_scale = 1 / math.sqrt(config.d_model) + else: + raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.") + self.logit_scale = logit_scale + + def get_model(self): + return self.transformer + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, LlavaMPTModel): + module.gradient_checkpointing = value + + def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, images=None): + return_dict = return_dict if return_dict is not None else self.config.return_dict + use_cache = use_cache if use_cache is not None else self.config.use_cache + + input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) + outputs = self.transformer(input_ids=input_ids, inputs_embeds=inputs_embeds, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache) + # FIXME: this is a hack to fix the multiple gpu inference issue in https://github.com/haotian-liu/LLaVA/issues/338 + logits = F.linear(outputs.last_hidden_state.to(self.transformer.wte.weight.device), self.transformer.wte.weight) + if self.logit_scale is not None: + if self.logit_scale == 0: + warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.') + logits *= self.logit_scale + loss = None + if labels is not None: + labels = torch.roll(labels, shifts=-1) + labels[:, -1] = -100 + loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1)) + return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + if inputs_embeds is not None: + raise NotImplementedError('inputs_embeds is not implemented for MPT yet') + attention_mask = kwargs['attention_mask'].bool() + if attention_mask[:, -1].sum() != attention_mask.shape[0]: + raise NotImplementedError('MPT does not support generation with right padding.') + if self.transformer.attn_uses_sequence_id and self.training: + sequence_id = torch.zeros_like(input_ids[:1]) + else: + sequence_id = None + if past_key_values is not None: + input_ids = input_ids[:, -1].unsqueeze(-1) + if self.transformer.prefix_lm: + prefix_mask = torch.ones_like(attention_mask) + if kwargs.get('use_cache') == False: + raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.') + else: + prefix_mask = None + return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True), "images": kwargs.get("images", None)} + + +AutoConfig.register("llava_mpt", LlavaMPTConfig) +AutoModelForCausalLM.register(LlavaMPTConfig, LlavaMPTForCausalLM) diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/adapt_tokenizer.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/adapt_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e640c157e8f5581953c518df0611a423225ef598 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/adapt_tokenizer.py @@ -0,0 +1,41 @@ +from typing import Union +from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast +Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] +NUM_SENTINEL_TOKENS: int = 100 + +def adapt_tokenizer_for_denoising(tokenizer: Tokenizer): + """Adds sentinel tokens and padding token (if missing). + + Expands the tokenizer vocabulary to include sentinel tokens + used in mixture-of-denoiser tasks as well as a padding token. + + All added tokens are added as special tokens. No tokens are + added if sentinel tokens and padding token already exist. + """ + sentinels_to_add = [f'' for i in range(NUM_SENTINEL_TOKENS)] + tokenizer.add_tokens(sentinels_to_add, special_tokens=True) + if tokenizer.pad_token is None: + tokenizer.add_tokens('', special_tokens=True) + tokenizer.pad_token = '' + assert tokenizer.pad_token_id is not None + sentinels = ''.join([f'' for i in range(NUM_SENTINEL_TOKENS)]) + _sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids + tokenizer.sentinel_token_ids = _sentinel_token_ids + +class AutoTokenizerForMOD(AutoTokenizer): + """AutoTokenizer + Adaptation for MOD. + + A simple wrapper around AutoTokenizer to make instantiating + an MOD-adapted tokenizer a bit easier. + + MOD-adapted tokenizers have sentinel tokens (e.g., ), + a padding token, and a property to get the token ids of the + sentinel tokens. + """ + + @classmethod + def from_pretrained(cls, *args, **kwargs): + """See `AutoTokenizer.from_pretrained` docstring.""" + tokenizer = super().from_pretrained(*args, **kwargs) + adapt_tokenizer_for_denoising(tokenizer) + return tokenizer \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/attention.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c758afa34c534a251fe6d164eb81a6f3a3230b --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/attention.py @@ -0,0 +1,300 @@ +"""Attention layers.""" +import math +import warnings +from typing import Optional +import torch +import torch.nn as nn +from einops import rearrange +from packaging import version +from torch import nn +from .norm import LPLayerNorm + +def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool): + if original_is_causal and num_query_tokens != num_key_tokens: + if num_query_tokens != 1: + raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.') + else: + return False + return original_is_causal + +def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False): + q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads) + kv_n_heads = 1 if multiquery else n_heads + k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads) + v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads) + if past_key_value is not None: + if len(past_key_value) != 0: + k = torch.cat([past_key_value[0], k], dim=3) + v = torch.cat([past_key_value[1], v], dim=2) + past_key_value = (k, v) + (b, _, s_q, d) = q.shape + s_k = k.size(-1) + if softmax_scale is None: + softmax_scale = 1 / math.sqrt(d) + attn_weight = q.matmul(k) * softmax_scale + if attn_bias is not None: + _s_q = max(0, attn_bias.size(2) - s_q) + _s_k = max(0, attn_bias.size(3) - s_k) + attn_bias = attn_bias[:, :, _s_q:, _s_k:] + if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q): + raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.') + attn_weight = attn_weight + attn_bias + min_val = torch.finfo(q.dtype).min + if key_padding_mask is not None: + if attn_bias is not None: + warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.') + attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val) + if is_causal and (not q.size(2) == 1): + s = max(s_q, s_k) + causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16) + causal_mask = causal_mask.tril() + causal_mask = causal_mask.to(torch.bool) + causal_mask = ~causal_mask + causal_mask = causal_mask[-s_q:, -s_k:] + attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val) + attn_weight = torch.softmax(attn_weight, dim=-1) + if dropout_p: + attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True) + out = attn_weight.to(v.dtype).matmul(v) + out = rearrange(out, 'b h s d -> b s (h d)') + if needs_weights: + return (out, attn_weight, past_key_value) + return (out, None, past_key_value) + +def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]): + for tensor in tensors: + if tensor.dtype not in valid_dtypes: + raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.') + if not tensor.is_cuda: + raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).') + +def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False): + try: + from flash_attn import bert_padding, flash_attn_interface + except: + raise RuntimeError('Please install flash-attn==1.0.3.post0') + check_valid_inputs(query, key, value) + if past_key_value is not None: + if len(past_key_value) != 0: + key = torch.cat([past_key_value[0], key], dim=1) + value = torch.cat([past_key_value[1], value], dim=1) + past_key_value = (key, value) + if attn_bias is not None: + _s_q = max(0, attn_bias.size(2) - query.size(1)) + _s_k = max(0, attn_bias.size(3) - key.size(1)) + attn_bias = attn_bias[:, :, _s_q:, _s_k:] + if attn_bias is not None: + raise NotImplementedError(f'attn_bias not implemented for flash attn.') + (batch_size, seqlen) = query.shape[:2] + if key_padding_mask is None: + key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool) + query_padding_mask = key_padding_mask[:, -query.size(1):] + (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask) + query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads) + (key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask) + key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads) + (value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask) + value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads) + if multiquery: + key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1)) + value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1)) + dropout_p = dropout_p if training else 0.0 + reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal) + output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights) + output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen) + return (output, None, past_key_value) + +def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False): + try: + from .flash_attn_triton import flash_attn_func + except: + _installed = False + if version.parse(torch.__version__) < version.parse('2.0.0'): + _installed = True + try: + from flash_attn.flash_attn_triton import flash_attn_func + except: + _installed = False + if not _installed: + raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.') + check_valid_inputs(query, key, value) + if past_key_value is not None: + if len(past_key_value) != 0: + key = torch.cat([past_key_value[0], key], dim=1) + value = torch.cat([past_key_value[1], value], dim=1) + past_key_value = (key, value) + if attn_bias is not None: + _s_q = max(0, attn_bias.size(2) - query.size(1)) + _s_k = max(0, attn_bias.size(3) - key.size(1)) + attn_bias = attn_bias[:, :, _s_q:, _s_k:] + if dropout_p: + raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.') + if needs_weights: + raise NotImplementedError(f'attn_impl: triton cannot return attn weights.') + if key_padding_mask is not None: + warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.') + (b_size, s_k) = key_padding_mask.shape[:2] + if attn_bias is None: + attn_bias = query.new_zeros(b_size, 1, 1, s_k) + attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min) + query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads) + key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads) + value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads) + if multiquery: + key = key.expand(*key.shape[:2], n_heads, key.size(-1)) + value = value.expand(*value.shape[:2], n_heads, value.size(-1)) + reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal) + attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale) + output = attn_output.view(*attn_output.shape[:2], -1) + return (output, None, past_key_value) + +class MultiheadAttention(nn.Module): + """Multi-head self attention. + + Using torch or triton attention implemetation enables user to also use + additive bias. + """ + + def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None): + super().__init__() + self.attn_impl = attn_impl + self.clip_qkv = clip_qkv + self.qk_ln = qk_ln + self.d_model = d_model + self.n_heads = n_heads + self.softmax_scale = softmax_scale + if self.softmax_scale is None: + self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads) + self.attn_dropout_p = attn_pdrop + self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device) + fuse_splits = (d_model, 2 * d_model) + self.Wqkv._fused = (0, fuse_splits) + if self.qk_ln: + layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm + self.q_ln = layernorm_class(self.d_model, device=device) + self.k_ln = layernorm_class(self.d_model, device=device) + if self.attn_impl == 'flash': + self.attn_fn = flash_attn_fn + elif self.attn_impl == 'triton': + self.attn_fn = triton_flash_attn_fn + if verbose: + warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.') + elif self.attn_impl == 'torch': + self.attn_fn = scaled_multihead_dot_product_attention + if torch.cuda.is_available() and verbose: + warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.') + else: + raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') + self.out_proj = nn.Linear(self.d_model, self.d_model, device=device) + self.out_proj._is_residual = True + + def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False): + qkv = self.Wqkv(x) + if self.clip_qkv: + qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv) + (query, key, value) = qkv.chunk(3, dim=2) + key_padding_mask = attention_mask + if self.qk_ln: + dtype = query.dtype + query = self.q_ln(query).to(dtype) + key = self.k_ln(key).to(dtype) + (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights) + return (self.out_proj(context), attn_weights, past_key_value) + +class MultiQueryAttention(nn.Module): + """Multi-Query self attention. + + Using torch or triton attention implemetation enables user to also use + additive bias. + """ + + def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None): + super().__init__() + self.attn_impl = attn_impl + self.clip_qkv = clip_qkv + self.qk_ln = qk_ln + self.d_model = d_model + self.n_heads = n_heads + self.head_dim = d_model // n_heads + self.softmax_scale = softmax_scale + if self.softmax_scale is None: + self.softmax_scale = 1 / math.sqrt(self.head_dim) + self.attn_dropout_p = attn_pdrop + self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device) + fuse_splits = (d_model, d_model + self.head_dim) + self.Wqkv._fused = (0, fuse_splits) + if self.qk_ln: + layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm + self.q_ln = layernorm_class(d_model, device=device) + self.k_ln = layernorm_class(self.head_dim, device=device) + if self.attn_impl == 'flash': + self.attn_fn = flash_attn_fn + elif self.attn_impl == 'triton': + self.attn_fn = triton_flash_attn_fn + if verbose: + warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.') + elif self.attn_impl == 'torch': + self.attn_fn = scaled_multihead_dot_product_attention + if torch.cuda.is_available() and verbose: + warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.') + else: + raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') + self.out_proj = nn.Linear(self.d_model, self.d_model, device=device) + self.out_proj._is_residual = True + + def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False): + qkv = self.Wqkv(x) + if self.clip_qkv: + qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv) + (query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2) + key_padding_mask = attention_mask + if self.qk_ln: + dtype = query.dtype + query = self.q_ln(query).to(dtype) + key = self.k_ln(key).to(dtype) + (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True) + return (self.out_proj(context), attn_weights, past_key_value) + +def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id): + if attn_impl == 'flash': + return None + elif attn_impl in ['torch', 'triton']: + if alibi: + if (prefix_lm or not causal) or use_sequence_id: + return (1, n_heads, seq_len, seq_len) + return (1, n_heads, 1, seq_len) + elif prefix_lm or use_sequence_id: + return (1, 1, seq_len, seq_len) + return None + else: + raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') + +def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8): + if attn_impl == 'flash': + return None + elif attn_impl in ['torch', 'triton']: + if alibi: + (device, dtype) = (attn_bias.device, attn_bias.dtype) + attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype)) + return attn_bias + else: + raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.') + +def gen_slopes(n_heads, alibi_bias_max=8, device=None): + _n_heads = 2 ** math.ceil(math.log2(n_heads)) + m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device) + m = m.mul(alibi_bias_max / _n_heads) + slopes = 1.0 / torch.pow(2, m) + if _n_heads != n_heads: + slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads] + return slopes.view(1, n_heads, 1, 1) + +def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None): + alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len) + if full: + alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1) + alibi_bias = alibi_bias.abs().mul(-1) + slopes = gen_slopes(n_heads, alibi_bias_max, device=device) + alibi_bias = alibi_bias * slopes + return alibi_bias.to(dtype=dtype) +ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention} \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/blocks.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..537e7f9190713bd73332aeb80702efa39320ca60 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/blocks.py @@ -0,0 +1,41 @@ +"""GPT Blocks used for the GPT Model.""" +from typing import Dict, Optional, Tuple +import torch +import torch.nn as nn +from .attention import ATTN_CLASS_REGISTRY +from .norm import NORM_CLASS_REGISTRY + +class MPTMLP(nn.Module): + + def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None): + super().__init__() + self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device) + self.act = nn.GELU(approximate='none') + self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device) + self.down_proj._is_residual = True + + def forward(self, x): + return self.down_proj(self.act(self.up_proj(x))) + +class MPTBlock(nn.Module): + + def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs): + del kwargs + super().__init__() + norm_class = NORM_CLASS_REGISTRY[norm_type.lower()] + attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']] + self.norm_1 = norm_class(d_model, device=device) + self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device) + self.norm_2 = norm_class(d_model, device=device) + self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device) + self.resid_attn_dropout = nn.Dropout(resid_pdrop) + self.resid_ffn_dropout = nn.Dropout(resid_pdrop) + + def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]: + a = self.norm_1(x) + (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal) + x = x + self.resid_attn_dropout(b) + m = self.norm_2(x) + n = self.ffn(m) + x = x + self.resid_ffn_dropout(n) + return (x, attn_weights, past_key_value) \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/configuration_mpt.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/configuration_mpt.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eb6fc59b50654ddbe19ed56ad8c0abd1b8efef --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/configuration_mpt.py @@ -0,0 +1,118 @@ +"""A HuggingFace-style model configuration.""" +from typing import Dict, Optional, Union +from transformers import PretrainedConfig +attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8} +init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0} + +class MPTConfig(PretrainedConfig): + model_type = 'mpt' + + def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs): + """The MPT configuration class. + + Args: + d_model (int): The size of the embedding dimension of the model. + n_heads (int): The number of attention heads. + n_layers (int): The number of layers in the model. + expansion_ratio (int): The ratio of the up/down scale in the MLP. + max_seq_len (int): The maximum sequence length of the model. + vocab_size (int): The size of the vocabulary. + resid_pdrop (float): The dropout probability applied to the attention output before combining with residual. + emb_pdrop (float): The dropout probability for the embedding layer. + learned_pos_emb (bool): Whether to use learned positional embeddings + attn_config (Dict): A dictionary used to configure the model's attention module: + attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention + attn_pdrop (float): The dropout probability for the attention layers. + attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'. + qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer. + clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to + this value. + softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None, + use the default scale of ``1/sqrt(d_keys)``. + prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an + extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix + can attend to one another bi-directionally. Tokens outside the prefix use causal attention. + attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id. + When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates + which sub-sequence each token belongs to. + Defaults to ``False`` meaning any provided `sequence_id` will be ignored. + alibi (bool): Whether to use the alibi bias instead of position embeddings. + alibi_bias_max (int): The maximum value of the alibi bias. + init_device (str): The device to use for parameter initialization. + logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value. + no_bias (bool): Whether to use bias in all layers. + verbose (int): The verbosity level. 0 is silent. + embedding_fraction (float): The fraction to scale the gradients of the embedding layer by. + norm_type (str): choose type of norm to use + multiquery_attention (bool): Whether to use multiquery attention implementation. + use_cache (bool): Whether or not the model should return the last key/values attentions + init_config (Dict): A dictionary used to configure the model initialization: + init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_', + 'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or + 'xavier_normal_'. These mimic the parameter initialization methods in PyTorch. + init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True. + emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer. + emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution + used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``. + init_std (float): The standard deviation of the normal distribution used to initialize the model, + if using the baseline_ parameter initialization scheme. + init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes. + fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes. + init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes. + --- + See llmfoundry.models.utils.param_init_fns.py for info on other param init config options + """ + self.d_model = d_model + self.n_heads = n_heads + self.n_layers = n_layers + self.expansion_ratio = expansion_ratio + self.max_seq_len = max_seq_len + self.vocab_size = vocab_size + self.resid_pdrop = resid_pdrop + self.emb_pdrop = emb_pdrop + self.learned_pos_emb = learned_pos_emb + self.attn_config = attn_config + self.init_device = init_device + self.logit_scale = logit_scale + self.no_bias = no_bias + self.verbose = verbose + self.embedding_fraction = embedding_fraction + self.norm_type = norm_type + self.use_cache = use_cache + self.init_config = init_config + if 'name' in kwargs: + del kwargs['name'] + if 'loss_fn' in kwargs: + del kwargs['loss_fn'] + super().__init__(**kwargs) + self._validate_config() + + def _set_config_defaults(self, config, config_defaults): + for (k, v) in config_defaults.items(): + if k not in config: + config[k] = v + return config + + def _validate_config(self): + self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults) + self.init_config = self._set_config_defaults(self.init_config, init_config_defaults) + if self.d_model % self.n_heads != 0: + raise ValueError('d_model must be divisible by n_heads') + if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])): + raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1") + if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']: + raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}") + if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']: + raise NotImplementedError('prefix_lm only implemented with torch and triton attention.') + if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']: + raise NotImplementedError('alibi only implemented with torch and triton attention.') + if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']: + raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.') + if self.embedding_fraction > 1 or self.embedding_fraction <= 0: + raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!') + if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model': + raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.") + if self.init_config.get('name', None) is None: + raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.") + if not self.learned_pos_emb and (not self.attn_config['alibi']): + raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.') \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/custom_embedding.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/custom_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..ab357952c397f47898863e8405c4958bb8de82fd --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/custom_embedding.py @@ -0,0 +1,11 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +class SharedEmbedding(nn.Embedding): + + def forward(self, input: Tensor, unembed: bool=False) -> Tensor: + if unembed: + return F.linear(input, self.weight) + return super().forward(input) \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a42186d982283add95b63d99fc118e845bcf9d --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py @@ -0,0 +1,484 @@ +""" +Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py +update imports to use 'triton_pre_mlir' + +*Experimental* implementation of FlashAttention in Triton. +Tested with triton==2.0.0.dev20221202. +Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions +other than 64: +https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207 +We'll update this implementation with the new Triton backend once this is fixed. + +We use the FlashAttention implementation from Phil Tillet a starting point. +https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py + +Changes: +- Implement both causal and non-causal attention. +- Implement both self-attention and cross-attention. +- Support arbitrary seqlens (not just multiples of 128), for both forward and backward. +- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward. +- Support attention bias. +- Speed up the forward pass a bit, and only store the LSE instead of m and l. +- Make the backward for d=128 much faster by reducing register spilling. +- Optionally parallelize the backward pass across seqlen_k, to deal with the case of +small batch size * nheads. + +Caution: +- This is an *experimental* implementation. The forward pass should be quite robust but +I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler). +- This implementation has only been tested on A100. +- If you plan to use headdim other than 64 and 128, you should test for race conditions +(due to the Triton compiler), as done in tests/test_flash_attn.py +"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions +for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident +that there are none left for other head dimensions. + +Differences between this Triton version and the CUDA version: +- Triton version doesn't support dropout. +- Triton forward is generally faster than CUDA forward, while Triton backward is +generally slower than CUDA backward. Overall Triton forward + backward is slightly slower +than CUDA forward + backward. +- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor). +- Triton version supports attention bias, while CUDA version doesn't. +""" +import math +import torch +import triton_pre_mlir as triton +import triton_pre_mlir.language as tl + +@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']}) +@triton.jit +def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_HEADDIM) + q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :]) + k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :]) + v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :]) + if BIAS_TYPE == 'vector': + b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n + elif BIAS_TYPE == 'matrix': + b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :]) + t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m + lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') + acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32) + if EVEN_M & EVEN_N: + if EVEN_HEADDIM: + q = tl.load(q_ptrs) + else: + q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + elif EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0) + else: + q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) + end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k) + for start_n in range(0, end_n, BLOCK_N): + start_n = tl.multiple_of(start_n, BLOCK_N) + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + k = tl.load(k_ptrs + start_n * stride_kn) + else: + k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0) + elif EVEN_HEADDIM: + k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0) + else: + k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k, trans_b=True) + if not EVEN_N: + qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf')) + if IS_CAUSAL: + qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf')) + if BIAS_TYPE != 'none': + if BIAS_TYPE == 'vector': + if EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == 'matrix': + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32) + qk = qk * softmax_scale + bias + m_ij = tl.maximum(tl.max(qk, 1), lse_i) + p = tl.exp(qk - m_ij[:, None]) + else: + m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i) + p = tl.exp(qk * softmax_scale - m_ij[:, None]) + l_ij = tl.sum(p, 1) + acc_o_scale = tl.exp(m_i - m_ij) + tl.store(t_ptrs, acc_o_scale) + acc_o_scale = tl.load(t_ptrs) + acc_o = acc_o * acc_o_scale[:, None] + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + v = tl.load(v_ptrs + start_n * stride_vn) + else: + v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0) + elif EVEN_HEADDIM: + v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0) + else: + v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) + p = p.to(v.dtype) + acc_o += tl.dot(p, v) + m_i = m_ij + l_i_new = tl.exp(lse_i - m_ij) + l_ij + lse_i = m_ij + tl.log(l_i_new) + o_scale = tl.exp(m_i - lse_i) + tl.store(t_ptrs, o_scale) + o_scale = tl.load(t_ptrs) + acc_o = acc_o * o_scale[:, None] + start_m = tl.program_id(0) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m + tl.store(lse_ptrs, lse_i) + offs_d = tl.arange(0, BLOCK_HEADDIM) + out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :]) + if EVEN_M: + if EVEN_HEADDIM: + tl.store(out_ptrs, acc_o) + else: + tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim) + elif EVEN_HEADDIM: + tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q) + else: + tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim)) + +@triton.jit +def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32) + do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32) + delta = tl.sum(o * do, axis=1) + tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta) + +@triton.jit +def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr): + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + tl.store(dv_ptrs, dv) + tl.store(dk_ptrs, dk) + else: + tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim) + tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim) + elif EVEN_HEADDIM: + tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k) + tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k) + else: + tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + +@triton.jit +def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): + begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M + offs_qm = begin_m + tl.arange(0, BLOCK_M) + offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_m = tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :]) + k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :]) + v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :]) + do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :]) + dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :]) + if BIAS_TYPE == 'vector': + b_ptrs = Bias + offs_n + elif BIAS_TYPE == 'matrix': + b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :]) + dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + if begin_m >= seqlen_q: + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM) + return + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + k = tl.load(k_ptrs) + v = tl.load(v_ptrs) + else: + k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + elif EVEN_HEADDIM: + k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + else: + k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) + v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) + num_block_m = tl.cdiv(seqlen_q, BLOCK_M) + for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M): + start_m = tl.multiple_of(start_m, BLOCK_M) + offs_m_curr = start_m + offs_m + if EVEN_M & EVEN_HEADDIM: + q = tl.load(q_ptrs) + elif EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) + else: + q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) + qk = tl.dot(q, k, trans_b=True) + if not EVEN_N: + qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf')) + if IS_CAUSAL: + qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf')) + if BIAS_TYPE != 'none': + tl.debug_barrier() + if BIAS_TYPE == 'vector': + if EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == 'matrix': + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32) + qk = qk * softmax_scale + bias + if not EVEN_M & EVEN_HEADDIM: + tl.debug_barrier() + lse_i = tl.load(LSE + offs_m_curr) + if BIAS_TYPE == 'none': + p = tl.exp(qk * softmax_scale - lse_i[:, None]) + else: + p = tl.exp(qk - lse_i[:, None]) + if EVEN_M & EVEN_HEADDIM: + do = tl.load(do_ptrs) + else: + do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) + dv += tl.dot(p.to(do.dtype), do, trans_a=True) + if not EVEN_M & EVEN_HEADDIM: + tl.debug_barrier() + dp = tl.dot(do, v, trans_b=True) + if not EVEN_HEADDIM: + tl.debug_barrier() + Di = tl.load(D + offs_m_curr) + ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype) + dk += tl.dot(ds, q, trans_a=True) + if not EVEN_M & EVEN_HEADDIM: + tl.debug_barrier() + if not ATOMIC_ADD: + if EVEN_M & EVEN_HEADDIM: + dq = tl.load(dq_ptrs, eviction_policy='evict_last') + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq, eviction_policy='evict_last') + elif EVEN_HEADDIM: + dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last') + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last') + else: + dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last') + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last') + else: + dq = tl.dot(ds, k) + if EVEN_M & EVEN_HEADDIM: + tl.atomic_add(dq_ptrs, dq) + elif EVEN_HEADDIM: + tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q) + else: + tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim)) + dq_ptrs += BLOCK_M * stride_dqm + q_ptrs += BLOCK_M * stride_qm + do_ptrs += BLOCK_M * stride_dom + if BIAS_TYPE == 'matrix': + b_ptrs += BLOCK_M * stride_bm + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM) + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + +@triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM']) +@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']}) +@triton.jit +def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + Q += off_b * stride_qb + off_h * stride_qh + K += off_b * stride_kb + off_h * stride_kh + V += off_b * stride_vb + off_h * stride_vh + DO += off_b * stride_dob + off_h * stride_doh + DQ += off_b * stride_dqb + off_h * stride_dqh + DK += off_b * stride_dkb + off_h * stride_dkh + DV += off_b * stride_dvb + off_h * stride_dvh + if BIAS_TYPE != 'none': + Bias += off_b * stride_bb + off_h * stride_bh + D += off_hb * seqlen_q_rounded + LSE += off_hb * seqlen_q_rounded + if not SEQUENCE_PARALLEL: + num_block_n = tl.cdiv(seqlen_k, BLOCK_N) + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N) + else: + start_n = tl.program_id(0) + _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N) + +def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None): + (batch, seqlen_q, nheads, d) = q.shape + (_, seqlen_k, _, _) = k.shape + assert k.shape == (batch, seqlen_k, nheads, d) + assert v.shape == (batch, seqlen_k, nheads, d) + assert d <= 128, 'FlashAttention only support head dimensions up to 128' + assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type' + assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16' + assert q.is_cuda and k.is_cuda and v.is_cuda + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + has_bias = bias is not None + bias_type = 'none' + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + if bias.stride(-1) != 1: + bias = bias.contiguous() + if bias.shape[2:] == (1, seqlen_k): + bias_type = 'vector' + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = 'matrix' + else: + raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)') + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + o = torch.empty_like(q) + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + BLOCK = 128 + num_warps = 4 if d <= 64 else 8 + grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads) + _fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1) + return (o, lse, softmax_scale) + +def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None): + if do.stride(-1) != 1: + do = do.contiguous() + (batch, seqlen_q, nheads, d) = q.shape + (_, seqlen_k, _, _) = k.shape + assert d <= 128 + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + assert lse.shape == (batch, nheads, seqlen_q_rounded) + assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1 + assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1 + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + dq_accum = torch.empty_like(q, dtype=torch.float32) + delta = torch.empty_like(lse) + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads) + _bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM) + has_bias = bias is not None + bias_type = 'none' + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + assert bias.stride(-1) == 1 + if bias.shape[2:] == (1, seqlen_k): + bias_type = 'vector' + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = 'matrix' + else: + raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)') + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads) + _bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM) + dq.copy_(dq_accum) + +class FlashAttnQKVPackedFunc(torch.autograd.Function): + + @staticmethod + def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None): + """ + qkv: (batch, seqlen, 3, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen). + ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen) + """ + if qkv.stride(-1) != 1: + qkv = qkv.contiguous() + (o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale) + ctx.save_for_backward(qkv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + (qkv, o, lse, bias) = ctx.saved_tensors + assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet' + with torch.inference_mode(): + dqkv = torch.empty_like(qkv) + _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) + return (dqkv, None, None, None) +flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply + +class FlashAttnKVPackedFunc(torch.autograd.Function): + + @staticmethod + def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None): + """ + q: (batch, seqlen_q, nheads, headdim) + kv: (batch, seqlen_k, 2, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + (q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]] + (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale) + ctx.save_for_backward(q, kv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + (q, kv, o, lse, bias) = ctx.saved_tensors + if len(ctx.needs_input_grad) >= 3: + assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet' + with torch.inference_mode(): + dq = torch.empty_like(q) + dkv = torch.empty_like(kv) + _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) + return (dq, dkv, None, None, None) +flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply + +class FlashAttnFunc(torch.autograd.Function): + + @staticmethod + def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None): + """ + q: (batch_size, seqlen_q, nheads, headdim) + k, v: (batch_size, seqlen_k, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + (q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]] + (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale) + ctx.save_for_backward(q, k, v, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + (q, k, v, o, lse, bias) = ctx.saved_tensors + assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet' + with torch.inference_mode(): + dq = torch.empty_like(q) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) + return (dq, dk, dv, None, None, None) +flash_attn_func = FlashAttnFunc.apply \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/hf_prefixlm_converter.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/hf_prefixlm_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..8c1a6487202a6400a7116a6bd68b493892ef0d14 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/hf_prefixlm_converter.py @@ -0,0 +1,415 @@ +"""Converts Huggingface Causal LM to Prefix LM. + +Conversion does lightweight surgery on a HuggingFace +Causal LM to convert it to a Prefix LM. + +Prefix LMs accepts a `bidirectional_mask` input in `forward` +and treat the input prompt as the prefix in `generate`. +""" +import math +import warnings +from types import MethodType +from typing import Any, Dict, List, Optional, Tuple, Union +import torch +from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss +from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom +from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom +from transformers.models.bloom.modeling_bloom import logging +from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel +from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM +from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM +from transformers.models.gptj.modeling_gptj import GPTJForCausalLM +from transformers.models.opt.modeling_opt import OPTForCausalLM +from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt +from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt +logger = logging.get_logger(__name__) +_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM) +CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM] + +def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES: + """Converts a GPT-style Causal LM to a Prefix LM. + + Supported HuggingFace model classes: + - `GPT2LMHeadModel` + - `GPTNeoForCausalLM` + - `GPTNeoXForCausalLM` + - `GPTJForCausalLM` + + See `convert_hf_causal_lm_to_prefix_lm` for more details. + """ + if hasattr(model, '_prefix_lm_converted'): + return model + assert isinstance(model, _SUPPORTED_GPT_MODELS) + assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models' + + def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]: + """Helper that gets a list of the model's attention modules. + + Each module has a `bias` buffer used for causal masking. The Prefix LM + conversion adds logic to dynamically manipulate these biases to support + Prefix LM attention masking. + """ + attn_modules = [] + if isinstance(model, GPTNeoXForCausalLM): + blocks = model.gpt_neox.layers + else: + blocks = model.transformer.h + for block in blocks: + if isinstance(model, GPTNeoForCausalLM): + if block.attn.attention_type != 'global': + continue + attn_module = block.attn.attention + elif isinstance(model, GPTNeoXForCausalLM): + attn_module = block.attention + else: + attn_module = block.attn + attn_modules.append(attn_module) + return attn_modules + setattr(model, '_original_forward', getattr(model, 'forward')) + setattr(model, '_original_generate', getattr(model, 'generate')) + + def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None): + """Wraps original forward to enable PrefixLM attention.""" + + def call_og_forward(): + if isinstance(self, GPTNeoXForCausalLM): + return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict) + else: + return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict) + if bidirectional_mask is None: + return call_og_forward() + assert isinstance(bidirectional_mask, torch.Tensor) + attn_modules = _get_attn_modules(model) + (b, s) = bidirectional_mask.shape + max_length = attn_modules[0].bias.shape[-1] + if s > max_length: + raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).') + assert s <= max_length + if s < max_length: + pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device) + bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1) + bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1) + for attn_module in attn_modules: + attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional) + output = call_og_forward() + for attn_module in attn_modules: + attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None] + return output + + def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]): + """Wraps original generate to enable PrefixLM attention.""" + attn_modules = _get_attn_modules(model) + for attn_module in attn_modules: + attn_module.bias.data[:] = 1 + output = self._original_generate(*args, **kwargs) + for attn_module in attn_modules: + attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None] + return output + setattr(model, 'forward', MethodType(forward, model)) + setattr(model, 'generate', MethodType(generate, model)) + setattr(model, '_prefix_lm_converted', True) + return model + +def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM: + """Converts a BLOOM Causal LM to a Prefix LM. + + Supported HuggingFace model classes: + - `BloomForCausalLM` + + See `convert_hf_causal_lm_to_prefix_lm` for more details. + """ + if hasattr(model, '_prefix_lm_converted'): + return model + assert isinstance(model, BloomForCausalLM) + assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models' + + def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor: + combined_attention_mask = None + device = attention_mask.device + (_, src_length) = input_shape + if src_length > 1: + combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length) + if bidirectional_mask is not None: + assert attention_mask.shape == bidirectional_mask.shape + expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length) + combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask) + expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length) + combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask + return combined_attention_mask + + def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + num_heads = self.config.n_head + closest_power_of_2 = 2 ** math.floor(math.log2(num_heads)) + base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32) + powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32) + slopes = torch.pow(base, powers) + if closest_power_of_2 != num_heads: + extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32) + num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2) + extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32) + slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0) + qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1) + ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1) + diffs = qa - ka + key_length - query_length + diffs = -diffs.abs() + alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length) + alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length) + return alibi.to(dtype) + KeyValueT = Tuple[torch.Tensor, torch.Tensor] + + def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: 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, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]: + if deprecated_arguments.pop('position_ids', False) is not False: + warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning) + if len(deprecated_arguments) > 0: + raise ValueError(f'Got unexpected arguments: {deprecated_arguments}') + 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 + if input_ids is not None and inputs_embeds is not None: + raise ValueError('You cannot specify both input_ids and 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 input_ids or inputs_embeds') + if past_key_values is None: + past_key_values = tuple([None] * len(self.h)) + head_mask = self.get_head_mask(head_mask, self.config.n_layer) + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + hidden_states = self.word_embeddings_layernorm(inputs_embeds) + presents = () if use_cache else None + all_self_attentions = () if output_attentions else None + all_hidden_states = () if output_hidden_states else None + seq_length_with_past = seq_length + past_key_values_length = 0 + if past_key_values[0] is not None: + tmp = past_key_values[0][0] + past_key_values_length = tmp.shape[2] + seq_length_with_past = seq_length_with_past + past_key_values_length + if attention_mask is None: + attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device) + else: + attention_mask = attention_mask.to(hidden_states.device) + alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device) + causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length) + for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)): + if output_hidden_states: + hst = (hidden_states,) + all_hidden_states = all_hidden_states + hst + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning('`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, use_cache=use_cache, output_attentions=output_attentions) + return custom_forward + outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i]) + else: + outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi) + hidden_states = outputs[0] + if use_cache is True: + presents = presents + (outputs[1],) + if output_attentions: + oa = (outputs[2 if use_cache else 1],) + all_self_attentions = all_self_attentions + oa + hidden_states = self.ln_f(hidden_states) + if output_hidden_states: + hst = (hidden_states,) + all_hidden_states = all_hidden_states + hst + if not return_dict: + return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)) + return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions) + setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer)) + setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer)) + setattr(model.transformer, 'forward', MethodType(forward, model.transformer)) + KeyValueT = Tuple[torch.Tensor, torch.Tensor] + + def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]: + """Replacement forward method for BloomCausalLM.""" + if deprecated_arguments.pop('position_ids', False) is not False: + warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning) + if len(deprecated_arguments) > 0: + raise ValueError(f'Got unexpected arguments: {deprecated_arguments}') + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict) + hidden_states = transformer_outputs[0] + lm_logits = self.lm_head(hidden_states) + loss = None + if labels is not None: + shift_logits = lm_logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + (batch_size, seq_length, vocab_size) = shift_logits.shape + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)) + if not return_dict: + output = (lm_logits,) + transformer_outputs[1:] + return (loss,) + output if loss is not None else output + return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions) + + def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict: + if past: + input_ids = input_ids[:, -1].unsqueeze(-1) + bidirectional_mask = None + if past[0][0].shape[0] == input_ids.shape[0]: + past = self._convert_to_bloom_cache(past) + else: + bidirectional_mask = torch.ones_like(input_ids) + return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask} + setattr(model, 'forward', MethodType(forward, model)) + setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model)) + setattr(model, '_prefix_lm_converted', True) + return model + +def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM: + """Converts an OPT Causal LM to a Prefix LM. + + Supported HuggingFace model classes: + - `OPTForCausalLM` + + See `convert_hf_causal_lm_to_prefix_lm` for more details. + """ + if hasattr(model, '_prefix_lm_converted'): + return model + assert isinstance(model, OPTForCausalLM) + assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models' + setattr(model, '_original_forward', getattr(model, 'forward')) + setattr(model, '_original_generate', getattr(model, 'generate')) + model.model.decoder.bidirectional_mask = None + + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + combined_attention_mask = None + if input_shape[-1] > 1: + if self.bidirectional_mask == 'g': + (bsz, src_length) = input_shape + combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device) + else: + combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device) + if self.bidirectional_mask is not None: + assert attention_mask.shape == self.bidirectional_mask.shape + expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device) + combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask) + if attention_mask is not None: + expanded_attn_mask = _expand_mask_opt(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 + setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder)) + + def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None): + + def call_og_forward(): + return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict) + if bidirectional_mask is None: + return call_og_forward() + self.model.decoder.bidirectional_mask = bidirectional_mask + try: + outputs = call_og_forward() + except: + self.model.decoder.bidirectional_mask = None + raise + self.model.decoder.bidirectional_mask = None + return outputs + + def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]): + """Wraps original generate to enable PrefixLM-style attention.""" + self.model.decoder.bidirectional_mask = 'g' + try: + output = self._original_generate(*args, **kwargs) + except: + self.model.decoder.bidirectional_mask = None + raise + self.model.decoder.bidirectional_mask = None + return output + setattr(model, 'forward', MethodType(forward, model)) + setattr(model, 'generate', MethodType(generate, model)) + setattr(model, '_prefix_lm_converted', True) + return model +_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM) +CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM] + +def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES: + """Converts a HuggingFace Causal LM to a Prefix LM. + + Supported HuggingFace model classes: + - `GPT2LMHeadModel` + - `GPTNeoForCausalLM` + - `GPTNeoXForCausalLM` + - `GPTJForCausalLM` + - `BloomForCausalLM` + - `OPTForCausalLM` + + Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the + `generate` method and/or select underlying methods depending on the model class. + + These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask". + + Notes on training: + To actually train the converted model as a Prefix LM, training batches will need to indicate + the prefix/target structure by including `bidirectional_mask` as part of the batch inputs. + + **This is not a standard input and requires custom layers either within or after your dataloader.** + + In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels` + such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`. + That is, the prefix portion of the sequence should not generate any loss. Loss should only be + generated by the target portion of the sequence. + + Notes on `GPTNeoForCausalLM`: + To simplify the implementation, "global" and "local" attention layers are handled differently. + For "global" layers, we handle conversion as described above. For "local" layers, which use a + causal attention mask within a restricted local window, we do not alter the masking. + + Notes on `forward` method conversion: + After conversion, the `forward` method will handle a new input, `bidirectional_mask`, + which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions + belonging to the prefix (prefix tokens can attend to one another bidirectionally), and + 0 indicates token positions belonging to the target. + + The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing + causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset + the causal masks before returning the result. + + Notes on `generate` method conversion: + After conversion, the `generate` method will have the same signature but will internally + convert all causal masks to be purely bidirectional, call the original `generate` method, and + (where appropriate) reset the causal masks before returning the result. + + This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token + "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates + each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one + another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and + previously-generated tokens (also as expected in a Prefix LM). + + To preserve the API, the original methods are renamed to `_original_forward` and + `_original_generate`, and replaced with new `forward` and `generate` methods that wrap + them, respectively. Although implementation details vary by model class. + """ + if isinstance(model, _SUPPORTED_GPT_MODELS): + return _convert_gpt_causal_lm_to_prefix_lm(model) + elif isinstance(model, BloomForCausalLM): + return _convert_bloom_causal_lm_to_prefix_lm(model) + elif isinstance(model, OPTForCausalLM): + return _convert_opt_causal_lm_to_prefix_lm(model) + else: + raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}') + +def add_bidirectional_mask_if_missing(batch: Dict[str, Any]): + """Attempts to add bidirectional_mask to batch if missing. + + Raises: + KeyError if bidirectional_mask is missing and can't be inferred + """ + if 'bidirectional_mask' not in batch: + if batch.get('mode', None) == 'icl_task': + batch['bidirectional_mask'] = batch['attention_mask'].clone() + for (i, continuation_indices) in enumerate(batch['continuation_indices']): + batch['bidirectional_mask'][i, continuation_indices] = 0 + elif 'labels' in batch and 'attention_mask' in batch: + batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask']) + else: + raise KeyError('No bidirectional_mask in batch and not sure how to construct one.') \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/meta_init_context.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/meta_init_context.py new file mode 100644 index 0000000000000000000000000000000000000000..6cba6fff0fe21fe222c7ab38eae44a9784c0be9c --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/meta_init_context.py @@ -0,0 +1,94 @@ +from contextlib import contextmanager +import torch +import torch.nn as nn + +@contextmanager +def init_empty_weights(include_buffers: bool=False): + """Meta initialization context manager. + + A context manager under which models are initialized with all parameters + on the meta device, therefore creating an empty model. Useful when just + initializing the model would blow the available RAM. + + Args: + include_buffers (`bool`, *optional*, defaults to `False`): Whether or + not to also put all buffers on the meta device while initializing. + + Example: + ```python + import torch.nn as nn + + # Initialize a model with 100 billions parameters in no time and without using any RAM. + with init_empty_weights(): + tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) + ``` + + + + Any model created under this context manager has no weights. As such you can't do something like + `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. + + + """ + with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f: + yield f + +@contextmanager +def init_on_device(device: torch.device, include_buffers: bool=False): + """Device initialization context manager. + + A context manager under which models are initialized with all parameters + on the specified device. + + Args: + device (`torch.device`): Device to initialize all parameters on. + include_buffers (`bool`, *optional*, defaults to `False`): Whether or + not to also put all buffers on the meta device while initializing. + + Example: + ```python + import torch.nn as nn + + with init_on_device(device=torch.device("cuda")): + tst = nn.Liner(100, 100) # on `cuda` device + ``` + """ + old_register_parameter = nn.Module.register_parameter + if include_buffers: + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + old_register_parameter(module, name, param) + if param is not None: + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer): + old_register_buffer(module, name, buffer) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + if include_buffers: + tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']} + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + + def wrapper(*args, **kwargs): + kwargs['device'] = device + return fn(*args, **kwargs) + return wrapper + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/modeling_mpt.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/modeling_mpt.py new file mode 100644 index 0000000000000000000000000000000000000000..13313441b13fc7a66cb65fd21b482a5de982e2c8 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/modeling_mpt.py @@ -0,0 +1,331 @@ +"""A simple, flexible implementation of a GPT model. + +Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py +""" +import math +import warnings +from typing import List, Optional, Tuple, Union +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from .attention import attn_bias_shape, build_attn_bias +from .blocks import MPTBlock +from .custom_embedding import SharedEmbedding +from .norm import NORM_CLASS_REGISTRY +from .configuration_mpt import MPTConfig +from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising +from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm +from .meta_init_context import init_empty_weights +from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ +try: + from .flash_attn_triton import flash_attn_func +except: + pass +Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] + +class MPTPreTrainedModel(PreTrainedModel): + config_class = MPTConfig + base_model_prefix = 'model' + _no_split_modules = ['MPTBlock'] + +class MPTModel(MPTPreTrainedModel): + + def __init__(self, config: MPTConfig): + config._validate_config() + super().__init__(config) + self.attn_impl = config.attn_config['attn_impl'] + self.prefix_lm = config.attn_config['prefix_lm'] + self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] + self.alibi = config.attn_config['alibi'] + self.alibi_bias_max = config.attn_config['alibi_bias_max'] + if config.init_device == 'mixed': + if dist.get_local_rank() == 0: + config.init_device = 'cpu' + else: + config.init_device = 'meta' + if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): + norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) + raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') + norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] + self.embedding_fraction = config.embedding_fraction + self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) + if not self.alibi: + self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) + self.emb_drop = nn.Dropout(config.emb_pdrop) + self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) + self.norm_f = norm_class(config.d_model, device=config.init_device) + if config.init_device != 'meta': + print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.') + self.apply(self.param_init_fn) + self.is_causal = not self.prefix_lm + self._attn_bias_initialized = False + self.attn_bias = None + self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) + if config.no_bias: + for module in self.modules(): + if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): + if config.verbose: + warnings.warn(f'Removing bias ({module.bias}) from {module}.') + module.register_parameter('bias', None) + if config.verbose and config.verbose > 2: + print(self) + if 'verbose' not in self.config.init_config: + self.config.init_config['verbose'] = self.config.verbose + if self.config.init_config['verbose'] > 1: + init_fn_name = self.config.init_config['name'] + warnings.warn(f'Using {init_fn_name} initialization.') + self.gradient_checkpointing = False + + def get_input_embeddings(self): + return self.wte + + def set_input_embeddings(self, value): + self.wte = value + + @torch.no_grad() + def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): + if not self._attn_bias_initialized: + if self.attn_bias_shape: + self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype) + self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max) + self._attn_bias_initialized = True + if self.attn_impl == 'flash': + return (self.attn_bias, attention_mask) + if self.attn_bias is not None: + self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) + attn_bias = self.attn_bias + if self.prefix_lm: + assert isinstance(attn_bias, torch.Tensor) + assert isinstance(prefix_mask, torch.Tensor) + attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) + if self.attn_uses_sequence_id and sequence_id is not None: + assert isinstance(attn_bias, torch.Tensor) + attn_bias = self._apply_sequence_id(attn_bias, sequence_id) + if attention_mask is not None: + s_k = attention_mask.shape[-1] + if attn_bias is None: + attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) + else: + _s_k = max(0, attn_bias.size(-1) - s_k) + attn_bias = attn_bias[:, :, :, _s_k:] + if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: + raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') + min_val = torch.finfo(attn_bias.dtype).min + attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) + return (attn_bias, None) + + def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): + (s_k, s_q) = attn_bias.shape[-2:] + if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: + raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') + seq_len = prefix_mask.shape[-1] + if seq_len > self.config.max_seq_len: + raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') + attn_bias = attn_bias[..., :seq_len, :seq_len] + causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) + prefix = prefix_mask.view(-1, 1, 1, seq_len) + cannot_attend = ~torch.logical_or(causal, prefix.bool()) + min_val = torch.finfo(attn_bias.dtype).min + attn_bias = attn_bias.masked_fill(cannot_attend, min_val) + return attn_bias + + def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): + seq_len = sequence_id.shape[-1] + if seq_len > self.config.max_seq_len: + raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') + attn_bias = attn_bias[..., :seq_len, :seq_len] + cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) + min_val = torch.finfo(attn_bias.dtype).min + attn_bias = attn_bias.masked_fill(cannot_attend, min_val) + return attn_bias + + def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None): + return_dict = return_dict if return_dict is not None else self.config.return_dict + use_cache = use_cache if use_cache is not None else self.config.use_cache + if attention_mask is not None: + attention_mask = attention_mask.bool() + if prefix_mask is not None: + prefix_mask = prefix_mask.bool() + if not return_dict: + raise NotImplementedError('return_dict False is not implemented yet for MPT') + if output_attentions: + if self.attn_impl != 'torch': + raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.') + if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: + raise NotImplementedError('MPT does not support training with left padding.') + if self.prefix_lm and prefix_mask is None: + raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') + if self.training: + if self.attn_uses_sequence_id and sequence_id is None: + raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') + elif self.attn_uses_sequence_id is False and sequence_id is not None: + warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') + if input_ids is not None: + S = input_ids.size(1) + assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' + tok_emb = self.wte(input_ids) + else: + assert inputs_embeds is not None + assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' + S = inputs_embeds.size(1) + tok_emb = inputs_embeds + if self.alibi: + x = tok_emb + else: + past_position = 0 + if past_key_values is not None: + if len(past_key_values) != self.config.n_layers: + raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') + past_position = past_key_values[0][0].size(1) + if self.attn_impl == 'torch': + past_position = past_key_values[0][0].size(3) + if S + past_position > self.config.max_seq_len: + raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') + pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) + if attention_mask is not None: + pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) + pos_emb = self.wpe(pos) + x = tok_emb + pos_emb + if self.embedding_fraction == 1: + x = self.emb_drop(x) + else: + x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) + assert isinstance(self.emb_drop, nn.Module) + x = self.emb_drop(x_shrunk) + (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) + if use_cache and past_key_values is None: + past_key_values = [() for _ in range(self.config.n_layers)] + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + for (b_idx, block) in enumerate(self.blocks): + if output_hidden_states: + assert all_hidden_states is not None + all_hidden_states = all_hidden_states + (x,) + past_key_value = past_key_values[b_idx] if past_key_values is not None else None + if self.gradient_checkpointing and self.training: + (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) + else: + (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) + if past_key_values is not None: + past_key_values[b_idx] = past_key_value + if output_attentions: + assert all_self_attns is not None + all_self_attns = all_self_attns + (attn_weights,) + x = self.norm_f(x) + if output_hidden_states: + assert all_hidden_states is not None + all_hidden_states = all_hidden_states + (x,) + return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns) + + def param_init_fn(self, module): + init_fn_name = self.config.init_config['name'] + MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config) + + def fsdp_wrap_fn(self, module): + return isinstance(module, MPTBlock) + + def activation_checkpointing_fn(self, module): + return isinstance(module, MPTBlock) + +class MPTForCausalLM(MPTPreTrainedModel): + + def __init__(self, config: MPTConfig): + super().__init__(config) + if not config.tie_word_embeddings: + raise ValueError('MPTForCausalLM only supports tied word embeddings') + print(f'Instantiating an MPTForCausalLM model from {__file__}') + self.transformer = MPTModel(config) + for child in self.transformer.children(): + if isinstance(child, torch.nn.ModuleList): + continue + if isinstance(child, torch.nn.Module): + child._fsdp_wrap = True + self.logit_scale = None + if config.logit_scale is not None: + logit_scale = config.logit_scale + if isinstance(logit_scale, str): + if logit_scale == 'inv_sqrt_d_model': + logit_scale = 1 / math.sqrt(config.d_model) + else: + raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.") + self.logit_scale = logit_scale + + def get_input_embeddings(self): + return self.transformer.wte + + def set_input_embeddings(self, value): + self.transformer.wte = value + + def get_output_embeddings(self): + return self.transformer.wte + + def set_output_embeddings(self, new_embeddings): + self.transformer.wte = new_embeddings + + def set_decoder(self, decoder): + self.transformer = decoder + + def get_decoder(self): + return self.transformer + + def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None): + return_dict = return_dict if return_dict is not None else self.config.return_dict + use_cache = use_cache if use_cache is not None else self.config.use_cache + if inputs_embeds is not None: + raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).') + outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache) + logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True) + if self.logit_scale is not None: + if self.logit_scale == 0: + warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.') + logits *= self.logit_scale + loss = None + if labels is not None: + labels = torch.roll(labels, shifts=-1) + labels[:, -1] = -100 + loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1)) + return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions) + + def param_init_fn(self, module): + init_fn_name = self.config.init_config['name'] + MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config) + + def fsdp_wrap_fn(self, module): + return isinstance(module, MPTBlock) + + def activation_checkpointing_fn(self, module): + return isinstance(module, MPTBlock) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + if inputs_embeds is not None: + raise NotImplementedError('inputs_embeds is not implemented for MPT yet') + attention_mask = kwargs['attention_mask'].bool() + if attention_mask[:, -1].sum() != attention_mask.shape[0]: + raise NotImplementedError('MPT does not support generation with right padding.') + if self.transformer.attn_uses_sequence_id and self.training: + sequence_id = torch.zeros_like(input_ids[:1]) + else: + sequence_id = None + if past_key_values is not None: + input_ids = input_ids[:, -1].unsqueeze(-1) + if self.transformer.prefix_lm: + prefix_mask = torch.ones_like(attention_mask) + if kwargs.get('use_cache') == False: + raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.') + else: + prefix_mask = None + return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)} + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + """Used by HuggingFace generate when using beam search with kv-caching. + + See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133 + for an example in transformers. + """ + 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 \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/norm.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..067b6140fae546e5cb49cb2b1e4e6af660ced60d --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/norm.py @@ -0,0 +1,56 @@ +import torch + +def _cast_if_autocast_enabled(tensor): + if torch.is_autocast_enabled(): + if tensor.device.type == 'cuda': + dtype = torch.get_autocast_gpu_dtype() + elif tensor.device.type == 'cpu': + dtype = torch.get_autocast_cpu_dtype() + else: + raise NotImplementedError() + return tensor.to(dtype=dtype) + return tensor + +class LPLayerNorm(torch.nn.LayerNorm): + + def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None): + super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype) + + def forward(self, x): + module_device = x.device + downcast_x = _cast_if_autocast_enabled(x) + downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight + downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias + with torch.autocast(enabled=False, device_type=module_device.type): + return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps) + +def rms_norm(x, weight=None, eps=1e-05): + output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) + if weight is not None: + return output * weight + return output + +class RMSNorm(torch.nn.Module): + + def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None): + super().__init__() + self.eps = eps + if weight: + self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device)) + else: + self.register_parameter('weight', None) + + def forward(self, x): + return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype) + +class LPRMSNorm(RMSNorm): + + def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None): + super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device) + + def forward(self, x): + downcast_x = _cast_if_autocast_enabled(x) + downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight + with torch.autocast(enabled=False, device_type=x.device.type): + return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype) +NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm} \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/language_model/mpt/param_init_fns.py b/approach/vlm/LLaVA/llava/model/language_model/mpt/param_init_fns.py new file mode 100644 index 0000000000000000000000000000000000000000..418b83ca2363288046f4b48b1d706c5607341fb5 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/language_model/mpt/param_init_fns.py @@ -0,0 +1,181 @@ +import math +import warnings +from collections.abc import Sequence +from functools import partial +from typing import Optional, Tuple, Union +import torch +from torch import nn +from .norm import NORM_CLASS_REGISTRY + +def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs): + del kwargs + if verbose > 1: + warnings.warn(f"Initializing network using module's reset_parameters attribute") + if hasattr(module, 'reset_parameters'): + module.reset_parameters() + +def fused_init_helper_(module: nn.Module, init_fn_): + _fused = getattr(module, '_fused', None) + if _fused is None: + raise RuntimeError(f'Internal logic error') + (dim, splits) = _fused + splits = (0, *splits, module.weight.size(dim)) + for (s, e) in zip(splits[:-1], splits[1:]): + slice_indices = [slice(None)] * module.weight.ndim + slice_indices[dim] = slice(s, e) + init_fn_(module.weight[slice_indices]) + +def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs): + del kwargs + if verbose > 1: + warnings.warn(f'If model has bias parameters they are initialized to 0.') + init_div_is_residual = init_div_is_residual + if init_div_is_residual is False: + div_is_residual = 1.0 + elif init_div_is_residual is True: + div_is_residual = math.sqrt(2 * n_layers) + elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int): + div_is_residual = init_div_is_residual + elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric(): + div_is_residual = float(init_div_is_residual) + else: + div_is_residual = 1.0 + raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}') + if init_div_is_residual is not False: + if verbose > 1: + warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.') + if isinstance(module, nn.Linear): + if hasattr(module, '_fused'): + fused_init_helper_(module, init_fn_) + else: + init_fn_(module.weight) + if module.bias is not None: + torch.nn.init.zeros_(module.bias) + if init_div_is_residual is not False and getattr(module, '_is_residual', False): + with torch.no_grad(): + module.weight.div_(div_is_residual) + elif isinstance(module, nn.Embedding): + if emb_init_std is not None: + std = emb_init_std + if std == 0: + warnings.warn(f'Embedding layer initialized to 0.') + emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std) + if verbose > 1: + warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.') + elif emb_init_uniform_lim is not None: + lim = emb_init_uniform_lim + if isinstance(lim, Sequence): + if len(lim) > 2: + raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.') + if lim[0] == lim[1]: + warnings.warn(f'Embedding layer initialized to {lim[0]}.') + else: + if lim == 0: + warnings.warn(f'Embedding layer initialized to 0.') + lim = [-lim, lim] + (a, b) = lim + emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b) + if verbose > 1: + warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.') + else: + emb_init_fn_ = init_fn_ + emb_init_fn_(module.weight) + elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))): + if verbose > 1: + warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.') + if hasattr(module, 'weight') and module.weight is not None: + torch.nn.init.ones_(module.weight) + if hasattr(module, 'bias') and module.bias is not None: + torch.nn.init.zeros_(module.bias) + elif isinstance(module, nn.MultiheadAttention): + if module._qkv_same_embed_dim: + assert module.in_proj_weight is not None + assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None) + assert d_model is not None + _d = d_model + splits = (0, _d, 2 * _d, 3 * _d) + for (s, e) in zip(splits[:-1], splits[1:]): + init_fn_(module.in_proj_weight[s:e]) + else: + assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None) + assert module.in_proj_weight is None + init_fn_(module.q_proj_weight) + init_fn_(module.k_proj_weight) + init_fn_(module.v_proj_weight) + if module.in_proj_bias is not None: + torch.nn.init.zeros_(module.in_proj_bias) + if module.bias_k is not None: + torch.nn.init.zeros_(module.bias_k) + if module.bias_v is not None: + torch.nn.init.zeros_(module.bias_v) + init_fn_(module.out_proj.weight) + if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False): + with torch.no_grad(): + module.out_proj.weight.div_(div_is_residual) + if module.out_proj.bias is not None: + torch.nn.init.zeros_(module.out_proj.bias) + else: + for _ in module.parameters(recurse=False): + raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.') + +def _normal_init_(std, mean=0.0): + return partial(torch.nn.init.normal_, mean=mean, std=std) + +def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs): + del kwargs + init_fn_ = _normal_init_(std=std) + if verbose > 1: + warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}') + generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs): + del kwargs + if init_std is None: + raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.") + _normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs): + del kwargs + std = math.sqrt(2 / (5 * d_model)) + _normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs): + """From section 2.3.1 of GPT-NeoX-20B: + + An Open-Source AutoregressiveLanguage Model — Black et. al. (2022) + see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151 + and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py + """ + del kwargs + residual_div = n_layers / math.sqrt(10) + if verbose > 1: + warnings.warn(f'setting init_div_is_residual to {residual_div}') + small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs): + del kwargs + if verbose > 1: + warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}') + kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity) + generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs): + del kwargs + if verbose > 1: + warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}') + kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity) + generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs): + del kwargs + xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain) + if verbose > 1: + warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}') + generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) + +def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs): + xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain) + if verbose > 1: + warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}') + generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose) +MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_} \ No newline at end of file diff --git a/approach/vlm/LLaVA/llava/model/llava_arch.py b/approach/vlm/LLaVA/llava/model/llava_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..fd538c93764347a496ba6cdb0859cd8ffcb02044 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/llava_arch.py @@ -0,0 +1,248 @@ +# Copyright 2023 Haotian Liu +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from abc import ABC, abstractmethod + +import torch +import torch.nn as nn + +from .multimodal_encoder.builder import build_vision_tower +from .multimodal_projector.builder import build_vision_projector + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + + +class LlavaMetaModel: + + def __init__(self, config): + super(LlavaMetaModel, self).__init__(config) + + if hasattr(config, "mm_vision_tower"): + self.vision_tower = build_vision_tower(config, delay_load=True) + self.mm_projector = build_vision_projector(config) + + def get_vision_tower(self): + vision_tower = getattr(self, 'vision_tower', None) + if type(vision_tower) is list: + vision_tower = vision_tower[0] + return vision_tower + + def initialize_vision_modules(self, model_args, fsdp=None): + vision_tower = model_args.vision_tower + mm_vision_select_layer = model_args.mm_vision_select_layer + mm_vision_select_feature = model_args.mm_vision_select_feature + pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter + + self.config.mm_vision_tower = vision_tower + + vision_tower = build_vision_tower(model_args) + + if fsdp is not None and len(fsdp) > 0: + self.vision_tower = [vision_tower] + else: + self.vision_tower = vision_tower + + self.config.use_mm_proj = True + self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear') + self.config.mm_hidden_size = vision_tower.hidden_size + self.config.mm_vision_select_layer = mm_vision_select_layer + self.config.mm_vision_select_feature = mm_vision_select_feature + + self.mm_projector = build_vision_projector(self.config) + + if pretrain_mm_mlp_adapter is not None: + mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu') + def get_w(weights, keyword): + return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k} + + self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector')) + + +class LlavaMetaForCausalLM(ABC): + + @abstractmethod + def get_model(self): + pass + + def get_vision_tower(self): + return self.get_model().get_vision_tower() + + def encode_images(self, images): + image_features = self.get_model().get_vision_tower()(images) + image_features = self.get_model().mm_projector(image_features) + return image_features + + def prepare_inputs_labels_for_multimodal( + self, input_ids, attention_mask, past_key_values, labels, images + ): + vision_tower = self.get_vision_tower() + if vision_tower is None or images is None or input_ids.shape[1] == 1: + if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1: + attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device) + return input_ids, attention_mask, past_key_values, None, labels + + if type(images) is list or images.ndim == 5: + concat_images = torch.cat([image for image in images], dim=0) + image_features = self.encode_images(concat_images) + split_sizes = [image.shape[0] for image in images] + image_features = torch.split(image_features, split_sizes, dim=0) + image_features = [x.flatten(0, 1) for x in image_features] + else: + image_features = self.encode_images(images) + + new_input_embeds = [] + new_labels = [] if labels is not None else None + cur_image_idx = 0 + for batch_idx, cur_input_ids in enumerate(input_ids): + if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: + # multimodal LLM, but the current sample is not multimodal + # FIXME: this is a hacky fix, for deepspeed zero3 to work + half_len = cur_input_ids.shape[0] // 2 + cur_image_features = image_features[cur_image_idx] + cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len]) + cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:]) + cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0) + new_input_embeds.append(cur_input_embeds) + if labels is not None: + new_labels.append(labels[batch_idx]) + cur_image_idx += 1 + continue + image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] + cur_new_input_embeds = [] + if labels is not None: + cur_labels = labels[batch_idx] + cur_new_labels = [] + assert cur_labels.shape == cur_input_ids.shape + while image_token_indices.numel() > 0: + cur_image_features = image_features[cur_image_idx] + image_token_start = image_token_indices[0] + if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach()) + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start])) + cur_new_input_embeds.append(cur_image_features) + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2])) + if labels is not None: + cur_new_labels.append(cur_labels[:image_token_start]) + cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) + cur_new_labels.append(cur_labels[image_token_start:image_token_start+1]) + cur_labels = cur_labels[image_token_start+2:] + else: + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start])) + cur_new_input_embeds.append(cur_image_features) + if labels is not None: + cur_new_labels.append(cur_labels[:image_token_start]) + cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype)) + cur_labels = cur_labels[image_token_start+1:] + cur_image_idx += 1 + if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): + cur_input_ids = cur_input_ids[image_token_start+2:] + else: + cur_input_ids = cur_input_ids[image_token_start+1:] + image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0] + if cur_input_ids.numel() > 0: + if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False): + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach()) + else: + cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids)) + if labels is not None: + cur_new_labels.append(cur_labels) + cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds] + cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0) + new_input_embeds.append(cur_new_input_embeds) + if labels is not None: + cur_new_labels = torch.cat(cur_new_labels, dim=0) + new_labels.append(cur_new_labels) + + if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds): + max_len = max(x.shape[0] for x in new_input_embeds) + + new_input_embeds_align = [] + for cur_new_embed in new_input_embeds: + cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0) + new_input_embeds_align.append(cur_new_embed) + new_input_embeds = torch.stack(new_input_embeds_align, dim=0) + + if labels is not None: + new_labels_align = [] + _new_labels = new_labels + for cur_new_label in new_labels: + cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0) + new_labels_align.append(cur_new_label) + new_labels = torch.stack(new_labels_align, dim=0) + + if attention_mask is not None: + new_attention_mask = [] + for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels): + new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device) + new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device) + cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0) + new_attention_mask.append(cur_new_attention_mask) + attention_mask = torch.stack(new_attention_mask, dim=0) + assert attention_mask.shape == new_labels.shape + else: + new_input_embeds = torch.stack(new_input_embeds, dim=0) + if labels is not None: + new_labels = torch.stack(new_labels, dim=0) + + if attention_mask is not None: + new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device) + attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1) + assert attention_mask.shape == new_input_embeds.shape[:2] + + return None, attention_mask, past_key_values, new_input_embeds, new_labels + + def initialize_vision_tokenizer(self, model_args, tokenizer): + if model_args.mm_use_im_patch_token: + tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if model_args.mm_use_im_start_end: + num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True) + self.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = self.get_input_embeddings().weight.data + output_embeddings = self.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = True + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False + + if model_args.pretrain_mm_mlp_adapter: + mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu') + embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight'] + assert num_new_tokens == 2 + if input_embeddings.shape == embed_tokens_weight.shape: + input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:] + elif embed_tokens_weight.shape[0] == num_new_tokens: + input_embeddings[-num_new_tokens:] = embed_tokens_weight + else: + raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.") + elif model_args.mm_use_im_patch_token: + if model_args.tune_mm_mlp_adapter: + for p in self.get_input_embeddings().parameters(): + p.requires_grad = False + for p in self.get_output_embeddings().parameters(): + p.requires_grad = False diff --git a/approach/vlm/LLaVA/llava/model/make_delta.py b/approach/vlm/LLaVA/llava/model/make_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae55d59c2c8bab80299272314a41bbeb959d8ed --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/make_delta.py @@ -0,0 +1,52 @@ +""" +Usage: +python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta +""" +import argparse + +import torch +from tqdm import tqdm +from transformers import AutoTokenizer, AutoModelForCausalLM +from llava.model.utils import auto_upgrade + + +def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id): + print("Loading base model") + base = AutoModelForCausalLM.from_pretrained( + base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Loading target model") + auto_upgrade(target_model_path) + target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) + + print("Calculating delta") + for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"): + if name not in base.state_dict(): + assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model' + continue + if param.data.shape == base.state_dict()[name].shape: + param.data -= base.state_dict()[name] + else: + assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}' + bparam = base.state_dict()[name] + param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam + + print("Saving delta") + if hub_repo_id: + kwargs = {"push_to_hub": True, "repo_id": hub_repo_id} + else: + kwargs = {} + target.save_pretrained(delta_path, **kwargs) + target_tokenizer = AutoTokenizer.from_pretrained(target_model_path) + target_tokenizer.save_pretrained(delta_path, **kwargs) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--base-model-path", type=str, required=True) + parser.add_argument("--target-model-path", type=str, required=True) + parser.add_argument("--delta-path", type=str, required=True) + parser.add_argument("--hub-repo-id", type=str, default=None) + args = parser.parse_args() + + make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id) diff --git a/approach/vlm/LLaVA/llava/model/multimodal_encoder/builder.py b/approach/vlm/LLaVA/llava/model/multimodal_encoder/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..2b13589d4e55af529fe0838c4130c2033ac10478 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/multimodal_encoder/builder.py @@ -0,0 +1,11 @@ +import os +from .clip_encoder import CLIPVisionTower + + +def build_vision_tower(vision_tower_cfg, **kwargs): + vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None)) + is_absolute_path_exists = os.path.exists(vision_tower) + if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion"): + return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs) + + raise ValueError(f'Unknown vision tower: {vision_tower}') diff --git a/approach/vlm/LLaVA/llava/model/multimodal_encoder/clip_encoder.py b/approach/vlm/LLaVA/llava/model/multimodal_encoder/clip_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb9015b0fc9fa93483ba77cc303b793e86c36fc --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/multimodal_encoder/clip_encoder.py @@ -0,0 +1,78 @@ +import torch +import torch.nn as nn + +from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig + + +class CLIPVisionTower(nn.Module): + def __init__(self, vision_tower, args, delay_load=False): + super().__init__() + + self.is_loaded = False + + self.vision_tower_name = vision_tower + self.select_layer = args.mm_vision_select_layer + self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch') + + if not delay_load: + self.load_model() + else: + self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name) + + def load_model(self): + self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name) + self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name) + self.vision_tower.requires_grad_(False) + + self.is_loaded = True + + def feature_select(self, image_forward_outs): + image_features = image_forward_outs.hidden_states[self.select_layer] + if self.select_feature == 'patch': + image_features = image_features[:, 1:] + elif self.select_feature == 'cls_patch': + image_features = image_features + else: + raise ValueError(f'Unexpected select feature: {self.select_feature}') + return image_features + + @torch.no_grad() + def forward(self, images): + if type(images) is list: + image_features = [] + for image in images: + image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True) + image_feature = self.feature_select(image_forward_out).to(image.dtype) + image_features.append(image_feature) + else: + image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True) + image_features = self.feature_select(image_forward_outs).to(images.dtype) + + return image_features + + @property + def dummy_feature(self): + return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype) + + @property + def dtype(self): + return self.vision_tower.dtype + + @property + def device(self): + return self.vision_tower.device + + @property + def config(self): + if self.is_loaded: + return self.vision_tower.config + else: + return self.cfg_only + + @property + def hidden_size(self): + return self.config.hidden_size + + @property + def num_patches(self): + return (self.config.image_size // self.config.patch_size) ** 2 diff --git a/approach/vlm/LLaVA/llava/model/multimodal_projector/builder.py b/approach/vlm/LLaVA/llava/model/multimodal_projector/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..31cd4f48e6055cd6d00a162af30b1c8139e26b57 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/multimodal_projector/builder.py @@ -0,0 +1,51 @@ +import torch +import torch.nn as nn +import re + + +class IdentityMap(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x, *args, **kwargs): + return x + + @property + def config(self): + return {"mm_projector_type": 'identity'} + + +class SimpleResBlock(nn.Module): + def __init__(self, channels): + super().__init__() + self.pre_norm = nn.LayerNorm(channels) + + self.proj = nn.Sequential( + nn.Linear(channels, channels), + nn.GELU(), + nn.Linear(channels, channels) + ) + def forward(self, x): + x = self.pre_norm(x) + return x + self.proj(x) + + +def build_vision_projector(config, delay_load=False, **kwargs): + projector_type = getattr(config, 'mm_projector_type', 'linear') + + if projector_type == 'linear': + return nn.Linear(config.mm_hidden_size, config.hidden_size) + + mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type) + if mlp_gelu_match: + mlp_depth = int(mlp_gelu_match.group(1)) + modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)] + for _ in range(1, mlp_depth): + modules.append(nn.GELU()) + modules.append(nn.Linear(config.hidden_size, config.hidden_size)) + return nn.Sequential(*modules) + + if projector_type == 'identity': + return IdentityMap() + + raise ValueError(f'Unknown projector type: {projector_type}') diff --git a/approach/vlm/LLaVA/llava/model/utils.py b/approach/vlm/LLaVA/llava/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2563f89c6cedf5e73508afec8f9979105df9b745 --- /dev/null +++ b/approach/vlm/LLaVA/llava/model/utils.py @@ -0,0 +1,20 @@ +from transformers import AutoConfig + + +def auto_upgrade(config): + cfg = AutoConfig.from_pretrained(config) + if 'llava' in config and 'llava' not in cfg.model_type: + assert cfg.model_type == 'llama' + print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.") + print("You must upgrade the checkpoint to the new code base (this can be done automatically).") + confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]") + if confirm.lower() in ["y", "yes"]: + print("Upgrading checkpoint...") + assert len(cfg.architectures) == 1 + setattr(cfg.__class__, "model_type", "llava") + cfg.architectures[0] = 'LlavaLlamaForCausalLM' + cfg.save_pretrained(config) + print("Checkpoint upgraded.") + else: + print("Checkpoint upgrade aborted.") + exit(1) diff --git a/approach/vlm/LLaVA/llava/serve/__init__.py b/approach/vlm/LLaVA/llava/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/approach/vlm/LLaVA/llava/serve/cli.py b/approach/vlm/LLaVA/llava/serve/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..fbabbfa76eb8c8af6be6bdc165f96cb9cb515244 --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/cli.py @@ -0,0 +1,119 @@ +import argparse +import torch + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria + +from PIL import Image + +import requests +from PIL import Image +from io import BytesIO +from transformers import TextStreamer + + +def load_image(image_file): + if image_file.startswith('http') or image_file.startswith('https'): + response = requests.get(image_file) + image = Image.open(BytesIO(response.content)).convert('RGB') + else: + image = Image.open(image_file).convert('RGB') + return image + + +def main(args): + # Model + disable_torch_init() + + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit) + + if 'llama-2' in model_name.lower(): + conv_mode = "llava_llama_2" + elif "v1" in model_name.lower(): + conv_mode = "llava_v1" + elif "mpt" in model_name.lower(): + conv_mode = "mpt" + else: + conv_mode = "llava_v0" + + if args.conv_mode is not None and conv_mode != args.conv_mode: + print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode)) + else: + args.conv_mode = conv_mode + + conv = conv_templates[args.conv_mode].copy() + if "mpt" in model_name.lower(): + roles = ('user', 'assistant') + else: + roles = conv.roles + + image = load_image(args.image_file) + image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda() + + while True: + try: + inp = input(f"{roles[0]}: ") + except EOFError: + inp = "" + if not inp: + print("exit...") + break + + print(f"{roles[1]}: ", end="") + + if image is not None: + # first message + if model.config.mm_use_im_start_end: + inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp + else: + inp = DEFAULT_IMAGE_TOKEN + '\n' + inp + conv.append_message(conv.roles[0], inp) + image = None + else: + # later messages + conv.append_message(conv.roles[0], inp) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda() + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensor, + do_sample=True, + temperature=0.2, + max_new_tokens=1024, + streamer=streamer, + use_cache=True, + stopping_criteria=[stopping_criteria]) + + outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip() + conv.messages[-1][-1] = outputs + + if args.debug: + print("\n", {"prompt": prompt, "outputs": outputs}, "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-file", type=str, required=True) + parser.add_argument("--num-gpus", type=int, default=1) + parser.add_argument("--conv-mode", type=str, default=None) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--max-new-tokens", type=int, default=512) + parser.add_argument("--load-8bit", action="store_true") + parser.add_argument("--load-4bit", action="store_true") + parser.add_argument("--debug", action="store_true") + args = parser.parse_args() + main(args) diff --git a/approach/vlm/LLaVA/llava/serve/controller.py b/approach/vlm/LLaVA/llava/serve/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..b61fca6ea9fe8aa37acd143784a3d76e90a58b9f --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/controller.py @@ -0,0 +1,298 @@ +""" +A controller manages distributed workers. +It sends worker addresses to clients. +""" +import argparse +import asyncio +import dataclasses +from enum import Enum, auto +import json +import logging +import time +from typing import List, Union +import threading + +from fastapi import FastAPI, Request +from fastapi.responses import StreamingResponse +import numpy as np +import requests +import uvicorn + +from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION +from llava.utils import build_logger, server_error_msg + + +logger = build_logger("controller", "controller.log") + + +class DispatchMethod(Enum): + LOTTERY = auto() + SHORTEST_QUEUE = auto() + + @classmethod + def from_str(cls, name): + if name == "lottery": + return cls.LOTTERY + elif name == "shortest_queue": + return cls.SHORTEST_QUEUE + else: + raise ValueError(f"Invalid dispatch method") + + +@dataclasses.dataclass +class WorkerInfo: + model_names: List[str] + speed: int + queue_length: int + check_heart_beat: bool + last_heart_beat: str + + +def heart_beat_controller(controller): + while True: + time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION) + controller.remove_stable_workers_by_expiration() + + +class Controller: + def __init__(self, dispatch_method: str): + # Dict[str -> WorkerInfo] + self.worker_info = {} + self.dispatch_method = DispatchMethod.from_str(dispatch_method) + + self.heart_beat_thread = threading.Thread( + target=heart_beat_controller, args=(self,)) + self.heart_beat_thread.start() + + logger.info("Init controller") + + def register_worker(self, worker_name: str, check_heart_beat: bool, + worker_status: dict): + if worker_name not in self.worker_info: + logger.info(f"Register a new worker: {worker_name}") + else: + logger.info(f"Register an existing worker: {worker_name}") + + if not worker_status: + worker_status = self.get_worker_status(worker_name) + if not worker_status: + return False + + self.worker_info[worker_name] = WorkerInfo( + worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], + check_heart_beat, time.time()) + + logger.info(f"Register done: {worker_name}, {worker_status}") + return True + + def get_worker_status(self, worker_name: str): + try: + r = requests.post(worker_name + "/worker_get_status", timeout=5) + except requests.exceptions.RequestException as e: + logger.error(f"Get status fails: {worker_name}, {e}") + return None + + if r.status_code != 200: + logger.error(f"Get status fails: {worker_name}, {r}") + return None + + return r.json() + + def remove_worker(self, worker_name: str): + del self.worker_info[worker_name] + + def refresh_all_workers(self): + old_info = dict(self.worker_info) + self.worker_info = {} + + for w_name, w_info in old_info.items(): + if not self.register_worker(w_name, w_info.check_heart_beat, None): + logger.info(f"Remove stale worker: {w_name}") + + def list_models(self): + model_names = set() + + for w_name, w_info in self.worker_info.items(): + model_names.update(w_info.model_names) + + return list(model_names) + + def get_worker_address(self, model_name: str): + if self.dispatch_method == DispatchMethod.LOTTERY: + worker_names = [] + worker_speeds = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_speeds.append(w_info.speed) + worker_speeds = np.array(worker_speeds, dtype=np.float32) + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + if True: # Directly return address + pt = np.random.choice(np.arange(len(worker_names)), + p=worker_speeds) + worker_name = worker_names[pt] + return worker_name + + # Check status before returning + while True: + pt = np.random.choice(np.arange(len(worker_names)), + p=worker_speeds) + worker_name = worker_names[pt] + + if self.get_worker_status(worker_name): + break + else: + self.remove_worker(worker_name) + worker_speeds[pt] = 0 + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + continue + return worker_name + elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE: + worker_names = [] + worker_qlen = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_qlen.append(w_info.queue_length / w_info.speed) + if len(worker_names) == 0: + return "" + min_index = np.argmin(worker_qlen) + w_name = worker_names[min_index] + self.worker_info[w_name].queue_length += 1 + logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}") + return w_name + else: + raise ValueError(f"Invalid dispatch method: {self.dispatch_method}") + + def receive_heart_beat(self, worker_name: str, queue_length: int): + if worker_name not in self.worker_info: + logger.info(f"Receive unknown heart beat. {worker_name}") + return False + + self.worker_info[worker_name].queue_length = queue_length + self.worker_info[worker_name].last_heart_beat = time.time() + logger.info(f"Receive heart beat. {worker_name}") + return True + + def remove_stable_workers_by_expiration(self): + expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION + to_delete = [] + for worker_name, w_info in self.worker_info.items(): + if w_info.check_heart_beat and w_info.last_heart_beat < expire: + to_delete.append(worker_name) + + for worker_name in to_delete: + self.remove_worker(worker_name) + + def worker_api_generate_stream(self, params): + worker_addr = self.get_worker_address(params["model"]) + if not worker_addr: + logger.info(f"no worker: {params['model']}") + ret = { + "text": server_error_msg, + "error_code": 2, + } + yield json.dumps(ret).encode() + b"\0" + + try: + response = requests.post(worker_addr + "/worker_generate_stream", + json=params, stream=True, timeout=5) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + yield chunk + b"\0" + except requests.exceptions.RequestException as e: + logger.info(f"worker timeout: {worker_addr}") + ret = { + "text": server_error_msg, + "error_code": 3, + } + yield json.dumps(ret).encode() + b"\0" + + + # Let the controller act as a worker to achieve hierarchical + # management. This can be used to connect isolated sub networks. + def worker_api_get_status(self): + model_names = set() + speed = 0 + queue_length = 0 + + for w_name in self.worker_info: + worker_status = self.get_worker_status(w_name) + if worker_status is not None: + model_names.update(worker_status["model_names"]) + speed += worker_status["speed"] + queue_length += worker_status["queue_length"] + + return { + "model_names": list(model_names), + "speed": speed, + "queue_length": queue_length, + } + + +app = FastAPI() + + +@app.post("/register_worker") +async def register_worker(request: Request): + data = await request.json() + controller.register_worker( + data["worker_name"], data["check_heart_beat"], + data.get("worker_status", None)) + + +@app.post("/refresh_all_workers") +async def refresh_all_workers(): + models = controller.refresh_all_workers() + + +@app.post("/list_models") +async def list_models(): + models = controller.list_models() + return {"models": models} + + +@app.post("/get_worker_address") +async def get_worker_address(request: Request): + data = await request.json() + addr = controller.get_worker_address(data["model"]) + return {"address": addr} + + +@app.post("/receive_heart_beat") +async def receive_heart_beat(request: Request): + data = await request.json() + exist = controller.receive_heart_beat( + data["worker_name"], data["queue_length"]) + return {"exist": exist} + + +@app.post("/worker_generate_stream") +async def worker_api_generate_stream(request: Request): + params = await request.json() + generator = controller.worker_api_generate_stream(params) + return StreamingResponse(generator) + + +@app.post("/worker_get_status") +async def worker_api_get_status(request: Request): + return controller.worker_api_get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="localhost") + parser.add_argument("--port", type=int, default=21001) + parser.add_argument("--dispatch-method", type=str, choices=[ + "lottery", "shortest_queue"], default="shortest_queue") + args = parser.parse_args() + logger.info(f"args: {args}") + + controller = Controller(args.dispatch_method) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/approach/vlm/LLaVA/llava/serve/examples/extreme_ironing.jpg b/approach/vlm/LLaVA/llava/serve/examples/extreme_ironing.jpg new file mode 100644 index 0000000000000000000000000000000000000000..638b078837f175039b2db49a63821288d9681daa Binary files /dev/null and b/approach/vlm/LLaVA/llava/serve/examples/extreme_ironing.jpg differ diff --git a/approach/vlm/LLaVA/llava/serve/examples/waterview.jpg b/approach/vlm/LLaVA/llava/serve/examples/waterview.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6f44ebaba1aa493b8bab3baa4e827b76752b1869 Binary files /dev/null and b/approach/vlm/LLaVA/llava/serve/examples/waterview.jpg differ diff --git a/approach/vlm/LLaVA/llava/serve/gradio_web_server.py b/approach/vlm/LLaVA/llava/serve/gradio_web_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8763fddabcc75182f6496ce53c46c4eacc73cc21 --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/gradio_web_server.py @@ -0,0 +1,420 @@ +import argparse +import datetime +import json +import os +import time + +import gradio as gr +import requests + +from llava.conversation import (default_conversation, conv_templates, + SeparatorStyle) +from llava.constants import LOGDIR +from llava.utils import (build_logger, server_error_msg, + violates_moderation, moderation_msg) +import hashlib + + +logger = build_logger("gradio_web_server", "gradio_web_server.log") + +headers = {"User-Agent": "LLaVA Client"} + +no_change_btn = gr.Button.update() +enable_btn = gr.Button.update(interactive=True) +disable_btn = gr.Button.update(interactive=False) + +priority = { + "vicuna-13b": "aaaaaaa", + "koala-13b": "aaaaaab", +} + + +def get_conv_log_filename(): + t = datetime.datetime.now() + name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json") + return name + + +def get_model_list(): + ret = requests.post(args.controller_url + "/refresh_all_workers") + assert ret.status_code == 200 + ret = requests.post(args.controller_url + "/list_models") + models = ret.json()["models"] + models.sort(key=lambda x: priority.get(x, x)) + logger.info(f"Models: {models}") + return models + + +get_window_url_params = """ +function() { + const params = new URLSearchParams(window.location.search); + url_params = Object.fromEntries(params); + console.log(url_params); + return url_params; + } +""" + + +def load_demo(url_params, request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}") + + dropdown_update = gr.Dropdown.update(visible=True) + if "model" in url_params: + model = url_params["model"] + if model in models: + dropdown_update = gr.Dropdown.update( + value=model, visible=True) + + state = default_conversation.copy() + return state, dropdown_update + + +def load_demo_refresh_model_list(request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}") + models = get_model_list() + state = default_conversation.copy() + dropdown_update = gr.Dropdown.update( + choices=models, + value=models[0] if len(models) > 0 else "" + ) + return state, dropdown_update + + +def vote_last_response(state, vote_type, model_selector, request: gr.Request): + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(time.time(), 4), + "type": vote_type, + "model": model_selector, + "state": state.dict(), + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +def upvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"upvote. ip: {request.client.host}") + vote_last_response(state, "upvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def downvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"downvote. ip: {request.client.host}") + vote_last_response(state, "downvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def flag_last_response(state, model_selector, request: gr.Request): + logger.info(f"flag. ip: {request.client.host}") + vote_last_response(state, "flag", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def regenerate(state, image_process_mode, request: gr.Request): + logger.info(f"regenerate. ip: {request.client.host}") + state.messages[-1][-1] = None + prev_human_msg = state.messages[-2] + if type(prev_human_msg[1]) in (tuple, list): + prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def clear_history(request: gr.Request): + logger.info(f"clear_history. ip: {request.client.host}") + state = default_conversation.copy() + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def add_text(state, text, image, image_process_mode, request: gr.Request): + logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") + if len(text) <= 0 and image is None: + state.skip_next = True + return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 + if args.moderate: + flagged = violates_moderation(text) + if flagged: + state.skip_next = True + return (state, state.to_gradio_chatbot(), moderation_msg, None) + ( + no_change_btn,) * 5 + + text = text[:1536] # Hard cut-off + if image is not None: + text = text[:1200] # Hard cut-off for images + if '' not in text: + # text = '' + text + text = text + '\n' + text = (text, image, image_process_mode) + if len(state.get_images(return_pil=True)) > 0: + state = default_conversation.copy() + state.append_message(state.roles[0], text) + state.append_message(state.roles[1], None) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request): + logger.info(f"http_bot. ip: {request.client.host}") + start_tstamp = time.time() + model_name = model_selector + + if state.skip_next: + # This generate call is skipped due to invalid inputs + yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 + return + + if len(state.messages) == state.offset + 2: + # First round of conversation + if "llava" in model_name.lower(): + if 'llama-2' in model_name.lower(): + template_name = "llava_llama_2" + elif "v1" in model_name.lower(): + if 'mmtag' in model_name.lower(): + template_name = "v1_mmtag" + elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + template_name = "v1_mmtag" + else: + template_name = "llava_v1" + elif "mpt" in model_name.lower(): + template_name = "mpt" + else: + if 'mmtag' in model_name.lower(): + template_name = "v0_mmtag" + elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower(): + template_name = "v0_mmtag" + else: + template_name = "llava_v0" + elif "mpt" in model_name: + template_name = "mpt_text" + elif "llama-2" in model_name: + template_name = "llama_2" + else: + template_name = "vicuna_v1" + new_state = conv_templates[template_name].copy() + new_state.append_message(new_state.roles[0], state.messages[-2][1]) + new_state.append_message(new_state.roles[1], None) + state = new_state + + # Query worker address + controller_url = args.controller_url + ret = requests.post(controller_url + "/get_worker_address", + json={"model": model_name}) + worker_addr = ret.json()["address"] + logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}") + + # No available worker + if worker_addr == "": + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + # Construct prompt + prompt = state.get_prompt() + + all_images = state.get_images(return_pil=True) + all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images] + for image, hash in zip(all_images, all_image_hash): + t = datetime.datetime.now() + filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg") + if not os.path.isfile(filename): + os.makedirs(os.path.dirname(filename), exist_ok=True) + image.save(filename) + + # Make requests + pload = { + "model": model_name, + "prompt": prompt, + "temperature": float(temperature), + "top_p": float(top_p), + "max_new_tokens": min(int(max_new_tokens), 1536), + "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2, + "images": f'List of {len(state.get_images())} images: {all_image_hash}', + } + logger.info(f"==== request ====\n{pload}") + + pload['images'] = state.get_images() + + state.messages[-1][-1] = "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + + try: + # Stream output + response = requests.post(worker_addr + "/worker_generate_stream", + headers=headers, json=pload, stream=True, timeout=10) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode()) + if data["error_code"] == 0: + output = data["text"][len(prompt):].strip() + state.messages[-1][-1] = output + "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + else: + output = data["text"] + f" (error_code: {data['error_code']})" + state.messages[-1][-1] = output + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + time.sleep(0.03) + except requests.exceptions.RequestException as e: + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + state.messages[-1][-1] = state.messages[-1][-1][:-1] + yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5 + + finish_tstamp = time.time() + logger.info(f"{output}") + + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(finish_tstamp, 4), + "type": "chat", + "model": model_name, + "start": round(start_tstamp, 4), + "finish": round(start_tstamp, 4), + "state": state.dict(), + "images": all_image_hash, + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + +title_markdown = (""" +# 🌋 LLaVA: Large Language and Vision Assistant +[[Project Page]](https://llava-vl.github.io) [[Paper]](https://arxiv.org/abs/2304.08485) [[Code]](https://github.com/haotian-liu/LLaVA) [[Model]](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md) +""") + +tos_markdown = (""" +### Terms of use +By using this service, users are required to agree to the following terms: +The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. +Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. +For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. +""") + + +learn_more_markdown = (""" +### License +The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. +""") + +block_css = """ + +#buttons button { + min-width: min(120px,100%); +} + +""" + +def build_demo(embed_mode): + textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False) + with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo: + state = gr.State() + + if not embed_mode: + gr.Markdown(title_markdown) + + with gr.Row(): + with gr.Column(scale=3): + with gr.Row(elem_id="model_selector_row"): + model_selector = gr.Dropdown( + choices=models, + value=models[0] if len(models) > 0 else "", + interactive=True, + show_label=False, + container=False) + + imagebox = gr.Image(type="pil") + image_process_mode = gr.Radio( + ["Crop", "Resize", "Pad", "Default"], + value="Default", + label="Preprocess for non-square image", visible=False) + + cur_dir = os.path.dirname(os.path.abspath(__file__)) + gr.Examples(examples=[ + [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"], + [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"], + ], inputs=[imagebox, textbox]) + + with gr.Accordion("Parameters", open=False) as parameter_row: + temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",) + top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",) + max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",) + + with gr.Column(scale=8): + chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550) + with gr.Row(): + with gr.Column(scale=8): + textbox.render() + with gr.Column(scale=1, min_width=50): + submit_btn = gr.Button(value="Send", variant="primary") + with gr.Row(elem_id="buttons") as button_row: + upvote_btn = gr.Button(value="👍 Upvote", interactive=False) + downvote_btn = gr.Button(value="👎 Downvote", interactive=False) + flag_btn = gr.Button(value="⚠️ Flag", interactive=False) + #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False) + regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) + clear_btn = gr.Button(value="🗑️ Clear", interactive=False) + + if not embed_mode: + gr.Markdown(tos_markdown) + gr.Markdown(learn_more_markdown) + url_params = gr.JSON(visible=False) + + # Register listeners + btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] + upvote_btn.click(upvote_last_response, + [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn]) + downvote_btn.click(downvote_last_response, + [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn]) + flag_btn.click(flag_last_response, + [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn]) + regenerate_btn.click(regenerate, [state, image_process_mode], + [state, chatbot, textbox, imagebox] + btn_list).then( + http_bot, [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list) + clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list) + + textbox.submit(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list + ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list) + submit_btn.click(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list + ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], + [state, chatbot] + btn_list) + + if args.model_list_mode == "once": + demo.load(load_demo, [url_params], [state, model_selector], + _js=get_window_url_params) + elif args.model_list_mode == "reload": + demo.load(load_demo_refresh_model_list, None, [state, model_selector]) + else: + raise ValueError(f"Unknown model list mode: {args.model_list_mode}") + + return demo + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int) + parser.add_argument("--controller-url", type=str, default="http://localhost:21001") + parser.add_argument("--concurrency-count", type=int, default=10) + parser.add_argument("--model-list-mode", type=str, default="once", + choices=["once", "reload"]) + parser.add_argument("--share", action="store_true") + parser.add_argument("--moderate", action="store_true") + parser.add_argument("--embed", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + models = get_model_list() + + logger.info(args) + demo = build_demo(args.embed) + demo.queue( + concurrency_count=args.concurrency_count, + api_open=False + ).launch( + server_name=args.host, + server_port=args.port, + share=args.share + ) diff --git a/approach/vlm/LLaVA/llava/serve/model_worker.py b/approach/vlm/LLaVA/llava/serve/model_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a7bcd0829d0120c4359400b958fc3ad6c6867f9c --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/model_worker.py @@ -0,0 +1,285 @@ +""" +A model worker executes the model. +""" +import argparse +import asyncio +import json +import time +import threading +import uuid + +from fastapi import FastAPI, Request, BackgroundTasks +from fastapi.responses import StreamingResponse +import requests +import torch +import uvicorn +from functools import partial + +from llava.constants import WORKER_HEART_BEAT_INTERVAL +from llava.utils import (build_logger, server_error_msg, + pretty_print_semaphore) +from llava.model.builder import load_pretrained_model +from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from transformers import TextIteratorStreamer +from threading import Thread + + +GB = 1 << 30 + +worker_id = str(uuid.uuid4())[:6] +logger = build_logger("model_worker", f"model_worker_{worker_id}.log") +global_counter = 0 + +model_semaphore = None + + +def heart_beat_worker(controller): + + while True: + time.sleep(WORKER_HEART_BEAT_INTERVAL) + controller.send_heart_beat() + + +class ModelWorker: + def __init__(self, controller_addr, worker_addr, + worker_id, no_register, + model_path, model_base, model_name, + load_8bit, load_4bit, device): + self.controller_addr = controller_addr + self.worker_addr = worker_addr + self.worker_id = worker_id + if model_path.endswith("/"): + model_path = model_path[:-1] + if model_name is None: + model_paths = model_path.split("/") + if model_paths[-1].startswith('checkpoint-'): + self.model_name = model_paths[-2] + "_" + model_paths[-1] + else: + self.model_name = model_paths[-1] + else: + self.model_name = model_name + + self.device = device + logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...") + self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model( + model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device) + self.is_multimodal = 'llava' in self.model_name.lower() + + if not no_register: + self.register_to_controller() + self.heart_beat_thread = threading.Thread( + target=heart_beat_worker, args=(self,)) + self.heart_beat_thread.start() + + def register_to_controller(self): + logger.info("Register to controller") + + url = self.controller_addr + "/register_worker" + data = { + "worker_name": self.worker_addr, + "check_heart_beat": True, + "worker_status": self.get_status() + } + r = requests.post(url, json=data) + assert r.status_code == 200 + + def send_heart_beat(self): + logger.info(f"Send heart beat. Models: {[self.model_name]}. " + f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " + f"global_counter: {global_counter}") + + url = self.controller_addr + "/receive_heart_beat" + + while True: + try: + ret = requests.post(url, json={ + "worker_name": self.worker_addr, + "queue_length": self.get_queue_length()}, timeout=5) + exist = ret.json()["exist"] + break + except requests.exceptions.RequestException as e: + logger.error(f"heart beat error: {e}") + time.sleep(5) + + if not exist: + self.register_to_controller() + + def get_queue_length(self): + if model_semaphore is None: + return 0 + else: + return args.limit_model_concurrency - model_semaphore._value + (len( + model_semaphore._waiters) if model_semaphore._waiters is not None else 0) + + def get_status(self): + return { + "model_names": [self.model_name], + "speed": 1, + "queue_length": self.get_queue_length(), + } + + @torch.inference_mode() + def generate_stream(self, params): + tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor + + prompt = params["prompt"] + ori_prompt = prompt + images = params.get("images", None) + num_image_tokens = 0 + if images is not None and len(images) > 0 and self.is_multimodal: + if len(images) > 0: + if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN): + raise ValueError("Number of images does not match number of tokens in prompt") + + images = [load_image_from_base64(image) for image in images] + images = process_images(images, image_processor, model.config) + + if type(images) is list: + images = [image.to(self.model.device, dtype=torch.float16) for image in images] + else: + images = images.to(self.model.device, dtype=torch.float16) + + replace_token = DEFAULT_IMAGE_TOKEN + if getattr(self.model.config, 'mm_use_im_start_end', False): + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token) + + num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches + else: + images = None + image_args = {"images": images} + else: + images = None + image_args = {} + + temperature = float(params.get("temperature", 1.0)) + top_p = float(params.get("top_p", 1.0)) + max_context_length = getattr(model.config, 'max_position_embeddings', 2048) + max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024) + stop_str = params.get("stop", None) + do_sample = True if temperature > 0.001 else False + + input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15) + + max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens) + + if max_new_tokens < 1: + yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0" + return + + thread = Thread(target=model.generate, kwargs=dict( + inputs=input_ids, + do_sample=do_sample, + temperature=temperature, + top_p=top_p, + max_new_tokens=max_new_tokens, + streamer=streamer, + stopping_criteria=[stopping_criteria], + use_cache=True, + **image_args + )) + thread.start() + + generated_text = ori_prompt + for new_text in streamer: + generated_text += new_text + if generated_text.endswith(stop_str): + generated_text = generated_text[:-len(stop_str)] + yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0" + + def generate_stream_gate(self, params): + try: + for x in self.generate_stream(params): + yield x + except ValueError as e: + print("Caught ValueError:", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + except torch.cuda.CudaError as e: + print("Caught torch.cuda.CudaError:", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + except Exception as e: + print("Caught Unknown Error", e) + ret = { + "text": server_error_msg, + "error_code": 1, + } + yield json.dumps(ret).encode() + b"\0" + + +app = FastAPI() + + +def release_model_semaphore(fn=None): + model_semaphore.release() + if fn is not None: + fn() + + +@app.post("/worker_generate_stream") +async def generate_stream(request: Request): + global model_semaphore, global_counter + global_counter += 1 + params = await request.json() + + if model_semaphore is None: + model_semaphore = asyncio.Semaphore(args.limit_model_concurrency) + await model_semaphore.acquire() + worker.send_heart_beat() + generator = worker.generate_stream_gate(params) + background_tasks = BackgroundTasks() + background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat)) + return StreamingResponse(generator, background=background_tasks) + + +@app.post("/worker_get_status") +async def get_status(request: Request): + return worker.get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="localhost") + parser.add_argument("--port", type=int, default=21002) + parser.add_argument("--worker-address", type=str, + default="http://localhost:21002") + parser.add_argument("--controller-address", type=str, + default="http://localhost:21001") + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--model-name", type=str) + parser.add_argument("--device", type=str, default="cuda") + parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.") + parser.add_argument("--limit-model-concurrency", type=int, default=5) + parser.add_argument("--stream-interval", type=int, default=1) + parser.add_argument("--no-register", action="store_true") + parser.add_argument("--load-8bit", action="store_true") + parser.add_argument("--load-4bit", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + if args.multi_modal: + logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.") + + worker = ModelWorker(args.controller_address, + args.worker_address, + worker_id, + args.no_register, + args.model_path, + args.model_base, + args.model_name, + args.load_8bit, + args.load_4bit, + args.device) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/approach/vlm/LLaVA/llava/serve/register_worker.py b/approach/vlm/LLaVA/llava/serve/register_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2c40295e0351f25709ba25554c9329f15bf0d2 --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/register_worker.py @@ -0,0 +1,26 @@ +""" +Manually register workers. + +Usage: +python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002 +""" + +import argparse + +import requests + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--controller-address", type=str) + parser.add_argument("--worker-name", type=str) + parser.add_argument("--check-heart-beat", action="store_true") + args = parser.parse_args() + + url = args.controller_address + "/register_worker" + data = { + "worker_name": args.worker_name, + "check_heart_beat": args.check_heart_beat, + "worker_status": None, + } + r = requests.post(url, json=data) + assert r.status_code == 200 diff --git a/approach/vlm/LLaVA/llava/serve/test_message.py b/approach/vlm/LLaVA/llava/serve/test_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6b090faed0e630b03b2294545050f1f4f5032cad --- /dev/null +++ b/approach/vlm/LLaVA/llava/serve/test_message.py @@ -0,0 +1,62 @@ +import argparse +import json + +import requests + +from llava.conversation import default_conversation + + +def main(): + if args.worker_address: + worker_addr = args.worker_address + else: + controller_addr = args.controller_address + ret = requests.post(controller_addr + "/refresh_all_workers") + ret = requests.post(controller_addr + "/list_models") + models = ret.json()["models"] + models.sort() + print(f"Models: {models}") + + ret = requests.post(controller_addr + "/get_worker_address", + json={"model": args.model_name}) + worker_addr = ret.json()["address"] + print(f"worker_addr: {worker_addr}") + + if worker_addr == "": + return + + conv = default_conversation.copy() + conv.append_message(conv.roles[0], args.message) + prompt = conv.get_prompt() + + headers = {"User-Agent": "LLaVA Client"} + pload = { + "model": args.model_name, + "prompt": prompt, + "max_new_tokens": args.max_new_tokens, + "temperature": 0.7, + "stop": conv.sep, + } + response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, + json=pload, stream=True) + + print(prompt.replace(conv.sep, "\n"), end="") + for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode("utf-8")) + output = data["text"].split(conv.sep)[-1] + print(output, end="\r") + print("") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--controller-address", type=str, default="http://localhost:21001") + parser.add_argument("--worker-address", type=str) + parser.add_argument("--model-name", type=str, default="facebook/opt-350m") + parser.add_argument("--max-new-tokens", type=int, default=32) + parser.add_argument("--message", type=str, default= + "Tell me a story with more than 1000 words.") + args = parser.parse_args() + + main() diff --git a/approach/vlm/LLaVA/llava/train/llama_flash_attn_monkey_patch.py b/approach/vlm/LLaVA/llava/train/llama_flash_attn_monkey_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..31db2eff8d1c4b3ae645583dfc5e156e818b6f1c --- /dev/null +++ b/approach/vlm/LLaVA/llava/train/llama_flash_attn_monkey_patch.py @@ -0,0 +1,115 @@ +from typing import Optional, Tuple +import warnings + +import torch + +import transformers +from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv + +try: + from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func +except ImportError: + from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func +from flash_attn.bert_padding import unpad_input, pad_input + + +def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = 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]]]: + if output_attentions: + warnings.warn( + "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead." + ) + + 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_key_value_heads, self.head_dim) + .transpose(1, 2) + ) + value_states = ( + self.v_proj(hidden_states) + .view(bsz, q_len, self.num_key_value_heads, self.head_dim) + .transpose(1, 2) + ) # shape: (b, num_heads, s, head_dim) + + 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 + ) + + if past_key_value is not None: + # reuse k, v + 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 + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + # Transform the data into the format required by flash attention + qkv = torch.stack([query_states, key_states, value_states], dim=2) + qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim] + key_padding_mask = attention_mask + + if key_padding_mask is None: + qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim) + cu_q_lens = torch.arange( + 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device + ) + max_s = q_len + output = flash_attn_unpadded_qkvpacked_func( + qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True + ) + output = output.view(bsz, q_len, -1) + else: + qkv = qkv.reshape(bsz, q_len, -1) + qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask) + qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) + output_unpad = flash_attn_unpadded_qkvpacked_func( + qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True + ) + output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim) + output = pad_input(output_unpad, indices, bsz, q_len) + + return self.o_proj(output), None, past_key_value + + +# Disable the transformation of the attention mask in LlamaModel as the flash attention +# requires the attention mask to be the same as the key_padding_mask +def _prepare_decoder_attention_mask( + self, attention_mask, input_shape, inputs_embeds, past_key_values_length +): + # [bsz, seq_len] + return attention_mask + + +def replace_llama_attn_with_flash_attn(): + cuda_major, cuda_minor = torch.cuda.get_device_capability() + if cuda_major < 8: + warnings.warn( + "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." + "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593" + ) + transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = ( + _prepare_decoder_attention_mask + ) + transformers.models.llama.modeling_llama.LlamaAttention.forward = forward diff --git a/approach/vlm/LLaVA/llava/train/llava_trainer.py b/approach/vlm/LLaVA/llava/train/llava_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6f4061328337edb130b8298d2b063445e0af45 --- /dev/null +++ b/approach/vlm/LLaVA/llava/train/llava_trainer.py @@ -0,0 +1,175 @@ +import os +import torch + +from torch.utils.data import Sampler + +from transformers import Trainer +from transformers.trainer import ( + has_length, +) +from typing import List, Optional + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + print(name, 'no ignore status') + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()} + return to_return + + +def split_to_even_chunks(indices, lengths, num_chunks): + """ + Split a list of indices into `chunks` chunks of roughly equal lengths. + """ + + if len(indices) % num_chunks != 0: + return [indices[i::num_chunks] for i in range(num_chunks)] + + num_indices_per_chunk = len(indices) // num_chunks + + chunks = [[] for _ in range(num_chunks)] + chunks_lengths = [0 for _ in range(num_chunks)] + for index in indices: + shortest_chunk = chunks_lengths.index(min(chunks_lengths)) + chunks[shortest_chunk].append(index) + chunks_lengths[shortest_chunk] += lengths[index] + if len(chunks[shortest_chunk]) == num_indices_per_chunk: + chunks_lengths[shortest_chunk] = float("inf") + + return chunks + + +def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + assert all(l != 0 for l in lengths), "Should not have zero length." + mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0]) + lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0]) + + assert len(mm_indices) > 0, "Should have at least one multimodal sample." + assert len(lang_indices) > 0, "Should have at least one language sample." + + mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)] + lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)] + megabatch_size = world_size * batch_size + mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)] + lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)] + + last_mm = mm_megabatches[-1] + last_lang = lang_megabatches[-1] + additional_batch = last_mm + last_lang + megabatches = mm_megabatches[:-1] + lang_megabatches[:-1] + megabatch_indices = torch.randperm(len(megabatches), generator=generator) + megabatches = [megabatches[i] for i in megabatch_indices] + + if len(additional_batch) >= megabatch_size: + megabatches = [additional_batch[:megabatch_size]] + megabatches + additional_batch = additional_batch[megabatch_size:] + + if len(additional_batch) > 0: + megabatches.append(additional_batch) + + return [i for megabatch in megabatches for i in megabatch] + + +def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True): + # We need to use torch for the random part as a distributed sampler will set the random seed for torch. + indices = torch.randperm(len(lengths), generator=generator) + megabatch_size = world_size * batch_size + megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] + megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] + megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches] + + return [i for megabatch in megabatches for batch in megabatch for i in batch] + + +class LengthGroupedSampler(Sampler): + r""" + Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while + keeping a bit of randomness. + """ + + def __init__( + self, + batch_size: int, + world_size: int, + lengths: Optional[List[int]] = None, + generator=None, + group_by_modality: bool = False, + ): + if lengths is None: + raise ValueError("Lengths must be provided.") + + self.batch_size = batch_size + self.world_size = world_size + self.lengths = lengths + self.generator = generator + self.group_by_modality = group_by_modality + + def __len__(self): + return len(self.lengths) + + def __iter__(self): + if self.group_by_modality: + indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + else: + indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator) + return iter(indices) + + +class LLaVATrainer(Trainer): + + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + if self.train_dataset is None or not has_length(self.train_dataset): + return None + + if self.args.group_by_modality_length: + lengths = self.train_dataset.modality_lengths + return LengthGroupedSampler( + # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps + self.args.train_batch_size, + world_size=self.args.world_size, + lengths=lengths, + group_by_modality=True, + ) + else: + return super()._get_train_sampler() + + def _save_checkpoint(self, model, trial, metrics=None): + if getattr(self.args, 'tune_mm_mlp_adapter', False): + from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + + run_dir = self._get_output_dir(trial=trial) + output_dir = os.path.join(run_dir, checkpoint_folder) + + # Only save Adapter + keys_to_match = ['mm_projector', 'vision_resampler'] + if getattr(self.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match) + + if self.args.local_rank == 0 or self.args.local_rank == -1: + self.model.config.save_pretrained(output_dir) + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + else: + super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics) + + def _save(self, output_dir: Optional[str] = None, state_dict=None): + if getattr(self.args, 'tune_mm_mlp_adapter', False): + pass + else: + super(LLaVATrainer, self)._save(output_dir, state_dict) diff --git a/approach/vlm/LLaVA/llava/train/train.py b/approach/vlm/LLaVA/llava/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..0d198f7e379df541e2b9a6fbd61310ea30f16f82 --- /dev/null +++ b/approach/vlm/LLaVA/llava/train/train.py @@ -0,0 +1,950 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import copy +from dataclasses import dataclass, field +import json +import logging +import pathlib +from typing import Dict, Optional, Sequence, List + +import torch + +import transformers + +from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from torch.utils.data import Dataset +from llava.train.llava_trainer import LLaVATrainer + +from llava import conversation as conversation_lib +from llava.model import * +from llava.mm_utils import tokenizer_image_token + +from PIL import Image + + +local_rank = None + + +def rank0_print(*args): + if local_rank == 0: + print(*args) + + +@dataclass +class ModelArguments: + model_name_or_path: Optional[str] = field(default="facebook/opt-125m") + version: Optional[str] = field(default="v0") + freeze_backbone: bool = field(default=False) + tune_mm_mlp_adapter: bool = field(default=False) + vision_tower: Optional[str] = field(default=None) + mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer + pretrain_mm_mlp_adapter: Optional[str] = field(default=None) + mm_projector_type: Optional[str] = field(default='linear') + mm_use_im_start_end: bool = field(default=False) + mm_use_im_patch_token: bool = field(default=True) + mm_vision_select_feature: Optional[str] = field(default="patch") + + +@dataclass +class DataArguments: + data_path: str = field(default=None, + metadata={"help": "Path to the training data."}) + lazy_preprocess: bool = False + is_multimodal: bool = False + image_folder: Optional[str] = field(default=None) + image_aspect_ratio: str = 'square' + image_grid_pinpoints: Optional[str] = field(default=None) + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + cache_dir: Optional[str] = field(default=None) + optim: str = field(default="adamw_torch") + remove_unused_columns: bool = field(default=False) + freeze_mm_mlp_adapter: bool = field(default=False) + mpt_attn_impl: Optional[str] = field(default="triton") + model_max_length: int = field( + default=512, + metadata={ + "help": + "Maximum sequence length. Sequences will be right padded (and possibly truncated)." + }, + ) + double_quant: bool = field( + default=True, + metadata={"help": "Compress the quantization statistics through double quantization."} + ) + quant_type: str = field( + default="nf4", + metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} + ) + bits: int = field( + default=16, + metadata={"help": "How many bits to use."} + ) + lora_enable: bool = False + lora_r: int = 64 + lora_alpha: int = 16 + lora_dropout: float = 0.05 + lora_weight_path: str = "" + lora_bias: str = "none" + group_by_modality_length: bool = field(default=False) + + +def maybe_zero_3(param, ignore_status=False, name=None): + from deepspeed import zero + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + if hasattr(param, "ds_id"): + if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: + if not ignore_status: + logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") + with zero.GatheredParameters([param]): + param = param.data.detach().cpu().clone() + else: + param = param.detach().cpu().clone() + return param + + +# Borrowed from peft.utils.get_peft_model_state_dict +def get_peft_state_maybe_zero_3(named_params, bias): + if bias == "none": + to_return = {k: t for k, t in named_params if "lora_" in k} + elif bias == "all": + to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} + elif bias == "lora_only": + to_return = {} + maybe_lora_bias = {} + lora_bias_names = set() + for k, t in named_params: + if "lora_" in k: + to_return[k] = t + bias_name = k.split("lora_")[0] + "bias" + lora_bias_names.add(bias_name) + elif "bias" in k: + maybe_lora_bias[k] = t + for k, t in maybe_lora_bias: + if bias_name in lora_bias_names: + to_return[bias_name] = t + else: + raise NotImplementedError + to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} + return to_return + + +def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): + to_return = {k: t for k, t in named_params if "lora_" not in k} + if require_grad_only: + to_return = {k: t for k, t in to_return.items() if t.requires_grad} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): + to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} + to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} + return to_return + + +def find_all_linear_names(model): + cls = torch.nn.Linear + lora_module_names = set() + for name, module in model.named_modules(): + if isinstance(module, cls): + names = name.split('.') + lora_module_names.add(names[0] if len(names) == 1 else names[-1]) + + + if 'lm_head' in lora_module_names: # needed for 16-bit + lora_module_names.remove('lm_head') + return list(lora_module_names) + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, + output_dir: str): + """Collects the state dict and dump to disk.""" + + if getattr(trainer.args, "tune_mm_mlp_adapter", False): + # Only save Adapter + keys_to_match = ['mm_projector'] + if getattr(trainer.args, "use_im_start_end", False): + keys_to_match.extend(['embed_tokens', 'embed_in']) + + weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) + trainer.model.config.save_pretrained(output_dir) + + current_folder = output_dir.split('/')[-1] + parent_folder = os.path.dirname(output_dir) + if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: + if current_folder.startswith('checkpoint-'): + mm_projector_folder = os.path.join(parent_folder, "mm_projector") + os.makedirs(mm_projector_folder, exist_ok=True) + torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) + else: + torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) + return + + if trainer.deepspeed: + torch.cuda.synchronize() + trainer.save_model(output_dir) + return + + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = { + key: value.cpu() + for key, value in state_dict.items() + } + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +def smart_tokenizer_and_embedding_resize( + special_tokens_dict: Dict, + tokenizer: transformers.PreTrainedTokenizer, + model: transformers.PreTrainedModel, +): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ + num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) + model.resize_token_embeddings(len(tokenizer)) + + if num_new_tokens > 0: + input_embeddings = model.get_input_embeddings().weight.data + output_embeddings = model.get_output_embeddings().weight.data + + input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( + dim=0, keepdim=True) + + input_embeddings[-num_new_tokens:] = input_embeddings_avg + output_embeddings[-num_new_tokens:] = output_embeddings_avg + + +def _tokenize_fn(strings: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer) -> Dict: + """Tokenize a list of strings.""" + tokenized_list = [ + tokenizer( + text, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ) for text in strings + ] + input_ids = labels = [ + tokenized.input_ids[0] for tokenized in tokenized_list + ] + input_ids_lens = labels_lens = [ + tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() + for tokenized in tokenized_list + ] + return dict( + input_ids=input_ids, + labels=labels, + input_ids_lens=input_ids_lens, + labels_lens=labels_lens, + ) + + +def _mask_targets(target, tokenized_lens, speakers): + # cur_idx = 0 + cur_idx = tokenized_lens[0] + tokenized_lens = tokenized_lens[1:] + target[:cur_idx] = IGNORE_INDEX + for tokenized_len, speaker in zip(tokenized_lens, speakers): + if speaker == "human": + target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX + cur_idx += tokenized_len + + +def _add_speaker_and_signal(header, source, get_conversation=True): + """Add speaker and start/end signal on each round.""" + BEGIN_SIGNAL = "### " + END_SIGNAL = "\n" + conversation = header + for sentence in source: + from_str = sentence["from"] + if from_str.lower() == "human": + from_str = conversation_lib.default_conversation.roles[0] + elif from_str.lower() == "gpt": + from_str = conversation_lib.default_conversation.roles[1] + else: + from_str = 'unknown' + sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + + sentence["value"] + END_SIGNAL) + if get_conversation: + conversation += sentence["value"] + conversation += BEGIN_SIGNAL + return conversation + + +def preprocess_multimodal( + sources: Sequence[str], + data_args: DataArguments +) -> Dict: + is_multimodal = data_args.is_multimodal + if not is_multimodal: + return sources + + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence['value']: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() + sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] + sentence['value'] = sentence['value'].strip() + if "mmtag" in conversation_lib.default_conversation.version: + sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '' + DEFAULT_IMAGE_TOKEN + '') + replace_token = DEFAULT_IMAGE_TOKEN + if data_args.mm_use_im_start_end: + replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) + + return sources + + +def preprocess_llama_2( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 + + # Mask targets + sep = "[/INST] " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_v1( + sources, + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + + if has_image: + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + else: + input_ids = tokenizer( + conversations, + return_tensors="pt", + padding="longest", + max_length=tokenizer.model_max_length, + truncation=True, + ).input_ids + + targets = input_ids.clone() + + assert conv.sep_style == conversation_lib.SeparatorStyle.TWO + + # Mask targets + sep = conv.sep + conv.roles[1] + ": " + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep2) + cur_len = 1 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + + if has_image: + round_len = len(tokenizer_image_token(rou, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 + else: + round_len = len(tokenizer(rou).input_ids) + instruction_len = len(tokenizer(parts[0]).input_ids) - 2 + + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_mpt( + sources, + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + conv = conversation_lib.default_conversation.copy() + roles = {"human": conv.roles[0], "gpt": conv.roles[1]} + + # Apply prompt templates + conversations = [] + for i, source in enumerate(sources): + if roles[source[0]["from"]] != conv.roles[0]: + # Skip the first one if it is not from human + source = source[1:] + + conv.messages = [] + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + assert role == conv.roles[j % 2], f"{i}" + conv.append_message(role, sentence["value"]) + conversations.append(conv.get_prompt()) + + # Tokenize conversations + input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) + targets = input_ids.clone() + assert conv.sep_style == conversation_lib.SeparatorStyle.MPT + + # Mask targets + sep = conv.sep + conv.roles[1] + for conversation, target in zip(conversations, targets): + total_len = int(target.ne(tokenizer.pad_token_id).sum()) + + rounds = conversation.split(conv.sep) + re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt + for conv_idx in range(3, len(rounds), 2): + re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt + cur_len = 0 + target[:cur_len] = IGNORE_INDEX + for i, rou in enumerate(re_rounds): + if rou == "": + break + + parts = rou.split(sep) + if len(parts) != 2: + break + parts[0] += sep + round_len = len(tokenizer_image_token(rou, tokenizer)) + len(tokenizer_image_token(conv.sep, tokenizer)) + instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) + target[cur_len : cur_len + instruction_len] = IGNORE_INDEX + + cur_len += round_len + target[cur_len:] = IGNORE_INDEX + + if cur_len < tokenizer.model_max_length: + if cur_len != total_len: + target[:] = IGNORE_INDEX + print( + f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." + f" (ignored)" + ) + + return dict( + input_ids=input_ids, + labels=targets, + ) + + +def preprocess_plain( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + # add end signal and concatenate together + conversations = [] + for source in sources: + assert len(source) == 2 + assert DEFAULT_IMAGE_TOKEN in source[0]['value'] + source[0]['value'] = DEFAULT_IMAGE_TOKEN + conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep + conversations.append(conversation) + # tokenize conversations + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) + target[:tokenized_len] = IGNORE_INDEX + + return dict(input_ids=input_ids, labels=targets) + + +def preprocess( + sources: Sequence[str], + tokenizer: transformers.PreTrainedTokenizer, + has_image: bool = False +) -> Dict: + """ + Given a list of sources, each is a conversation list. This transform: + 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; + 2. Concatenate conversations together; + 3. Tokenize the concatenated conversation; + 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. + """ + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: + return preprocess_plain(sources, tokenizer) + if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: + return preprocess_llama_2(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version.startswith("v1"): + return preprocess_v1(sources, tokenizer, has_image=has_image) + if conversation_lib.default_conversation.version == "mpt": + return preprocess_mpt(sources, tokenizer) + # add end signal and concatenate together + conversations = [] + for source in sources: + header = f"{conversation_lib.default_conversation.system}\n\n" + conversation = _add_speaker_and_signal(header, source) + conversations.append(conversation) + # tokenize conversations + def get_tokenize_len(prompts): + return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] + + if has_image: + input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] + else: + conversations_tokenized = _tokenize_fn(conversations, tokenizer) + input_ids = conversations_tokenized["input_ids"] + + targets = copy.deepcopy(input_ids) + for target, source in zip(targets, sources): + if has_image: + tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) + else: + tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] + speakers = [sentence["from"] for sentence in source] + _mask_targets(target, tokenized_lens, speakers) + + return dict(input_ids=input_ids, labels=targets) + + +class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__(self, data_path: str, + tokenizer: transformers.PreTrainedTokenizer, + data_args: DataArguments): + super(LazySupervisedDataset, self).__init__() + list_data_dict = json.load(open(data_path, "r")) + + rank0_print("Formatting inputs...Skip in lazy mode") + self.tokenizer = tokenizer + self.list_data_dict = list_data_dict + self.data_args = data_args + + def __len__(self): + return len(self.list_data_dict) + + @property + def lengths(self): + length_list = [] + for sample in self.list_data_dict: + img_tokens = 128 if 'image' in sample else 0 + length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens) + return length_list + + @property + def modality_lengths(self): + length_list = [] + for sample in self.list_data_dict: + cur_len = sum(len(conv['value'].split()) for conv in sample['conversations']) + cur_len = cur_len if 'image' in sample else -cur_len + length_list.append(cur_len) + return length_list + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + sources = self.list_data_dict[i] + if isinstance(i, int): + sources = [sources] + assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME + if 'image' in sources[0]: + image_file = self.list_data_dict[i]['image'] + image_folder = self.data_args.image_folder + processor = self.data_args.image_processor + image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') + if self.data_args.image_aspect_ratio == 'pad': + def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + image = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) + image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + else: + image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] + sources = preprocess_multimodal( + copy.deepcopy([e["conversations"] for e in sources]), + self.data_args) + else: + sources = copy.deepcopy([e["conversations"] for e in sources]) + data_dict = preprocess( + sources, + self.tokenizer, + has_image=('image' in self.list_data_dict[i])) + if isinstance(i, int): + data_dict = dict(input_ids=data_dict["input_ids"][0], + labels=data_dict["labels"][0]) + + # image exist in the data + if 'image' in self.list_data_dict[i]: + data_dict['image'] = image + elif self.data_args.is_multimodal: + # image does not exist in the data, but the model is multimodal + crop_size = self.data_args.image_processor.crop_size + data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) + return data_dict + + +@dataclass +class DataCollatorForSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + + tokenizer: transformers.PreTrainedTokenizer + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + input_ids, labels = tuple([instance[key] for instance in instances] + for key in ("input_ids", "labels")) + input_ids = torch.nn.utils.rnn.pad_sequence( + input_ids, + batch_first=True, + padding_value=self.tokenizer.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, + batch_first=True, + padding_value=IGNORE_INDEX) + input_ids = input_ids[:, :self.tokenizer.model_max_length] + labels = labels[:, :self.tokenizer.model_max_length] + batch = dict( + input_ids=input_ids, + labels=labels, + attention_mask=input_ids.ne(self.tokenizer.pad_token_id), + ) + + if 'image' in instances[0]: + images = [instance['image'] for instance in instances] + if all(x is not None and x.shape == images[0].shape for x in images): + batch['images'] = torch.stack(images) + else: + batch['images'] = images + + return batch + + +def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, + data_args) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + train_dataset = LazySupervisedDataset(tokenizer=tokenizer, + data_path=data_args.data_path, + data_args=data_args) + data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) + return dict(train_dataset=train_dataset, + eval_dataset=None, + data_collator=data_collator) + + +def train(): + global local_rank + + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments)) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + local_rank = training_args.local_rank + compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + + bnb_model_from_pretrained_args = {} + if training_args.bits in [4, 8]: + from transformers import BitsAndBytesConfig + bnb_model_from_pretrained_args.update(dict( + device_map={"": training_args.device}, + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + quantization_config=BitsAndBytesConfig( + load_in_4bit=training_args.bits == 4, + load_in_8bit=training_args.bits == 8, + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=compute_dtype, + bnb_4bit_use_double_quant=training_args.double_quant, + bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} + ) + )) + + if model_args.vision_tower is not None: + if 'mpt' in model_args.model_name_or_path: + config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True) + config.attn_config['attn_impl'] = training_args.mpt_attn_impl + model = LlavaMPTForCausalLM.from_pretrained( + model_args.model_name_or_path, + config=config, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = LlavaLlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + else: + model = transformers.LlamaForCausalLM.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + **bnb_model_from_pretrained_args + ) + model.config.use_cache = False + + if model_args.freeze_backbone: + model.model.requires_grad_(False) + + if training_args.bits in [4, 8]: + from peft import prepare_model_for_kbit_training + model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) + + if training_args.gradient_checkpointing: + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if training_args.lora_enable: + from peft import LoraConfig, get_peft_model + lora_config = LoraConfig( + r=training_args.lora_r, + lora_alpha=training_args.lora_alpha, + target_modules=find_all_linear_names(model), + lora_dropout=training_args.lora_dropout, + bias=training_args.lora_bias, + task_type="CAUSAL_LM", + ) + if training_args.bits == 16: + if training_args.bf16: + model.to(torch.bfloat16) + if training_args.fp16: + model.to(torch.float16) + rank0_print("Adding LoRA adapters...") + model = get_peft_model(model, lora_config) + + if 'mpt' in model_args.model_name_or_path: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right" + ) + else: + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=training_args.cache_dir, + model_max_length=training_args.model_max_length, + padding_side="right", + use_fast=False, + ) + + if model_args.version == "v0": + if tokenizer.pad_token is None: + smart_tokenizer_and_embedding_resize( + special_tokens_dict=dict(pad_token="[PAD]"), + tokenizer=tokenizer, + model=model, + ) + elif model_args.version == "v0.5": + tokenizer.pad_token = tokenizer.unk_token + else: + tokenizer.pad_token = tokenizer.unk_token + if model_args.version in conversation_lib.conv_templates: + conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] + else: + conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] + + if model_args.vision_tower is not None: + model.get_model().initialize_vision_modules( + model_args=model_args, + fsdp=training_args.fsdp + ) + + vision_tower = model.get_vision_tower() + vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) + + data_args.image_processor = vision_tower.image_processor + data_args.is_multimodal = True + + model.config.image_aspect_ratio = data_args.image_aspect_ratio + model.config.image_grid_pinpoints = data_args.image_grid_pinpoints + + model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter + if model_args.tune_mm_mlp_adapter: + model.requires_grad_(False) + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = True + + model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter + if training_args.freeze_mm_mlp_adapter: + for p in model.get_model().mm_projector.parameters(): + p.requires_grad = False + + if training_args.bits in [4, 8]: + model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) + + model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end + training_args.use_im_start_end = model_args.mm_use_im_start_end + model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token + model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) + + if training_args.bits in [4, 8]: + from peft.tuners.lora import LoraLayer + for name, module in model.named_modules(): + if isinstance(module, LoraLayer): + if training_args.bf16: + module = module.to(torch.bfloat16) + if 'norm' in name: + module = module.to(torch.float32) + if 'lm_head' in name or 'embed_tokens' in name: + if hasattr(module, 'weight'): + if training_args.bf16 and module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + data_module = make_supervised_data_module(tokenizer=tokenizer, + data_args=data_args) + trainer = LLaVATrainer(model=model, + tokenizer=tokenizer, + args=training_args, + **data_module) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + trainer.save_state() + + model.config.use_cache = True + + if training_args.lora_enable: + state_dict = get_peft_state_maybe_zero_3( + model.named_parameters(), training_args.lora_bias + ) + non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3( + model.named_parameters() + ) + if training_args.local_rank == 0 or training_args.local_rank == -1: + model.config.save_pretrained(training_args.output_dir) + model.save_pretrained(training_args.output_dir, state_dict=state_dict) + torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin')) + else: + safe_save_model_for_hf_trainer(trainer=trainer, + output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/approach/vlm/LLaVA/llava/train/train_mem.py b/approach/vlm/LLaVA/llava/train/train_mem.py new file mode 100644 index 0000000000000000000000000000000000000000..2487d317855b27d5b07a755ee0389667e4964f02 --- /dev/null +++ b/approach/vlm/LLaVA/llava/train/train_mem.py @@ -0,0 +1,13 @@ +# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: +# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: +# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn. + +# Need to call this before importing transformers. +from llava.train.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn + +replace_llama_attn_with_flash_attn() + +from llava.train.train import train + +if __name__ == "__main__": + train() diff --git a/approach/vlm/LLaVA/llava/utils.py b/approach/vlm/LLaVA/llava/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7163c0ba1d9a81d81a950bce61e0f0db06066e --- /dev/null +++ b/approach/vlm/LLaVA/llava/utils.py @@ -0,0 +1,126 @@ +import datetime +import logging +import logging.handlers +import os +import sys + +import requests + +from llava.constants import LOGDIR + +server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" +moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN." + +handler = None + + +def build_logger(logger_name, logger_filename): + global handler + + formatter = logging.Formatter( + fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + # Set the format of root handlers + if not logging.getLogger().handlers: + logging.basicConfig(level=logging.INFO) + logging.getLogger().handlers[0].setFormatter(formatter) + + # Redirect stdout and stderr to loggers + stdout_logger = logging.getLogger("stdout") + stdout_logger.setLevel(logging.INFO) + sl = StreamToLogger(stdout_logger, logging.INFO) + sys.stdout = sl + + stderr_logger = logging.getLogger("stderr") + stderr_logger.setLevel(logging.ERROR) + sl = StreamToLogger(stderr_logger, logging.ERROR) + sys.stderr = sl + + # Get logger + logger = logging.getLogger(logger_name) + logger.setLevel(logging.INFO) + + # Add a file handler for all loggers + if handler is None: + os.makedirs(LOGDIR, exist_ok=True) + filename = os.path.join(LOGDIR, logger_filename) + handler = logging.handlers.TimedRotatingFileHandler( + filename, when='D', utc=True) + handler.setFormatter(formatter) + + for name, item in logging.root.manager.loggerDict.items(): + if isinstance(item, logging.Logger): + item.addHandler(handler) + + return logger + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + """ + def __init__(self, logger, log_level=logging.INFO): + self.terminal = sys.stdout + self.logger = logger + self.log_level = log_level + self.linebuf = '' + + def __getattr__(self, attr): + return getattr(self.terminal, attr) + + def write(self, buf): + temp_linebuf = self.linebuf + buf + self.linebuf = '' + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross platform. + if line[-1] == '\n': + self.logger.log(self.log_level, line.rstrip()) + else: + self.linebuf += line + + def flush(self): + if self.linebuf != '': + self.logger.log(self.log_level, self.linebuf.rstrip()) + self.linebuf = '' + + +def disable_torch_init(): + """ + Disable the redundant torch default initialization to accelerate model creation. + """ + import torch + setattr(torch.nn.Linear, "reset_parameters", lambda self: None) + setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) + + +def violates_moderation(text): + """ + Check whether the text violates OpenAI moderation API. + """ + url = "https://api.openai.com/v1/moderations" + headers = {"Content-Type": "application/json", + "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} + text = text.replace("\n", "") + data = "{" + '"input": ' + f'"{text}"' + "}" + data = data.encode("utf-8") + try: + ret = requests.post(url, headers=headers, data=data, timeout=5) + flagged = ret.json()["results"][0]["flagged"] + except requests.exceptions.RequestException as e: + flagged = False + except KeyError as e: + flagged = False + + return flagged + + +def pretty_print_semaphore(semaphore): + if semaphore is None: + return "None" + return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" diff --git a/approach/vlm/LLaVA/scripts/convert_sqa_to_llava.py b/approach/vlm/LLaVA/scripts/convert_sqa_to_llava.py new file mode 100644 index 0000000000000000000000000000000000000000..26fe3002413a23b5029e540c8b338ebb14307bf6 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/convert_sqa_to_llava.py @@ -0,0 +1,88 @@ +import json +import os +import fire +import re +from convert_sqa_to_llava_base_prompt import build_prompt_chatbot + + +def convert_to_llava(base_dir, split, prompt_format="QCM-LEA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot( + problems, split_indices, prompt_format, + use_caption=False, is_test=False) + + target_format = [] + for prob_id, (input, output) in split_problems.items(): + if input.startswith('Question: '): + input = input.replace('Question: ', '') + if output.startswith('Answer: '): + output = output.replace('Answer: ', '') + + raw_prob_data = problems[prob_id] + if raw_prob_data['image'] is None: + target_format.append({ + "id": prob_id, + "conversations": [ + {'from': 'human', 'value': f"{input}"}, + {'from': 'gpt', 'value': f"{output}"}, + ], + }) + + else: + target_format.append({ + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data['image']), + "conversations": [ + {'from': 'human', 'value': f"{input}\n"}, + {'from': 'gpt', 'value': f"{output}"}, + ], + }) + + print(f'Number of samples: {len(target_format)}') + + with open(os.path.join(base_dir, f"llava_{split}_{prompt_format}.json"), "w") as f: + json.dump(target_format, f, indent=2) + + +def convert_to_jsonl(base_dir, split, prompt_format="QCM-LEPA"): + split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[split] + problems = json.load(open(os.path.join(base_dir, "problems.json"))) + + split_problems = build_prompt_chatbot( + problems, split_indices, prompt_format, + use_caption=False, is_test=False) + + writer = open(os.path.join(base_dir, f"scienceqa_{split}_{prompt_format}.jsonl"), "w") + for prob_id, (input, output) in split_problems.items(): + if input.startswith('Question: '): + input = input.replace('Question: ', '') + if output.startswith('Answer: '): + output = output.replace('Answer: ', '') + + raw_prob_data = problems[prob_id] + if raw_prob_data['image'] is None: + data = { + "id": prob_id, + "instruction": f"{input}", + "output": f"{output}", + } + + else: + data = { + "id": prob_id, + "image": os.path.join(prob_id, raw_prob_data['image']), + "instruction": f"{input}\n", + "output": f"{output}", + } + writer.write(json.dumps(data) + '\n') + writer.close() + + +def main(task, **kwargs): + globals()[task](**kwargs) + + +if __name__ == "__main__": + fire.Fire(main) diff --git a/approach/vlm/LLaVA/scripts/convert_sqa_to_llava_base_prompt.py b/approach/vlm/LLaVA/scripts/convert_sqa_to_llava_base_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..b327fcc29eb44d7fe68be35da25bafa0e1d6feba --- /dev/null +++ b/approach/vlm/LLaVA/scripts/convert_sqa_to_llava_base_prompt.py @@ -0,0 +1,334 @@ +def get_question_text(problem): + question = problem['question'] + return question + + +def get_context_text(problem, use_caption): + txt_context = problem['hint'] + img_context = problem['caption'] if use_caption else "" + context = " ".join([txt_context, img_context]).strip() + if context == "": + context = "N/A" + return context + + +def get_choice_text(probelm, options): + choices = probelm['choices'] + choice_list = [] + for i, c in enumerate(choices): + choice_list.append("({}) {}".format(options[i], c)) + choice_txt = " ".join(choice_list) + #print(choice_txt) + return choice_txt + + +def get_answer(problem, options): + return options[problem['answer']] + + +def get_lecture_text(problem): + # \\n: GPT-3 can generate the lecture with more tokens. + lecture = problem['lecture'].replace("\n", "\\n") + return lecture + + +def get_solution_text(problem): + # \\n: GPT-3 can generate the solution with more tokens + solution = problem['solution'].replace("\n", "\\n") + return solution + + +def create_one_example_chatbot(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + elif output_format == 'LEPA': + output = '' + if len(lecture.strip()) > 0: + output += f"LECTURE: {lecture}\n" + if len(solution.strip()) > 0: + output += f"SOLUTION: {solution}\n" + output += '###\n' + output += f"ANSWER: {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if input.endswith("BECAUSE:"): + input = input.replace("BECAUSE:", "").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + return input, output + + +def create_one_example(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + + text = input + output + text = text.replace(" ", " ").strip() + if text.endswith("BECAUSE:"): + text = text.replace("BECAUSE:", "").strip() + return text + + + +def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True): + + input_format, output_format = format.split("-") + + ## Inputs + if input_format == "CQM": + input = f"Context: {context}\nQuestion: {question}\nOptions: {choice}\n" + elif input_format == "QCM": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\n" + # upper bound experiment + elif input_format == "QCML": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture}\n" + elif input_format == "QCME": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {solution}\n" + elif input_format == "QCMLE": + input = f"Question: {question}\nContext: {context}\nOptions: {choice}\nBECAUSE: {lecture} {solution}\n" + + elif input_format == "QCLM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture}\nOptions: {choice}\n" + elif input_format == "QCEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {solution}\nOptions: {choice}\n" + elif input_format == "QCLEM": + input = f"Question: {question}\nContext: {context}\nBECAUSE: {lecture} {solution}\nOptions: {choice}\n" + + # Outputs + if test_example: + output = "Answer:" + elif output_format == 'A': + output = f"Answer: The answer is {answer}." + + elif output_format == 'AL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution}" + elif output_format == 'AE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture}" + elif output_format == 'ALE': + output = f"Answer: The answer is {answer}. BECAUSE: {lecture} {solution}" + elif output_format == 'AEL': + output = f"Answer: The answer is {answer}. BECAUSE: {solution} {lecture}" + + elif output_format == 'LA': + output = f"Answer: {lecture} The answer is {answer}." + elif output_format == 'EA': + output = f"Answer: {solution} The answer is {answer}." + elif output_format == 'LEA': + output = f"Answer: {lecture} {solution} The answer is {answer}." + elif output_format == 'ELA': + output = f"Answer: {solution} {lecture} The answer is {answer}." + + input = input.replace(" ", " ").strip() + output = output.replace(" ", " ").strip() + if output.endswith("BECAUSE:"): + output = output.replace("BECAUSE:", "").strip() + + user_prompt = {"role": "user", "content": f"Can you explain {input}?"} + assistant_prompt = {"role": "assistant", "content": f"{output}"} + + return user_prompt, assistant_prompt + + +def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False): + examples = {} + + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], use_caption) + choice = get_choice_text(problems[qid], options) + answer = get_answer(problems[qid], options) + lecture = get_lecture_text(problems[qid]).replace('\\n', '\n') + solution = get_solution_text(problems[qid]).replace('\\n', '\n') + + train_example = create_one_example_chatbot(prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=is_test) + examples[qid] = train_example + return examples + + +def build_prompt(problems, shot_qids, test_qid, args): + + examples = [] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + train_example = create_one_example(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=False) + examples.append(train_example) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + test_example = create_one_example(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=True) + examples.append(test_example) + + # create the prompt input + prompt_input = '\n\n'.join(examples) + + return prompt_input + + +def build_prompt_gpt4(problems, shot_qids, test_qid, args): + + prompt_array = [{"role": "system", "content": "You are a helpful assistant."}] + + # n-shot training examples + for qid in shot_qids: + question = get_question_text(problems[qid]) + context = get_context_text(problems[qid], args.use_caption) + choice = get_choice_text(problems[qid], args.options) + answer = get_answer(problems[qid], args.options) + lecture = get_lecture_text(problems[qid]) + solution = get_solution_text(problems[qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=False) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + # test example + question = get_question_text(problems[test_qid]) + context = get_context_text(problems[test_qid], args.use_caption) + choice = get_choice_text(problems[test_qid], args.options) + answer = get_answer(problems[test_qid], args.options) + lecture = get_lecture_text(problems[test_qid]) + solution = get_solution_text(problems[test_qid]) + + user_prompt, assistant_prompt = create_one_example_gpt4(args.prompt_format, + question, + context, + choice, + answer, + lecture, + solution, + test_example=True) + prompt_array.append(user_prompt) + prompt_array.append(assistant_prompt) + + return prompt_array \ No newline at end of file diff --git a/approach/vlm/LLaVA/scripts/finetune.sh b/approach/vlm/LLaVA/scripts/finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..9314affd72bd06ab260c3e8b36fbf5a4974c995f --- /dev/null +++ b/approach/vlm/LLaVA/scripts/finetune.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/finetune_full_schedule.sh b/approach/vlm/LLaVA/scripts/finetune_full_schedule.sh new file mode 100644 index 0000000000000000000000000000000000000000..533f3f4097db3844846d4a843d765c6df1762ba0 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/finetune_full_schedule.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_158k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune \ + --num_train_epochs 3 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/finetune_lora.sh b/approach/vlm/LLaVA/scripts/finetune_lora.sh new file mode 100644 index 0000000000000000000000000000000000000000..46242a6371e8c9680dcfec5c955c3610555a3146 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/finetune_lora.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 4 \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/finetune_qlora.sh b/approach/vlm/LLaVA/scripts/finetune_qlora.sh new file mode 100644 index 0000000000000000000000000000000000000000..1af397d40c925aa18794ffc9650c7cb50f0430d7 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/finetune_qlora.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +################## VICUNA ################## +# PROMPT_VERSION=v1 +# MODEL_VERSION="vicuna-v1-3-7b" +################## VICUNA ################## + +################## LLaMA-2 ################## +# PROMPT_VERSION="llava_llama_2" +# MODEL_VERSION="llama-2-7b-chat" +################## LLaMA-2 ################## + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --lora_enable True \ + --bits 4 \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path ./playground/data/llava_instruct_80k.json \ + --image_folder /path/to/coco/train2017 \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/llava-$MODEL_VERSION-pretrain/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-finetune_lora \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --lazy_preprocess True \ + --dataloader_num_workers 4 \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/finetune_sqa.sh b/approach/vlm/LLaVA/scripts/finetune_sqa.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c1590fdc7511370e8ccc285dcc9c053379b9134 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/finetune_sqa.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path lmsys/vicuna-13b-v1.3 \ + --version $PROMPT_VERSION \ + --data_path /Data/ScienceQA/data/scienceqa/llava_train_QCM-LEA.json \ + --image_folder /Data/ScienceQA/data/scienceqa/images/train \ + --vision_tower openai/clip-vit-large-patch14 \ + --pretrain_mm_mlp_adapter ./checkpoints/huggingface/liuhaotian/llava-pretrain-vicuna-13b-v1.3/mm_projector.bin \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-vicuna-13b-v1.3-pretrain_lcs558k_plain-ScienceQA_QCM_LEA-12e \ + --num_train_epochs 12 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 50000 \ + --save_total_limit 1 \ + --learning_rate 2e-5 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/merge_lora_weights.py b/approach/vlm/LLaVA/scripts/merge_lora_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..3b39cc7beb12301379af7daebbb5553fa92093ea --- /dev/null +++ b/approach/vlm/LLaVA/scripts/merge_lora_weights.py @@ -0,0 +1,22 @@ +import argparse +from llava.model.builder import load_pretrained_model +from llava.mm_utils import get_model_name_from_path + + +def merge_lora(args): + model_name = get_model_name_from_path(args.model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, device_map='cpu') + + model.save_pretrained(args.save_model_path) + tokenizer.save_pretrained(args.save_model_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, required=True) + parser.add_argument("--model-base", type=str, required=True) + parser.add_argument("--save-model-path", type=str, required=True) + + args = parser.parse_args() + + merge_lora(args) diff --git a/approach/vlm/LLaVA/scripts/pretrain.sh b/approach/vlm/LLaVA/scripts/pretrain.sh new file mode 100644 index 0000000000000000000000000000000000000000..5326e4cc47b78fef423a76823b66982fb66227b2 --- /dev/null +++ b/approach/vlm/LLaVA/scripts/pretrain.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# Uncomment and set the following variables correspondingly to run this script: + +# MODEL_VERSION=vicuna-v1-3-7b +# MODEL_VERSION=llama-2-7b-chat + +########### DO NOT CHANGE ########### +########### USE THIS FOR BOTH ########### +PROMPT_VERSION=plain +########### DO NOT CHANGE ########### + +deepspeed llava/train/train_mem.py \ + --deepspeed ./scripts/zero2.json \ + --model_name_or_path ./checkpoints/$MODEL_VERSION \ + --version $PROMPT_VERSION \ + --data_path /path/to/pretrain_data.json \ + --image_folder /path/to/images \ + --vision_tower openai/clip-vit-large-patch14 \ + --tune_mm_mlp_adapter True \ + --mm_vision_select_layer -2 \ + --mm_use_im_start_end False \ + --mm_use_im_patch_token False \ + --bf16 True \ + --output_dir ./checkpoints/llava-$MODEL_VERSION-pretrain \ + --num_train_epochs 1 \ + --per_device_train_batch_size 16 \ + --per_device_eval_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --evaluation_strategy "no" \ + --save_strategy "steps" \ + --save_steps 24000 \ + --save_total_limit 1 \ + --learning_rate 2e-3 \ + --weight_decay 0. \ + --warmup_ratio 0.03 \ + --lr_scheduler_type "cosine" \ + --logging_steps 1 \ + --tf32 True \ + --model_max_length 2048 \ + --gradient_checkpointing True \ + --dataloader_num_workers 4 \ + --lazy_preprocess True \ + --report_to wandb diff --git a/approach/vlm/LLaVA/scripts/sqa_eval_batch.sh b/approach/vlm/LLaVA/scripts/sqa_eval_batch.sh new file mode 100644 index 0000000000000000000000000000000000000000..adbf46ef7a6e86181b5927002597ef786add5bde --- /dev/null +++ b/approach/vlm/LLaVA/scripts/sqa_eval_batch.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +CHUNKS=8 +for IDX in {0..7}; do + CUDA_VISIBLE_DEVICES=$IDX python -m llava.eval.model_vqa_science \ + --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \ + --question-file ~/haotian/datasets/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \ + --image-folder ~/haotian/datasets/ScienceQA/data/scienceqa/images/test \ + --answers-file ./test_llava-13b-chunk$CHUNKS_$IDX.jsonl \ + --num-chunks $CHUNKS \ + --chunk-idx $IDX \ + --conv-mode llava_v1 & +done diff --git a/approach/vlm/LLaVA/scripts/sqa_eval_gather.sh b/approach/vlm/LLaVA/scripts/sqa_eval_gather.sh new file mode 100644 index 0000000000000000000000000000000000000000..525bd43b850e9f6a923158abd23bca6f8d15650e --- /dev/null +++ b/approach/vlm/LLaVA/scripts/sqa_eval_gather.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +CHUNKS=8 +output_file="test_llava-13b.jsonl" + +# Clear out the output file if it exists. +> "$output_file" + +# Loop through the indices and concatenate each file. +for idx in $(seq 0 $((CHUNKS-1))); do + cat "./test_llava-13b-chunk${idx}.jsonl" >> "$output_file" +done + +python llava/eval/eval_science_qa.py \ + --base-dir ~/haotian/datasets/ScienceQA/data/scienceqa \ + --result-file ./test_llava-13b.jsonl \ + --output-file ./test_llava-13b_output.json \ + --output-result ./test_llava-13b_result.json